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

WebAuthn Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard

Enforces strict origin-bound, cryptographically random, ephemeral challenge-nonce verification for WebAuthn Level 3 conditional UI ceremonies. Prevents passkey replay, token-binding circumvention, and passkey injection during silent auto-fill credential generation by ensuring single-use consumption and session isolation. Guarantees that conditional mediation public key credential requests cannot be intercepted or replayed across tab contexts or origin boundaries.

Prohibited Anti-Pattern: Persisting static challenges in sessions or unauthenticated cookies during conditional UI pre-flight passkey requests

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard - Enforces strict origin-bound, cryptographically random, ephemeral challenge-nonce verification for WebAuthn Level 3 conditional UI ceremonies. Prevents passkey replay, token-binding circumvention, and passkey injection during silent auto-fill credential generation by ensuring single-use consumption and session isolation. Guarantees that conditional mediation public key credential requests cannot be intercepted or replayed across tab contexts or origin boundaries.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/lib/webauthn/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-conditional-mediation-nonce-verification-standard"
---

# WebAuthn Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting static challenges in sessions or unauthenticated cookies during conditional UI pre-flight passkey requests

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Level 3 Conditional Mediation Auto-Fill Nonce Verification Standard. You must reject any authentication implementation that treats conditional mediation passkey challenges as static, globally scoped, or decoupleable from ephemeral transport sessions. Ensure every assertion response during conditional UI flows validates an origin-bound, single-use, cryptographically verified nonce tied strictly to the request context.

## Strict Guidelines
- Engineers MUST ALWAYS generate cryptographically secure, high-entropy challenges (minimum 32 bytes from a CSPRNG) on the server for each conditional UI auto-fill invocation.
- Engineers MUST ALWAYS store the conditional challenge in an ephemeral, single-use distributed store or cryptographically signed, partitioned, SameSite=Strict HTTP-only cookie with a maximum TTL of 120 seconds.
- Engineers MUST NOT allow reused, cached, or static challenges across multiple WebAuthn navigator.credentials.get() invocations.
- Services MUST atomically invalidate and consume the conditional challenge immediately upon the first verification attempt, regardless of whether the cryptographic verification succeeds or fails.
- Services MUST strictly verify clientDataJSON against expected properties: type must match 'webauthn.get', challenge must match the retrieved nonce via constant-time comparison, and origin must strictly match the expected fully qualified domain name (including scheme and port).
- Components NEVER trigger navigator.credentials.get({ mediation: 'conditional' }) without an AbortController signal to safely cancel dangling ceremonies upon component unmount or explicit user interaction.

## Bad vs Good Implementations
### Server-Side Challenge Creation & Verification for WebAuthn Level 3 Conditional Mediation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is static, stored across the entire session, not bound to an ephemeral nonce, and not invalidated upon access. Furthermore, comparison is vulnerable to timing attacks, clientDataJSON origin/type are unchecked, and the challenge is not single-use.
```typescript
import { Request, Response } from 'express';

// ANTI-PATTERN: Reusing a static or long-lived session challenge without origin/nonce binding
export async function getConditionalOptions(req: Request, res: Response) {
  const session = req.session as any;
  if (!session.webauthnChallenge) {
    session.webauthnChallenge = 'insecure-static-challenge-token';
  }
  return res.json({
    challenge: Buffer.from(session.webauthnChallenge).toString('base64url'),
    rpId: 'example.com',
    userVerification: 'preferred'
  });
}

export async function verifyConditionalAssertion(req: Request, res: Response) {
  const { id, rawId, response } = req.body;
  const session = req.session as any;
  const clientData = JSON.parse(Buffer.from(response.clientDataJSON, 'base64url').toString('utf8'));

  // Flaw: Vulnerable to replay attacks, no timing-safe check, challenge not revoked
  if (clientData.challenge !== Buffer.from(session.webauthnChallenge).toString('base64url')) {
    return res.status(401).send('Invalid challenge');
  }
  return res.json({ verified: true });
}
```

#### Production Standard (Correct)
> **Standard**: Generates 32 bytes of cryptographic randomness, isolates it with an ephemeral nonce, enforces a 120-second TTL, and atomically consumes it using Redis GETDEL to eliminate replay. Origin, ceremony type, and timing-safe challenge equality are rigorously enforced.
```typescript
import { Request, Response } from 'express';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { redisClient } from '../lib/redis';

const CHALLENGE_TTL_SECONDS = 120;
const EXPECTED_ORIGIN = 'https://auth.example.com';
const RP_ID = 'auth.example.com';

export async function getConditionalOptions(req: Request, res: Response) {
  const challengeBytes = randomBytes(32);
  const nonce = randomBytes(16).toString('hex');
  const challengeBase64 = challengeBytes.toString('base64url');

  // Ephemeral storage bound to single-use nonce key with strict TTL
  const storageKey = `webauthn:conditional:${nonce}`;
  await redisClient.set(storageKey, challengeBase64, 'EX', CHALLENGE_TTL_SECONDS);

  // Return options with nonce identifier to correlate verification payload
  return res.json({
    challenge: challengeBase64,
    rpId: RP_ID,
    userVerification: 'preferred',
    nonce
  });
}

export async function verifyConditionalAssertion(req: Request, res: Response) {
  const { nonce, response } = req.body;
  if (typeof nonce !== 'string' || !response?.clientDataJSON) {
    return res.status(400).json({ error: 'Malformed assertion payload' });
  }

  const storageKey = `webauthn:conditional:${nonce}`;
  // Atomic fetch-and-delete prevents race conditions and replay attacks
  const expectedChallenge = await redisClient.getdel(storageKey);
  if (!expectedChallenge) {
    return res.status(401).json({ error: 'Challenge expired or already consumed' });
  }

  let clientData: { type: string; challenge: string; origin: string };
  try {
    clientData = JSON.parse(Buffer.from(response.clientDataJSON, 'base64url').toString('utf8'));
  } catch {
    return res.status(400).json({ error: 'Invalid clientDataJSON encoding' });
  }

  if (clientData.type !== 'webauthn.get' || clientData.origin !== EXPECTED_ORIGIN) {
    return res.status(403).json({ error: 'Origin or ceremony type mismatch' });
  }

  const expectedBuf = Buffer.from(expectedChallenge, 'utf8');
  const actualBuf = Buffer.from(clientData.challenge, 'utf8');
  if (expectedBuf.length !== actualBuf.length || !timingSafeEqual(expectedBuf, actualBuf)) {
    return res.status(401).json({ error: 'Cryptographic challenge verification failed' });
  }

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

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: WebAuthn Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard

WebAuthn Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict origin-bound, cryptographically random, ephemeral challenge-nonce verification for WebAuthn Level 3 conditional UI ceremonies. Prevents passkey replay, token-binding circumvention, and passkey injection during silent auto-fill credential generation by ensuring single-use consumption and session isolation. Guarantees that conditional mediation public key credential requests cannot be intercepted or replayed across tab contexts or 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: Persisting static challenges in sessions or unauthenticated cookies during conditional UI pre-flight passkey requests 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 DriftPersisting static challenges in sessions or unauthenticated cookies during conditional UI pre-flight passkey requestsCritical
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 cryptographically secure, high-entropy challenges (minimum 32 bytes from a CSPRNG) on the server for each conditional UI auto-fill invocation.

Engineers MUST ALWAYS generate cryptographically secure, high-entropy challenges (minimum 32 bytes from a CSPRNG) on the server for each conditional UI auto-fill invocation.

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 store the conditional challenge in an ephemeral, single-use distributed store or cryptographically signed, partitioned, SameSite=Strict HTTP-only cookie with a maximum TTL of 120 seconds.

Engineers MUST ALWAYS store the conditional challenge in an ephemeral, single-use distributed store or cryptographically signed, partitioned, SameSite=Strict HTTP-only cookie with a maximum TTL of 120 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.
3

Engineers MUST NOT allow reused, cached, or static challenges across multiple WebAuthn navigator.credentials.get() invocations.

Engineers MUST NOT allow reused, cached, or static challenges across multiple WebAuthn navigator.credentials.get() invocations.

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 atomically invalidate and consume the conditional challenge immediately upon the first verification attempt, regardless of whether the cryptographic verification succeeds or fails.

Services MUST atomically invalidate and consume the conditional challenge immediately upon the first verification attempt, regardless of whether the cryptographic verification succeeds or fails.

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 strictly verify clientDataJSON against expected properties

Services MUST strictly verify clientDataJSON against expected properties: type must match 'webauthn.get', challenge must match the retrieved nonce via constant-time comparison, and origin must strictly match the expected fully qualified domain name (including scheme and port).

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

Components NEVER trigger navigator.credentials.get({ mediation: 'conditional' }) without an AbortController signal to safely cancel dangling ceremonies upon component unmount or explicit user interaction.

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 Level 3 Conditional Mediation Auto-Fill Ephemeral Nonce & Challenge Binding Standard critical for AI coding assistants?

Enforces strict origin-bound, cryptographically random, ephemeral challenge-nonce verification for WebAuthn Level 3 conditional UI ceremonies. Prevents passkey replay, token-binding circumvention, and passkey injection during silent auto-fill credential generation by ensuring single-use consumption and session isolation. Guarantees that conditional mediation public key credential requests cannot be intercepted or replayed across tab contexts or 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 (Persisting static challenges in sessions or unauthenticated cookies during conditional UI pre-flight passkey requests) 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