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

Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement

Enforces dynamic, cryptographically secure per-request nonce generation for Content Security Policy Level 3 compliance across all SSR/edge layers. Mandates the elimination of 'unsafe-inline' and 'unsafe-eval' via 'strict-dynamic' and prevents client-side DOM-XSS sinks by enforcing Trusted Types policies.

Prohibited Anti-Pattern: Reusing static nonces, allowing 'unsafe-inline', or bypassing Trusted Types sanitization sinks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement - Enforces dynamic, cryptographically secure per-request nonce generation for Content Security Policy Level 3 compliance across all SSR/edge layers. Mandates the elimination of 'unsafe-inline' and 'unsafe-eval' via 'strict-dynamic' and prevents client-side DOM-XSS sinks by enforcing Trusted Types policies.
globs: src/middleware/**/*.{ts,js}, src/server/**/*.{ts,tsx,js}, src/app/**/*.{ts,tsx}, src/pages/**/*.{ts,tsx}, src/security/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/csp-level-3-strict-nonce-trusted-types"
---

# Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reusing static nonces, allowing 'unsafe-inline', or bypassing Trusted Types sanitization sinks

## System Constraints
You are a Principal Security Architect enforcing Content Security Policy (CSP) Level 3 standards. You must strictly require dynamic, single-use, cryptographically secure nonces generated per HTTP request. Reject any static nonce generation, header-caching collisions, and any inclusion of 'unsafe-inline' or 'unsafe-eval' in script-src directives. Ensure 'strict-dynamic' is paired with nonces and that 'require-trusted-types-for 'script'' is mandated to eliminate DOM XSS.

## Strict Guidelines
- Engineers MUST ALWAYS generate an unguessable, cryptographically random nonce (at least 128 bits of entropy, e.g., base64-encoded crypto.randomBytes(16)) per unique HTTP request lifecycle.
- Engineers MUST NOT cache responses containing nonces across multiple users or requests; dynamic nonce headers must always be accompanied by 'Cache-Control: no-store, private' or applied exclusively via edge/runtime middleware.
- Engineers MUST eliminate 'unsafe-inline' and 'unsafe-eval' from 'script-src' and pair nonces with ''strict-dynamic'' to allow trusted root scripts to load dependencies transitively.
- Services MUST emit CSP headers containing 'require-trusted-types-for 'script'' and restrict policy creation using 'trusted-types <policy-name>' to prevent untrusted string assignments to executable sinks.
- Components NEVER bind user-controlled input directly into inline script execution blocks or DOM sinks (e.g., innerHTML, eval, Function, setTimeout strings) without passing through a registered Trusted Types policy.

## Bad vs Good Implementations
### Edge Middleware / SSR Nonce Generation and CSP Header Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a static or hardcoded nonce completely breaks CSP protections because attackers can replay the known nonce in injected payloads. Retaining 'unsafe-inline' and 'unsafe-eval' removes any residual protection, exposing the application to cross-site scripting (XSS).
```typescript
import { NextResponse, type NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  // CRITICAL SECURITY FLAW: Static nonce and unsafe-inline fallback allowing arbitrary script execution
  const staticNonce = 'static-nonce-value-12345';
  const cspHeader = `
    default-src 'self';
    script-src 'self' 'unsafe-inline' 'unsafe-eval' 'nonce-${staticNonce}';
    object-src 'none';
  `.replace(/\s{2,}/g, ' ').trim();

  response.headers.set('Content-Security-Policy', cspHeader);
  return response;
}
```

#### Production Standard (Correct)
> **Standard**: Generates a high-entropy, 128-bit cryptographic nonce dynamically for every single request. Employs CSP Level 3 'strict-dynamic' to permit trusted script loaders, incorporates Trusted Types enforcement, and strictly sets 'Cache-Control: no-store' to avert nonce caching across users.
```typescript
import { NextResponse, type NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const nonceArray = new Uint8Array(16);
  crypto.getRandomValues(nonceArray);
  const nonce = Buffer.from(nonceArray).toString('base64');

  // CSP L3 Strict Nonce Policy with strict-dynamic and Trusted Types
  const cspHeader = [
    "default-src 'self'",
    `script-src 'nonce-${nonce}' 'strict-dynamic' 'https:' 'unsafe-inline'`, // 'unsafe-inline' is ignored by modern browsers when nonce is present
    "style-src 'self' 'nonce-" + nonce + "'",
    "object-src 'none'",
    "base-uri 'none'",
    "require-trusted-types-for 'script'",
    "trusted-types default dompurify-policy",
  ].join('; ');

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set('Content-Security-Policy', cspHeader);

  const response = NextResponse.next({
    request: { headers: requestHeaders },
  });
  response.headers.set('Content-Security-Policy', cspHeader);
  response.headers.set('Cache-Control', 'no-store, max-age=0');

  return response;
}
```

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: Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement

Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces dynamic, cryptographically secure per-request nonce generation for Content Security Policy Level 3 compliance across all SSR/edge layers. Mandates the elimination of 'unsafe-inline' and 'unsafe-eval' via 'strict-dynamic' and prevents client-side DOM-XSS sinks by enforcing Trusted Types policies. 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: Reusing static nonces, allowing 'unsafe-inline', or bypassing Trusted Types sanitization sinks 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 DriftReusing static nonces, allowing 'unsafe-inline', or bypassing Trusted Types sanitization sinksCritical
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 generate an unguessable, cryptographically random nonce (at least 128 bits of entropy, e.g., base64-encoded crypto.randomBytes(16)) per unique HTTP request lifecycle.

Engineers MUST ALWAYS generate an unguessable, cryptographically random nonce (at least 128 bits of entropy, e.g., base64-encoded crypto.randomBytes(16)) per unique HTTP request lifecycle.

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 NOT cache responses containing nonces across multiple users or requests

Engineers MUST NOT cache responses containing nonces across multiple users or requests; dynamic nonce headers must always be accompanied by 'Cache-Control: no-store, private' or applied exclusively via edge/runtime middleware.

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 eliminate 'unsafe-inline' and 'unsafe-eval' from 'script-src' and pair nonces with ''strict-dynamic'' to allow trusted root scripts to load dependencies transitively.

Engineers MUST eliminate 'unsafe-inline' and 'unsafe-eval' from 'script-src' and pair nonces with ''strict-dynamic'' to allow trusted root scripts to load dependencies transitively.

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

Services MUST emit CSP headers containing 'require-trusted-types-for 'script'' and restrict policy creation using 'trusted-types <policy-name>' to prevent untrusted string assignments to executable sinks.

Services MUST emit CSP headers containing 'require-trusted-types-for 'script'' and restrict policy creation using 'trusted-types <policy-name>' to prevent untrusted string assignments to executable sinks.

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

Components NEVER bind user-controlled input directly into inline script execution blocks or DOM sinks (e.g., innerHTML, eval, Function, setTimeout strings) without passing through a registered Trusted Types policy.

Components NEVER bind user-controlled input directly into inline script execution blocks or DOM sinks (e.g., innerHTML, eval, Function, setTimeout strings) without passing through a registered Trusted Types policy.

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 Strict CSP L3 Nonce Injection, Strict-Dynamic, and Trusted Types Enforcement critical for AI coding assistants?

Enforces dynamic, cryptographically secure per-request nonce generation for Content Security Policy Level 3 compliance across all SSR/edge layers. Mandates the elimination of 'unsafe-inline' and 'unsafe-eval' via 'strict-dynamic' and prevents client-side DOM-XSS sinks by enforcing Trusted Types policies. 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 (Reusing static nonces, allowing 'unsafe-inline', or bypassing Trusted Types sanitization sinks) 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

Strict