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

W3C FedCM Browser-Enforced IdP Sandbox and Token Relay Invariant

Enforces strict browser-mediated identity assertion handoffs using the W3C Federated Credential Management (FedCM) API. Eliminates silent iframe postMessage hacks and covert link-decoration tracking vectors, guaranteeing that Relying Party and Identity Provider token exchanges execute exclusively via browser-sandboxed origin boundaries with verified 'Sec-Fetch-Dest: webidentity' constraints.

Prohibited Anti-Pattern: Bypassing FedCM with Silent Hidden iFrames, Dynamic Link Decoration, or Unverified Token PostMessage Channels

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: W3C FedCM Browser-Enforced IdP Sandbox and Token Relay Invariant - Enforces strict browser-mediated identity assertion handoffs using the W3C Federated Credential Management (FedCM) API. Eliminates silent iframe postMessage hacks and covert link-decoration tracking vectors, guaranteeing that Relying Party and Identity Provider token exchanges execute exclusively via browser-sandboxed origin boundaries with verified 'Sec-Fetch-Dest: webidentity' constraints.
globs: src/auth/**/*.{ts,tsx,js}, src/services/identity/**/*.{ts,js}, src/controllers/auth/**/*.{ts,js}, src/middleware/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fedcm-browser-idp-sandbox-token-relay"
---

# W3C FedCM Browser-Enforced IdP Sandbox and Token Relay Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Bypassing FedCM with Silent Hidden iFrames, Dynamic Link Decoration, or Unverified Token PostMessage Channels

## System Constraints
You are a Principal Security Architect enforcing the W3C FedCM Browser-Enforced IdP Sandbox and Token Relay Invariant. Your responsibility is to strictly eliminate fallback mechanisms relying on third-party cookies, silent iframe embedding, and query-parameter token relays. Mandate browser-mediated navigator.credentials.get identity assertions, enforce IdP server-side origin and Sec-Fetch-Dest header validation, and ensure all token exchanges conform to unalterable browser mediation boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS invoke `navigator.credentials.get()` with explicit `identity.providers` configuration for federated single sign-on rather than instantiating hidden iframes or script injections.
- Engineers MUST NOT implement fallback authentication flows that rely on third-party cookie access, partitioned iframe popups, or covert session pinging.
- IdP endpoints (token, accounts, and client metadata) MUST strictly validate the presence of the `Sec-Fetch-Dest: webidentity` request header and reject requests without it with HTTP 400 or 403.
- Services MUST validate the `Origin` and `Referer` headers against the registered Relying Party `client_id` inside the `id_assertion_endpoint` before issuing identity assertions.
- Components NEVER store or relay transient FedCM identity tokens across non-browser-mediated channels such as URL hash fragments, window postMessage relays, or unencrypted local storage.

## Bad vs Good Implementations
### Relying Party Authentication Handoff and IdP Server-Side Assertion Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example utilizes hidden iframes and cross-window postMessage listeners. This relies on third-party cookie persistence, enables cross-site user tracking via link decoration ('session_sync=true'), and fails to enforce browser-mediated isolation. The IdP server endpoint omits mandatory `Sec-Fetch-Dest: webidentity` validation.
```typescript
import { Request, Response } from 'express';

// Anti-pattern: Client uses silent iframe fallback and custom postMessage
export async function clientSideLogin() {
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  // Relies on 3P cookies and covert tracking link-decoration
  iframe.src = 'https://idp.example.com/auth/silent-check?client_id=rp_123&session_sync=true';
  document.body.appendChild(iframe);

  return new Promise((resolve) => {
    window.addEventListener('message', (event) => {
      // Insecure cross-origin postMessage reception
      if (event.data?.token) {
        resolve(event.data.token);
      }
    });
  });
}

// Anti-pattern: Server blindly returns token without FedCM header assertion
export async function idpAssertionEndpoint(req: Request, res: Response) {
  const { client_id, account_id } = req.body;
  // Missing Sec-Fetch-Dest verification; vulnerable to CSRF and cross-site scraping
  const token = generateIdToken(client_id, account_id);
  return res.json({ token });
}
```

#### Production Standard (Correct)
> **Standard**: The good example utilizes the standard browser `navigator.credentials.get` FedCM interface, which mediates identity retrieval directly within the user agent sandbox without exposing third-party cookies or permitting silent tracking. The IdP endpoint validates `Sec-Fetch-Dest: webidentity` and matches the browser origin against registered Relying Party configurations.
```typescript
import { Request, Response } from 'express';

// Compliant: Browser-mediated FedCM API identity request
export async function clientSideLogin(): Promise<string> {
  if (!('IdentityCredential' in window)) {
    throw new Error('FedCM is required for federated authentication; legacy third-party cookie fallbacks are disallowed.');
  }

  const credential = await navigator.credentials.get({
    identity: {
      context: 'signin',
      providers: [{
        configURL: 'https://idp.example.com/fedcm.json',
        clientId: 'rp_123',
        nonce: crypto.randomUUID(),
      }],
    },
  }) as unknown as { token: string } | null;

  if (!credential?.token) {
    throw new Error('Identity assertion rejected or failed by user mediation');
  }

  return credential.token;
}

// Compliant: IdP assertion endpoint validating FedCM browser security invariants
export async function idpAssertionEndpoint(req: Request, res: Response) {
  const secFetchDest = req.headers['sec-fetch-dest'];
  const origin = req.headers['origin'];
  
  if (secFetchDest !== 'webidentity') {
    return res.status(403).json({ error: 'invalid_request', error_description: 'Request must originate from FedCM browser mediation' });
  }

  const { client_id, account_id, nonce } = req.body;
  if (!origin || !isAllowedOriginForClient(client_id, origin)) {
    return res.status(400).json({ error: 'unauthorized_client', error_description: 'Origin mismatch for client_id' });
  }

  const token = generateIdToken(client_id, account_id, nonce);
  return res.json({ token });
}
```

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 Browser-Enforced IdP Sandbox and Token Relay Invariant

W3C FedCM Browser-Enforced IdP Sandbox and Token Relay Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict browser-mediated identity assertion handoffs using the W3C Federated Credential Management (FedCM) API. Eliminates silent iframe postMessage hacks and covert link-decoration tracking vectors, guaranteeing that Relying Party and Identity Provider token exchanges execute exclusively via browser-sandboxed origin boundaries with verified 'Sec-Fetch-Dest: webidentity' constraints. 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: Bypassing FedCM with Silent Hidden iFrames, Dynamic Link Decoration, or Unverified Token PostMessage Channels 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 DriftBypassing FedCM with Silent Hidden iFrames, Dynamic Link Decoration, or Unverified Token PostMessage ChannelsCritical
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 invoke `navigator.credentials.get()` with explicit `identity.providers` configuration for federated single sign-on rather than instantiating hidden iframes or script injections.

Engineers MUST ALWAYS invoke `navigator.credentials.get()` with explicit `identity.providers` configuration for federated single sign-on rather than instantiating hidden iframes or script injections.

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 implement fallback authentication flows that rely on third-party cookie access, partitioned iframe popups, or covert session pinging.

Engineers MUST NOT implement fallback authentication flows that rely on third-party cookie access, partitioned iframe popups, or covert session pinging.

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 endpoints (token, accounts, and client metadata) MUST strictly validate the presence of the `Sec-Fetch-Dest

IdP endpoints (token, accounts, and client metadata) MUST strictly validate the presence of the `Sec-Fetch-Dest: webidentity` request header and reject requests without it with HTTP 400 or 403.

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 validate the `Origin` and `Referer` headers against the registered Relying Party `client_id` inside the `id_assertion_endpoint` before issuing identity assertions.

Services MUST validate the `Origin` and `Referer` headers against the registered Relying Party `client_id` inside the `id_assertion_endpoint` before issuing 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.
5

Components NEVER store or relay transient FedCM identity tokens across non-browser-mediated channels such as URL hash fragments, window postMessage relays, or unencrypted local storage.

Components NEVER store or relay transient FedCM identity tokens across non-browser-mediated channels such as URL hash fragments, window postMessage relays, or unencrypted local storage.

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 Browser-Enforced IdP Sandbox and Token Relay Invariant critical for AI coding assistants?

Enforces strict browser-mediated identity assertion handoffs using the W3C Federated Credential Management (FedCM) API. Eliminates silent iframe postMessage hacks and covert link-decoration tracking vectors, guaranteeing that Relying Party and Identity Provider token exchanges execute exclusively via browser-sandboxed origin boundaries with verified 'Sec-Fetch-Dest: webidentity' constraints. 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 (Bypassing FedCM with Silent Hidden iFrames, Dynamic Link Decoration, or Unverified Token PostMessage Channels) 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