Security
Revision notes.
| Threat | What it is | Defence |
|---|---|---|
| XSS | attacker-injected script runs in your page | escape output, textContent not innerHTML, sanitize (DOMPurify), CSP |
| CSRF | forged request using the victim's cookies | CSRF tokens, SameSite cookies, check origin |
| CORS | browser blocks cross-origin reads by default | server sets Access-Control-Allow-*; don't disable checks blindly |
| CSP | Content-Security-Policy header restricting sources | default-src 'self'; blocks inline scripts/injections |
| Injection | untrusted data in queries/HTML | parameterize, validate, escape |
| Insecure storage | secrets/tokens in localStorage |
prefer httpOnly cookies for auth tokens |
// ❌ XSS — never do this with user input
el.innerHTML = userInput;
// ✅ safe
el.textContent = userInput;
el.append(document.createTextNode(userInput));
Cookies:
Set-Cookie: token=...; HttpOnly; Secure; SameSite=Strict; Path=/
HttpOnly→ JS can't read it (mitigates XSS token theft).Secure→ HTTPS only.SameSite→ CSRF mitigation.
JWT basics: a signed token header.payload.signature. The signature proves integrity; the payload is base64, not encrypted — never put secrets in it. Verify signature server-side; keep expiry short; store carefully (httpOnly cookie preferred over localStorage).
Secure coding: validate all input, never trust the client, use parameterized queries, keep dependencies patched (npm audit), avoid eval/new Function on untrusted input, apply least privilege, don't leak stack traces to users.
Interview Q&A#
Q1. What is XSS and three ways to prevent it? Where does CSP fit?
XSS is attacker-injected script running in your page's origin. Prevent it by escaping output / using textContent instead of innerHTML, sanitizing rich HTML (e.g. DOMPurify), and validating input. CSP is a defence-in-depth layer — a Content-Security-Policy header (default-src 'self') that blocks inline scripts and unauthorized sources, containing damage even if a hole slips through.
Q2. How does SameSite help against CSRF?
SameSite=Strict/Lax tells the browser not to send the cookie on cross-site requests, so a forged request from an attacker's page won't carry the victim's auth cookie — defeating the classic CSRF vector.
Q3. Why is it risky to store JWTs in localStorage?
localStorage is readable by any JavaScript on the page, so a single XSS flaw lets an attacker steal the token. An httpOnly cookie can't be read by JS, so it's the safer store (paired with SameSite/Secure).