Client-Side Web Security
Protect browser clients against code injection, request forgery, UI redress, cross-site leaks, and unsafe third-party scripts with layered, context-aware controls.
XSS Prevention (Context-Aware)
- HTML context: prefer
textContent. If HTML is required, sanitize with a vetted library (e.g., DOMPurify) and strict allow-lists.
- Attribute context: always quote attributes and encode values.
- JavaScript context: do not build JS from untrusted strings; avoid inline event handlers; use
addEventListener.
- URL context: validate protocol/domain and encode; block
javascript: and data URLs where inappropriate.
- Redirects/forwards: never use user input directly for destinations; use server-side mapping (ID to URL) or validate against trusted domain allow-lists.
- CSS context: allow-list values; never inject raw style text from users.
Example sanitization:
const clean = DOMPurify.sanitize(userHtml, {
ALLOWED_TAGS: ['b','i','p','a','ul','li'],
ALLOWED_ATTR: ['href','target','rel'],
ALLOW_DATA_ATTR: false
});
DOM-based XSS and Dangerous Sinks
- Prohibit
innerHTML, outerHTML, document.write with untrusted data.
- Prohibit
eval, new Function, string-based setTimeout/setInterval.
- Validate and encode data before assigning to
location or event handler properties.
- Use strict mode and explicit variable declarations to prevent global namespace pollution from DOM clobbering.
- Adopt Trusted Types and enforce strict CSP to prevent DOM sink exploitation.
Trusted Types + CSP:
Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; require-trusted-types-for 'script'
Content Security Policy (CSP)
- Prefer nonce-based or hash-based CSP over domain allow-lists.
- Start with Report-Only mode; collect violations; then enforce.
- Baseline to aim for:
default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests.
CSRF Defense
- Fix XSS first; then layer CSRF defenses.
- Use framework-native CSRF protections and synchronizer tokens on all state-changing requests.
- Cookie settings:
SameSite=Lax or Strict; sessions Secure and HttpOnly; use __Host- prefix when possible.
- Validate Origin/Referer; require custom headers for API mutations in SPA token models.
- Never use GET for state changes; validate tokens on POST/PUT/DELETE/PATCH only. Enforce HTTPS for all token transmission.
Clickjacking Defense
- Primary:
Content-Security-Policy: frame-ancestors 'none' or a specific allow-list.
- Fallback for legacy browsers:
X-Frame-Options: DENY or SAMEORIGIN.
- Consider UX confirmations for sensitive actions when framing is required.
Cross-Site Leaks (XS-Leaks) Controls
- Use
SameSite cookies appropriately; prefer Strict for sensitive actions.
- Adopt Fetch Metadata protections to block suspicious cross-site requests.
- Isolate browsing contexts: COOP/COEP and CORP where applicable.
- Disable caching and add user-unique tokens for sensitive responses to prevent cache probing.
Third-Party JavaScript
- Minimize and isolate: prefer sandboxed iframes with
sandbox and postMessage origin checks.
- Use Subresource Integrity (SRI) for external scripts and monitor for changes.
- Provide a first-party, sanitized data layer; deny direct DOM access from tags where possible.
- Govern via tag manager controls and vendor contracts; keep libraries updated.
SRI example:
<script src="https://cdn.vendor.com/app.js"
integrity="sha384-..." crossorigin="anonymous"></script>
HTML5, CORS, WebSockets, Storage
- postMessage: always specify exact target origin; verify
event.origin on receive.
- CORS: avoid
*; allow-list origins; validate preflights; do not rely on CORS for authorization.
- WebSockets: require
wss://, origin checks, auth, message size limits, and safe JSON parsing.
- Client storage: never store secrets in
localStorage/sessionStorage; prefer HttpOnly cookies; if unavoidable, isolate via Web Workers.
- Links: add
rel="noopener noreferrer" to external target=_blank links.
HTTP Security Headers
- HSTS: enforce HTTPS everywhere.
- X-Content-Type-Options:
nosniff.
- Referrer-Policy and Permissions-Policy: restrict sensitive signals and capabilities.
AJAX and Safe DOM APIs
- Avoid dynamic code execution; use function callbacks, not strings.
- Build JSON with
JSON.stringify; never via string concatenation.
- Prefer creating elements and setting
textContent/safe attributes over raw HTML insertion.
Implementation Checklist
Test Plan
- Automated checks for dangerous DOM/API patterns.
- E2E tests for CSRF and clickjacking; CSP report monitoring.
- Manual probes for XS-Leaks (frame count, timing, cache) and open redirect behavior.
1---2name: client-side-security3description: Apply when reviewing or writing browser-facing code that handles user input, renders HTML, sets cookies, or loads third-party scripts. Covers XSS, CSRF, CSP, clickjacking, XS-Leaks, and HTTP security headers.4---56# Client-Side Web Security78Protect browser clients against code injection, request forgery, UI redress, cross-site leaks, and unsafe third-party scripts with layered, context-aware controls.910## XSS Prevention (Context-Aware)1112- **HTML context**: prefer `textContent`. If HTML is required, sanitize with a vetted library (e.g., DOMPurify) and strict allow-lists.13- **Attribute context**: always quote attributes and encode values.14- **JavaScript context**: do not build JS from untrusted strings; avoid inline event handlers; use `addEventListener`.15- **URL context**: validate protocol/domain and encode; block `javascript:` and data URLs where inappropriate.16- **Redirects/forwards**: never use user input directly for destinations; use server-side mapping (ID to URL) or validate against trusted domain allow-lists.17- **CSS context**: allow-list values; never inject raw style text from users.1819Example sanitization:2021```javascript22const clean = DOMPurify.sanitize(userHtml, {23 ALLOWED_TAGS: ['b','i','p','a','ul','li'],24 ALLOWED_ATTR: ['href','target','rel'],25 ALLOW_DATA_ATTR: false26});27```2829## DOM-based XSS and Dangerous Sinks3031- Prohibit `innerHTML`, `outerHTML`, `document.write` with untrusted data.32- Prohibit `eval`, `new Function`, string-based `setTimeout`/`setInterval`.33- Validate and encode data before assigning to `location` or event handler properties.34- Use strict mode and explicit variable declarations to prevent global namespace pollution from DOM clobbering.35- Adopt Trusted Types and enforce strict CSP to prevent DOM sink exploitation.3637Trusted Types + CSP:3839```http40Content-Security-Policy: script-src 'self' 'nonce-{random}'; object-src 'none'; base-uri 'self'; require-trusted-types-for 'script'41```4243## Content Security Policy (CSP)4445- Prefer nonce-based or hash-based CSP over domain allow-lists.46- Start with Report-Only mode; collect violations; then enforce.47- Baseline to aim for: `default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; form-action 'self'; object-src 'none'; base-uri 'none'; upgrade-insecure-requests`.4849## CSRF Defense5051- Fix XSS first; then layer CSRF defenses.52- Use framework-native CSRF protections and synchronizer tokens on all state-changing requests.53- Cookie settings: `SameSite=Lax` or `Strict`; sessions `Secure` and `HttpOnly`; use `__Host-` prefix when possible.54- Validate Origin/Referer; require custom headers for API mutations in SPA token models.55- Never use GET for state changes; validate tokens on POST/PUT/DELETE/PATCH only. Enforce HTTPS for all token transmission.5657## Clickjacking Defense5859- Primary: `Content-Security-Policy: frame-ancestors 'none'` or a specific allow-list.60- Fallback for legacy browsers: `X-Frame-Options: DENY` or `SAMEORIGIN`.61- Consider UX confirmations for sensitive actions when framing is required.6263## Cross-Site Leaks (XS-Leaks) Controls6465- Use `SameSite` cookies appropriately; prefer `Strict` for sensitive actions.66- Adopt Fetch Metadata protections to block suspicious cross-site requests.67- Isolate browsing contexts: COOP/COEP and CORP where applicable.68- Disable caching and add user-unique tokens for sensitive responses to prevent cache probing.6970## Third-Party JavaScript7172- Minimize and isolate: prefer sandboxed iframes with `sandbox` and postMessage origin checks.73- Use Subresource Integrity (SRI) for external scripts and monitor for changes.74- Provide a first-party, sanitized data layer; deny direct DOM access from tags where possible.75- Govern via tag manager controls and vendor contracts; keep libraries updated.7677SRI example:7879```html80<script src="https://cdn.vendor.com/app.js"81 integrity="sha384-..." crossorigin="anonymous"></script>82```8384## HTML5, CORS, WebSockets, Storage8586- **postMessage**: always specify exact target origin; verify `event.origin` on receive.87- **CORS**: avoid `*`; allow-list origins; validate preflights; do not rely on CORS for authorization.88- **WebSockets**: require `wss://`, origin checks, auth, message size limits, and safe JSON parsing.89- **Client storage**: never store secrets in `localStorage`/`sessionStorage`; prefer HttpOnly cookies; if unavoidable, isolate via Web Workers.90- **Links**: add `rel="noopener noreferrer"` to external `target=_blank` links.9192## HTTP Security Headers9394- **HSTS**: enforce HTTPS everywhere.95- **X-Content-Type-Options**: `nosniff`.96- **Referrer-Policy** and **Permissions-Policy**: restrict sensitive signals and capabilities.9798## AJAX and Safe DOM APIs99100- Avoid dynamic code execution; use function callbacks, not strings.101- Build JSON with `JSON.stringify`; never via string concatenation.102- Prefer creating elements and setting `textContent`/safe attributes over raw HTML insertion.103104## Implementation Checklist105106- [ ] Contextual encoding/sanitization for every sink; no dangerous APIs without guards107- [ ] Strict CSP with nonces and Trusted Types; violations monitored108- [ ] CSRF tokens on all state-changing requests; secure cookie attributes109- [ ] Frame protections set; XS-Leak mitigations enabled (Fetch Metadata, COOP/COEP/CORP)110- [ ] Third-party JS isolated with SRI and sandbox; vetted data layer only111- [ ] HTML5/CORS/WebSocket usage hardened; no secrets in web storage112- [ ] Security headers enabled and validated113114## Test Plan115116- Automated checks for dangerous DOM/API patterns.117- E2E tests for CSRF and clickjacking; CSP report monitoring.118- Manual probes for XS-Leaks (frame count, timing, cache) and open redirect behavior.