This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fedcm-multi-idp-disconnect-autoreauth-boundary

FedCM Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement

Enforces cryptographically bound nonces, explicit IdentityCredential.disconnect invocations upon session revocation, and strict mediation policy controls across Multi-IdP FedCM flows. Prevents cross-account token fixation, unauthenticated auto-reauth bypasses, and cross-site tracking across federated identity boundaries.

Prohibited Anti-Pattern: Permissive Multi-IdP Auto-Reauth without Nonce Binding and Missing IdentityCredential.disconnect Cleanup

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FedCM Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement - Enforces cryptographically bound nonces, explicit IdentityCredential.disconnect invocations upon session revocation, and strict mediation policy controls across Multi-IdP FedCM flows. Prevents cross-account token fixation, unauthenticated auto-reauth bypasses, and cross-site tracking across federated identity boundaries.
globs: src/auth/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/lib/fedcm/**/*.{ts,tsx}, src/hooks/useFedCM.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fedcm-multi-idp-disconnect-autoreauth-boundary"
---

# FedCM Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive Multi-IdP Auto-Reauth without Nonce Binding and Missing IdentityCredential.disconnect Cleanup

## System Constraints
You are a Principal Software Architect enforcing W3C FedCM Multi-IdP Disconnect & Auto-Reauth Token Boundary invariants. Mandate cryptographic nonce generation, strict IdP configURL validation against an immutable allowlist, explicit IdentityCredential.disconnect() teardown on RP logout, and strict mediation mode isolation to prevent token fixation and silent cross-site tracking.

## Strict Guidelines
- Engineers MUST ALWAYS generate and bind a cryptographically secure, single-use nonce via crypto.getRandomValues() to every FedCM IdentityProviderRequestOptions entry.
- Engineers MUST ALWAYS invoke IdentityCredential.disconnect() during RP logout or IdP account unlinking to invalidate the browser's FedCM permission boundary with the IdP.
- Engineers MUST NOT accept FedCM credentials without verifying the returned token's configURL and issuer against a strictly typed RP provider allowlist.
- Engineers MUST explicitly enforce mediation: 'required' for step-up authentication or account switching to block silent auto-reauth hijack attacks.
- Services MUST perform server-side verification of the assertion token (signature, audience, issuer, expiry, and nonce) before establishing a persisted session.

## Bad vs Good Implementations
### FedCM Multi-IdP Request and Disconnect Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits cryptographic nonces, allowing token fixation and replay attacks. Uses unconstrained mediation without validating whether auto-reauth is safe. Fails to call IdentityCredential.disconnect() during logout, leaving the browser-IdP connection active and permitting unauthorized silent re-authentication on subsequent visits.
```typescript
import { useState } from 'react';

export async function loginWithFedCM() {
  // VULNERABLE: No nonces, unconstrained mediation, no configURL verification
  const credential = await navigator.credentials.get({
    identity: {
      providers: [
        { configURL: 'https://idp1.example.com/fedcm.json', clientId: 'rp-client-1' },
        { configURL: 'https://idp2.example.com/fedcm.json', clientId: 'rp-client-2' },
      ],
    },
    mediation: 'optional', // Allows silent auto-reauth without session continuity validation
  }) as any;

  if (credential) {
    // Trusts client token without checking origin or matching against active state
    await fetch('/api/auth/callback', {
      method: 'POST',
      body: JSON.stringify({ token: credential.token }),
    });
  }
}

export async function logout() {
  // VULNERABLE: RP session wiped, but FedCM IdP connection remains active
  // Allows silent auto-reauth to resurrect the session on next visit
  await fetch('/api/auth/logout', { method: 'POST' });
  window.location.reload();
}
```

#### Production Standard (Correct)
> **Standard**: Implements an immutable IdP allowlist, attaches unique cryptographically random nonces to all provider options, strictly gates mediation modes based on authentication context, and invokes IdentityCredential.disconnect() with proper account hinting during logout to tear down browser-mediated IdP state.
```typescript
const TRUSTED_IDP_CONFIGS = Object.freeze({
  IDP_ONE: 'https://idp1.example.com/fedcm.json',
  IDP_TWO: 'https://idp2.example.com/fedcm.json',
} as const);

type SupportedIdP = (typeof TRUSTED_IDP_CONFIGS)[keyof typeof TRUSTED_IDP_CONFIGS];

interface FedCMAuthResult {
  token: string;
  nonce: string;
  configURL: SupportedIdP;
}

function generateCryptographicNonce(): string {
  const bytes = new Uint8Array(32);
  crypto.getRandomValues(bytes);
  return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}

export async function loginWithFedCM(stepUpRequired = false): Promise<FedCMAuthResult> {
  if (!('IdentityCredential' in window)) {
    throw new Error('FedCM is not supported in this browser environment');
  }

  const sessionNonce = generateCryptographicNonce();
  // Store transient nonce in session storage to verify upon server round-trip
  sessionStorage.setItem('fedcm_active_nonce', sessionNonce);

  const providers = [
    { configURL: TRUSTED_IDP_CONFIGS.IDP_ONE, clientId: 'rp-client-1', nonce: sessionNonce },
    { configURL: TRUSTED_IDP_CONFIGS.IDP_TWO, clientId: 'rp-client-2', nonce: sessionNonce },
  ];

  const credential = (await navigator.credentials.get({
    identity: {
      providers,
      context: 'signin',
    },
    // Enforce interactive prompt if step-up required; otherwise require explicit consent
    mediation: stepUpRequired ? 'required' : 'conditional',
  })) as (Credential & { token: string; configURL?: string }) | null;

  if (!credential || !credential.token) {
    throw new Error('FedCM authentication cancelled or failed');
  }

  const selectedProvider = providers.find((p) => p.configURL === credential.configURL);
  if (!selectedProvider) {
    throw new Error('Untrusted or unrequested IdP returned from FedCM mediation');
  }

  return {
    token: credential.token,
    nonce: sessionNonce,
    configURL: selectedProvider.configURL as SupportedIdP,
  };
}

export async function logoutAndDisconnectIdP(configURL: SupportedIdP, accountHint: string): Promise<void> {
  try {
    if ('IdentityCredential' in window && 'disconnect' in (window as any).IdentityCredential) {
      await (window as any).IdentityCredential.disconnect({
        configURL,
        clientId: configURL === TRUSTED_IDP_CONFIGS.IDP_ONE ? 'rp-client-1' : 'rp-client-2',
        accountHint,
      });
    }
  } finally {
    sessionStorage.removeItem('fedcm_active_nonce');
    await fetch('/api/auth/logout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ configURL, accountHint }),
    });
  }
}
```

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 Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement

FedCM Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces cryptographically bound nonces, explicit IdentityCredential.disconnect invocations upon session revocation, and strict mediation policy controls across Multi-IdP FedCM flows. Prevents cross-account token fixation, unauthenticated auto-reauth bypasses, and cross-site tracking across federated identity boundaries. 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: Permissive Multi-IdP Auto-Reauth without Nonce Binding and Missing IdentityCredential.disconnect Cleanup 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 DriftPermissive Multi-IdP Auto-Reauth without Nonce Binding and Missing IdentityCredential.disconnect CleanupCritical
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 generate and bind a cryptographically secure, single-use nonce via crypto.getRandomValues() to every FedCM IdentityProviderRequestOptions entry.

Engineers MUST ALWAYS generate and bind a cryptographically secure, single-use nonce via crypto.getRandomValues() to every FedCM IdentityProviderRequestOptions entry.

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 invoke IdentityCredential.disconnect() during RP logout or IdP account unlinking to invalidate the browser's FedCM permission boundary with the IdP.

Engineers MUST ALWAYS invoke IdentityCredential.disconnect() during RP logout or IdP account unlinking to invalidate the browser's FedCM permission boundary with the IdP.

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 accept FedCM credentials without verifying the returned token's configURL and issuer against a strictly typed RP provider allowlist.

Engineers MUST NOT accept FedCM credentials without verifying the returned token's configURL and issuer against a strictly typed RP provider allowlist.

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

Engineers MUST explicitly enforce mediation

Engineers MUST explicitly enforce mediation: 'required' for step-up authentication or account switching to block silent auto-reauth hijack attacks.

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 perform server-side verification of the assertion token (signature, audience, issuer, expiry, and nonce) before establishing a persisted session.

Services MUST perform server-side verification of the assertion token (signature, audience, issuer, expiry, and nonce) before establishing a persisted session.

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 Multi-IdP Disconnect & Auto-Reauth Token Boundary Enforcement critical for AI coding assistants?

Enforces cryptographically bound nonces, explicit IdentityCredential.disconnect invocations upon session revocation, and strict mediation policy controls across Multi-IdP FedCM flows. Prevents cross-account token fixation, unauthenticated auto-reauth bypasses, and cross-site tracking across federated identity boundaries. 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 (Permissive Multi-IdP Auto-Reauth without Nonce Binding and Missing IdentityCredential.disconnect Cleanup) 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