The sessions unit explained how a server recognizes a signed-in user, and the CORS unit explained how a server can allow a page from another origin to read its responses. Both rest on security rules that the browser enforces and that the application must supplement. This unit states those rules exactly and examines three common vulnerability classes. Each has a different cause, so each has a different defense, and a defense aimed at the wrong class does nothing: CORS configuration does not stop XSS, and escaping HTML does not stop SQL injection.
1. Origins and the same-origin policy
Definition 8.4.1
(Origin)
An origin is the triple (scheme, host, port), for example https://app.example.test:443. If the URL omits the port, the default for the scheme applies: 443 for https, 80 for http. The path, query string and fragment are not part of the origin. Two URLs have the same origin exactly when all three components are equal.
Take https://app.example.test/ as the reference.
| URL | Same origin? | Reason |
|---|---|---|
https://app.example.test/notes?id=1 | yes | path and query are not part of the origin |
https://app.example.test:443/ | yes | 443 is the default port for https |
http://app.example.test/ | no | scheme differs |
https://api.example.test/ | no | host differs |
https://app.example.test:8443/ | no | port differs |
The same-origin policy (SOP) is the browser rule that, by default, a script running in one origin may not read data from another origin: it cannot read the DOM of a cross-origin document, and it cannot read the response to a cross-origin fetch unless the other server permits it (that permission is CORS). Two precise limits matter for what follows. The SOP restricts reading, not sending: a page can still cause the browser to send a cross-origin request, for example by submitting a form or loading an image, and the server will receive it. And cookies are scoped by host, path and attributes, not by origin, so the browser attaches a site's cookies to such a request automatically.
2. Cross-site scripting (XSS)
Definition. Cross-site scripting is a vulnerability in which attacker-controlled data is placed into a page so that the browser interprets it as markup or script. The attacker's script then runs in the origin of the vulnerable page, with that origin's privileges. The SOP does not help, because the script is not a foreign origin: it is running inside this one. It can read the page, send same-origin requests with the user's cookies, and change what the user sees. An HttpOnly cookie cannot be read by the script, but the script can still make requests that carry the cookie, so the actions are performed even though the cookie value is not stolen.
The usual classification is by where the data comes from. Stored XSS keeps the payload on the server (a comment, a profile field) and serves it to every viewer. Reflected XSS puts request data, such as a query parameter, directly into the response. DOM-based XSS happens entirely in client code, when JavaScript writes untrusted data into the page with an unsafe API.
The vulnerable pattern is:
const name = new URLSearchParams(location.search).get("name");
document.getElementById("greeting").innerHTML = "Hello, " + name;
If name is <img src="x" onerror="alert(1)">, assigning it to innerHTML makes the browser parse an img element; the image fails to load, and the onerror handler executes. Note that a script element inserted through innerHTML does not run, but event-handler attributes do, so filtering the word "script" is not a defense.
Defenses.
- Treat data as data. Use
textContent(orcreateTextNode) rather thaninnerHTML: the string is displayed literally and never parsed as markup.
document.getElementById("greeting").textContent = "Hello, " + name;
- Escape for the context when output must be generated as markup, using a vetted template engine or framework. The set of characters to encode depends on the context: HTML text, attribute value, JavaScript string and URL each need different encoding. React escapes string children by default, which is why
dangerouslySetInnerHTMLis named as it is; URLs placed inhreforsrcstill need their scheme checked, becausejavascript:URLs are executable. - Sanitize with a well-maintained library only when users are truly allowed to submit HTML; a hand-written filter is unreliable.
- Content Security Policy (a response header that restricts where scripts may load from and whether inline scripts run) is a second layer that reduces the damage of a missed escape. It does not replace correct output handling.
Counterexample mode
Removing the word script does not remove the payload
Claim: stripping every occurrence of <script from a comment, as in text.replace(/<script/gi, ""), makes item.innerHTML = text safe. Take the comment <img src="x" onerror="alert(1)">. It contains no <script, so the filter returns it unchanged, the browser builds an img element, the request for x fails and alert(1) runs in the page's origin. The filter blocks one carrier of script and leaves every event-handler attribute available. The repair is not a longer blacklist but a different output operation: assign the comment to textContent, or sanitize with a maintained library when formatting must be allowed.
3. Cross-site request forgery (CSRF)
Definition. CSRF makes a victim's browser send a request to a site where the victim is signed in, without the victim intending it. It needs three conditions together: the request changes state; the site authenticates it using credentials the browser attaches automatically, typically a session cookie; and the server accepts the request without any value that an attacker's page cannot supply. The attacker never reads the response, which is why the SOP's read restriction does not prevent it.
Example. A bank's endpoint is POST https://bank.example.test/transfer with fields to and amount, authenticated by a session cookie. A page at https://evil.example.test contains a form with those fields pointing at that URL and submits it automatically. The browser sends the cookie for bank.example.test along with the request, so the bank sees an authenticated request.
Defenses.
SameSitecookies.SameSite=Strictwithholds the cookie from every cross-site request.SameSite=Laxwithholds it from cross-site subrequests and from cross-sitePOSTnavigations, but still sends it on a top-level navigation that uses a safe method such asGET, for example a click on a link.SameSite=Noneallows cross-site sending and must be combined withSecure. Two consequences follow: state-changing operations must never useGET, and "same-site" is not "same-origin" —app.example.testandapi.example.testare same-site (assumingexample.testis the registrable domain) but different origins, so SameSite alone does not protect against a hostile sibling subdomain.- CSRF tokens. The server issues an unpredictable token tied to the session, embeds it in the page, and requires it in each state-changing request body or custom header. An attacker's page cannot read the token, because of the SOP, and so cannot include it. A custom request header also forces a CORS preflight for cross-origin requests, which the attacker's page cannot pass.
- Origin checks. Browsers send an
Originheader on cross-originPOSTrequests; the server can reject values outside an allow-list. This is a supplement, not a replacement for tokens.
Not defenses: allowing only POST (forms can submit POST), keeping the cookie HttpOnly (the browser still sends it), or using HTTPS (the forged request is also HTTPS). Credentials that JavaScript attaches explicitly, such as a bearer token in an Authorization header, are not sent automatically and so are not CSRF-prone, but a token that JavaScript can read is exposed if XSS occurs.
4. Injection
Definition. Injection occurs when untrusted data is combined with a command or query so that the data can change its structure. The common cause is building a query string by concatenation.
SQL example:
const sql = "SELECT id FROM users WHERE name = '" + name + "'";
For name = alice the query is SELECT id FROM users WHERE name = 'alice'. For name = ' OR '1'='1 it becomes SELECT id FROM users WHERE name = '' OR '1'='1', whose condition is true for every row. The defense is a parameterized query, where the driver sends the query text and the values separately so that values are never parsed as SQL:
const [rows] = await db.execute("SELECT id FROM users WHERE name = ?", [name]);
NoSQL operator injection. MongoDB filters are objects, and express.json() turns JSON from the client into objects. Consider:
const user = await User.findOne({ username: req.body.username, password: req.body.password });
A client can send {"username":"alice","password":{"$ne":null}}. The filter object then contains the operator $ne, which matches any user named alice whose password field is not null, so no password is needed. Mongoose casts filter values to schema types, but it does not by itself reject operator objects, so the application must. Validate that each field has the expected primitive type, and do not look up a user by password at all: find the user by name, then compare the submitted password against a stored salted hash produced by a deliberately slow password-hashing function.
const { username, password } = req.body;
if (typeof username !== "string" || typeof password !== "string") {
return res.status(400).json({ error: "invalid input" });
}
const user = await User.findOne({ username });
Mongoose also offers a sanitizeFilter option that treats nested objects in filters as literal values rather than operators. In every case the principle is the same: separate data from code, and validate the type and shape of external input at the boundary.
5. Worked example: tracing an XSS payload
Worked example 8.4.2
(Tracing a stored XSS payload)
A comment page stores comments and renders each with item.innerHTML = comment.text. A user posts the text <img src="x" onerror="alert(1)">.
- The server stores the string unchanged (stored XSS).
- Another user loads the page; the script runs
item.innerHTML = .... - The browser parses the string into an
imgelement with anonerrorattribute. - The image request for
xfails, the handler runs, andalert(1)executes in the origin of the comments site.
Changing the line to item.textContent = comment.text makes step 3 produce a text node, so the user sees the literal characters and nothing executes. Apply one encoding mechanism, once, at output; escaping the text and then also assigning it with textContent would display visible entity text such as <.
6. Worked example: CSRF with and without SameSite
Worked example 8.4.3
(CSRF with and without SameSite)
A site bank.example.test sets its session cookie as session=...; Secure; HttpOnly; SameSite=Lax.
- The attacker page auto-submits
POST /transfer. UnderLaxthe cookie is withheld on this cross-sitePOST, so the request arrives without a session and the server responds as for an unauthenticated user. The attack fails. - Suppose the application also exposes
GET /transfer?to=mallory&amount=100. The attacker lures the victim into clicking a link to it. A click is a top-level navigation with a safe method, soLaxsends the cookie, and the transfer succeeds. The cause is that aGETrequest changes state. - If the cookie were instead
SameSite=None, the forgedPOSTwould carry the cookie. A server that requires a valid CSRF token in the request would reject it with 403, since the attacker's page cannot read the token.
Across the three cases the outcome turns on two separate questions: does the forged request carry the cookie, and does the server demand a value that the attacker's page cannot obtain? Under Lax, SameSite withholds the cookie only from cross-site subrequests and unsafe-method navigations, so keeping GET free of side effects and verifying a token are what complete the defense.
7. Worked example: matching each finding to its defense
Worked example 8.4.4
(Matching three findings to their defenses)
A review of a small Express application reports three findings.
| Finding | Vulnerability class | Defense that removes the cause |
|---|---|---|
A search route responds with "<p>Results for " + req.query.q + "</p>" | reflected XSS | output q as text, through an escaping template engine or textContent in the client |
POST /account/email changes the address using only the session cookie | CSRF | SameSite on the session cookie plus a server-verified CSRF token |
Order.find({ owner: req.body.owner }) accepts any JSON value for owner | NoSQL operator injection | require typeof owner === "string", or enable sanitizeFilter |
Each defense acts on the step at which that attack succeeds. In the search route the browser parses attacker text as markup, so encoding the output removes the cause; adding CORS headers would change nothing, because the injected script runs in the search page's own origin. In the email route the forged request succeeds because the browser attaches the cookie and the server asks for nothing else; the token supplies a value that a cross-site page cannot read. In the order query a client-supplied object such as {"$ne": null} becomes an operator; checking the type keeps the value a plain string. Swapping the defenses, for instance escaping owner as HTML, would leave every finding exploitable.
8. Common mistakes
- Escaping data once for HTML and again for a different context, producing both double encoding and gaps.
- Believing
HttpOnlyprevents XSS. It prevents reading one cookie, not acting with it. - Believing
SameSite=Laxjustifies state-changingGETroutes. - Building queries by concatenating
req.body,req.queryorreq.params, or passing parsed JSON objects directly as filters without checking their types.
Common mistake
(Relying on CORS to stop forged requests)
A server sends Access-Control-Allow-Origin: https://app.example.test and nothing else, and its owner concludes that other sites cannot change state. A page at https://evil.example.test submits an ordinary form POST to /transfer. That is a simple cross-origin request, so the browser sends it without a preflight, and the server runs it whenever the browser also attaches the session cookie. CORS decides only whether the attacker's script may read the response. It is not consulted at all for XSS, because injected script runs in the vulnerable page's own origin. The defenses are the ones in the XSS and CSRF sections: safe output, SameSite, a verified CSRF token.
Common mistake
(Validating only in the browser)
An input carries maxlength="80", and the developer assumes titles are therefore at most 80 characters long. A request sent from a command-line client, such as curl -X POST -H "Content-Type: application/json" -d '{"title":"..."}' with a 500-character title, never passes through that form and is stored unless the server checks the length itself. Browser checks improve the user's experience; the server must enforce every rule that matters.
Exercises
Quick check
(Compare origins)
Relative to https://shop.example.test:8443/cart, state whether each URL has the same origin: (a) https://shop.example.test:8443/checkout, (b) https://shop.example.test/cart, (c) http://shop.example.test:8443/cart, (d) https://www.shop.example.test:8443/cart.
Solution
(a) Same origin: only the path differs. (b) Different: no port means 443 for https, which differs from 8443. (c) Different: the scheme is http, not https. (d) Different: the host www.shop.example.test differs from shop.example.test.
Quick check
(InnerHTML versus textContent)
A page runs el.innerHTML = comment.text. State what the user sees if the text is <b>hi</b> with innerHTML and with textContent, and which version is safe for untrusted comments.
Solution
With innerHTML the browser parses the markup and shows the word hi in bold; the same mechanism would execute an event-handler payload, so it is unsafe for untrusted text. With textContent the literal characters <b>hi</b> are displayed, and nothing is parsed. The textContent version is safe. If comments must be allowed to contain formatting, run the HTML through a maintained sanitizer first.
Quick check
(Which measures stop CSRF?)
For a cookie-authenticated POST /delete-account endpoint, decide whether each measure stops a forged cross-site request: (a) accept only POST; (b) SameSite=Strict on the session cookie; (c) a server-verified CSRF token in a custom header; (d) marking the cookie HttpOnly.
Solution
(a) No: a hostile page can submit a form using POST. (b) Yes for requests initiated from another site, because the cookie is not sent; it does not cover a request from a same-site hostile subdomain. (c) Yes: the attacker's page cannot read the token, and the custom header also triggers a preflight that the attacker's origin cannot satisfy. (d) No: HttpOnly stops scripts reading the cookie but the browser still attaches it to the forged request.
Quick check
(Repair a concatenated SQL query)
A route builds "SELECT * FROM orders WHERE id = " + id. Give the resulting SQL for id = 5 OR 1=1 and write the corrected parameterized call.
Solution
The text becomes SELECT * FROM orders WHERE id = 5 OR 1=1, whose condition holds for every row, so all orders are returned. A corrected call is await db.execute("SELECT * FROM orders WHERE id = ?", [id]). The driver sends id as a value, so the string 5 OR 1=1 is compared as a value (and converted or rejected as a number), not parsed as SQL. Validating that id is an integer before the query is a further sensible check.
Quick check
(An operator in a login filter)
A login handler runs User.findOne({ username: req.body.username, password: req.body.password }) and receives {"username":"alice","password":{"$ne":null}}. State the filter that is executed, why it succeeds without the password, and a fix.
Solution
The filter is { username: "alice", password: { $ne: null } }. The $ne operator matches any document whose password is not null, so alice's document matches without knowing her password. The fix is to reject non-string inputs (typeof username !== "string" || typeof password !== "string" gives a 400), look the user up by username only, and compare the submitted password with the stored salted hash using a password-hashing function's verify routine.