This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fedcm-idp-partitioned-cookie-silent-token-exchange

W3C FedCM IdP Partitioned Cookie and Silent Token Exchange Guardrail

Enforces strict origin validation, Sec-Fetch-Dest verification, CHIPS-compliant partitioned cookie attributes, and constant-time responses on FedCM IdP endpoints under complete third-party cookie deprecation. Prevents cross-site timing side-channels, unauthorized account probing, and silent federated token exfiltration across untrusted Relying Parties.

Prohibited Anti-Pattern: Unvalidated cross-origin FedCM endpoints with variable-time execution and legacy third-party cookie dependency

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: W3C FedCM IdP Partitioned Cookie and Silent Token Exchange Guardrail - Enforces strict origin validation, Sec-Fetch-Dest verification, CHIPS-compliant partitioned cookie attributes, and constant-time responses on FedCM IdP endpoints under complete third-party cookie deprecation. Prevents cross-site timing side-channels, unauthorized account probing, and silent federated token exfiltration across untrusted Relying Parties.
globs: src/auth/**/*.{ts,tsx}, src/idp/**/*.{ts,tsx}, src/server/routes/fedcm/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fedcm-idp-partitioned-cookie-silent-token-exchange"
---

# W3C FedCM IdP Partitioned Cookie and Silent Token Exchange Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated cross-origin FedCM endpoints with variable-time execution and legacy third-party cookie dependency

## System Constraints
You are a Principal Security Architect enforcing the W3C FedCM (Federated Credential Management) API standard and Privacy Sandbox compliance. Mandate strict validation of Sec-Fetch-Dest headers, Relying Party (RP) origin verification, partitioned cookie attributes (CHIPS), and constant-time response mitigation to prevent timing-based cross-site account enumeration.

## Strict Guidelines
- Engineers MUST ALWAYS verify that incoming FedCM requests contain the 'Sec-Fetch-Dest: webidentity' header and explicitly reject any request omitting or spoofing this header with HTTP 400.
- Engineers MUST ALWAYS validate the incoming 'Origin' header against the registered Relying Party (RP) allowlist for the requested client ID before processing accounts or identity assertions.
- Engineers MUST NOT rely on unpartitioned third-party cookies; all authentication cookies exchanged in cross-site FedCM flows MUST specify 'Secure; HttpOnly; SameSite=None; Partitioned'.
- Services MUST enforce constant-time or padded execution on the accounts endpoint to prevent cross-site timing attacks that measure latency variations between authenticated and unauthenticated states.
- Services MUST return standard FedCM error contracts without leaking specific internal auth errors, stack traces, or granular reason codes to unverified RPs.
- Components NEVER expose silent token exchange endpoints without cryptographic nonce binding and verification against the RP's registered redirect/metadata endpoint.

## Bad vs Good Implementations
### FedCM Accounts Endpoint Handler with Timing Defense and Header Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to enforce 'Sec-Fetch-Dest: webidentity', reflects arbitrary origin headers without RP client ID registration checks, relies on unpartitioned cookies, and leaks authentication status through variable-latency early returns.
```typescript
import { Request, Response } from 'express';
import { db } from '../db';

export async function handleFedCMAccounts(req: Request, res: Response) {
  // VULNERABLE: No Sec-Fetch-Dest header check
  // VULNERABLE: Permissive CORS allowing any origin
  res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  const sessionId = req.cookies['idp_session'];
  if (!sessionId) {
    // VULNERABLE: Immediate return exposes timing differential vs DB lookup
    return res.status(401).json({ error: 'unauthenticated' });
  }

  // VULNERABLE: Unpartitioned cookie reliance, unvalidated RP origin
  const session = await db.sessions.findUnique({ where: { id: sessionId }, include: { user: true } });
  if (!session) {
    return res.status(401).json({ error: 'invalid_session' });
  }

  return res.json({
    accounts: [{
      id: session.user.id,
      name: session.user.name,
      email: session.user.email
    }]
  });
}
```

#### Production Standard (Correct)
> **Standard**: Validates 'Sec-Fetch-Dest: webidentity', verifies the RP origin against registered client records, targets '__Host-' partitioned cookies, and pads execution latency to neutralize cross-site account enumeration timing attacks.
```typescript
import { Request, Response } from 'express';
import { db } from '../db';
import { timingSafeEqual } from 'node:crypto';

const MIN_LATENCY_MS = 150;

export async function handleFedCMAccounts(req: Request, res: Response) {
  const startTime = Date.now();

  // 1. Mandatory Sec-Fetch-Dest invariant
  const fetchDest = req.headers['sec-fetch-dest'];
  if (fetchDest !== 'webidentity') {
    return res.status(400).json({ error: 'invalid_request', error_description: 'Missing Sec-Fetch-Dest: webidentity' });
  }

  // 2. Strict Origin verification against registered RP
  const origin = req.headers['origin'];
  const clientId = req.query.client_id as string;
  if (!origin || !clientId) {
    return res.status(400).json({ error: 'invalid_request' });
  }

  const registeredRp = await db.relyingParties.findUnique({ where: { clientId } });
  if (!registeredRp || registeredRp.origin !== origin) {
    return res.status(403).json({ error: 'unauthorized_client' });
  }

  res.setHeader('Access-Control-Allow-Origin', origin);
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  // 3. Partitioned Cookie resolution (CHIPS)
  const sessionId = req.cookies['__Host-idp_session'];
  let accounts: Array<{ id: string; name: string; email: string }> = [];

  if (sessionId) {
    const session = await db.sessions.findUnique({ where: { id: sessionId }, include: { user: true } });
    if (session && session.isValid) {
      accounts = [{
        id: session.user.id,
        name: session.user.name,
        email: session.user.email
      }];
    }
  }

  // 4. Timing attack defense: pad response to eliminate auth-state timing oracle
  const elapsed = Date.now() - startTime;
  if (elapsed < MIN_LATENCY_MS) {
    await new Promise((resolve) => setTimeout(resolve, MIN_LATENCY_MS - elapsed));
  }

  if (accounts.length === 0) {
    return res.status(401).json({ error: 'unauthenticated' });
  }

  return res.json({ accounts });
}
```

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 IdP Partitioned Cookie and Silent Token Exchange Guardrail

W3C FedCM IdP Partitioned Cookie and Silent Token Exchange Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict origin validation, Sec-Fetch-Dest verification, CHIPS-compliant partitioned cookie attributes, and constant-time responses on FedCM IdP endpoints under complete third-party cookie deprecation. Prevents cross-site timing side-channels, unauthorized account probing, and silent federated token exfiltration across untrusted Relying Parties. 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: Unvalidated cross-origin FedCM endpoints with variable-time execution and legacy third-party cookie dependency 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 DriftUnvalidated cross-origin FedCM endpoints with variable-time execution and legacy third-party cookie dependencyCritical
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 verify that incoming FedCM requests contain the 'Sec-Fetch-Dest

Engineers MUST ALWAYS verify that incoming FedCM requests contain the 'Sec-Fetch-Dest: webidentity' header and explicitly reject any request omitting or spoofing this header with HTTP 400.

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 ALWAYS validate the incoming 'Origin' header against the registered Relying Party (RP) allowlist for the requested client ID before processing accounts or identity assertions.

Engineers MUST ALWAYS validate the incoming 'Origin' header against the registered Relying Party (RP) allowlist for the requested client ID before processing accounts or identity assertions.

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 rely on unpartitioned third-party cookies

Engineers MUST NOT rely on unpartitioned third-party cookies; all authentication cookies exchanged in cross-site FedCM flows MUST specify 'Secure; HttpOnly; SameSite=None; Partitioned'.

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 enforce constant-time or padded execution on the accounts endpoint to prevent cross-site timing attacks that measure latency variations between authenticated and unauthenticated states.

Services MUST enforce constant-time or padded execution on the accounts endpoint to prevent cross-site timing attacks that measure latency variations between authenticated and unauthenticated states.

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 return standard FedCM error contracts without leaking specific internal auth errors, stack traces, or granular reason codes to unverified RPs.

Services MUST return standard FedCM error contracts without leaking specific internal auth errors, stack traces, or granular reason codes to unverified RPs.

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 expose silent token exchange endpoints without cryptographic nonce binding and verification against the RP's registered redirect/metadata endpoint.

Components NEVER expose silent token exchange endpoints without cryptographic nonce binding and verification against the RP's registered redirect/metadata endpoint.

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 IdP Partitioned Cookie and Silent Token Exchange Guardrail critical for AI coding assistants?

Enforces strict origin validation, Sec-Fetch-Dest verification, CHIPS-compliant partitioned cookie attributes, and constant-time responses on FedCM IdP endpoints under complete third-party cookie deprecation. Prevents cross-site timing side-channels, unauthorized account probing, and silent federated token exfiltration across untrusted Relying Parties. 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 (Unvalidated cross-origin FedCM endpoints with variable-time execution and legacy third-party cookie dependency) 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