Security for Engineers/Web & Browser Security

XSS & Content Security Policy

Reflected, stored, DOM XSS; output encoding; CSP directives; and React/framework escaping defaults.

3/5Overview: 30m

XSS types

TypeMechanism
ReflectedMalicious script in URL echoed in response
StoredScript saved in DB, served to other users
DOMClient JS writes untrusted data to DOM

Attack goal: run attacker's JS in victim's browser → steal cookies/tokens, act as user.

Defense layers

  1. Output encoding — escape HTML/JS context (<&lt;)
  2. CSP — whitelist script sources
  3. HttpOnly cookies — JS can't read session cookie
  4. Framework defaults — React escapes JSX; dangerous with dangerouslySetInnerHTML

Content Security Policy (CSP)

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'

Blocks inline script unless 'unsafe-inline' (avoid). Report-only mode for rollout.

Staff tip: CSP is defense-in-depth, not substitute for encoding.

When sanitization is needed

Rich text (Markdown → HTML) — use allowlist sanitizer (DOMPurify). Never regex HTML.

Fullstack interview

"User comments with HTML" — stored XSS risk. Answer: sanitize server-side, encode on render, CSP, separate cookie domain for API.

Backend-only engineers

Still need XSS literacy — you render JSON consumed by frontend; error messages and redirects can reflect input.

Cross-reference: Auth for HttpOnly session cookies; frontend framework depth is out of scope for this roadmap.

Further Reading

Hands-On Tasks (Optional)

Security design drills — threat modeling, auth flows, and incident playbooks. Assumes Networking (TLS) fundamentals.

  • Remediate stored XSS

    User bio rendered as raw HTML in profile page. List three layers: encode on output, sanitize if HTML needed, CSP header value.

    15m