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

WebAuthn Conditional UI Passkey Replay & Cross-Session Injection Guardrail

Enforces single-use ephemeral challenge lifecycle management, atomic consumption, and strict session-to-challenge binding for WebAuthn Conditional Mediation ceremonies. Mitigates passkey autofill replay attacks, cross-session UI injection, and assertion race conditions across browser tabs.

Prohibited Anti-Pattern: Non-Atomic Challenge Invalidation and Unbound Ephemeral Challenges in Passkey Conditional Autofill

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional UI Passkey Replay & Cross-Session Injection Guardrail - Enforces single-use ephemeral challenge lifecycle management, atomic consumption, and strict session-to-challenge binding for WebAuthn Conditional Mediation ceremonies. Mitigates passkey autofill replay attacks, cross-session UI injection, and assertion race conditions across browser tabs.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/api/auth/**/*.{ts,tsx}, src/**/pages/login/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-ui-replay-guardrail"
---

# WebAuthn Conditional UI Passkey Replay & Cross-Session Injection Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Non-Atomic Challenge Invalidation and Unbound Ephemeral Challenges in Passkey Conditional Autofill

## System Constraints
You are a Principal Security Architect enforcing zero-trust WebAuthn Conditional UI ceremonies. You must guarantee that authentication challenges are single-use, cryptographically bound to the initiating session token, stored with a hard TTL not exceeding 120 seconds, atomically consumed on first verification read, and validated against clientDataJSON origin and RP ID hash invariants.

## Strict Guidelines
- Services MUST generate cryptographically secure, random challenges (minimum 32 bytes) with an expiration TTL <= 120 seconds for conditional autofill requests.
- Services MUST atomically retrieve and delete (e.g., Redis GETDEL or SQL DELETE ... RETURNING) the stored challenge on the first verification attempt, preventing any second verification attempt even if the first fails.
- Services MUST cryptographically bind the challenge to the client's current session or pre-session cookie; challenges MUST NOT be shared across anonymous sessions or accepted without session proof.
- Frontend components MUST manage conditional autofill using an explicit AbortController and immediately abort any active conditional mediation before initiating an interactive modal ceremony.
- Verification routines MUST explicitly validate clientDataJSON.type === 'webauthn.get', verify clientDataJSON.origin exactly matches the configured RP origin, and verify clientDataJSON.challenge matches the consumed challenge.
- Verification handlers MUST inspect authenticatorData flags (UP and optionally UV) and enforce monotonic counter increments when the credential counter is non-zero to detect cloned authenticators.

## Bad vs Good Implementations
### WebAuthn Conditional Challenge Verification and Replay Prevention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is generated statically or without high-entropy randomness, stored in-memory without a session-bound key, read without atomic deletion (enabling race conditions/replay attacks), deleted only after verification succeeds instead of immediately, and relies on untrusted incoming origin headers.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

const challengeCache = new Map<string, string>();

export async function getConditionalOptions(req: Request, res: Response) {
  const challenge = 'static-or-weak-challenge'; // Anti-pattern: Non-cryptographic / static
  challengeCache.set(req.body.username ?? 'anonymous', challenge);
  return res.json({ challenge });
}

export async function verifyConditionalAssertion(req: Request, res: Response) {
  const { username, assertionResponse } = req.body;
  const expectedChallenge = challengeCache.get(username ?? 'anonymous');
  
  // Anti-pattern: Read without atomic deletion exposes replay window during concurrent requests
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'No challenge found' });
  }

  const verification = await verifyAuthenticationResponse({
    response: assertionResponse,
    expectedChallenge,
    expectedOrigin: req.headers.origin as string, // Anti-pattern: Trusting untrusted incoming header
    expectedRPID: 'localhost',
    authenticator: { credentialPublicKey: Buffer.from([]), credentialID: Buffer.from([]), counter: 0 },
  });

  if (verification.verified) {
    challengeCache.delete(username ?? 'anonymous'); // Anti-pattern: Delete only on success allows brute force/replay on fail
    return res.json({ success: true });
  }
  return res.status(401).json({ error: 'Verification failed' });
}
```

#### Production Standard (Correct)
> **Standard**: Generates a 32-byte cryptographically secure challenge, cryptographically binds it to a secure session cookie hash, applies an atomic Redis GETDEL on initial read (consuming it regardless of verification success/failure), asserts strict constant origin and RP ID, and checks clone detection counter invariants.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import crypto from 'node:crypto';
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL!);
const CHALLENGE_TTL_SECONDS = 120;
const EXPECTED_ORIGIN = process.env.RP_ORIGIN!; // e.g., 'https://app.example.com'
const EXPECTED_RP_ID = process.env.RP_ID!;       // e.g., 'app.example.com'

export async function getConditionalOptions(req: Request, res: Response) {
  const sessionId = req.cookies.__Host_SessionId;
  if (!sessionId) {
    return res.status(401).json({ error: 'Missing secure session token' });
  }

  const challenge = crypto.randomBytes(32).toString('base64url');
  const key = `webauthn:challenge:${crypto.createHash('sha256').update(sessionId).digest('hex')}`;

  // Store single-use challenge bound to session with strict TTL
  await redis.set(key, challenge, 'EX', CHALLENGE_TTL_SECONDS);

  return res.json({
    challenge,
    rpId: EXPECTED_RP_ID,
    timeout: CHALLENGE_TTL_SECONDS * 1000,
    userVerification: 'preferred',
  });
}

export async function verifyConditionalAssertion(req: Request, res: Response) {
  const sessionId = req.cookies.__Host_SessionId;
  if (!sessionId) {
    return res.status(401).json({ error: 'Missing secure session token' });
  }

  const key = `webauthn:challenge:${crypto.createHash('sha256').update(sessionId).digest('hex')}`;
  
  // Invariant: Atomic read-and-delete (GETDEL) prevents replay and concurrent reuse
  const expectedChallenge = await redis.getdel(key);
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'Challenge expired, consumed, or invalid' });
  }

  const { assertionResponse, credential } = req.body;

  try {
    const verification = await verifyAuthenticationResponse({
      response: assertionResponse,
      expectedChallenge,
      expectedOrigin: EXPECTED_ORIGIN,
      expectedRPID: EXPECTED_RP_ID,
      authenticator: {
        credentialPublicKey: Buffer.from(credential.publicKey, 'base64url'),
        credentialID: Buffer.from(credential.id, 'base64url'),
        counter: credential.counter,
      },
      requireUserVerification: false,
    });

    if (!verification.verified) {
      return res.status(401).json({ error: 'WebAuthn assertion rejected' });
    }

    // Monotonic counter verification for clone detection
    if (verification.authenticationInfo.newCounter <= credential.counter && credential.counter > 0) {
      return res.status(403).json({ error: 'Potential authenticator clone detected' });
    }

    return res.json({ success: true, newCounter: verification.authenticationInfo.newCounter });
  } catch (error) {
    return res.status(400).json({ error: 'Malformed assertion payload' });
  }
}
```

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 Conditional UI Passkey Replay & Cross-Session Injection Guardrail

WebAuthn Conditional UI Passkey Replay & Cross-Session Injection Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces single-use ephemeral challenge lifecycle management, atomic consumption, and strict session-to-challenge binding for WebAuthn Conditional Mediation ceremonies. Mitigates passkey autofill replay attacks, cross-session UI injection, and assertion race conditions across browser tabs. 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: Non-Atomic Challenge Invalidation and Unbound Ephemeral Challenges in Passkey Conditional Autofill 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 DriftNon-Atomic Challenge Invalidation and Unbound Ephemeral Challenges in Passkey Conditional AutofillCritical
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 generate cryptographically secure, random challenges (minimum 32 bytes) with an expiration TTL <= 120 seconds for conditional autofill requests.

Services MUST generate cryptographically secure, random challenges (minimum 32 bytes) with an expiration TTL <= 120 seconds for conditional autofill requests.

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 retrieve and delete (e.g., Redis GETDEL or SQL DELETE ... RETURNING) the stored challenge on the first verification attempt, preventing any second verification attempt even if the first fails.

Services MUST atomically retrieve and delete (e.g., Redis GETDEL or SQL DELETE ... RETURNING) the stored challenge on the first verification attempt, preventing any second verification attempt even if the first 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.
3

Services MUST cryptographically bind the challenge to the client's current session or pre-session cookie

Services MUST cryptographically bind the challenge to the client's current session or pre-session cookie; challenges MUST NOT be shared across anonymous sessions or accepted without session proof.

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

Frontend components MUST manage conditional autofill using an explicit AbortController and immediately abort any active conditional mediation before initiating an interactive modal ceremony.

Frontend components MUST manage conditional autofill using an explicit AbortController and immediately abort any active conditional mediation before initiating an interactive modal ceremony.

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

Verification routines MUST explicitly validate clientDataJSON.type === 'webauthn.get', verify clientDataJSON.origin exactly matches the configured RP origin, and verify clientDataJSON.challenge matches the consumed challenge.

Verification routines MUST explicitly validate clientDataJSON.type === 'webauthn.get', verify clientDataJSON.origin exactly matches the configured RP origin, and verify clientDataJSON.challenge matches the consumed 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.
6

Verification handlers MUST inspect authenticatorData flags (UP and optionally UV) and enforce monotonic counter increments when the credential counter is non-zero to detect cloned authenticators.

Verification handlers MUST inspect authenticatorData flags (UP and optionally UV) and enforce monotonic counter increments when the credential counter is non-zero to detect cloned authenticators.

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 UI Passkey Replay & Cross-Session Injection Guardrail critical for AI coding assistants?

Enforces single-use ephemeral challenge lifecycle management, atomic consumption, and strict session-to-challenge binding for WebAuthn Conditional Mediation ceremonies. Mitigates passkey autofill replay attacks, cross-session UI injection, and assertion race conditions across browser tabs. 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 (Non-Atomic Challenge Invalidation and Unbound Ephemeral Challenges in Passkey Conditional Autofill) 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