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

FedCM Enterprise Identity Isolation and Origin Guardrail

Enforces strict browser-mediated Federated Credential Management (FedCM) protocols across enterprise Relying Parties (RP) and Identity Providers (IdP). Eliminates fallback reliance on degraded third-party storage access or silent iframe redirect chains by anchoring cross-origin session initialization to validated FedCM manifest trust boundaries and explicit user-mediated credential assertions.

Prohibited Anti-Pattern: Silent Iframe PostMessage Loops and Third-Party Cookie Dependent SSO Flows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FedCM Enterprise Identity Isolation and Origin Guardrail - Enforces strict browser-mediated Federated Credential Management (FedCM) protocols across enterprise Relying Parties (RP) and Identity Providers (IdP). Eliminates fallback reliance on degraded third-party storage access or silent iframe redirect chains by anchoring cross-origin session initialization to validated FedCM manifest trust boundaries and explicit user-mediated credential assertions.
globs: src/**/*.{ts,tsx,js,jsx}, server/**/*.{ts,js}, routes/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fedcm-identity-isolation-standard"
---

# FedCM Enterprise Identity Isolation and Origin Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Silent Iframe PostMessage Loops and Third-Party Cookie Dependent SSO Flows

## System Constraints
You are a Principal Security Architect enforcing the Federated Credential Management (FedCM) Identity Isolation Standard. You must mandate strict adherence to browser-mediated authentication primitives via navigator.credentials.get({ identity }), validate FedCM HTTP endpoints (configURL, client_id, accounts_endpoint, id_assertion_endpoint), enforce the Sec-Fetch-Dest: webidentity and Sec-Fetch-Mode headers, and prohibit any covert iframe trackers, document.cookie state passing across origins, or unauthorized pop-up fallbacks without explicit user gestures.

## Strict Guidelines
- Engineers MUST ALWAYS verify browser FedCM availability via ('IdentityCredential' in window) before initiating federated authentication requests.
- Engineers MUST ALWAYS structure navigator.credentials.get() calls with explicit identity.providers defining the configURL, clientId, and appropriate nonce/params.
- Engineers MUST NOT rely on hidden iframes, silent token refresh loops via third-party cookies, or cross-origin Storage Access API workarounds for primary identity establishment.
- IdP endpoints (accounts, client metadata, assertion) MUST ALWAYS validate the 'Sec-Fetch-Dest: webidentity' request header and reject any request where it is absent.
- Assertion endpoints MUST ALWAYS validate that the Origin header matches the registered client_id redirect/origin domain before returning identity tokens.
- Components NEVER store FedCM-resolved identity tokens in unencrypted localStorage or accessible global browser state; tokens must be exchanged for HttpOnly, SameSite=Lax/Strict session artifacts.

## Bad vs Good Implementations
### RP-Side Authentication: Legacy Iframe Storage Access vs. FedCM Identity Mediation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on third-party cookies and cross-origin iframe postMessage channels that break under tracking protection/third-party cookie phaseout. Lacks browser-mediated origin validation, nonce verification, and user presence consent.
```typescript
export async function loginWithIdP(idpOrigin: string): Promise<string> {
  // Anti-pattern: Relying on hidden iframe and third-party cookies for silent authentication
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  iframe.src = `${idpOrigin}/auth/silent-check-sso.html`;
  document.body.appendChild(iframe);

  return new Promise((resolve, reject) => {
    const handler = (event: MessageEvent) => {
      if (event.origin !== idpOrigin) return;
      window.removeEventListener('message', handler);
      document.body.removeChild(iframe);
      if (event.data.type === 'SSO_SUCCESS') {
        // Vulnerable: Token exposed over ambient postMessage without browser-mediated consent
        localStorage.setItem('auth_token', event.data.token);
        resolve(event.data.token);
      } else {
        reject(new Error('Silent auth failed'));
      }
    };
    window.addEventListener('message', handler);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements the FedCM IdentityCredential API with mediation parameters, cryptographic nonce validation, and exchanges the assertion token via a secure first-party endpoint, completely eliminating reliance on third-party cookies.
```typescript
interface FedCMTokenResponse {
  token: string;
}

export async function loginWithFedCM(
  configUrl: string,
  clientId: string,
  nonce: string
): Promise<FedCMTokenResponse> {
  if (!('IdentityCredential' in window)) {
    throw new Error('FedCM unsupported: Redirect-based user-gesture fallback required.');
  }

  try {
    // Browser-mediated, partitioned identity request immune to third-party cookie restrictions
    const credential = (await navigator.credentials.get({
      identity: {
        context: 'signin',
        providers: [{
          configURL: configUrl,
          clientId: clientId,
          nonce: nonce
        }]
      },
      mediation: 'optional'
    })) as unknown as { token: string } | null;

    if (!credential || !credential.token) {
      throw new Error('FedCM mediation cancelled or empty credential returned.');
    }

    // Send token to backend RP session endpoint to exchange for HttpOnly cookie
    const response = await fetch('/api/auth/session', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'same-origin',
      body: JSON.stringify({ identityToken: credential.token, nonce })
    });

    if (!response.ok) {
      throw new Error(`Failed to exchange FedCM token: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    // Gracefully bubble error to trigger explicit top-level redirect flow
    throw new Error(`FedCM authentication failed: ${(error as Error).message}`);
  }
}
```

### IdP-Side Assertion Endpoint: Missing Webidentity Sec-Fetch Validation vs. Strict Header Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The endpoint does not enforce FedCM-specific security headers (Sec-Fetch-Dest: webidentity), permitting cross-origin CSRF/replay attacks from standard fetch or form submissions.
```typescript
import { Request, Response } from 'express';

export async function handleIdAssertion(req: Request, res: Response) {
  // Anti-pattern: Endpoint blindly processes identity token assertions without verifying FedCM headers
  const { client_id, account_id, nonce } = req.body;

  if (!client_id || !account_id) {
    return res.status(400).json({ error: 'Missing parameters' });
  }

  // Generates token without asserting browser-mediated fetch destination
  const token = await generateJwt({ sub: account_id, aud: client_id, nonce });
  return res.json({ token });
}
```

#### Production Standard (Correct)
> **Standard**: Validates the browser-enforced Sec-Fetch-Dest: webidentity header, verifies client origin registration against registered metadata, and returns a time-bound signed JWT with nonce assertion.
```typescript
import { Request, Response } from 'express';

interface AssertionBody {
  client_id: string;
  account_id: string;
  nonce?: string;
  disclosure_text_shown?: boolean;
}

export async function handleFedCMIdAssertion(req: Request, res: Response) {
  // 1. Mandate the browser-enforced FedCM destination header
  const secFetchDest = req.headers['sec-fetch-dest'];
  if (secFetchDest !== 'webidentity') {
    return res.status(400).json({
      error: 'invalid_request',
      error_description: 'Sec-Fetch-Dest header must be webidentity'
    });
  }

  const origin = req.headers['origin'];
  const { client_id, account_id, nonce } = req.body as AssertionBody;

  // 2. Strict Origin and Client ID cross-validation
  const client = await findRegisteredClient(client_id);
  if (!client || !origin || !client.allowedOrigins.includes(origin)) {
    return res.status(403).json({
      error: 'unauthorized_client',
      error_description: 'Origin mismatch or unregistered client_id'
    });
  }

  // 3. Issue scoped token with explicit audience and nonce to satisfy RP validation
  const token = await signFederatedAssertion({
    sub: account_id,
    aud: client_id,
    nonce: nonce ?? null,
    iss: process.env.IDP_ISSUER_URL!,
    exp: Math.floor(Date.now() / 1000) + 300
  });

  return res.status(200).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: FedCM Enterprise Identity Isolation and Origin Guardrail

FedCM Enterprise Identity Isolation and Origin Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict browser-mediated Federated Credential Management (FedCM) protocols across enterprise Relying Parties (RP) and Identity Providers (IdP). Eliminates fallback reliance on degraded third-party storage access or silent iframe redirect chains by anchoring cross-origin session initialization to validated FedCM manifest trust boundaries and explicit user-mediated credential assertions. 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: Silent Iframe PostMessage Loops and Third-Party Cookie Dependent SSO Flows 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 DriftSilent Iframe PostMessage Loops and Third-Party Cookie Dependent SSO FlowsCritical
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 browser FedCM availability via ('IdentityCredential' in window) before initiating federated authentication requests.

Engineers MUST ALWAYS verify browser FedCM availability via ('IdentityCredential' in window) before initiating federated authentication requests.

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 structure navigator.credentials.get() calls with explicit identity.providers defining the configURL, clientId, and appropriate nonce/params.

Engineers MUST ALWAYS structure navigator.credentials.get() calls with explicit identity.providers defining the configURL, clientId, and appropriate nonce/params.

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 hidden iframes, silent token refresh loops via third-party cookies, or cross-origin Storage Access API workarounds for primary identity establishment.

Engineers MUST NOT rely on hidden iframes, silent token refresh loops via third-party cookies, or cross-origin Storage Access API workarounds for primary identity establishment.

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

IdP endpoints (accounts, client metadata, assertion) MUST ALWAYS validate the 'Sec-Fetch-Dest

IdP endpoints (accounts, client metadata, assertion) MUST ALWAYS validate the 'Sec-Fetch-Dest: webidentity' request header and reject any request where it is absent.

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

Assertion endpoints MUST ALWAYS validate that the Origin header matches the registered client_id redirect/origin domain before returning identity tokens.

Assertion endpoints MUST ALWAYS validate that the Origin header matches the registered client_id redirect/origin domain before returning identity tokens.

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 store FedCM-resolved identity tokens in unencrypted localStorage or accessible global browser state

Components NEVER store FedCM-resolved identity tokens in unencrypted localStorage or accessible global browser state; tokens must be exchanged for HttpOnly, SameSite=Lax/Strict session artifacts.

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 FedCM Enterprise Identity Isolation and Origin Guardrail critical for AI coding assistants?

Enforces strict browser-mediated Federated Credential Management (FedCM) protocols across enterprise Relying Parties (RP) and Identity Providers (IdP). Eliminates fallback reliance on degraded third-party storage access or silent iframe redirect chains by anchoring cross-origin session initialization to validated FedCM manifest trust boundaries and explicit user-mediated credential assertions. 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 (Silent Iframe PostMessage Loops and Third-Party Cookie Dependent SSO Flows) 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

FedCM