This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fedcm-passkey-conditional-mediation-replay-defense-standard

FedCM & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers

Enforces mandatory single-use cryptographic nonce validation within clientDataJSON for Federated Credential Management (FedCM) and Passkey Conditional UI flows. Requires server-side verification to atomically consume assertion nonces against a distributed TTL-bounded ring buffer (e.g., Redis atomics) to definitively prevent cross-origin relay and replay attacks during silent browser identity assertions.

Prohibited Anti-Pattern: Stateless Nonce Acceptance or Non-Atomic Challenge Verification in Federated/Conditional WebAuthn Assertions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FedCM & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers - Enforces mandatory single-use cryptographic nonce validation within clientDataJSON for Federated Credential Management (FedCM) and Passkey Conditional UI flows. Requires server-side verification to atomically consume assertion nonces against a distributed TTL-bounded ring buffer (e.g., Redis atomics) to definitively prevent cross-origin relay and replay attacks during silent browser identity assertions.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,js}, api/auth/**/*.{ts,js}, lib/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fedcm-passkey-conditional-mediation-replay-defense-standard"
---

# FedCM & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stateless Nonce Acceptance or Non-Atomic Challenge Verification in Federated/Conditional WebAuthn Assertions

## System Constraints
You are a Principal Security Architect enforcing the FedCM & Passkey Conditional Mediation Replay Defense Standard. You must mandate that all passkey assertion verifications and FedCM token exchange endpoints strictly parse clientDataJSON, extract nonces/challenges, and execute an atomic consume-and-invalidate operation against a distributed TTL ring buffer before validating cryptographic signatures.

## Strict Guidelines
- Services MUST extract, UTF-8 decode, and JSON-parse `clientDataJSON` to verify that `origin` matches the expected fully qualified relying-party origin and `type` equals `webauthn.get`.
- Services MUST atomically claim assertion nonces using a distributed atomic primitive (such as a Redis Lua script with `SET NX EX` or atomic hash ring deletion) before running CPU-intensive signature verification.
- Engineers MUST NOT maintain nonce verification state solely in local process memory (e.g., in-memory `Set` or `Map`), as this fails across multi-node or serverless deployments.
- Services MUST reject assertions immediately if the decoded challenge/nonce does not exist in the distributed buffer, has expired, or was already consumed.
- Engineers MUST set a conservative Time-to-Live (TTL) between 60 to 120 seconds on conditional mediation challenges to bound replay windows.
- Components NEVER accept arbitrary or unpinned nonces supplied as separate HTTP body fields; the challenge MUST originate directly from the cryptographically bound `clientDataJSON.challenge`.

## Bad vs Good Implementations
### FedCM / Passkey Assertion Nonce Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is stored in process memory, which completely breaks in multi-container environments. Furthermore, checking challenge presence before signature validation without atomic invalidation creates a race condition where multiple concurrent requests can replay the same assertion before deletion.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

// Flawed: Local in-memory store fails across horizontal replicas;
// Nonce check is decoupled from atomic deletion, creating a race-condition replay window.
const localChallengeStore = new Set<string>();

export async function verifyPasskeyAssertionBad(req: Request) {
  const assertion = await req.json();
  const rawClientData = Buffer.from(assertion.response.clientDataJSON, 'base64url').toString('utf8');
  const clientData = JSON.parse(rawClientData);

  // VULNERABLE: In-memory check subject to multi-pod relay; no origin validation;
  // Non-atomic read-then-delete allows parallel assertion replay.
  if (!localChallengeStore.has(clientData.challenge)) {
    throw new Error('Challenge not found');
  }

  const verification = await verifyAuthenticationResponse({
    response: assertion,
    expectedChallenge: clientData.challenge,
    expectedOrigin: 'https://example.com',
    expectedRPID: 'example.com',
    authenticator: { credentialPublicKey: Buffer.from([]), counter: 0 } as any
  });

  localChallengeStore.delete(clientData.challenge);
  return verification;
}
```

#### Production Standard (Correct)
> **Standard**: Validates the challenge and origin directly within clientDataJSON, and uses a distributed Redis Lua script to atomically check-and-delete the challenge key before executing cryptographic verification, eliminating replay race conditions across distributed server clusters.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { Redis } from 'ioredis';

// Atomic consumption script: returns 1 if key existed and was deleted, 0 otherwise
const ATOMIC_CONSUME_LUA = `
if redis.call('EXISTS', KEYS[1]) == 1 then
  redis.call('DEL', KEYS[1])
  return 1
else
  return 0
end
`;

export async function verifyPasskeyAssertionGood(
  redis: Redis,
  assertion: any,
  expectedOrigin: string,
  expectedRPID: string,
  authenticator: any
) {
  // 1. Decode and strictly parse clientDataJSON
  const rawClientData = Buffer.from(assertion.response.clientDataJSON, 'base64url').toString('utf8');
  const clientData = JSON.parse(rawClientData);

  if (clientData.type !== 'webauthn.get') {
    throw new Error('Invalid assertion type');
  }

  if (clientData.origin !== expectedOrigin) {
    throw new Error(`Origin mismatch: expected ${expectedOrigin}, got ${clientData.origin}`);
  }

  const challengeNonce = clientData.challenge;
  const cacheKey = `auth:nonce:${challengeNonce}`;

  // 2. Atomic consume: distributed single-use validation prevents replay across all nodes
  const consumed = await redis.eval(ATOMIC_CONSUME_LUA, 1, cacheKey);
  if (consumed !== 1) {
    throw new Error('Assertion nonce invalid, already consumed, or expired');
  }

  // 3. Complete cryptographic verification once nonce ownership is secured
  const verification = await verifyAuthenticationResponse({
    response: assertion,
    expectedChallenge: challengeNonce,
    expectedOrigin,
    expectedRPID,
    authenticator
  });

  if (!verification.verified) {
    throw new Error('Cryptographic assertion verification failed');
  }

  return verification;
}
```

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 & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers

FedCM & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers defines an industrial-grade behavioral standard for security engineering. Enforces mandatory single-use cryptographic nonce validation within clientDataJSON for Federated Credential Management (FedCM) and Passkey Conditional UI flows. Requires server-side verification to atomically consume assertion nonces against a distributed TTL-bounded ring buffer (e.g., Redis atomics) to definitively prevent cross-origin relay and replay attacks during silent browser identity 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: Stateless Nonce Acceptance or Non-Atomic Challenge Verification in Federated/Conditional WebAuthn Assertions 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 DriftStateless Nonce Acceptance or Non-Atomic Challenge Verification in Federated/Conditional WebAuthn AssertionsCritical
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

Services MUST extract, UTF-8 decode, and JSON-parse `clientDataJSON` to verify that `origin` matches the expected fully qualified relying-party origin and `type` equals `webauthn.get`.

Services MUST extract, UTF-8 decode, and JSON-parse `clientDataJSON` to verify that `origin` matches the expected fully qualified relying-party origin and `type` equals `webauthn.get`.

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

Services MUST atomically claim assertion nonces using a distributed atomic primitive (such as a Redis Lua script with `SET NX EX` or atomic hash ring deletion) before running CPU-intensive signature verification.

Services MUST atomically claim assertion nonces using a distributed atomic primitive (such as a Redis Lua script with `SET NX EX` or atomic hash ring deletion) before running CPU-intensive signature verification.

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 maintain nonce verification state solely in local process memory (e.g., in-memory `Set` or `Map`), as this fails across multi-node or serverless deployments.

Engineers MUST NOT maintain nonce verification state solely in local process memory (e.g., in-memory `Set` or `Map`), as this fails across multi-node or serverless deployments.

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 reject assertions immediately if the decoded challenge/nonce does not exist in the distributed buffer, has expired, or was already consumed.

Services MUST reject assertions immediately if the decoded challenge/nonce does not exist in the distributed buffer, has expired, or was already consumed.

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

Engineers MUST set a conservative Time-to-Live (TTL) between 60 to 120 seconds on conditional mediation challenges to bound replay windows.

Engineers MUST set a conservative Time-to-Live (TTL) between 60 to 120 seconds on conditional mediation challenges to bound replay windows.

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 accept arbitrary or unpinned nonces supplied as separate HTTP body fields

Components NEVER accept arbitrary or unpinned nonces supplied as separate HTTP body fields; the challenge MUST originate directly from the cryptographically bound `clientDataJSON.challenge`.

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 & Passkey Conditional Mediation Replay Defense via Distributed Atomic Nonce Ring Buffers critical for AI coding assistants?

Enforces mandatory single-use cryptographic nonce validation within clientDataJSON for Federated Credential Management (FedCM) and Passkey Conditional UI flows. Requires server-side verification to atomically consume assertion nonces against a distributed TTL-bounded ring buffer (e.g., Redis atomics) to definitively prevent cross-origin relay and replay attacks during silent browser identity 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 (Stateless Nonce Acceptance or Non-Atomic Challenge Verification in Federated/Conditional WebAuthn Assertions) 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