BT San Technology

4 August 2026

XSS, SQL injection and CSRF: understanding web risks well enough to talk with developers

24 min read · Websites and web apps

Illustration: a laptop showing a web page beside a check panel with coloured dots, a hand writing a checklist on a clipboard, beside a zip case and a security key
AI-generated illustration

A search box that echoes the typed words back onto the page, a list filter that carries on into an SQL command, and a transfer button that runs the moment the browser sends a request with a cookie. All three have the same root: the system takes something that came from outside and treats it as its own, whether that is text that turns into HTML, a value that turns into part of a command, or a request that is taken to be the user's intent.

This article builds a small demo app with node:http and node:sqlite that listens on the local machine only. Each flaw has a vulnerable version (/v/...) and a fixed version (/f/...) side by side, and a script sends the smallest possible request to both so you can see which one breaks and which one refuses. Executives can read the tables and explanations and know what to ask the development team. Engineers can run the code and follow along.

Scope: all test strings in this article are for the demo app in the example folder only. Do not use them against anyone else's website or system. Defensive testing on a real system is allowed only on systems you own or have written permission to test.

Three hypothetical scenarios

All three are hypothetical scenarios used for explanation. They are not projects of any BT San customer.

  • An online shop has a product search box. The results page prints the search term straight back. A link with a crafted search term is passed around in a chat. Someone who clicks the link while logged in lets another person's script run in the name of the shop's website (XSS).
  • A back-office system for the sales team has a customer name search. The code joins the search term into an SQL command. A staff member who types a name containing a single quote gets an error page, while someone who deliberately adds extra conditions gets rows they should not see (SQL injection).
  • An internal app has an approve button that sends a POST to the same endpoint used every day. When a staff member stays logged in and opens another web page, that page hides a form that submits the request by itself. The system sees a valid cookie and approves it (CSRF).

Facts from the documents I read

TopicWhat the documentation saysEffect on the code
XSSOWASP says the primary defense is context-aware output encoding (HTML body, attribute, JavaScript, URL), and that no single technique fixes XSS completely.Pick the encoder by where the data ends up, and cover every spot.
CSPMDN says CSP limits what injected code can do, and that setting a CSP is not a substitute for sanitizing data: do both as defense in depth. OWASP warns that CSP is easy to set wrongly, so it should not be the primary control.Add the CSP header as a backup layer after encoding is in place.
escape hatchOWASP gives examples of ways around automatic encoding, such as React's dangerouslySetInnerHTML, Angular's bypassSecurityTrust, and Lit's unsafeHTML, and recommends textContent instead of innerHTML.Code review must search for these specifically.
SQL injectionOWASP says the primary defense is to separate the command structure from the values with a parameterized query. Table or column names cannot be bound as parameters; they must be mapped from the user's choice to a value that the code defines itself.Values must always enter as parameters. Use an allow-list for column names.
Input validationOWASP says input validation is a supplement and does not replace parameter binding, and that writing your own escaping is strongly discouraged.Check type and range as a second layer.
CSRFOWASP: use a synchronizer token tied to the session, check the Origin as a whole value, and make sure GET never changes state. SameSite is an extra layer that should not be relied on alone, because Lax still sends the cookie on top-level navigation with GET, and its scope is the site, not the origin.Use several layers together.
SameSiteMDN says Lax does not send the cookie on cross-site POST but does send it on navigation with safe methods, and some browsers apply Lax when no value is given.Always set SameSite yourself. Do not wait for the default.
XSS defeats CSRFOWASP says an XSS flaw bypasses every CSRF defense, because the script runs as the user.Close both problems; do not pick just one.
Summary of the OWASP Cheat Sheet Series and MDN as read on 2026-11-21. For the latest details in each version, check the originals.

Files in the example

The code is in the folder examples/xss-sql-injection-csrf-defensive-basics/. It uses only Node 24 built-ins, with no npm install. TypeScript runs directly with the node command on a .ts file, and node:sqlite may print a warning that it is still experimental, which is why --no-warnings is added.

FilePurpose
escape.tsThe escapeHtml function for HTML content and for quoted attributes.
db.tsAn in-memory node:sqlite database with the users and accounts tables.
app.tsA node:http server with a /v/ route (vulnerable) and an /f/ route (fixed) for all three flaws.
demo.tsStarts the server on a random port, sends small requests to both versions, and prints the results.
security.test.tsThe node:test test suite.
output.txtThe real output of running demo.ts.

Flaw 1: XSS is joining text into HTML

The problem appears when user text is joined into HTML and the browser cannot tell which part is page structure and which part is text. The vulnerable version joins the string directly. The fixed version encodes special characters first and also sets a CSP header as a backup layer.

app.ts · lines 38–47
    if (path === "/v/search") {
      const q = url.searchParams.get("q") ?? "";
      // ช่องโหว่: ต่อสตริงตรง ๆ และไม่มี CSP
      return send(res, 200, "text/html", `<h1>ผลค้นหา</h1><p>คุณค้นหา: ${q}</p>`);
    }
    if (path === "/f/search") {
      const q = url.searchParams.get("q") ?? "";
      // แก้: เข้ารหัสตามบริบท (เนื้อหา HTML) และเพิ่ม CSP เป็นชั้นสำรอง
      return send(res, 200, "text/html", `<h1>ผลค้นหา</h1><p>คุณค้นหา: ${escapeHtml(q)}</p>`, { "content-security-policy": CSP });
    }
app.ts: the /v/search route joins the string directly, while /f/search encodes it and sends a CSP.
escape.ts
// escapeHtml ใช้กับข้อความที่จะไปอยู่ใน "เนื้อหา HTML" หรือ "attribute ที่มีเครื่องหมายคำพูดครอบ" เท่านั้น
// ไม่ใช้กับ JavaScript, URL หรือ CSS: แต่ละบริบทต้องใช้ตัวเข้ารหัสของบริบทนั้น
const MAP: Record<string, string> = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;",
};

export function escapeHtml(value: string): string {
  return value.replace(/[&<>"']/g, (ch) => MAP[ch]);
}
escape.ts: the encoder for HTML content and quoted attribute contexts.

A common beginner mistake is to think one function works everywhere. This encoder works only for HTML content and quoted attributes. If the data ends up in a script, a URL or CSS, you need the encoder for that context (OWASP lists separate rules for each context), and never put user data where code or an identifier name belongs.

The CSP in the example is very strict (default-src 'none') because the page is plain text. It tells the browser not to load or run anything except what is explicitly allowed, so if encoding fails at even one spot, the injected script still cannot run. A real page has its own scripts and styles, so the policy has to be adjusted to match: use a per-response nonce for any inline script that is needed, and avoid unsafe-inline.

Flaw 2: SQL injection is joining a value into a command

The database receives a command as a single block of text. If the value the user typed is joined in, the database parser reads the quote marks and keywords in that value as part of the command. The example deliberately includes the condition is_admin = 0 in the command so you can see that the condition can be bypassed.

app.ts · lines 50–65
    if (path === "/v/user") {
      const name = url.searchParams.get("name") ?? "";
      try {
        // ช่องโหว่: ค่าจากผู้ใช้กลายเป็นส่วนหนึ่งของคำสั่ง SQL
        const rows = db.prepare(`SELECT name, email FROM users WHERE name = '${name}' AND is_admin = 0`).all();
        return send(res, 200, "application/json", JSON.stringify(rows));
      } catch (e) {
        return send(res, 500, "application/json", JSON.stringify({ error: (e as Error).message }));
      }
    }
    if (path === "/f/user") {
      const name = url.searchParams.get("name") ?? "";
      // แก้: โครงคำสั่งคงที่ ค่าส่งแยกผ่านพารามิเตอร์
      const rows = db.prepare("SELECT name, email FROM users WHERE name = ? AND is_admin = 0").all(name);
      return send(res, 200, "application/json", JSON.stringify(rows));
    }
app.ts: /v/user joins the string into the SQL, while /f/user uses ? and passes the value separately in .all(name).

The fixed version does not sanitize the value at all. It separates the value from the command structure from the start. The database receives a closed command structure first, and then receives the value as pure data, so a name containing a quote is compared as one name and not found. What binding cannot do is table names, column names and sort direction (ASC or DESC). If users can pick a column to sort by, map the choice to values the code writes itself, for example an object with the keys name and email, and reject everything outside the list.

Flaw 3: CSRF is the browser attaching the cookie without the user knowing

Another site does not need to know your cookie. It only needs to make your browser send a request to the site you are logged in to, and the browser attaches the cookie by itself. A server that trusts only the cookie cannot tell whether the request came from its own form or from another page. The example uses three layers at once: a SameSite=Lax cookie, an Origin check, and a token tied to the session.

app.ts · lines 68–77
    if (path === "/v/login" || path === "/f/login") {
      const id = randomBytes(16).toString("hex");
      sessions.set(id, { user: "somchai", csrf: randomBytes(16).toString("hex") });
      const base = `sid=${id}; Path=/; HttpOnly`;
      // เวอร์ชันแก้ตั้ง SameSite=Lax; เวอร์ชันช่องโหว่ไม่ระบุ (ทดสอบเอง ไม่ให้ขึ้นกับค่าตั้งต้นของเบราว์เซอร์)
      return send(res, 200, "text/plain", "logged in", { "set-cookie": path === "/f/login" ? base + "; SameSite=Lax" : base });
    }
    if (path === "/f/form" && session) {
      return send(res, 200, "text/html", `<form method="post" action="/f/transfer"><input type="hidden" name="csrf" value="${escapeHtml(session.csrf)}"></form>`);
    }
app.ts: sets the cookie for both versions and issues the form with the embedded token.
app.ts · lines 78–91
    if (path === "/v/transfer" && req.method === "POST") {
      if (!session) return send(res, 401, "text/plain", "login required");
      // ช่องโหว่: เชื่อแค่ cookie ไม่มีอะไรบอกว่าคำขอมาจากฟอร์มของเรา
      return transfer(res, session.user, await readForm(req));
    }
    if (path === "/f/transfer" && req.method === "POST") {
      if (!session) return send(res, 401, "text/plain", "login required");
      // ชั้นที่ 1: Origin ต้องตรงทั้งก้อน (ไม่มี Origin = ปฏิเสธ ไม่ยอมรับ null)
      if (req.headers.origin !== allowedOrigin()) return send(res, 403, "text/plain", "bad origin");
      const form = await readForm(req);
      // ชั้นที่ 2: synchronizer token ผูกกับ session
      if (!sameToken(form.get("csrf") ?? "", session.csrf)) return send(res, 403, "text/plain", "bad csrf token");
      return transfer(res, session.user, form);
    }
app.ts: /v/transfer trusts only the cookie, while /f/transfer checks the Origin and then the token.
app.ts · lines 95–106
  function transfer(res: ServerResponse, from: string, form: URLSearchParams) {
    const to = form.get("to") ?? "";
    const amount = Number(form.get("amount"));
    // การตรวจค่าเป็นชั้นเสริม: จำนวนเต็มบวก และผู้รับต้องมีอยู่จริง
    if (!Number.isInteger(amount) || amount <= 0) return send(res, 400, "text/plain", "bad amount");
    const bal = db.prepare("SELECT balance FROM accounts WHERE owner = ?").get(from) as { balance: number };
    if (bal.balance < amount) return send(res, 400, "text/plain", "insufficient funds");
    const target = db.prepare("UPDATE accounts SET balance = balance + ? WHERE owner = ?").run(amount, to);
    if (target.changes === 0) return send(res, 400, "text/plain", "unknown recipient");
    db.prepare("UPDATE accounts SET balance = balance - ? WHERE owner = ?").run(amount, from);
    send(res, 200, "text/plain", "transferred " + amount);
  }
app.ts: the transfer function validates values as an extra layer and uses parameters in every SQL command.
  • The token must be random and tied to the session. Send it in the form or a header, not in a cookie or URL, and compare it with timingSafeEqual.
  • The Origin must match as a whole value, not a check that "the domain name appears in it", because example.org.attacker.com would pass a loose check. If there is no Origin, reject the request.
  • SameSite=Lax helps keep the cookie off cross-site POST requests, but its scope is the site (the registered domain). Sibling subdomains still count as the same site, so it is not enough as the only layer.
  • GET must not change state, because Lax still sends the cookie on navigation with GET.
  • Most frameworks have a built-in CSRF mechanism. Use the framework's own before writing your own.

Real output

output.txt
== 1. XSS (ข้อความทดสอบแบบไม่เป็นอันตราย) ==
/v/search                                 แท็กถูกส่งไปเป็นโครงสร้าง HTML
  header CSP                              (ไม่มี)
/f/search                                 แท็กถูกเข้ารหัสเป็นข้อความ
  header CSP                              default-src 'none'; style-src 'self'; base-uri 'none'; form-action 'self'

== 2. SQL injection ==
/v/user ?name=x' OR '1'='1' --            status 200 แถวที่ได้: 3
/f/user ?name=x' OR '1'='1' --            status 200 แถวที่ได้: 0
/f/user ?name=malee                       status 200 [{"name":"malee","email":"[email protected]"}]
/v/user (ทะลุ is_admin=0)                 200 [{"name":"admin","email":"[email protected]"}]

== 3. CSRF (จำลองคำขอที่มาจากเว็บอื่น) ==
/v/transfer ไม่มี token                   status 200 mallory=500
  Set-Cookie ของ /f/login                 sid=<สุ่ม>; Path=/; HttpOnly; SameSite=Lax
/f/transfer ไม่มี token                   status 403 bad csrf token mallory=500
/f/transfer Origin ผิด                    status 403 bad origin mallory=500
/f/transfer ฟอร์มจริง                     status 200 transferred 500 mallory=1000
/f/transfer จำนวนติดลบ                    status 400 bad amount mallory=1000
Real output from 2026-11-21 using node --no-warnings demo.ts (Node 24.21). Session id values are replaced with <random> so the output is repeatable.
  1. XSS: /v/search sends the test tag through as HTML structure and has no CSP. /f/search shows it as text and has a CSP header.
  2. SQL injection: the vulnerable version returns 3 rows when it should show only ordinary users, and the is_admin = 0 condition is bypassed so the admin row is visible. The fixed version returns 0 rows, and searching for a real name still works normally.
  3. CSRF: a request with only a cookie passes the vulnerable version, and the recipient's balance becomes 500. The fixed side answers 403 both when there is no token and when the Origin is wrong, and the balance does not change. A real form with both an Origin and a token can transfer, and a negative amount is rejected with 400.
  4. The recipient's balance (mallory) on the CSRF line shows whether the attack actually had an effect, rather than just reading the status code.

The script sends requests with fetch and sets the cookie and Origin itself to simulate a cross-site request, which lets it test each layer separately. In a real browser, SameSite=Lax would already keep the cookie off a cross-site POST. The example therefore shows that if that layer leaks, the Origin and token layers still block the request.

demo.ts · lines 38–58
console.log("\n== 3. CSRF (จำลองคำขอที่มาจากเว็บอื่น) ==");
const form = "to=mallory&amount=500";
const hdr = { "content-type": "application/x-www-form-urlencoded" };
const v = (await call("/v/login")).cookie!.split(";")[0];
let r = await call("/v/transfer", { method: "POST", headers: { ...hdr, cookie: v, origin: "http://evil.example" }, body: form });
line("/v/transfer ไม่มี token", `status ${r.status} mallory=${balance()}`);

const loginF = await call("/f/login");
line("  Set-Cookie ของ /f/login", loginF.cookie!.replace(/sid=[0-9a-f]+/, "sid=<สุ่ม>"));
const f = loginF.cookie!.split(";")[0];
const token = /name="csrf" value="([0-9a-f]+)"/.exec((await call("/f/form", { headers: { cookie: f } })).body)![1];
r = await call("/f/transfer", { method: "POST", headers: { ...hdr, cookie: f, origin }, body: form });
line("/f/transfer ไม่มี token", `status ${r.status} ${r.body} mallory=${balance()}`);
r = await call("/f/transfer", { method: "POST", headers: { ...hdr, cookie: f, origin: "http://evil.example" }, body: form + "&csrf=" + token });
line("/f/transfer Origin ผิด", `status ${r.status} ${r.body} mallory=${balance()}`);
r = await call("/f/transfer", { method: "POST", headers: { ...hdr, cookie: f, origin }, body: form + "&csrf=" + token });
line("/f/transfer ฟอร์มจริง", `status ${r.status} ${r.body} mallory=${balance()}`);
r = await call("/f/transfer", { method: "POST", headers: { ...hdr, cookie: f, origin }, body: "to=mallory&amount=-5&csrf=" + token });
line("/f/transfer จำนวนติดลบ", `status ${r.status} ${r.body} mallory=${balance()}`);

server.close();
demo.ts: part three sends simulated requests to /v/transfer and /f/transfer in turn.

Test suite

security.test.ts uses node --test and starts a real server on a random port. It tests six things: the XSS encoder in both versions, two SQL injection cases (a value that widens the condition, and a single quote that makes the vulnerable version error), and CSRF in both versions. The tests focus on confirming that the fixed version refuses and the balance does not change, rather than just looking at the response code.

security.test.ts · lines 53–69
test("CSRF: เวอร์ชันแก้ปฏิเสธเมื่อไม่มี token หรือ Origin ผิด และรับเฉพาะฟอร์มจริง", async () => {
  const login = await fetch(origin + "/f/login");
  assert.match(login.headers.get("set-cookie") ?? "", /SameSite=Lax/);
  const cookie = (login.headers.get("set-cookie") ?? "").split(";")[0];
  const token = /value="([0-9a-f]+)"/.exec((await get("/f/form", cookie)).body)![1];
  const post = (body: string, o: string | undefined) =>
    fetch(origin + "/f/transfer", { method: "POST", headers: { ...hdr, cookie, ...(o ? { origin: o } : {}) }, body });
  const before0 = mallory();
  assert.equal((await post("to=mallory&amount=5", origin)).status, 403);
  assert.equal((await post("to=mallory&amount=5&csrf=" + token, "http://evil.example")).status, 403);
  assert.equal((await post("to=mallory&amount=5&csrf=" + token, undefined)).status, 403);
  assert.equal((await post("to=mallory&amount=5&csrf=wrong", origin)).status, 403);
  assert.equal(mallory(), before0);
  assert.equal((await post("to=mallory&amount=5&csrf=" + token, origin)).status, 200);
  assert.equal(mallory(), before0 + 5);
  assert.equal((await post("to=mallory&amount=1.5&csrf=" + token, origin)).status, 400);
});
security.test.ts: the CSRF case for the fixed version, covering no token, wrong Origin, no Origin, wrong token and a real form.

How far frameworks help, and where they stop

Modern templates encode output automatically, and most ORMs bind parameters for you. These defaults prevent most mistakes, but every framework has an exit that bypasses the protection, and real flaws are usually there.

What the framework does for youProtection stops whenWhat to check in code review
Encodes values inserted into templatesYou use a way around encoding, such as dangerouslySetInnerHTML, innerHTML, unsafeHTML, Angular's bypassSecurityTrust, or you skip sanitization before showing HTML that users wrote.Search for these in every place. If you must show user HTML, use a maintained sanitizer such as DOMPurify as OWASP recommends, and never edit the text after sanitizing.
ORM binds parameters for youYou write a raw query, or join strings in the ORM's query language (OWASP says JPQL and HQL can also be at risk), or you pass a column name from the user into order by.Search for raw queries in every place. Use parameters that bind by name, and an allow-list for column names.
Built-in CSRF mechanismAn endpoint is exempted, an API authenticated by cookie has the check turned off, or there is an XSS flaw.Look at the list of exempted endpoints and the reason for each.
This table is general guidance. API names and versions for each framework must be checked in the documentation of the one you use.

Input validation is a second layer, not the fix

The transfer function checks that the amount is a positive integer and that the recipient exists. This kind of check is good because it reduces strange data and makes error messages clear, but it does not protect against the three flaws. A name like O'Brien is valid data and you cannot reject the single quote, and a list of forbidden characters can always be missed. What is safe is to encode by context, bind parameters and check where the request came from, and then validate values as an extra layer. OWASP says the same: validation supplements but does not replace parameter binding.

When you use this in practice

  • The sessions and tokens in the example live in an in-memory Map and never expire (simplified). A real system needs a central store, expiry, and a new session after login.
  • Set cookies as Secure and HttpOnly on HTTPS. The example does not set Secure because it runs on http localhost.
  • Roll out CSP in steps. Start in report-only mode to see which scripts the real pages depend on, then enforce.
  • Routes that accept JSON through an API that uses a header instead of a cookie have a different CSRF risk from forms. Analyze them according to the authentication method actually used.
  • Log rejected requests (403 from a token or Origin check) to spot unusual patterns, but do not log tokens or values that users typed in.

Applying this to business systems

  • Shops and booking sites: the search box, the review box and the contact form are where user data comes back onto the page. Encode every one and set a CSP.
  • Back-office systems or internal ERP: reports with many filter conditions often build SQL by hand, so review them with extra care, including sorting by a column the user picks.
  • Apps with approve or transfer buttons: every endpoint that changes state needs a token and an Origin check, and GET must never change state.

Common mistakes

  • Using an HTML encoder on data that ends up in a script, a URL or CSS.
  • Believing the ORM covers everything, then joining strings into a complex raw query.
  • Stripping dangerous characters (a blacklist) instead of encoding and using parameters.
  • Checking Origin with includes or startsWith instead of comparing the whole value.
  • Relying on SameSite alone, or leaving it as the browser default.
  • Using GET for actions that change data.
  • Adding a CSP and then stopping the work on encoding, or adding unsafe-inline to keep an existing page working.
  • Thinking CSRF is closed so XSS no longer matters, when XSS bypasses CSRF defenses.

Checklist for the team

  1. List every place where user data is shown on a page, grouped by context (content, attribute, script, URL).
  2. Search the code for framework escape hatches and raw queries, and give a reason for each one.
  3. Check that every SQL command takes values through parameters, and that column names the user picks go through an allow-list.
  4. Every endpoint that changes state needs a token and an Origin check, and GET must be safe.
  5. Set cookies as HttpOnly and Secure, and set SameSite yourself.
  6. Set CSP starting in report-only mode, then enforce once it is clean.
  7. Write a test suite that attacks the fixed version and confirms that data state does not change.
  8. Set a review cycle for whenever a feature that accepts data or changes state is added.

Limits: this article explains defensive basics with a small demo app. It is not a security certification, and it does not cover DOM-based XSS, stored XSS that goes through a database, authentication, authorization, or other types of attack. All scenarios are hypothetical. You must check the measures specific to your own system.

References

  1. OWASP — Cross Site Scripting Prevention (accessed 2026-11-21)
  2. OWASP — SQL Injection Prevention (accessed 2026-11-21)
  3. OWASP — Cross-Site Request Forgery Prevention (accessed 2026-11-21)
  4. MDN — Content Security Policy (CSP) (accessed 2026-11-21)
  5. MDN — Set-Cookie (SameSite, HttpOnly, Secure) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer