@capagents/forgeqe 3.1.1 → 3.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOW_TO_USE.md +5152 -1869
- package/README.md +155 -434
- package/THIRD_PARTY_NOTICES.md +210 -1
- package/dist/docs-site/CREDITS.md +6 -0
- package/dist/docs-site/architecture-map/index.html +1 -1
- package/dist/docs-site/docs/app-theme.css +126 -13
- package/dist/docs-site/docs/architecture/index.html +56 -530
- package/dist/docs-site/docs/architecture-reference/index.html +1781 -0
- package/dist/docs-site/docs/area-api/index.html +491 -0
- package/dist/docs-site/docs/area-automated-tests/index.html +1777 -0
- package/dist/docs-site/docs/area-browser/index.html +472 -0
- package/dist/docs-site/docs/area-data/index.html +595 -0
- package/dist/docs-site/docs/area-desktop/index.html +802 -0
- package/dist/docs-site/docs/area-mobile/index.html +683 -0
- package/dist/docs-site/docs/area-operations/index.html +1243 -0
- package/dist/docs-site/docs/area-pull-requests/index.html +290 -0
- package/dist/docs-site/docs/area-quality/index.html +427 -0
- package/dist/docs-site/docs/area-release/index.html +435 -0
- package/dist/docs-site/docs/area-setup/index.html +1595 -0
- package/dist/docs-site/docs/area-systems/index.html +191 -0
- package/dist/docs-site/docs/area-test-cases/index.html +927 -0
- package/dist/docs-site/docs/containers/index.html +168 -189
- package/dist/docs-site/docs/cost-architecture/index.html +110 -113
- package/dist/docs-site/docs/custom-agents-first-run/index.html +121 -67
- package/dist/docs-site/docs/desktop/index.html +363 -373
- package/dist/docs-site/docs/desktop-ci/index.html +39 -36
- package/dist/docs-site/docs/docs-tabs.js +56 -0
- package/dist/docs-site/docs/evidence/index.html +297 -300
- package/dist/docs-site/docs/feature-test-prompts/index.html +79 -73
- package/dist/docs-site/docs/get-started/index.html +791 -0
- package/dist/docs-site/docs/graphify/index.html +45 -48
- package/dist/docs-site/docs/guardrails/index.html +35 -23
- package/dist/docs-site/docs/index.html +18 -6729
- package/dist/docs-site/docs/mobile/index.html +223 -210
- package/dist/docs-site/docs/model-routing/index.html +84 -65
- package/dist/docs-site/docs/overview/index.html +192 -0
- package/dist/docs-site/docs/product-graph/index.html +60 -62
- package/dist/docs-site/docs/product-knowledge/index.html +24 -17
- package/dist/docs-site/docs/product-views/index.html +57 -60
- package/dist/docs-site/docs/reference/index.html +409 -0
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/docs-site/docs/using/index.html +798 -0
- package/dist/docs-site/docs/web-app/index.html +168 -111
- package/dist/docs-site/security/index.html +930 -0
- package/dist/docs-site/security/security-theme.css +161 -0
- package/dist/docs-site/security/security.js +1465 -0
- package/dist/docs-site/vendor/react-18.3.1.production.min.js +31 -0
- package/dist/docs-site/vendor/react-dom-18.3.1.production.min.js +267 -0
- package/dist/docs-site/vendor/reactflow-11.11.4.umd.js +10 -0
- package/dist/forgeqe.js +1903 -1896
- package/dist/web/THIRD_PARTY_NOTICES.md +0 -136
- package/dist/web/assets/Agent-3pV8Rwap.js +8 -0
- package/dist/web/assets/AgentWork-DAnmH0My.js +2 -0
- package/dist/web/assets/ApiTests-DW4MRFzG.js +10 -0
- package/dist/web/assets/Browse-Bd0ZZfc2.js +1 -0
- package/dist/web/assets/Chat-DnBUm_97.js +3 -0
- package/dist/web/assets/CommandPalette-B1O9aDTk.js +1 -0
- package/dist/web/assets/Compare-1v7_ca7z.js +1 -0
- package/dist/web/assets/Cost-CWrc4McH.js +1 -0
- package/dist/web/assets/Data-rWSiG4Cq.js +6 -0
- package/dist/web/assets/Desktop-3x6EQqos.js +1 -0
- package/dist/web/assets/DesktopReview-cSA10Rm3.js +1 -0
- package/dist/web/assets/Evidence-CKy3o7cw.js +1 -0
- package/dist/web/assets/Explore-CMAxWE_8.js +2 -0
- package/dist/web/assets/Features-haQchkhA.js +1 -0
- package/dist/web/assets/Flags-BaQjYi_t.js +2 -0
- package/dist/web/assets/Flaky-DUuC0qTn.js +1 -0
- package/dist/web/assets/Impact-CP0H8ygo.js +3 -0
- package/dist/web/assets/Jobs-cYxoYd3i.js +5 -0
- package/dist/web/assets/KindPage-DWW8gN5_.js +6 -0
- package/dist/web/assets/Migration-Bsm7WU1d.js +2 -0
- package/dist/web/assets/PageAgent-c95zT2PJ.js +1 -0
- package/dist/web/assets/Product-BQSiR28a.js +7 -0
- package/dist/web/assets/Production-CAv0Vtoy.js +1 -0
- package/dist/web/assets/Quality-aQPaPYQc.js +1 -0
- package/dist/web/assets/Readiness-CkknP87n.js +1 -0
- package/dist/web/assets/Record-09IsC9U-.js +1 -0
- package/dist/web/assets/Regression-BL4MfN47.js +5 -0
- package/dist/web/assets/RelationGraph-Dg4fqt7l.js +1 -0
- package/dist/web/assets/Reports-CMV1l-iS.js +2 -0
- package/dist/web/assets/Response-DTBFBeKB.js +9 -0
- package/dist/web/assets/Responsive-DBRQ9FUO.js +3 -0
- package/dist/web/assets/RunDiff-CMDrnsA3.js +1 -0
- package/dist/web/assets/Runs-Dkeu6_vZ.js +2 -0
- package/dist/web/assets/Settings-KjKm8h-_.js +21 -0
- package/dist/web/assets/Steps-HYHK9psI.js +2 -0
- package/dist/web/assets/TestCases-Cv6-OSv0.js +1 -0
- package/dist/web/assets/TestData-DbEfNlUE.js +2 -0
- package/dist/web/assets/TestDebt-DzHQIU4X.js +1 -0
- package/dist/web/assets/TestManagement-BgRTGHMT.js +1 -0
- package/dist/web/assets/Tosca-DZpHAtnH.js +3 -0
- package/dist/web/assets/WhatsNew-jp0c4WSV.js +1 -0
- package/dist/web/assets/agents-C0Jg2pN8.js +1 -0
- package/dist/web/assets/coverage-BB9BLjGz.js +5 -0
- package/dist/web/assets/dataParts-DEPK4eQE.js +3 -0
- package/dist/web/assets/diff-CcNwLCX6.js +2 -0
- package/dist/web/assets/families-gkpkloLT.js +1 -0
- package/dist/web/assets/filters-C7phIFfd.js +1 -0
- package/dist/web/assets/fold-i73P-EDV.js +1 -0
- package/dist/web/assets/head-BtTqyLlj.js +1 -0
- package/dist/web/assets/highlight-DZI39CzZ.js +4 -0
- package/dist/web/assets/index-ClFOh63x.css +2 -0
- package/dist/web/assets/index-YGWJEkAT.js +64 -0
- package/dist/web/assets/input-C2vQ9O3a.js +1 -0
- package/dist/web/assets/jsx-runtime-LKYXHABd.js +1 -0
- package/dist/web/assets/logos-BmbNTDu2.js +1 -0
- package/dist/web/assets/palette-XFlqvgZl.js +1 -0
- package/dist/web/assets/paletteCommands-DsbD2ASU.js +1 -0
- package/dist/web/assets/parts-DEVx2Sea.js +1 -0
- package/dist/web/assets/productParts-Bi-XjszL.js +1 -0
- package/dist/web/assets/qualityParts-Dbu01g7G.js +1 -0
- package/dist/web/assets/recordTest--Wr40QdN.js +1 -0
- package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/web/assets/route-Dg53WdFu.js +1 -0
- package/dist/web/index.html +11 -6
- package/docs/ARCHITECTURE.md +50 -563
- package/docs/ARCHITECTURE_REFERENCE.md +1484 -0
- package/docs/BASAL.md +1 -1
- package/docs/CONTAINERS.md +87 -87
- package/docs/CUSTOM_AGENTS_FIRST_RUN.md +125 -43
- package/docs/DESKTOP-CI.md +18 -3
- package/docs/DESKTOP.md +306 -286
- package/docs/EVIDENCE.md +1 -1
- package/docs/MOBILE.md +107 -75
- package/docs/MODEL_ROUTING.md +48 -15
- package/docs/PRODUCT_KNOWLEDGE.md +2 -0
- package/docs/WEB_APP.md +143 -75
- package/docs/feature-test-prompts.md +29 -16
- package/docs/user-guide.html +5402 -2269
- package/forgeqe.example.yaml +3 -3
- package/guardrails/README.md +22 -2
- package/knowledge/README.md +15 -2
- package/package.json +1 -1
- package/prompts/brain.md +1 -0
- package/prompts/page-differs.md +1 -1
- package/prompts/requests-rule.md +1 -1
- package/prompts/test-reviewer.md +1 -1
- package/prompts/test-rules.md +3 -4
- package/py/forgeqe_engine/recordsession.py +100 -24
- package/skills/web-guidance/LICENSE +202 -0
- package/skills/web-guidance/SKILL.md +76 -0
- package/skills/web-guidance/UPSTREAM +67 -0
- package/skills/web-guidance/references/accessibility/accessibility.md +585 -0
- package/skills/web-guidance/references/accessibility/accessible-error-announcement.md +302 -0
- package/skills/web-guidance/references/accessibility/accessible-generated-content.md +41 -0
- package/skills/web-guidance/references/accessibility/respect-os-text-scale.md +127 -0
- package/skills/web-guidance/references/css/responsive-design.md +16 -0
- package/skills/web-guidance/references/forms/autofill-address-form.md +86 -0
- package/skills/web-guidance/references/forms/autofill-payment-form.md +142 -0
- package/skills/web-guidance/references/forms/autofill-sign-in-form.md +145 -0
- package/skills/web-guidance/references/forms/autofill-sign-up-form.md +155 -0
- package/skills/web-guidance/references/forms/forms.md +415 -0
- package/skills/web-guidance/references/forms/ime-safe-enter-submit.md +115 -0
- package/skills/web-guidance/references/forms/required-field-feedback.md +317 -0
- package/skills/web-guidance/references/forms/select-menu-interaction.md +310 -0
- package/skills/web-guidance/references/forms/slider.md +184 -0
- package/skills/web-guidance/references/forms/sms-otp-form.md +208 -0
- package/skills/web-guidance/references/forms/switch.md +60 -0
- package/skills/web-guidance/references/forms/validate-input-after-interaction.md +406 -0
- package/skills/web-guidance/references/performance/break-up-long-tasks.md +64 -0
- package/skills/web-guidance/references/performance/identify-heavy-scripts.md +69 -0
- package/skills/web-guidance/references/performance/identify-inp-causes.md +105 -0
- package/skills/web-guidance/references/performance/interaction-paint-timing.md +200 -0
- package/skills/web-guidance/references/performance/optimize-image-priority.md +73 -0
- package/skills/web-guidance/references/performance/performance.md +384 -0
- package/skills/web-guidance/references/privacy/privacy.md +247 -0
- package/skills/web-guidance/references/security/passkey-authentication.md +218 -0
- package/skills/web-guidance/references/security/passkey-management.md +310 -0
- package/skills/web-guidance/references/security/passkey-reauthentication.md +142 -0
- package/skills/web-guidance/references/security/passkey-registration.md +186 -0
- package/skills/web-guidance/references/security/passkeys.md +39 -0
- package/skills/web-guidance/references/security/sanitize-untrusted-html.md +105 -0
- package/skills/web-guidance/references/security/secure-external-subresources.md +202 -0
- package/skills/web-guidance/references/security/security.md +390 -0
- package/skills/web-guidance/references/security/trusted-types.md +141 -0
- package/skills/web-guidance/references/security/validate-origins.md +197 -0
- package/skills/web-guidance/references/security/verify-email-ownership.md +235 -0
- package/skills/web-guidance/references/ui-atoms/position-aware-tooltips.md +173 -0
- package/skills/web-guidance/references/ui-atoms/responsive-table.md +122 -0
- package/skills/web-guidance/references/ui-atoms/viewport-aware-dropdowns.md +178 -0
- package/skills/web-guidance/references/ui-behaviors/drag-and-drop.md +108 -0
- package/skills/web-guidance/references/ui-behaviors/light-dismiss-a-dialog.md +89 -0
- package/skills/web-guidance/references/ui-behaviors/motion.md +97 -0
- package/skills/web-guidance/references/ui-behaviors/platform-controls-dismiss-dialog.md +40 -0
- package/skills/web-guidance/references/ui-behaviors/prevent-page-scroll-under-modal-dialog.md +59 -0
- package/skills/web-guidance/references/ui-behaviors/search-hidden-content.md +141 -0
- package/skills/web-guidance/references/ui-behaviors/sortable-table.md +140 -0
- package/skills/web-guidance/references/ui-components/accordion.md +343 -0
- package/skills/web-guidance/references/ui-components/breadcrumbs.md +168 -0
- package/skills/web-guidance/references/ui-components/carousel.md +206 -0
- package/skills/web-guidance/references/ui-components/checkbox.md +144 -0
- package/skills/web-guidance/references/ui-components/dialog.md +218 -0
- package/skills/web-guidance/references/ui-components/hovercard.md +391 -0
- package/skills/web-guidance/references/ui-components/menu.md +415 -0
- package/skills/web-guidance/references/ui-components/navbar.md +281 -0
- package/skills/web-guidance/references/ui-components/navigation-drawer.md +429 -0
- package/skills/web-guidance/references/ui-components/persistent-toast-notifications.md +185 -0
- package/skills/web-guidance/references/ui-components/progress.md +181 -0
- package/skills/web-guidance/references/ui-components/spinner.md +179 -0
- package/skills/web-guidance/references/ui-components/tabs.md +371 -0
- package/skills/web-guidance/references/ui-components/toolbar.md +277 -0
- package/skills/web-guidance/references/user-experience/form-factor-adaptation.md +120 -0
- package/skills/web-guidance/references/user-experience/natural-interactions.md +155 -0
- package/skills/web-guidance/references/visual-design/color.md +43 -0
- package/skills/web-guidance/references/visual-design/dark-mode.md +350 -0
- package/dist/web/assets/AgentWork-DwAI0_Of.js +0 -2
- package/dist/web/assets/ApiTests-C0vFSHmM.js +0 -10
- package/dist/web/assets/Browse-5jfdtRc5.js +0 -2
- package/dist/web/assets/Chat-B3uhI94O.js +0 -3
- package/dist/web/assets/CommandPalette-D2J4nf5y.js +0 -1
- package/dist/web/assets/Compare-CN75w1p9.js +0 -1
- package/dist/web/assets/Cost-QoxyjR95.js +0 -1
- package/dist/web/assets/Data-BAvkcBVt.js +0 -6
- package/dist/web/assets/Desktop-BXdOIalN.js +0 -1
- package/dist/web/assets/DesktopReview-Bl2SrPP0.js +0 -1
- package/dist/web/assets/Evidence-BJ_I52CD.js +0 -1
- package/dist/web/assets/Explore-D9AuyTip.js +0 -2
- package/dist/web/assets/Features-CusGMDR9.js +0 -1
- package/dist/web/assets/Flags-CycGFuUP.js +0 -2
- package/dist/web/assets/Flaky-BcSzJogN.js +0 -1
- package/dist/web/assets/Impact-CJHnyZ21.js +0 -3
- package/dist/web/assets/Jobs-4xcFzEFo.js +0 -5
- package/dist/web/assets/KindPage-BielEIej.js +0 -6
- package/dist/web/assets/Migration-NwanKpJg.js +0 -2
- package/dist/web/assets/PageAgent-CNw4NXva.js +0 -1
- package/dist/web/assets/Product-DS3LJZ4P.js +0 -7
- package/dist/web/assets/Production-D3zsyNIS.js +0 -1
- package/dist/web/assets/Quality-Ctj2YpC4.js +0 -1
- package/dist/web/assets/Readiness-DGcRr_co.js +0 -1
- package/dist/web/assets/Record-Cc-wGe_Y.js +0 -1
- package/dist/web/assets/Regression-DcsbrRa1.js +0 -5
- package/dist/web/assets/Reports-BkCn0-Sf.js +0 -2
- package/dist/web/assets/Response-BP0UwQcW.js +0 -9
- package/dist/web/assets/Responsive-C8U7dumd.js +0 -3
- package/dist/web/assets/RunDiff-BhABuhF_.js +0 -1
- package/dist/web/assets/Runs-OwdWEYBv.js +0 -2
- package/dist/web/assets/Steps-BvzbQyoD.js +0 -2
- package/dist/web/assets/TestCases-CLq_6JA5.js +0 -1
- package/dist/web/assets/TestData-B0oKAhp6.js +0 -2
- package/dist/web/assets/TestDebt-8NLQ5YV_.js +0 -1
- package/dist/web/assets/TestManagement-2LYQ7vsN.js +0 -1
- package/dist/web/assets/Tosca-DfvMpPTG.js +0 -3
- package/dist/web/assets/WhatsNew-BGFNGwqN.js +0 -1
- package/dist/web/assets/families-DYlN5v0i.js +0 -1
- package/dist/web/assets/filters-faaSnoIq.js +0 -1
- package/dist/web/assets/fold-CUjwWAK3.js +0 -1
- package/dist/web/assets/frame-BLPdAXUq.js +0 -13
- package/dist/web/assets/head-CsTxBsO0.js +0 -1
- package/dist/web/assets/index-CxiCvGZq.js +0 -78
- package/dist/web/assets/index-dOIsrzhD.css +0 -2
- package/dist/web/assets/line-icons-CwZWt93L.js +0 -1
- package/dist/web/assets/logos-dGuc1jIM.js +0 -1
- package/dist/web/assets/markdown-BI3F-SJ1.js +0 -10
- package/dist/web/assets/paletteCommands-QJiCuUEr.js +0 -1
- package/dist/web/assets/parts-CdF1f7yS.js +0 -1
- package/dist/web/assets/productParts-hNLD9fN0.js +0 -1
- package/dist/web/assets/qualityParts-CT25lBWU.js +0 -1
- package/dist/web/assets/recordTest-P792aBUt.js +0 -1
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
# Web Security
|
|
2
|
+
|
|
3
|
+
Guidelines for implementing preventative security measures on the web safely and incrementally.
|
|
4
|
+
|
|
5
|
+
**NOTE**: This skill covers standard web platform defenses, focusing mostly on the browser. Applications still require comprehensive server-side security, authorization models, and input validation.
|
|
6
|
+
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
- When to apply this skill
|
|
10
|
+
- Phase 1: Quick Wins & Obvious Anti-Patterns
|
|
11
|
+
- 1.1 Secure Contexts
|
|
12
|
+
- 1.2 Avoid Dangerous DOM Sinks
|
|
13
|
+
- 1.3 Secure Cookies
|
|
14
|
+
- 1.4 Clickjacking Protection (Frame-Ancestors & X-Frame-Options)
|
|
15
|
+
- 1.5 Secure Window Messaging (postMessage)
|
|
16
|
+
- Phase 2: Discovery & Data Collection (Prerequisites)
|
|
17
|
+
- 2.1 Inspect the Application
|
|
18
|
+
- 2.2 Deploy Report-Only Policies
|
|
19
|
+
- 2.3 Data Hygiene for Reports
|
|
20
|
+
- 2.4 Automated Discovery via Browser APIs and DevTools
|
|
21
|
+
- Phase 3: Interpreting Results & Enforcement
|
|
22
|
+
- Core enforcement
|
|
23
|
+
- 3.1 Analyzing CSP Reports
|
|
24
|
+
- 3.2 Enforcing Content Security Policy (CSP)
|
|
25
|
+
- 3.3 Trusted Types Enforcement
|
|
26
|
+
- 3.4 Cross-Origin Opener Policy (COOP)
|
|
27
|
+
- 3.5 Cross-Origin Resource Policy (CORP)
|
|
28
|
+
- 3.6 Cross-Origin Isolation
|
|
29
|
+
- 3.7 Fetch Metadata (Resource Isolation)
|
|
30
|
+
- Companion policies (deploy in parallel)
|
|
31
|
+
- HTTP Strict Transport Security (HSTS)
|
|
32
|
+
- X-Content-Type-Options
|
|
33
|
+
- Referrer Policy
|
|
34
|
+
- Permissions Policy
|
|
35
|
+
- Subresource Integrity (SRI)
|
|
36
|
+
- Cross-Origin Resource Sharing (CORS)
|
|
37
|
+
- Clear-Site-Data (Logout)
|
|
38
|
+
|
|
39
|
+
## When to apply this skill
|
|
40
|
+
|
|
41
|
+
The right starting point depends on the application and whether you can update the codebase directly:
|
|
42
|
+
|
|
43
|
+
- **Auditing and hardening a codebase directly**: Apply Phase 1 code hygiene, wire up Phase 2 reporting (`Reporting-Endpoints` and `report-to`), and enforce Phase 3 headers (`Content-Security-Policy` with nonces/hashes, `'strict-dynamic'`, `'report-sample'`, `object-src 'none'`, `base-uri 'none'`, `frame-ancestors 'none'` (or `'self'`), and `require-trusted-types-for 'script'`, plus COOP, CORP, Fetch Metadata, HSTS, `X-Content-Type-Options`, `Referrer-Policy`, and `Permissions-Policy`) directly by updating `<script>` tags, cookies, and server middleware in the same pass.
|
|
44
|
+
- **Staged rollout on a large production site with unknown third-party dependencies**: Start with Phase 1 quick wins and deploy Phase 2 report-only headers alongside enforced companion policies while collecting violation telemetry, then promote the report-only policies to Phase 3 enforcement.
|
|
45
|
+
- **Greenfield app or SaaS template / framework defaults**: Ship Phase 1 hygiene and Phase 3 enforced policies by default, with Phase 2 reporting configured so regressions are captured immediately.
|
|
46
|
+
|
|
47
|
+
**Focusing on Leverage**: While Phase 1 and 2 establish baseline hygiene and violation visibility, Phase 3 core enforcement represents the highest-leverage security work. Specifically, Injection/XSS mitigation through enforced CSP (§3.2) and Trusted Types (§3.3) addresses the largest practical threat, while companion policies and isolation defenses provide important defense-in-depth.
|
|
48
|
+
|
|
49
|
+
## Phase 1: Quick Wins & Obvious Anti-Patterns
|
|
50
|
+
|
|
51
|
+
Before attempting to deploy global security policies, focus on code-level hygiene and immediate fixes that do not risk breaking the application.
|
|
52
|
+
|
|
53
|
+
### 1.1 Secure Contexts
|
|
54
|
+
- **DO**: Deliver resources over HTTPS to protect against both passive and active network attackers.
|
|
55
|
+
- **DO**: Serve a header like `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` to force HTTPS whenever possible.
|
|
56
|
+
- **TIP**: In production rollout, start with a short `max-age` (e.g., 300 seconds) and incrementally increase to 1 year. A misconfigured HSTS with a long max-age can render the site permanently inaccessible until the cache expires in every browser that saw it.
|
|
57
|
+
|
|
58
|
+
### 1.2 Avoid Dangerous DOM Sinks
|
|
59
|
+
- **DO**: Prefer `textContent` or `innerText` over `innerHTML` when setting text content.
|
|
60
|
+
- **DO**: Use `setHTML()` (part of the Sanitizer API; see `sanitize-untrusted-html` (references/security/sanitize-untrusted-html.md)) when available to safely insert untrusted HTML without going through `innerHTML`.
|
|
61
|
+
- **DO NOT**: Use `innerHTML` or `setHTMLUnsafe` with untrusted or unsanitized input.
|
|
62
|
+
- **DO**: Use DOMParser or create elements programmatically (`document.createElement`) instead of concatenating HTML strings.
|
|
63
|
+
|
|
64
|
+
**Dangerous sinks to grep for**: `innerHTML`, `outerHTML`, `document.write`, `eval`, `setTimeout` with a string argument, `script.src`.
|
|
65
|
+
|
|
66
|
+
**Code Pattern:**
|
|
67
|
+
```javascript
|
|
68
|
+
// Unsafe
|
|
69
|
+
element.innerHTML = `Hello, ${untrustedName}!`;
|
|
70
|
+
|
|
71
|
+
// Safe
|
|
72
|
+
element.textContent = `Hello, ${untrustedName}!`;
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Trusted Types can enforce this pattern at runtime by blocking string assignments to dangerous sinks. Deploying it is a CSP enforcement step with real breakage risk — see §3.3.
|
|
76
|
+
|
|
77
|
+
### 1.3 Secure Cookies
|
|
78
|
+
Ensure session and application cookies are configured securely by default, whether set via `Set-Cookie` headers or framework session configuration (such as Astro or Express session middleware).
|
|
79
|
+
- **DO**: Name first-party session cookies with the `__Host-` prefix (`name: '__Host-session'`) when used by a single domain. This requires `Secure` (`secure: true`), `Path=/` (`path: '/'`), and omitting the `Domain` attribute, protecting against same-site and network attackers.
|
|
80
|
+
- **DO**: Prefer naming cookies with the `__Secure-` prefix when `__Host-` isn't appropriate. This requires the `Secure` attribute, and protects against network attackers.
|
|
81
|
+
- **DO**: Set `HttpOnly` (`httpOnly: true`) on session and authentication cookies so they cannot be read by injected client-side scripts, and explicitly set `SameSite=Lax` (`sameSite: 'lax'`) for standard first-party cookies.
|
|
82
|
+
- **DO**: If your application will be embedded as an iframe in third-party contexts, use `SameSite=None; Secure; Partitioned`.
|
|
83
|
+
- **DO NOT**: Rely on unpartitioned `SameSite=None` — these are being systematically blocked for tracking prevention.
|
|
84
|
+
|
|
85
|
+
```http
|
|
86
|
+
Set-Cookie: __Host-session_id=value; SameSite=Lax; HttpOnly; Secure; Path=/
|
|
87
|
+
Set-Cookie: third_party_var=value; SameSite=None; Secure; Partitioned
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 1.4 Clickjacking Protection (Frame-Ancestors & X-Frame-Options)
|
|
91
|
+
Clickjacking protection is easy to deploy, carries extremely low risk of breaking legitimate functionality, and provides immediate defense against malicious UI redressing. Choose the policy tier that matches your framing requirements:
|
|
92
|
+
- **DO (Default — no framing needed)**: Set `Content-Security-Policy: frame-ancestors 'none'` alongside `X-Frame-Options: DENY` when your pages never need to be embedded in an iframe.
|
|
93
|
+
- **DO (Same-origin framing only)**: Set `Content-Security-Policy: frame-ancestors 'self'` alongside `X-Frame-Options: SAMEORIGIN` when your application embeds its own pages in same-origin iframes.
|
|
94
|
+
- **DO (Specific cross-origin framing required)**: Set `Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com` and **omit `X-Frame-Options`** (`X-Frame-Options` cannot express cross-origin allowlists—`ALLOW-FROM` is obsolete and unsupported—and `DENY` or `SAMEORIGIN` would block the embed in any client that evaluates `X-Frame-Options` without `frame-ancestors`).
|
|
95
|
+
- **DO (Arbitrary framing explicitly required)**: Only omit both `frame-ancestors` and `X-Frame-Options` on routes designed as publicly embeddable widgets.
|
|
96
|
+
|
|
97
|
+
```http
|
|
98
|
+
# Default (never framed):
|
|
99
|
+
Content-Security-Policy: frame-ancestors 'none';
|
|
100
|
+
X-Frame-Options: DENY
|
|
101
|
+
|
|
102
|
+
# Same-origin framing allowed:
|
|
103
|
+
Content-Security-Policy: frame-ancestors 'self';
|
|
104
|
+
X-Frame-Options: SAMEORIGIN
|
|
105
|
+
|
|
106
|
+
# Specific cross-origin framing allowed (omit X-Frame-Options):
|
|
107
|
+
Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com;
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### 1.5 Secure Window Messaging (postMessage)
|
|
111
|
+
If your application communicates with other origins using `window.postMessage`, you must strictly validate the sender and receiver.
|
|
112
|
+
- **DO**: Always validate the `event.origin` of incoming messages on the receiver side using strict equality against a list of trusted origins (or use the `Origin` API when comparing against URLs/elements, checking schemeful same-site relationships, or distinguishing opaque sandboxed iframe origins; see `validate-origins` (references/security/validate-origins.md)). Do **not** trust wildcards (`*`), substring checks, or unverified payloads.
|
|
113
|
+
- **DO**: Always specify a target origin (rather than the wildcard `*`) when calling `postMessage` to send sensitive data, ensuring only the intended origin can receive it.
|
|
114
|
+
- **DO**: Validate and sanitize the properties of incoming message payloads before performing operations or writing them to DOM sinks. Manual JSON serialization is unnecessary as `postMessage` handles object cloning internally.
|
|
115
|
+
|
|
116
|
+
```javascript
|
|
117
|
+
// Receiver (Safe - traditional string check)
|
|
118
|
+
window.addEventListener('message', (event) => {
|
|
119
|
+
if (event.origin !== 'https://trusted-origin.com') return;
|
|
120
|
+
const data = event.data;
|
|
121
|
+
if (data && data.action === 'update') {
|
|
122
|
+
// Process data safely
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// Sender (Safe)
|
|
127
|
+
targetWindow.postMessage({ action: 'update' }, 'https://trusted-origin.com');
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Phase 2: Discovery & Data Collection (Prerequisites)
|
|
131
|
+
|
|
132
|
+
Do not blindly apply strict policies to an existing application. You must first understand the application's constraints by collecting data.
|
|
133
|
+
|
|
134
|
+
### 2.1 Inspect the Application
|
|
135
|
+
Before turning anything on, gather facts:
|
|
136
|
+
- **Grep for existing security headers** in server config, middleware, CDN/edge config, and meta tags: `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Permissions-Policy`, `Cross-Origin-*`, `Access-Control-*`, `Timing-Allow-Origin`, `Reporting-Endpoints`.
|
|
137
|
+
- **Enumerate inline scripts and styles** in server-rendered templates and static HTML — these will need nonces, hashes, or refactoring.
|
|
138
|
+
- **List third-party script origins** loaded by the app (analytics, ads, tag managers, CDNs). These dictate what `script-src` must allow or whether `'strict-dynamic'` is viable.
|
|
139
|
+
- **Identify popup-dependent flows**: OAuth, payment gateways, SSO. These constrain COOP choices.
|
|
140
|
+
- **Identify cross-origin embeds and embedders**: iframes the app loads, and sites that embed the app. These constrain COEP/CORP/`frame-ancestors`.
|
|
141
|
+
- **Enumerate required browser features**: List any features (camera, geolocation, microphone, fullscreen) used by the app or embedded third-party widgets to inform `Permissions-Policy`.
|
|
142
|
+
- **Identify dynamic dependencies**: Check if third-party scripts are versioned or if they receive silent updates, determining if `SRI` can be used.
|
|
143
|
+
- **Map cross-site integrations**: List all incoming Webhooks, cross-site APIs, or SSO redirect endpoints so `Fetch Metadata` resource isolation policies don't break them.
|
|
144
|
+
|
|
145
|
+
### 2.2 Deploy Report-Only Policies
|
|
146
|
+
Use "Report-Only" headers to identify potential breakages before they happen.
|
|
147
|
+
- **DO**: Use report-only headers to dry-run policies without enforcement. Standard report-only headers include:
|
|
148
|
+
- `Content-Security-Policy-Report-Only` for CSP rules.
|
|
149
|
+
- `Cross-Origin-Opener-Policy-Report-Only` for COOP isolation.
|
|
150
|
+
- `Cross-Origin-Embedder-Policy-Report-Only` for COEP isolation.
|
|
151
|
+
- `Document-Policy-Report-Only` for document features.
|
|
152
|
+
- **DO**: Define a `Reporting-Endpoints` header so violations have somewhere to go, and reference its name from `report-to`. Recommend setting an endpoint named `default`, which will automatically capture deprecation and crash reports.
|
|
153
|
+
- **DO**: Run report-only for long enough to cover real traffic patterns (typically days to weeks), not just synthetic testing.
|
|
154
|
+
|
|
155
|
+
**Example headers:**
|
|
156
|
+
```http
|
|
157
|
+
Reporting-Endpoints: default="https://reports.example/default", main-endpoint="https://reports.example/main"
|
|
158
|
+
Content-Security-Policy-Report-Only: script-src 'nonce-{RANDOM}' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; require-trusted-types-for 'script'; report-to main-endpoint;
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
The `'strict-dynamic'`, `https:`, and `'unsafe-inline'` tokens together form a backwards-compatibility ladder: modern browsers honor `'strict-dynamic'` (nonce-propagating) and ignore the others; older browsers fall back to `https:`; very old browsers fall back to `'unsafe-inline'`. The fallbacks are harmless on any browser that supports a stricter token.
|
|
162
|
+
|
|
163
|
+
**Managing report false-positives**: Reporting endpoints receive a significant volume of false-positive violation reports caused by client-side middleware, aggressive browser extensions, ancient browsers, web crawlers, or antivirus scanners. When analyzing report-only logs, focus on high-frequency patterns from modern user-agents and filter out noise before making deployment decisions. Specifically:
|
|
164
|
+
- **Filter out noise**: Ignore reports sent by old browsers with known bugs triggering spurious violations, reports for markup known to be injected by popular browser extensions or client-side middleware (like identical reports seen across many distinct applications), and reports that do not contain enough information to debug.
|
|
165
|
+
- **Ignore low-volume reports**: If a policy is deployed, a low violation volume often indicates a false positive that can be safely ignored.
|
|
166
|
+
- **Leverage `'report-sample'`**: Always include `'report-sample'` in your `script-src` directives. This instructs the browser to include the first 40 characters of the violating script or inline code snippet in the violation report, which makes debugging much easier.
|
|
167
|
+
|
|
168
|
+
### 2.3 Data Hygiene for Reports
|
|
169
|
+
- **DO NOT**: Include sensitive data (PII, authentication tokens, session identifiers, query strings with secrets) in logs or violation reports. Mask or omit them at the edge before they reach the reporting endpoint.
|
|
170
|
+
|
|
171
|
+
### 2.4 Automated Discovery via Browser APIs and DevTools
|
|
172
|
+
- **Reporting API**: Use `Reporting-Endpoints` in combination with report-only headers (e.g., `Content-Security-Policy-Report-Only`, `Document-Policy-Report-Only`) to have the browser automatically post violations to your server.
|
|
173
|
+
- **Browser DevTools**: Use the **Issues Tab** in modern browsers (e.g., Chrome DevTools). It automatically surfaces blocked resources, mixed content, third-party cookie deprecation warnings, and feature policy violations without you having to crawl the codebase manually.
|
|
174
|
+
|
|
175
|
+
## Phase 3: Interpreting Results & Enforcement
|
|
176
|
+
|
|
177
|
+
After inspecting the application (or collecting report-only data), enforce your security policies. Phase 3 has two tracks that are enforced together:
|
|
178
|
+
|
|
179
|
+
- **Core enforcement** — high-leverage XSS and isolation defenses (`Content-Security-Policy`, Trusted Types, COOP, CORP, and Fetch Metadata).
|
|
180
|
+
- **Companion policies (deploy in parallel)** — low-risk headers (`Strict-Transport-Security`, `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, `Clear-Site-Data`) that should always be enabled alongside core enforcement.
|
|
181
|
+
|
|
182
|
+
### Core enforcement
|
|
183
|
+
|
|
184
|
+
#### 3.1 Analyzing CSP Reports
|
|
185
|
+
|
|
186
|
+
When reviewing CSP violation reports, first separate the noise (per §2.2) from legitimate application issues. For violations that appear to be caused by an incompatibility in your application (usually those where the "Sample" or "Blocked URI" seem like legitimate scripts or assets that might be present in your markup):
|
|
187
|
+
- **Code Search**: Search your codebase for the offending script source, URL, or hash to see if it is present in your code, dynamic server templates, or static HTML files.
|
|
188
|
+
- **Console Auditing**: Open the page that triggered the violation (the "Document URI" in the report) using the same browser, and check the developer tools/console for CSP violations while exercising as much application functionality as possible (some violations only trigger on specific user interactions).
|
|
189
|
+
|
|
190
|
+
Once filtered and triaged, analyze the reports against the following common scenarios:
|
|
191
|
+
|
|
192
|
+
- **Scenario**: Many violations for inline scripts.
|
|
193
|
+
- **Condition**: The app uses a framework that relies on inline scripts.
|
|
194
|
+
- **Decision**: Implement Nonces (server-rendered) or Hashes (static) before enforcing.
|
|
195
|
+
- **Scenario**: Violations for third-party analytics scripts.
|
|
196
|
+
- **Condition**: The scripts are required.
|
|
197
|
+
- **Decision**: Use `'strict-dynamic'` with a per-request nonce so the analytics loader can attach its dependencies. Do **not** add the analytics origin to a URL allowlist — domain allowlists are bypassable via open redirects, JSONP, and dependency injection on the listed origin.
|
|
198
|
+
- **Scenario**: Trusted Types violations on specific sinks.
|
|
199
|
+
- **Condition**: Legacy code paths still write strings to `innerHTML` etc.
|
|
200
|
+
- **Decision**: Refactor those sinks (per §1.2) or route them through a Trusted Types policy (§3.3) before enforcing.
|
|
201
|
+
|
|
202
|
+
#### 3.2 Enforcing Content Security Policy (CSP)
|
|
203
|
+
When enforcing `Content-Security-Policy`, always keep `Reporting-Endpoints` and `report-to` wired up on the enforced header so any regressions remain visible.
|
|
204
|
+
|
|
205
|
+
**Mandatory directives to set:**
|
|
206
|
+
- `script-src 'nonce-{RANDOM}' 'strict-dynamic' 'report-sample'` (or SHA-256/384/512 script hashes for static HTML) — the core directive of any CSP and the primary mechanism to prevent XSS.
|
|
207
|
+
- `object-src 'none'` — blocks plugin-based code execution (`<object>`, `<embed>`).
|
|
208
|
+
- `base-uri 'none'` — blocks `<base>` tag hijacking of relative URLs.
|
|
209
|
+
- `frame-ancestors 'none'` (or `'self'` when same-origin framing is needed) — prevents clickjacking alongside `X-Frame-Options: DENY` (or `SAMEORIGIN`; see §1.4).
|
|
210
|
+
- `require-trusted-types-for 'script'` — enforces Trusted Types runtime checks on DOM XSS sinks (§3.3).
|
|
211
|
+
- `report-to <endpoint>` — sends violation reports to the endpoint defined in `Reporting-Endpoints`.
|
|
212
|
+
- *Optional*: `form-action 'self'` prevents form submissions to attacker-controlled origins.
|
|
213
|
+
|
|
214
|
+
**Enforced Header Example (CSP with reporting):**
|
|
215
|
+
```http
|
|
216
|
+
Reporting-Endpoints: main-endpoint="https://reports.example/main"
|
|
217
|
+
Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; require-trusted-types-for 'script'; report-to main-endpoint;
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
HTML for nonce-based CSP:
|
|
221
|
+
```html
|
|
222
|
+
<script nonce="{RANDOM}" src="https://example.com/script.js"></script>
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
**Server / Middleware Per-Request Nonce Generation:**
|
|
226
|
+
In server-rendered or SSR middleware (such as Node.js, Express, or Astro middleware), generate a fresh cryptographic nonce on every request, attach it to `Content-Security-Policy`, and pass the nonce into your template/SSR rendering context so only trusted template `<script>` tags receive it:
|
|
227
|
+
|
|
228
|
+
```javascript
|
|
229
|
+
const bytes = new Uint8Array(16);
|
|
230
|
+
crypto.getRandomValues(bytes);
|
|
231
|
+
const nonce = btoa(String.fromCharCode(...bytes));
|
|
232
|
+
|
|
233
|
+
const csp = [
|
|
234
|
+
`script-src 'nonce-${nonce}' 'strict-dynamic' 'report-sample'`,
|
|
235
|
+
"object-src 'none'",
|
|
236
|
+
"base-uri 'none'",
|
|
237
|
+
"frame-ancestors 'none'", // or "frame-ancestors 'self'" if same-origin framing is needed
|
|
238
|
+
"require-trusted-types-for 'script'",
|
|
239
|
+
'report-to main-endpoint',
|
|
240
|
+
].join('; ');
|
|
241
|
+
|
|
242
|
+
headers.set('Reporting-Endpoints', 'main-endpoint="https://reports.example/main"');
|
|
243
|
+
headers.set('Content-Security-Policy', csp);
|
|
244
|
+
|
|
245
|
+
// Pass the per-request nonce into your template/SSR rendering context (or replace an
|
|
246
|
+
// explicit placeholder token in a static template before interpolating any user data):
|
|
247
|
+
res.locals.nonce = nonce; // e.g., <script nonce="<%= nonce %>" src="/app.js"></script>
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
For static/cached HTML (SPAs) where a per-response nonce is not possible, use hash-based CSP: compute the `sha256-` hash of each script and list the hashes in `script-src` alongside `'strict-dynamic' 'report-sample'`.
|
|
251
|
+
|
|
252
|
+
**Avoid**:
|
|
253
|
+
- Broad scheme or domain allowlists (such as `https:` alone or `script-src https://cdn.example.com` without `'strict-dynamic'`) as the primary `script-src` protection — they are easily bypassed by open redirects, JSONP endpoints, and dependency injection on the allowed origin.
|
|
254
|
+
- Rewriting already-rendered HTML with a regular expression (such as `html.replace(/<script\b.../gi, ...)`) to stamp CSP nonces onto every `<script>` tag — post-processing rendered HTML cannot distinguish developer-authored `<script>` tags from untrusted `<script>` tags introduced via reflected or stored HTML injection, authorizing attacker-injected scripts under `script-src 'nonce-...'`.
|
|
255
|
+
|
|
256
|
+
#### 3.3 Trusted Types Enforcement
|
|
257
|
+
Trusted Types enforces source-level guidance at runtime by blocking raw string assignments to dangerous DOM XSS sinks (`innerHTML`, `outerHTML`, `document.write`, `script.src`, `script.textContent`) unless they pass through a named policy.
|
|
258
|
+
|
|
259
|
+
- **DO**: Enforce Trusted Types in your `Content-Security-Policy` header by including the `require-trusted-types-for 'script'` directive.
|
|
260
|
+
- **DO**: Sanitize any HTML sink assignments through a named `trustedTypes.createPolicy(...)` instance rather than assigning raw strings (or prefer `element.setHTML()` directly, which sanitizes HTML without needing a Trusted Types policy).
|
|
261
|
+
- **DO NOT**: Create a pass-through policy (such as `createHTML: (s) => s`) that returns unsanitized input unchanged, as this neutralizes Trusted Types protection.
|
|
262
|
+
- **DO**: Consult the dedicated `trusted-types` (references/security/trusted-types.md) guide for full implementation details, including `trusted-types` policy allowlisting and rollout strategies.
|
|
263
|
+
|
|
264
|
+
```javascript
|
|
265
|
+
const htmlPolicy = window.trustedTypes?.createPolicy('app-html', {
|
|
266
|
+
createHTML(input) {
|
|
267
|
+
return String(input)
|
|
268
|
+
.replace(/&/g, '&')
|
|
269
|
+
.replace(/</g, '<')
|
|
270
|
+
.replace(/>/g, '>')
|
|
271
|
+
.replace(/"/g, '"')
|
|
272
|
+
.replace(/'/g, ''');
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
#### 3.4 Cross-Origin Opener Policy (COOP)
|
|
278
|
+
|
|
279
|
+
Lowest-risk of the three. Deploy if the app is **not** an OAuth provider, payment processor, or otherwise expected to be reached from an opener.
|
|
280
|
+
|
|
281
|
+
- **DO**: Use `Cross-Origin-Opener-Policy: same-origin-allow-popups` — prevents a malicious opener from mounting XS-leaks attacks while still allowing OAuth and payment flows that *the app itself* initiates.
|
|
282
|
+
- **DO NOT**: Jump straight to `same-origin` unless you have explicitly verified that no integrations rely on cross-origin `window.opener` access.
|
|
283
|
+
|
|
284
|
+
#### 3.5 Cross-Origin Resource Policy (CORP)
|
|
285
|
+
|
|
286
|
+
Set CORP explicitly on each response based on whether it should be embeddable in other contexts. Two core benefits: it protects resources from malicious cross-origin reads, and ensures compatibility when pages request stronger client-side isolation.
|
|
287
|
+
|
|
288
|
+
- **DO**: Default to `Cross-Origin-Resource-Policy: same-origin` for app-internal responses (such as HTML documents, internal endpoints, authenticated data, user session JSON, and restricted internal scripts).
|
|
289
|
+
- **DO**: Use `same-site` for endpoints utilized across subdomains of the same eTLD+1.
|
|
290
|
+
- **DO**: Provide `cross-origin` exclusively for resources created for generic embedding or widely cached delivery (e.g., static shared assets or public CDNs).
|
|
291
|
+
|
|
292
|
+
#### 3.6 Cross-Origin Isolation
|
|
293
|
+
|
|
294
|
+
Highest deployment breakage risk. You only need to deploy this infrastructure if the application requires features relying on `SharedArrayBuffer` (e.g., WebAssembly multi-threading or shared memory architectures). If not required, skip this policy group.
|
|
295
|
+
|
|
296
|
+
- **Preferred path (Chromium environments)**: Enable `Document-Isolation-Policy: isolate-and-credentialless`. This provides client-side isolation comparable to COEP while instructing the browser to strip cookies and authentication credentials from non-CORS cross-origin resource fetches rather than blocking them outright. Note that this is supported primarily in Chrome (142+) and other vendors have not yet shown interest, so evaluate carefully based on your target audience. Apps that need to *block* cross-origin resources lacking explicit CORP opt-in (rather than load them with credentials stripped) can adopt `isolate-and-require-corp` instead. This is stricter and harder to deploy — it requires the same subresource audit as the cross-browser path below.
|
|
297
|
+
- **Cross-browser path (Complex enforcement)**: Require `Cross-Origin-Opener-Policy: same-origin` coupled with `Cross-Origin-Embedder-Policy: require-corp`. Every embedded subresource (images, styles, external media) MUST serve an explicit `Cross-Origin-Resource-Policy` header or the browser will prevent it from loading.
|
|
298
|
+
|
|
299
|
+
```http
|
|
300
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
301
|
+
Cross-Origin-Embedder-Policy: require-corp
|
|
302
|
+
Cross-Origin-Resource-Policy: same-origin
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
#### 3.7 Fetch Metadata (Resource Isolation)
|
|
306
|
+
Server-side enforcement that uses `Sec-Fetch-*` request headers to reject suspicious cross-site requests. Requires the cross-site integration mapping from §2.1 before enforcing.
|
|
307
|
+
|
|
308
|
+
- **DO**: Implement a server-side resource isolation policy that checks `Sec-Fetch-*` headers and rejects `cross-site` requests for non-navigational endpoints.
|
|
309
|
+
- **DO**: Reject disallowed requests *before* authentication or authorization checks, so the response does not leak timing information about whether a resource or session exists.
|
|
310
|
+
- **DO**: Include `Vary: Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site` to prevent intermediate caches (CDNs) from serving cached responses to attackers.
|
|
311
|
+
- **CAUTION**: `same-site` trusts every subdomain under your eTLD+1. If any subdomain hosts user-generated content, a legacy app, or otherwise untrusted code, drop `same-site` from the allowlist and accept only `same-origin` and `none`.
|
|
312
|
+
- **CAUTION**: Misconfiguring these checks will block legitimate API requests coming from cross-site integrations, SSO handlers, or Webhooks. Ensure you log and test your `Sec-Fetch-*` constraints beforehand.
|
|
313
|
+
|
|
314
|
+
```javascript
|
|
315
|
+
app.use((req, res, next) => {
|
|
316
|
+
res.setHeader('Vary', 'Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site');
|
|
317
|
+
|
|
318
|
+
const site = req.get('Sec-Fetch-Site');
|
|
319
|
+
const mode = req.get('Sec-Fetch-Mode');
|
|
320
|
+
const dest = req.get('Sec-Fetch-Dest');
|
|
321
|
+
|
|
322
|
+
if (!site) return next(); // Fallback for legacy browsers
|
|
323
|
+
|
|
324
|
+
if (['same-origin', 'same-site', 'none'].includes(site)) return next();
|
|
325
|
+
|
|
326
|
+
// Allow standard navigate GET requests (link clicks)
|
|
327
|
+
if (site === 'cross-site' && mode === 'navigate' && req.method === 'GET' && !['object', 'embed'].includes(dest)) {
|
|
328
|
+
return next();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
res.status(403).send('Forbidden');
|
|
332
|
+
});
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
### Companion policies (deploy in parallel)
|
|
336
|
+
|
|
337
|
+
These carry significantly lower breakage risk than the core enforcement track. They can be deployed alongside — or before — the CSP and isolation rollouts.
|
|
338
|
+
|
|
339
|
+
#### HTTP Strict Transport Security (HSTS)
|
|
340
|
+
- **DO**: `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload` to force HTTPS.
|
|
341
|
+
- **TIP**: In production rollout, start with a short `max-age` (e.g., 300 seconds) and incrementally increase to 1 year. A misconfigured HSTS with a long max-age can render the site permanently inaccessible until the cache expires in every browser that saw it.
|
|
342
|
+
|
|
343
|
+
#### X-Content-Type-Options
|
|
344
|
+
- **DO**: Set `X-Content-Type-Options: nosniff` to block MIME-type sniffing.
|
|
345
|
+
- **DO**: Ensure the server serves correct `Content-Type` headers for all resources (`application/javascript` for scripts, `application/json` for APIs, `text/html` for documents, etc.) so the browser can strictly enforce the `nosniff` constraint.
|
|
346
|
+
|
|
347
|
+
#### Referrer Policy
|
|
348
|
+
- **DO**: Use `Referrer-Policy: strict-origin-when-cross-origin` as a safe default.
|
|
349
|
+
|
|
350
|
+
#### Permissions Policy
|
|
351
|
+
- **DO**: Disable unused browser features (camera, geolocation, microphone) for the page and iframes using Structured Fields syntax.
|
|
352
|
+
- **DO**: Disable `focus-without-user-activation` for third-party iframes to prevent focus stealing.
|
|
353
|
+
- **DO**: When delegating features to an iframe, use the `allow` attribute in HTML *in addition* to the header.
|
|
354
|
+
- **CAUTION**: Unintentionally blocking a delegated feature will cause silent failures in third-party widgets (like embedded video players or payment gateways). Audit third-party dependencies before blocking.
|
|
355
|
+
|
|
356
|
+
```http
|
|
357
|
+
Permissions-Policy: camera=(), geolocation=(), microphone=(), focus-without-user-activation=()
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
```html
|
|
361
|
+
<iframe src="https://trusted-video.com/player" allow="fullscreen; camera; focus-without-user-activation 'none'"></iframe>
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
#### Subresource Integrity (SRI)
|
|
365
|
+
- **DO**: Use the `integrity` attribute with a cryptographic hash (preferring `sha384`, `sha512`, or `sha256`) when loading third-party scripts and stylesheets, combined with `crossorigin="anonymous"` (see `secure-external-subresources` (references/security/secure-external-subresources.md) for securing HTML and CSS subresources with SRI, CORS, and Referrer Policy).
|
|
366
|
+
- **DO**: Ensure the server/CDN sends an appropriate `Access-Control-Allow-Origin` header so the browser can compute the hash.
|
|
367
|
+
- **DO NOT**: Use SRI for dynamic or unversioned assets — silent updates will cause script execution to fail. SRI is strictly for immutable, versioned assets.
|
|
368
|
+
|
|
369
|
+
```html
|
|
370
|
+
<script src="https://cdn.example.com/lib@1.0.0.js" integrity="sha384-oqVu...Y8wC" crossorigin="anonymous"></script>
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
#### Cross-Origin Resource Sharing (CORS)
|
|
374
|
+
CORS is a permission grant, not a defense — it tells the browser which cross-origin reads to allow. The risk is misconfiguring it as too permissive.
|
|
375
|
+
|
|
376
|
+
- **DO**: Validate the `Origin` header on the server and set `Access-Control-Allow-Origin` dynamically to specific origins (rather than wildcard `*`).
|
|
377
|
+
- **DO NOT**: Use wildcard `*` for `Access-Control-Allow-Origin` if `Access-Control-Allow-Credentials: true` is required — the browser will reject the response.
|
|
378
|
+
- **DO**: Handle preflight (`OPTIONS`) requests by returning appropriate headers before processing data.
|
|
379
|
+
|
|
380
|
+
```http
|
|
381
|
+
Access-Control-Allow-Origin: https://trusted-app.com
|
|
382
|
+
Access-Control-Allow-Credentials: true
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
#### Clear-Site-Data (Logout)
|
|
386
|
+
- **DO**: Send `Clear-Site-Data: "cookies", "storage", "cache"` on logout endpoints to ensure complete session termination; omitting any of these directives leaves active session cookies, Web Storage state, or cached authenticated pages behind.
|
|
387
|
+
|
|
388
|
+
```http
|
|
389
|
+
Clear-Site-Data: "cookies", "storage", "cache"
|
|
390
|
+
```
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Prevent DOM-based XSS attacks with Trusted Types
|
|
2
|
+
|
|
3
|
+
Trusted Types is a security feature that helps prevent DOM-based Cross-Site Scripting (DOM XSS) by requiring that data being passed into "dangerous" browser APIs (known as sinks) is first converted into a specific type, such as `TrustedHTML`.
|
|
4
|
+
|
|
5
|
+
By default, many DOM APIs (like `innerHTML` or `document.write`) accept raw strings. If a string contains malicious script from an untrusted source, it can be executed. Trusted Types changes this behavior: once enabled via CSP, these sinks will only accept `TrustedHTML` objects created by authorized policies.
|
|
6
|
+
|
|
7
|
+
## Key Implementation Details
|
|
8
|
+
|
|
9
|
+
To use Trusted Types, follow four main steps:
|
|
10
|
+
|
|
11
|
+
1. Define a security policy that specifies how to sanitize or transform strings.
|
|
12
|
+
2. Use that policy to create Trusted Type objects from raw strings.
|
|
13
|
+
3. Use the Trusted Type objects when writing to DOM sinks.
|
|
14
|
+
4. Enforce Trusted Types using a Content Security Policy (CSP).
|
|
15
|
+
|
|
16
|
+
### 1. Creating a Policy
|
|
17
|
+
|
|
18
|
+
A policy is a set of rules for sanitizing content. You create it using `trustedTypes.createPolicy()`, typically delegating to a sanitizer library such as DOMPurify or your application's HTML escaping rules:
|
|
19
|
+
|
|
20
|
+
```javascript
|
|
21
|
+
import DOMPurify from 'dompurify';
|
|
22
|
+
|
|
23
|
+
const myPolicy = trustedTypes.createPolicy('sanitize-html', {
|
|
24
|
+
createHTML: (input) =>
|
|
25
|
+
// Return a sanitized string; createPolicy() wraps it in a TrustedHTML object.
|
|
26
|
+
// Example using DOMPurify:
|
|
27
|
+
DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false }),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
// Example using HTML escaping (for environments without third-party sanitizers):
|
|
31
|
+
const escapePolicy = trustedTypes.createPolicy('escape-html', {
|
|
32
|
+
createHTML: (input) =>
|
|
33
|
+
String(input)
|
|
34
|
+
.replaceAll('&', '&')
|
|
35
|
+
.replaceAll('<', '<')
|
|
36
|
+
.replaceAll('>', '>')
|
|
37
|
+
.replaceAll('"', '"')
|
|
38
|
+
.replaceAll("'", '''),
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
> [!WARNING]
|
|
43
|
+
> Character-level HTML escaping (`escapePolicy`) converts all markup into plain text and is **not** a context-aware HTML sanitizer. If you only need plain text, prefer `element.textContent` (which is not a Trusted Types sink). Never interpolate `escapePolicy.createHTML()` output into another HTML template string—such as an unquoted attribute (`<img src=${escaped}>`) or a URL attribute (`<a href="${escaped}">`, where `javascript:` URLs are not neutralized by entity escaping). Use a full HTML sanitizer (`DOMPurify` or `element.setHTML()`, covered in `sanitize-untrusted-html` (references/security/sanitize-untrusted-html.md)) whenever accepting HTML markup or attributes.
|
|
44
|
+
|
|
45
|
+
### 2. Using the Policy
|
|
46
|
+
|
|
47
|
+
Instead of passing a string directly to a sink, you call the policy's creation method.
|
|
48
|
+
|
|
49
|
+
```javascript
|
|
50
|
+
const untrustedInput = '<p>Hello, <strong>world</strong>!</p><img src="x" onerror="alert(1)">';
|
|
51
|
+
|
|
52
|
+
// In an enforced environment, this would throw a TypeError:
|
|
53
|
+
// element.innerHTML = untrustedInput;
|
|
54
|
+
|
|
55
|
+
// This returns a TrustedHTML object with unsafe elements and attributes removed:
|
|
56
|
+
const cleanHTML = myPolicy.createHTML(untrustedInput);
|
|
57
|
+
// Result: "<p>Hello, <strong>world</strong>!</p><img src=\"x\">"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 3. Transitioning sinks to use Trusted Types
|
|
61
|
+
|
|
62
|
+
Update each instance where you write to a sink to first convert it to a Trusted Type object. To help locate where code needs to be updated, you can define a temporary `default` policy that logs when a sink is written to with a string rather than a TrustedType.
|
|
63
|
+
|
|
64
|
+
```javascript
|
|
65
|
+
trustedTypes.createPolicy("default", {
|
|
66
|
+
createHTML(value) {
|
|
67
|
+
console.warn("String passed instead of Trusted Type.");
|
|
68
|
+
return DOMPurify.sanitize(value, { RETURN_TRUSTED_TYPE: false });
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Common sinks that support Trusted Types include:
|
|
74
|
+
- **HTML:** `element.innerHTML`, `element.outerHTML`, `document.write()`, `element.setHTMLUnsafe()`, `Document.parseHTMLUnsafe()`
|
|
75
|
+
- **Script:** `<script>` text content, `eval()`
|
|
76
|
+
- **ScriptURL:** `<script src>`, `Worker()`, `SharedWorker()`
|
|
77
|
+
|
|
78
|
+
```javascript
|
|
79
|
+
// Assign the TrustedHTML object.
|
|
80
|
+
element.innerHTML = cleanHTML;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Note that the "safe" HTML sanitization methods (`element.setHTML()` and `Document.parseHTML()`, covered in `sanitize-untrusted-html` (references/security/sanitize-untrusted-html.md)), do not require a Trusted Types policy, as they always sanitize potential XSS attacks natively.
|
|
84
|
+
|
|
85
|
+
### 4. Enforcing Trusted Types with CSP
|
|
86
|
+
|
|
87
|
+
Trusted Types should be rolled out incrementally to avoid breaking your application. While full enforcement provides the strongest protection, it carries a risk of site breakage if every sink write hasn't been migrated.
|
|
88
|
+
|
|
89
|
+
#### Prerequisites
|
|
90
|
+
|
|
91
|
+
- **Framework cooperation**: If your application's framework (or any third-party library that writes to DOM sinks) does not produce `TrustedHTML` or `TrustedScript` values, you cannot enforce Trusted Types without breaking that code. Audit framework support before starting the rollout.
|
|
92
|
+
- **Sink refactoring**: Ensure you have identified and refactored dangerous sinks to use your Trusted Types policies.
|
|
93
|
+
|
|
94
|
+
#### Rollout Strategy
|
|
95
|
+
|
|
96
|
+
1. **Report-Only**: First, roll out using the `Content-Security-Policy-Report-Only` header. This will log violations to your reporting endpoint without actually blocking the writes.
|
|
97
|
+
```http
|
|
98
|
+
Content-Security-Policy-Report-Only: require-trusted-types-for 'script';
|
|
99
|
+
```
|
|
100
|
+
2. **Enforcement**: Once you have integrated your policies and violation reports drop to zero, move to full enforcement.
|
|
101
|
+
|
|
102
|
+
```http
|
|
103
|
+
Content-Security-Policy: require-trusted-types-for 'script';
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
You can also restrict which policies are allowed to be created (list your policy names such as `sanitize-html` or `escape-html`, include `dompurify` if your policy delegates to `DOMPurify.sanitize()`—which internally creates a `dompurify` policy—and include `default` if you register a default policy during migration):
|
|
107
|
+
|
|
108
|
+
```http
|
|
109
|
+
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types sanitize-html escape-html dompurify;
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
With this CSP in place, any writes to a sink that don't use Trusted Types will throw an error. In addition, attempting to create a Trusted Type policy with a name not listed in `trusted-types` will throw an error.
|
|
113
|
+
|
|
114
|
+
You can also set this CSP as a `<meta>` tag in your document's `<head>`, although this is potentially less secure.
|
|
115
|
+
|
|
116
|
+
```html
|
|
117
|
+
<!-- First child of `<head>`, as earlier tags will not enforce this CSP. -->
|
|
118
|
+
<meta
|
|
119
|
+
http-equiv="Content-Security-Policy"
|
|
120
|
+
content="require-trusted-types-for 'script'; trusted-types sanitize-html escape-html dompurify;"
|
|
121
|
+
/>
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Fallback strategies
|
|
125
|
+
|
|
126
|
+
Baseline status for Trusted types: Newly available. It's been Baseline since 2026-02-24.
|
|
127
|
+
Supported by: Chrome 83 (May 2020), Edge 83 (May 2020), Firefox 148 (Feb 2026), and Safari 26 (Sep 2025).
|
|
128
|
+
|
|
129
|
+
For browsers that do not yet support Trusted Types, you can use a minimal "tinyfill" to ensure your code doesn't break while still providing sanitization.
|
|
130
|
+
|
|
131
|
+
```javascript
|
|
132
|
+
if (!window.trustedTypes) {
|
|
133
|
+
window.trustedTypes = {
|
|
134
|
+
createPolicy: (name, rules) => rules,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
This allows you to write your code using the Trusted Types pattern today. Supporting browsers will enforce the types, while older browsers will still execute your sanitization logic via the mock policy.
|
|
140
|
+
|
|
141
|
+
If a browser doesn't support Trusted Types, it will simply treat the `TrustedHTML` objects as strings (if using the tinyfill) or won't have the enforcement check at the sink level.
|