This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: w3c-trusted-types-strict-csp-l3-enforcement

W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement

Enforces mathematically verifiable defenses against client-side DOM-based Cross-Site Scripting (XSS) by mandating W3C Trusted Types and CSP Level 3 strict nonces. Direct injection sink mutations (innerHTML, outerHTML, script.src) are prohibited unless routed through pre-compiled, audited TrustedType policies. All executable script tags must carry cryptographically secure per-request nonces, deprecating unsafe-inline and wildcard domain allowlists.

Prohibited Anti-Pattern: Unsanitized DOM Sink Mutations and Permissive Host-Based CSP Policies Permitting Arbitrary Script Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement - Enforces mathematically verifiable defenses against client-side DOM-based Cross-Site Scripting (XSS) by mandating W3C Trusted Types and CSP Level 3 strict nonces. Direct injection sink mutations (innerHTML, outerHTML, script.src) are prohibited unless routed through pre-compiled, audited TrustedType policies. All executable script tags must carry cryptographically secure per-request nonces, deprecating unsafe-inline and wildcard domain allowlists.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,js}, index.html, next.config.js, vite.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/w3c-trusted-types-strict-csp-l3-enforcement"
---

# W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unsanitized DOM Sink Mutations and Permissive Host-Based CSP Policies Permitting Arbitrary Script Execution

## System Constraints
You are a Principal Security Architect enforcing W3C Trusted Types and strict nonce-based Content Security Policy (CSP) Level 3. Mandate invariant structural isolation between untrusted input and DOM sinks. Direct assignments to dangerous sinks (innerHTML, outerHTML, document.write, script.src) without an audited Trusted Types policy must be rejected. Enforce per-request cryptographically secure CSP nonces, blocking unsafe-inline, unsafe-eval, and permissive domain whitelists.

## Strict Guidelines
- Engineers MUST ALWAYS emit strict CSP Level 3 headers: `Content-Security-Policy: object-src 'none'; script-src 'nonce-{RANDOM}' 'strict-dynamic'; require-trusted-types-for 'script'; trusted-types default app-sanitizer; base-uri 'none';`.
- Engineers MUST route all DOM injection sinks (`element.innerHTML`, `element.outerHTML`, `document.write`, `iframe.srcdoc`, `script.text`, `script.src`) through audited `window.trustedTypes.createPolicy` factories.
- Engineers MUST NOT implement permissive wildcard or pass-through `default` Trusted Types policies that return unvalidated raw strings.
- Code MUST sanitize dynamic HTML markup using hardened sanitizers (e.g., DOMPurify configured with `RETURN_TRUSTED_TYPE: true`) within policy callbacks.
- Services MUST generate high-entropy (minimum 128-bit, base64-encoded) cryptographically secure pseudorandom nonces per HTTP response and bind them identically to both the CSP header and valid dynamic script tags.
- Components NEVER utilize legacy JavaScript execution sinks (`eval()`, `new Function()`, `setTimeout(string)`, `setInterval(string)`) or inline event handlers (`onclick`, `onerror`).

## Bad vs Good Implementations
### Unsafe DOM Sink Injection vs. Certified Trusted Types Policy Sanitization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly assigning raw strings to innerHTML bypasses type-safe sanitization and violates CSP Level 3 require-trusted-types-for directives, leading to arbitrary code execution if userGeneratedMarkup contains attacker-controlled payloads.
```typescript
export function renderUnsafePreview(container: HTMLElement, userGeneratedMarkup: string): void {
  // VULNERABILITY: Direct DOM sink mutation allows DOM-based XSS.
  // Violates CSP require-trusted-types-for 'script' and triggers a runtime TypeError in compliant browsers.
  container.innerHTML = userGeneratedMarkup;
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates DOM mutation within a declared Trusted Types policy ('app-sanitizer') using DOMPurify with an explicit tag and attribute allowlist, ensuring strict compliance with W3C Trusted Types and eliminating DOM XSS.
```typescript
import DOMPurify from 'dompurify';

declare global {
  interface Window {
    trustedTypes?: {
      createPolicy(
        name: string,
        rules: {
          createHTML?: (input: string) => string;
          createScript?: (input: string) => string;
          createScriptURL?: (input: string) => string;
        }
      ): TrustedTypePolicy;
    };
  }
  interface TrustedTypePolicy {
    createHTML(input: string): TrustedHTML;
  }
  type TrustedHTML = unknown;
}

// Compile singleton policy once with validated sanitizer
export const appSanitizerPolicy = typeof window !== 'undefined' && window.trustedTypes
  ? window.trustedTypes.createPolicy('app-sanitizer', {
      createHTML: (input: string): string => {
        return DOMPurify.sanitize(input, {
          ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
          ALLOWED_ATTR: ['href', 'title', 'target'],
          RETURN_TRUSTED_TYPE: false,
        });
      },
    })
  : null;

export function renderSecurePreview(container: HTMLElement, userGeneratedMarkup: string): void {
  if (appSanitizerPolicy) {
    // Compliant with require-trusted-types-for 'script'
    container.innerHTML = appSanitizerPolicy.createHTML(userGeneratedMarkup) as unknown as string;
  } else {
    // Fallback for non-supporting browsers using identical sanitization rules
    container.innerHTML = DOMPurify.sanitize(userGeneratedMarkup, {
      ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
      ALLOWED_ATTR: ['href', 'title', 'target'],
    });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement

W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces mathematically verifiable defenses against client-side DOM-based Cross-Site Scripting (XSS) by mandating W3C Trusted Types and CSP Level 3 strict nonces. Direct injection sink mutations (innerHTML, outerHTML, script.src) are prohibited unless routed through pre-compiled, audited TrustedType policies. All executable script tags must carry cryptographically secure per-request nonces, deprecating unsafe-inline and wildcard domain allowlists. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unsanitized DOM Sink Mutations and Permissive Host-Based CSP Policies Permitting Arbitrary Script Execution Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnsanitized DOM Sink Mutations and Permissive Host-Based CSP Policies Permitting Arbitrary Script ExecutionCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS emit strict CSP Level 3 headers

Engineers MUST ALWAYS emit strict CSP Level 3 headers: `Content-Security-Policy: object-src 'none'; script-src 'nonce-{RANDOM}' 'strict-dynamic'; require-trusted-types-for 'script'; trusted-types default app-sanitizer; base-uri 'none';`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST route all DOM injection sinks (`element.innerHTML`, `element.outerHTML`, `document.write`, `iframe.srcdoc`, `script.text`, `script.src`) through audited `window.trustedTypes.createPolicy` factories.

Engineers MUST route all DOM injection sinks (`element.innerHTML`, `element.outerHTML`, `document.write`, `iframe.srcdoc`, `script.text`, `script.src`) through audited `window.trustedTypes.createPolicy` factories.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT implement permissive wildcard or pass-through `default` Trusted Types policies that return unvalidated raw strings.

Engineers MUST NOT implement permissive wildcard or pass-through `default` Trusted Types policies that return unvalidated raw strings.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST sanitize dynamic HTML markup using hardened sanitizers (e.g., DOMPurify configured with `RETURN_TRUSTED_TYPE

Code MUST sanitize dynamic HTML markup using hardened sanitizers (e.g., DOMPurify configured with `RETURN_TRUSTED_TYPE: true`) within policy callbacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST generate high-entropy (minimum 128-bit, base64-encoded) cryptographically secure pseudorandom nonces per HTTP response and bind them identically to both the CSP header and valid dynamic script tags.

Services MUST generate high-entropy (minimum 128-bit, base64-encoded) cryptographically secure pseudorandom nonces per HTTP response and bind them identically to both the CSP header and valid dynamic script tags.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER utilize legacy JavaScript execution sinks (`eval()`, `new Function()`, `setTimeout(string)`, `setInterval(string)`) or inline event handlers (`onclick`, `onerror`).

Components NEVER utilize legacy JavaScript execution sinks (`eval()`, `new Function()`, `setTimeout(string)`, `setInterval(string)`) or inline event handlers (`onclick`, `onerror`).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is W3C Trusted Types and Strict Nonce-Based CSP Level 3 Enforcement critical for AI coding assistants?

Enforces mathematically verifiable defenses against client-side DOM-based Cross-Site Scripting (XSS) by mandating W3C Trusted Types and CSP Level 3 strict nonces. Direct injection sink mutations (innerHTML, outerHTML, script.src) are prohibited unless routed through pre-compiled, audited TrustedType policies. All executable script tags must carry cryptographically secure per-request nonces, deprecating unsafe-inline and wildcard domain allowlists. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unsanitized DOM Sink Mutations and Permissive Host-Based CSP Policies Permitting Arbitrary Script Execution) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

W3C