This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-conditional-mediation-nonce-boundary

WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary

Enforces strict cryptographic coupling of server-issued challenge nonces to client transport bindings and canonical relying party origins during WebAuthn conditional mediation (autofill). Prevents passkey replay, cross-origin assertion injection, and passkey phishing across embedded frames or shared origin boundaries.

Prohibited Anti-Pattern: Decoupled Challenge Verification and Permissive Origin Matching in Autofill Passkey Assertions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary - Enforces strict cryptographic coupling of server-issued challenge nonces to client transport bindings and canonical relying party origins during WebAuthn conditional mediation (autofill). Prevents passkey replay, cross-origin assertion injection, and passkey phishing across embedded frames or shared origin boundaries.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/services/webauthn/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-nonce-boundary"
---

# WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Decoupled Challenge Verification and Permissive Origin Matching in Autofill Passkey Assertions

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary. You must ensure all passkey assertion ceremonies initiated via conditional mediation ('mediation: conditional') cryptographically bind server challenges to session identifiers and strictly validate clientDataJSON origins, RP IDs, and challenge consumption atomically.

## Strict Guidelines
- Engineers MUST ALWAYS cryptographically bind WebAuthn challenge nonces to the client session or transport-layer context using an HMAC or ephemeral session store with a maximum TTL of 60 seconds.
- Engineers MUST atomically consume challenge nonces on the server using single-use primitive operations (e.g., Redis GETDEL or atomic database transitions) prior to signature validation to eliminate replay attacks.
- Services MUST verify that clientDataJSON.type is strictly 'webauthn.get' and clientDataJSON.origin exactly matches the server's canonical origin, rejecting regex approximations, wildcard domains, or scheme downgrades.
- Services MUST evaluate authenticatorData flags to ensure the User Presence (UP) bit is set to 1, and verify the User Verification (UV) flag meets the Relying Party policy even under conditional autofill UI.
- Components NEVER trigger navigator.credentials.get({ mediation: 'conditional' }) using pre-generated static nonces or unauthenticated cross-origin challenge endpoints.

## Bad vs Good Implementations
### Conditional Mediation Challenge Generation & Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is decoupled from the user's session identifier, permitting an attacker to relay challenges across parallel browser contexts. The origin check uses String.includes, allowing phishing domains like 'example.com.attacker.com'. Additionally, the challenge is deleted post-verification instead of atomically consumed prior to processing.
```typescript
import { Request, Response } from 'express';

// INSECURE: Challenge is not bound to session; origin is checked with loose substring
const challenges = new Map<string, string>();

export async function handleAssertion(req: Request, res: Response) {
  const { credential, clientDataJSONRaw } = req.body;
  const clientData = JSON.parse(Buffer.from(clientDataJSONRaw, 'base64url').toString('utf8'));

  // Flaw 1: Decoupled challenge lookup from client payload without session binding
  const storedChallenge = challenges.get(clientData.challenge);
  if (!storedChallenge) {
    return res.status(401).json({ error: 'Invalid challenge' });
  }

  // Flaw 2: Permissive substring origin check allows attacker-controlled origins
  if (!clientData.origin.includes('example.com')) {
    return res.status(403).json({ error: 'Origin mismatch' });
  }

  // Flaw 3: Nonce not consumed atomically before signature check (replay window)
  // ... verify signature ...
  challenges.delete(clientData.challenge);

  return res.json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: The solution binds the ephemeral challenge to the specific authenticated session key using Redis GETDEL for single-use consumption. It enforces exact canonical origin equality ('https://auth.example.com'), constant-time buffer comparison to prevent timing attacks, and validates both the SHA-256 RP ID hash and the User Presence flag in authenticatorData.
```typescript
import { Request, Response } from 'express';
import crypto from 'node:crypto';
import { Redis } from 'ioredis';

interface AuthenticatorAssertionResponse {
  id: string;
  rawId: string;
  response: {
    authenticatorData: string;
    clientDataJSON: string;
    signature: string;
    userHandle?: string;
  };
  type: 'public-key';
}

const EXPECTED_ORIGIN = 'https://auth.example.com';
const EXPECTED_RP_ID = 'example.com';
const CHALLENGE_PREFIX = 'webauthn:challenge:';

export async function verifyConditionalAssertion(
  req: Request,
  res: Response,
  redis: Redis
) {
  const sessionId = req.session?.id;
  if (!sessionId) {
    return res.status(401).json({ error: 'Unauthenticated session boundary' });
  }

  const assertion = req.body as AuthenticatorAssertionResponse;
  const clientDataRaw = Buffer.from(assertion.response.clientDataJSON, 'base64url');
  const clientData = JSON.parse(clientDataRaw.toString('utf8'));

  if (clientData.type !== 'webauthn.get') {
    return res.status(400).json({ error: 'Invalid ceremony type' });
  }

  // Invariant 1: Exact canonical origin equivalence check
  if (clientData.origin !== EXPECTED_ORIGIN) {
    return res.status(403).json({ error: 'Origin attestation boundary violation' });
  }

  // Invariant 2: Atomic challenge retrieval and consumption bound to session context
  const challengeKey = `${CHALLENGE_PREFIX}${sessionId}`;
  const expectedChallenge = await redis.getdel(challengeKey);

  if (!expectedChallenge) {
    return res.status(401).json({ error: 'Challenge expired, missing, or already consumed' });
  }

  // Invariant 3: Constant-time comparison of challenge nonces
  const clientChallengeBuffer = Buffer.from(clientData.challenge, 'base64url');
  const expectedChallengeBuffer = Buffer.from(expectedChallenge, 'base64url');

  if (
    clientChallengeBuffer.length !== expectedChallengeBuffer.length ||
    !crypto.timingSafeEqual(clientChallengeBuffer, expectedChallengeBuffer)
  ) {
    return res.status(401).json({ error: 'Cryptographic challenge mismatch' });
  }

  // Invariant 4: Validate authenticatorData flags (RP ID hash and UP bit)
  const authData = Buffer.from(assertion.response.authenticatorData, 'base64url');
  const rpIdHash = authData.subarray(0, 32);
  const expectedRpIdHash = crypto.createHash('sha256').update(EXPECTED_RP_ID).digest();

  if (!crypto.timingSafeEqual(rpIdHash, expectedRpIdHash)) {
    return res.status(403).json({ error: 'RP ID attestation mismatch' });
  }

  const flags = authData[32];
  const userPresence = (flags & 0x01) !== 0;
  if (!userPresence) {
    return res.status(403).json({ error: 'User Presence (UP) flag required' });
  }

  return res.json({ verified: true });
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary

WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic coupling of server-issued challenge nonces to client transport bindings and canonical relying party origins during WebAuthn conditional mediation (autofill). Prevents passkey replay, cross-origin assertion injection, and passkey phishing across embedded frames or shared origin 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: Decoupled Challenge Verification and Permissive Origin Matching in Autofill Passkey 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 DriftDecoupled Challenge Verification and Permissive Origin Matching in Autofill Passkey 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

Engineers MUST ALWAYS cryptographically bind WebAuthn challenge nonces to the client session or transport-layer context using an HMAC or ephemeral session store with a maximum TTL of 60 seconds.

Engineers MUST ALWAYS cryptographically bind WebAuthn challenge nonces to the client session or transport-layer context using an HMAC or ephemeral session store with a maximum TTL of 60 seconds.

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 atomically consume challenge nonces on the server using single-use primitive operations (e.g., Redis GETDEL or atomic database transitions) prior to signature validation to eliminate replay attacks.

Engineers MUST atomically consume challenge nonces on the server using single-use primitive operations (e.g., Redis GETDEL or atomic database transitions) prior to signature validation to eliminate replay 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.
3

Services MUST verify that clientDataJSON.type is strictly 'webauthn.get' and clientDataJSON.origin exactly matches the server's canonical origin, rejecting regex approximations, wildcard domains, or scheme downgrades.

Services MUST verify that clientDataJSON.type is strictly 'webauthn.get' and clientDataJSON.origin exactly matches the server's canonical origin, rejecting regex approximations, wildcard domains, or scheme downgrades.

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 evaluate authenticatorData flags to ensure the User Presence (UP) bit is set to 1, and verify the User Verification (UV) flag meets the Relying Party policy even under conditional autofill UI.

Services MUST evaluate authenticatorData flags to ensure the User Presence (UP) bit is set to 1, and verify the User Verification (UV) flag meets the Relying Party policy even under conditional autofill UI.

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 trigger navigator.credentials.get({ mediation

Components NEVER trigger navigator.credentials.get({ mediation: 'conditional' }) using pre-generated static nonces or unauthenticated cross-origin challenge endpoints.

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 WebAuthn Conditional Mediation Cross-Origin Nonce Attestation Boundary critical for AI coding assistants?

Enforces strict cryptographic coupling of server-issued challenge nonces to client transport bindings and canonical relying party origins during WebAuthn conditional mediation (autofill). Prevents passkey replay, cross-origin assertion injection, and passkey phishing across embedded frames or shared origin 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 (Decoupled Challenge Verification and Permissive Origin Matching in Autofill Passkey 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

WebAuthn