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

WebAuthn Level 3 Strict Origin Binding & Single-Use Challenge Lifecycle

Enforces cryptographically bound origin verification, strict RP ID matching, and atomic single-use challenge expiration for WebAuthn Level 3 Conditional UI (autofill) flows. Mitigates asynchronous replay attacks and credential forwarding across origins by mandating sub-minute TTLs, atomic challenge consumption, and topOrigin validation in nested contexts.

Prohibited Anti-Pattern: Reusable Session Challenges and Permissive Origin Matching in Passkey Autofill Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Strict Origin Binding & Single-Use Challenge Lifecycle - Enforces cryptographically bound origin verification, strict RP ID matching, and atomic single-use challenge expiration for WebAuthn Level 3 Conditional UI (autofill) flows. Mitigates asynchronous replay attacks and credential forwarding across origins by mandating sub-minute TTLs, atomic challenge consumption, and topOrigin validation in nested contexts.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/server/services/passkey*.{ts,js}, api/**/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-conditional-ui-binding"
---

# WebAuthn Level 3 Strict Origin Binding & Single-Use Challenge Lifecycle

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reusable Session Challenges and Permissive Origin Matching in Passkey Autofill Verification

## System Constraints
You are a Principal Security Architect enforcing FIDO Alliance and W3C WebAuthn Level 3 specifications. Conditional UI passkey flows expose extended attack surfaces because challenges remain active while waiting for user autofill interaction. You must enforce atomic challenge consumption (GETDEL semantics) prior to signature validation, verify clientDataJSON against canonical expected origins, validate topOrigin extensions when embedded, and prevent challenge lifetimes from exceeding 60 seconds.

## Strict Guidelines
- Services MUST atomically consume and invalidate challenges from persistent shared storage (e.g., Redis GETDEL) before signature parsing to eliminate concurrency races and replay attacks.
- Engineers MUST set a maximum Time-To-Live (TTL) of 60 seconds on challenges generated for conditional mediation (`mediation: 'conditional'`).
- Services MUST verify that `clientDataJSON.origin` exactly matches the expected canonical origin (scheme, host, port) and rejects wildcard or loose regex matching.
- Services MUST validate the WebAuthn Level 3 `topOrigin` client extension if the assertion originates from cross-origin iframes or federated contexts.
- Engineers MUST NOT store challenges in client-accessible cookies, unhashed JWTs, or client-side storage where they can be observed or reused across sessions.
- Services MUST enforce `userVerification: 'required'` or verify the UV flag in `authenticatorData` when authenticating high-privilege access.

## Bad vs Good Implementations
### Vulnerable Passkey Assertion: Reusable Session Challenge & Weak Origin Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is read from session storage without atomic consumption (GETDEL), allowing concurrent replay requests. Origin matching uses a permissive substring search instead of an exact cryptographic match, exposing the application to cross-origin credential relay.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

export async function verifyPasskeyBad(req: Request, res: Response) {
  const { body } = req;
  // Flaw 1: Session-stored challenge is not atomically invalidated before verification
  const expectedChallenge = req.session.currentChallenge;
  
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'Missing challenge' });
  }

  // Flaw 2: Loose origin verification vulnerable to subdomain takeovers or sibling origins
  const result = await verifyAuthenticationResponse({
    response: body,
    expectedChallenge,
    expectedOrigin: (origin) => origin.includes('example.com'),
    expectedRPID: 'example.com',
    authenticator: req.session.userAuthenticator,
  });

  // Flaw 3: Challenge deleted only after verification succeeds, allowing concurrent replay
  if (result.verified) {
    delete req.session.currentChallenge;
    return res.json({ success: true });
  }

  return res.status(401).json({ error: 'Authentication failed' });
}
```

#### Production Standard (Correct)
> **Standard**: Uses Redis `getdel` to ensure the challenge can only be verified once, even under concurrent execution. The origin and RP ID are strictly matched against canonical constants, user verification is enforced, and counter state is tracked to prevent authenticator cloning.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse, VerifiedAuthenticationResponse } from '@simplewebauthn/server';
import { redis } from '../lib/redis';

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

export async function verifyPasskeyGood(req: Request, res: Response) {
  const { passkeyResponse, challengeId } = req.body;

  if (!challengeId || typeof challengeId !== 'string') {
    return res.status(400).json({ error: 'Invalid challenge identifier' });
  }

  // Invariant 1: Atomic GETDEL prevents race conditions and replay attacks
  const challengeKey = `webauthn:challenge:${challengeId}`;
  const expectedChallenge = await redis.getdel(challengeKey);

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

  const authenticator = await getAuthenticatorByCredentialId(passkeyResponse.id);
  if (!authenticator) {
    return res.status(404).json({ error: 'Authenticator not registered' });
  }

  // Invariant 2: WebAuthn L3 exact origin and RPID verification with User Verification enforcement
  let verification: VerifiedAuthenticationResponse;
  try {
    verification = await verifyAuthenticationResponse({
      response: passkeyResponse,
      expectedChallenge,
      expectedOrigin: EXPECTED_ORIGIN,
      expectedRPID: EXPECTED_RP_ID,
      authenticator: {
        credentialPublicKey: authenticator.publicKey,
        credentialID: authenticator.credentialId,
        counter: authenticator.signCounter,
      },
      requireUserVerification: true,
    });
  } catch (err) {
    return res.status(401).json({ error: 'Cryptographic signature verification failed' });
  }

  if (!verification.verified) {
    return res.status(401).json({ error: 'Assertion invalid' });
  }

  // Invariant 3: Update monotonic sign counter to detect cloned authenticators
  await updateSignCounter(authenticator.id, verification.authenticationInfo.newCounter);

  return res.json({ success: 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 Strict Origin Binding & Single-Use Challenge Lifecycle

WebAuthn Level 3 Strict Origin Binding & Single-Use Challenge Lifecycle defines an industrial-grade behavioral standard for security engineering. Enforces cryptographically bound origin verification, strict RP ID matching, and atomic single-use challenge expiration for WebAuthn Level 3 Conditional UI (autofill) flows. Mitigates asynchronous replay attacks and credential forwarding across origins by mandating sub-minute TTLs, atomic challenge consumption, and topOrigin validation in nested contexts. 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: Reusable Session Challenges and Permissive Origin Matching in Passkey Autofill Verification 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 DriftReusable Session Challenges and Permissive Origin Matching in Passkey Autofill VerificationCritical
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 atomically consume and invalidate challenges from persistent shared storage (e.g., Redis GETDEL) before signature parsing to eliminate concurrency races and replay attacks.

Services MUST atomically consume and invalidate challenges from persistent shared storage (e.g., Redis GETDEL) before signature parsing to eliminate concurrency races and 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.
2

Engineers MUST set a maximum Time-To-Live (TTL) of 60 seconds on challenges generated for conditional mediation (`mediation

Engineers MUST set a maximum Time-To-Live (TTL) of 60 seconds on challenges generated for conditional mediation (`mediation: 'conditional'`).

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.origin` exactly matches the expected canonical origin (scheme, host, port) and rejects wildcard or loose regex matching.

Services MUST verify that `clientDataJSON.origin` exactly matches the expected canonical origin (scheme, host, port) and rejects wildcard or loose regex matching.

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 validate the WebAuthn Level 3 `topOrigin` client extension if the assertion originates from cross-origin iframes or federated contexts.

Services MUST validate the WebAuthn Level 3 `topOrigin` client extension if the assertion originates from cross-origin iframes or federated contexts.

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 NOT store challenges in client-accessible cookies, unhashed JWTs, or client-side storage where they can be observed or reused across sessions.

Engineers MUST NOT store challenges in client-accessible cookies, unhashed JWTs, or client-side storage where they can be observed or reused across sessions.

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

Services MUST enforce `userVerification

Services MUST enforce `userVerification: 'required'` or verify the UV flag in `authenticatorData` when authenticating high-privilege access.

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 Strict Origin Binding & Single-Use Challenge Lifecycle critical for AI coding assistants?

Enforces cryptographically bound origin verification, strict RP ID matching, and atomic single-use challenge expiration for WebAuthn Level 3 Conditional UI (autofill) flows. Mitigates asynchronous replay attacks and credential forwarding across origins by mandating sub-minute TTLs, atomic challenge consumption, and topOrigin validation in nested contexts. 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 (Reusable Session Challenges and Permissive Origin Matching in Passkey Autofill Verification) 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