This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: w3c-fedcm-identity-assertion-sandboxing-guardrail

W3C FedCM Assertion Sandboxing & Anti-Tracking Guardrail

Enforces strict origin isolation, cryptographic nonce binding, and deterministic timing protections when interacting with the W3C Federated Credential Management (FedCM) API. Eliminates silent cross-site timing deanonymization while maintaining Enterprise SSO session continuity without fallback to third-party or partitioned cookies.

Prohibited Anti-Pattern: Unsandboxed FedCM Invocation with Leaked RP Context and Timing-Dependent Assertion Responses

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: W3C FedCM Assertion Sandboxing & Anti-Tracking Guardrail - Enforces strict origin isolation, cryptographic nonce binding, and deterministic timing protections when interacting with the W3C Federated Credential Management (FedCM) API. Eliminates silent cross-site timing deanonymization while maintaining Enterprise SSO session continuity without fallback to third-party or partitioned cookies.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,js}, pages/api/**/*.{ts,js}, app/api/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/w3c-fedcm-identity-assertion-sandboxing-guardrail"
---

# W3C FedCM Assertion Sandboxing & Anti-Tracking Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unsandboxed FedCM Invocation with Leaked RP Context and Timing-Dependent Assertion Responses

## System Constraints
You are a Principal Security Architect enforcing W3C FedCM Identity Assertion Context Sandboxing. Mandate strict cryptographic nonce generation, context enumeration, rigorous validation of 'Sec-Fetch-Dest: webidentity', and deterministic response times on identity assertion endpoints to completely eliminate cross-site tracking and timing side-channels.

## Strict Guidelines
- Engineers MUST ALWAYS supply a cryptographically secure, single-use, high-entropy nonce in 'navigator.credentials.get({ identity: ... })' to guarantee replay prevention and bind the assertion to the client execution context.
- Engineers MUST NOT rely on ambient storage, silent iframe pings, or partitioned third-party cookies (CHIPS) as fallbacks when FedCM is supported by the client user agent.
- IdP Identity Assertion endpoints MUST ALWAYS reject requests lacking the 'Sec-Fetch-Dest: webidentity' and strict 'Origin' headers with an immediate HTTP 400/403 status prior to any database lookups.
- Services MUST execute identity assertion token lookups and cryptographic signature verifications within constant-time bounds (or artificial uniform delay windows) to prevent timing-based user enumeration by malicious Relying Parties.
- Components NEVER pass unvalidated query parameters, dynamic URLs, or unvetted RP-state strings directly into the FedCM 'clientId' or 'context' configuration properties.

## Bad vs Good Implementations
### FedCM Assertion Request & Server-Side WebIdentity Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits cryptographic nonces, fails to declare assertion context, and attempts a silent iframe-based fallback that leaks user browsing presence through cookies and network timing vectors.
```typescript
// VULNERABLE: Lacks cryptographic nonce, uses silent fallback to tracking cookies,
// and does not sandbox invocation context or handle timing side-channels.
export async function authenticateEnterpriseUser(idpConfigUrl: string, clientId: string) {
  try {
    const credential = await navigator.credentials.get({
      identity: {
        providers: [{
          configURL: idpConfigUrl,
          clientId: clientId
        }]
      }
    }) as any;
    return credential?.token;
  } catch (err) {
    // Anti-pattern: Silently falls back to an iframe pinging partitioned cookies
    const iframe = document.createElement('iframe');
    iframe.src = `https://idp.enterprise.com/silent-login?clientId=${clientId}`;
    document.body.appendChild(iframe);
    return null;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit 256-bit nonce bound to the session, enforces `mediation: 'conditional'` with context sandboxing, uses an AbortController to enforce deterministic timeouts, explicitly rejects legacy iframe/3PC tracking fallbacks, and validates the `Sec-Fetch-Dest: webidentity` protocol header on the backend.
```typescript
// SECURE: Nonce-bound assertion, strict context sandboxing, AbortController timeout,
// and explicit enforcement of FedCM webidentity architecture without tracking fallbacks.
export interface FedCMAuthResult {
  token: string;
  nonce: string;
}

export async function authenticateEnterpriseUser(
  idpConfigUrl: string,
  clientId: string,
  timeoutMs: number = 30000
): Promise<FedCMAuthResult> {
  if (!('IdentityCredential' in window) || !navigator.credentials?.get) {
    throw new Error('FedCM unsupported: Ambient cookie fallback strictly forbidden');
  }

  // Generate high-entropy 256-bit cryptographically secure nonce
  const nonceBytes = new Uint8Array(32);
  window.crypto.getRandomValues(nonceBytes);
  const nonce = Array.from(nonceBytes, (b) => b.toString(16).padStart(2, '0')).join('');

  const controller = new AbortController();
  const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const credential = await navigator.credentials.get({
      signal: controller.signal,
      mediation: 'conditional',
      identity: {
        context: 'signin',
        providers: [{
          configURL: idpConfigUrl,
          clientId: clientId,
          nonce: nonce
        }]
      }
    }) as { token?: string } | null;

    if (!credential?.token) {
      throw new Error('Identity assertion rejected or empty');
    }

    return { token: credential.token, nonce };
  } finally {
    clearTimeout(timeoutHandle);
  }
}

// Backend Guardrail (Node.js/Next.js/Express Handler for id_assertion_endpoint)
import type { IncomingMessage, ServerResponse } from 'http';
import crypto from 'node:crypto';

export function validateFedCMAssertionRequest(req: IncomingMessage, res: ServerResponse): boolean {
  const secFetchDest = req.headers['sec-fetch-dest'];
  const origin = req.headers['origin'];

  // Strict invariant: Browser MUST send sec-fetch-dest: webidentity
  if (secFetchDest !== 'webidentity' || !origin) {
    res.writeHead(400, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'invalid_request', error_description: 'Missing Sec-Fetch-Dest header' }));
    return false;
  }
  return true;
}
```

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 FedCM Assertion Sandboxing & Anti-Tracking Guardrail

W3C FedCM Assertion Sandboxing & Anti-Tracking Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict origin isolation, cryptographic nonce binding, and deterministic timing protections when interacting with the W3C Federated Credential Management (FedCM) API. Eliminates silent cross-site timing deanonymization while maintaining Enterprise SSO session continuity without fallback to third-party or partitioned cookies. 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: Unsandboxed FedCM Invocation with Leaked RP Context and Timing-Dependent Assertion Responses 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 DriftUnsandboxed FedCM Invocation with Leaked RP Context and Timing-Dependent Assertion ResponsesCritical
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 supply a cryptographically secure, single-use, high-entropy nonce in 'navigator.credentials.get({ identity

Engineers MUST ALWAYS supply a cryptographically secure, single-use, high-entropy nonce in 'navigator.credentials.get({ identity: ... })' to guarantee replay prevention and bind the assertion to the client execution context.

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 rely on ambient storage, silent iframe pings, or partitioned third-party cookies (CHIPS) as fallbacks when FedCM is supported by the client user agent.

Engineers MUST NOT rely on ambient storage, silent iframe pings, or partitioned third-party cookies (CHIPS) as fallbacks when FedCM is supported by the client user agent.

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

IdP Identity Assertion endpoints MUST ALWAYS reject requests lacking the 'Sec-Fetch-Dest

IdP Identity Assertion endpoints MUST ALWAYS reject requests lacking the 'Sec-Fetch-Dest: webidentity' and strict 'Origin' headers with an immediate HTTP 400/403 status prior to any database lookups.

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 execute identity assertion token lookups and cryptographic signature verifications within constant-time bounds (or artificial uniform delay windows) to prevent timing-based user enumeration by malicious Relying Parties.

Services MUST execute identity assertion token lookups and cryptographic signature verifications within constant-time bounds (or artificial uniform delay windows) to prevent timing-based user enumeration by malicious Relying Parties.

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 pass unvalidated query parameters, dynamic URLs, or unvetted RP-state strings directly into the FedCM 'clientId' or 'context' configuration properties.

Components NEVER pass unvalidated query parameters, dynamic URLs, or unvetted RP-state strings directly into the FedCM 'clientId' or 'context' configuration properties.

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 FedCM Assertion Sandboxing & Anti-Tracking Guardrail critical for AI coding assistants?

Enforces strict origin isolation, cryptographic nonce binding, and deterministic timing protections when interacting with the W3C Federated Credential Management (FedCM) API. Eliminates silent cross-site timing deanonymization while maintaining Enterprise SSO session continuity without fallback to third-party or partitioned cookies. 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 (Unsandboxed FedCM Invocation with Leaked RP Context and Timing-Dependent Assertion Responses) 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