This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: speculation-rules-cross-origin-partitioning-standard

Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API

Enforces strict isolation, anonymous credential modes, and Sec-Purpose headers validation when using the W3C Speculation Rules API for prefetching and prerendering. Prevents cross-site information leaks (XS-Leaks), speculative timing attacks, and CSRF/state mutation via unpartitioned cross-origin speculative fetching.

Prohibited Anti-Pattern: Unrestricted Credentialed Speculative Execution Across Origins Without Partitioning Guards

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API - Enforces strict isolation, anonymous credential modes, and Sec-Purpose headers validation when using the W3C Speculation Rules API for prefetching and prerendering. Prevents cross-site information leaks (XS-Leaks), speculative timing attacks, and CSRF/state mutation via unpartitioned cross-origin speculative fetching.
globs: src/**/*.{ts,tsx,js,jsx}, public/**/*.html, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/speculation-rules-cross-origin-partitioning-standard"
---

# Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unrestricted Credentialed Speculative Execution Across Origins Without Partitioning Guards

## System Constraints
You are a Principal Security Architect enforcing safe usage of the W3C Speculation Rules API. Speculative prerendering and prefetching must never leak authenticated state, mutate server-side state, or establish unpartitioned cross-origin cache side-channels. Mandate anonymous credential modes, strictly isolate cross-origin speculation targets, and enforce server-side validation against prefetching state-modifying routes.

## Strict Guidelines
- Engineers MUST ALWAYS set `requires: ["anonymous-client-ip-when-cross-origin"]` or explicit credential omission when configuring cross-origin speculative rules.
- Engineers MUST NOT configure prerender rules (`source: "list"` or `source: "document"`) pointing to cross-origin endpoints unless the target origin explicitly serves matching `Supports-Loading-Mode: credentialed-prerender` headers and strict partitioning is acknowledged.
- Engineers MUST NEVER speculatively prefetch or prerender HTTP routes that perform state mutations (GET routes that trigger side-effects, session resets, or transaction writes).
- Code SHOULD dynamically inject `<script type="speculationrules">` only after sanitizing target URLs against an explicit allowlist of idempotent, read-only origin endpoints.
- Services MUST inspect incoming HTTP headers for `Sec-Purpose: prefetch` or `Sec-Purpose: prerender` and drop/reject any requests that attempt side-effects, tracking increments, or authenticated state alterations during speculative execution.
- Components NEVER attach wildcard speculation rules (e.g., `href_matches: "/*"`) without explicit negative selector constraints excluding logout, checkout, OAuth, and API routes.

## Bad vs Good Implementations
### Speculation Rule Script Injection with Cross-Origin Partitioning Guards

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Injecting candidate URLs without filtering allows cross-origin targets to receive authenticated cookies and client IPs, opening XS-Leak side-channels. Furthermore, prerendering non-idempotent or cross-origin URLs can cause unauthorized state mutations and CSRF vulnerabilities.
```typescript
// VULNERABLE: Indiscriminate prefetching and prerendering across origins with full credentials
export function injectSpeculationRules(candidateUrls: string[]): void {
  const script = document.createElement('script');
  script.type = 'speculationrules';
  script.textContent = JSON.stringify({
    prefetch: [
      {
        source: 'list',
        urls: candidateUrls // Leaks user cookies and IP to cross-origin targets; exposes XS-Leak
      }
    ],
    prerender: [
      {
        source: 'list',
        urls: candidateUrls // May execute state-mutating requests (e.g., /logout, /checkout)
      }
    ]
  });
  document.head.appendChild(script);
}
```

#### Production Standard (Correct)
> **Standard**: Sanitizes speculative candidate URLs to exclude mutable operations (auth, checkout, api), confines prerenders to safe local origins, and explicitly sets anonymous IP/credential protection requirements to avoid cross-origin side channels.
```typescript
// SECURE: Partitioned, credential-isolated speculation rules with explicit route exclusions
interface SpeculationRulesConfig {
  prefetchUrls: string[];
  prerenderUrls: string[];
  trustedOrigin: string;
}

export function injectSafeSpeculationRules(config: SpeculationRulesConfig): void {
  const isSafeRelativeUrl = (url: string): boolean => {
    try {
      const parsed = new URL(url, window.location.origin);
      const isExcluded = /\/(api|auth|logout|checkout|admin)(\/|$)/i.test(parsed.pathname);
      return parsed.origin === window.location.origin && !isExcluded;
    } catch {
      return false;
    }
  };

  const safePrefetch = config.prefetchUrls.filter(isSafeRelativeUrl);
  const safePrerender = config.prerenderUrls.filter(isSafeRelativeUrl);

  const rules = {
    prefetch: [
      {
        source: 'list',
        urls: safePrefetch,
        requires: ['anonymous-client-ip-when-cross-origin']
      }
    ],
    prerender: [
      {
        source: 'list',
        urls: safePrerender,
        eagerness: 'conservative'
      }
    ]
  };

  const script = document.createElement('script');
  script.type = 'speculationrules';
  script.textContent = JSON.stringify(rules);
  document.head.appendChild(script);
}
```

### Server-Side Middleware Guarding Against Speculative Side-Effects

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If a browser speculatively prerenders this GET route, user deactivation will execute silently in a speculative execution context without user intent.
```typescript
// VULNERABLE: Express/Node route executing side-effects during speculative prefetch/prerender
import { Request, Response } from 'express';

export function handleAccountDeactivation(req: Request, res: Response): void {
  // Insecure GET with side-effect vulnerable to speculative prerender execution
  const userId = req.session.userId;
  deactivateUser(userId);
  res.status(200).json({ status: 'deactivated' });
}
```

#### Production Standard (Correct)
> **Standard**: Middleware explicitly checks the Sec-Purpose header to halt speculative requests from hitting sensitive logic, and enforces non-idempotent HTTP verbs for all state modifications.
```typescript
// SECURE: Rejecting state mutation on speculative requests and verifying HTTP idempotency
import { Request, Response, NextFunction } from 'express';

export function blockSpeculativeExecution(req: Request, res: Response, next: NextFunction): void {
  const purpose = req.header('Sec-Purpose') || req.header('Purpose');
  const isSpeculative = purpose && /prerender|prefetch/i.test(purpose);

  if (isSpeculative) {
    // 503 or 425 Early Hints prevents caching or executing unprompted speculative actions
    res.status(425).set('Cache-Control', 'no-store').send('Speculative execution disallowed on this resource');
    return;
  }

  next();
}

export function handleAccountDeactivation(req: Request, res: Response): void {
  // State changes MUST require POST/DELETE with CSRF verification
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method Not Allowed' });
    return;
  }
  deactivateUser(req.session.userId);
  res.status(200).json({ status: 'deactivated' });
}
```

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: Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API

Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API defines an industrial-grade behavioral standard for frontend engineering. Enforces strict isolation, anonymous credential modes, and Sec-Purpose headers validation when using the W3C Speculation Rules API for prefetching and prerendering. Prevents cross-site information leaks (XS-Leaks), speculative timing attacks, and CSRF/state mutation via unpartitioned cross-origin speculative fetching. 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: Unrestricted Credentialed Speculative Execution Across Origins Without Partitioning Guards 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 DriftUnrestricted Credentialed Speculative Execution Across Origins Without Partitioning GuardsCritical
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 set `requires

Engineers MUST ALWAYS set `requires: ["anonymous-client-ip-when-cross-origin"]` or explicit credential omission when configuring cross-origin speculative rules.

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 configure prerender rules (`source

Engineers MUST NOT configure prerender rules (`source: "list"` or `source: "document"`) pointing to cross-origin endpoints unless the target origin explicitly serves matching `Supports-Loading-Mode: credentialed-prerender` headers and strict partitioning is acknowledged.

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 NEVER speculatively prefetch or prerender HTTP routes that perform state mutations (GET routes that trigger side-effects, session resets, or transaction writes).

Engineers MUST NEVER speculatively prefetch or prerender HTTP routes that perform state mutations (GET routes that trigger side-effects, session resets, or transaction writes).

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 SHOULD dynamically inject `<script type="speculationrules">` only after sanitizing target URLs against an explicit allowlist of idempotent, read-only origin endpoints.

Code SHOULD dynamically inject `<script type="speculationrules">` only after sanitizing target URLs against an explicit allowlist of idempotent, read-only origin endpoints.

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 inspect incoming HTTP headers for `Sec-Purpose

Services MUST inspect incoming HTTP headers for `Sec-Purpose: prefetch` or `Sec-Purpose: prerender` and drop/reject any requests that attempt side-effects, tracking increments, or authenticated state alterations during speculative execution.

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 attach wildcard speculation rules (e.g., `href_matches

Components NEVER attach wildcard speculation rules (e.g., `href_matches: "/*"`) without explicit negative selector constraints excluding logout, checkout, OAuth, and API routes.

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 Mandatory Partitioning and Credential Isolation for W3C Speculation Rules API critical for AI coding assistants?

Enforces strict isolation, anonymous credential modes, and Sec-Purpose headers validation when using the W3C Speculation Rules API for prefetching and prerendering. Prevents cross-site information leaks (XS-Leaks), speculative timing attacks, and CSRF/state mutation via unpartitioned cross-origin speculative fetching. 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 (Unrestricted Credentialed Speculative Execution Across Origins Without Partitioning Guards) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Mandatory