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

WebAuthn Conditional UI Single-Use Challenge and Session Binding

Enforces atomic, single-use cryptographically bound challenge validation for WebAuthn Conditional UI (autofill) interactions. Prevents race-condition authentication hijacking, replay attacks, and session fixation by requiring challenge consumption to be atomic and strictly bound to the initiating client session.

Prohibited Anti-Pattern: Reusing Challenges or Verifying Conditional UI Assertions Non-Atomically

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional UI Single-Use Challenge and Session Binding - Enforces atomic, single-use cryptographically bound challenge validation for WebAuthn Conditional UI (autofill) interactions. Prevents race-condition authentication hijacking, replay attacks, and session fixation by requiring challenge consumption to be atomic and strictly bound to the initiating client session.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/pages/api/auth/**/*.{ts,js}, src/app/api/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-ui-session-guardrail"
---

# WebAuthn Conditional UI Single-Use Challenge and Session Binding

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reusing Challenges or Verifying Conditional UI Assertions Non-Atomically

## System Constraints
You are a Principal Security Architect enforcing invariants for WebAuthn Conditional UI (autofill) implementations. Conditional UI keeps challenges alive while users interact with the page, exposing systems to replay windows, cross-tab race conditions, and session fixation. You must mandate that every WebAuthn challenge is cryptographically random, ephemeral, strictly tied to the originating session token, and consumed via an atomic get-and-delete operation upon the first verification attempt regardless of whether the assertion succeeds or fails.

## Strict Guidelines
- Engineers MUST ALWAYS consume WebAuthn challenges atomically using single-operation primitives (e.g., Redis GETDEL, SQL DELETE ... RETURNING, or transactional CAS) before starting signature verification.
- Engineers MUST NOT allow challenge reuse across multiple autofill cycles or fallback requests; any failed verification MUST immediately invalidate the active challenge.
- Services MUST cryptographically bind the WebAuthn challenge to the caller's secure, HTTP-only ephemeral pre-auth session cookie or device fingerprint.
- Components NEVER expose raw challenges to client-side storage mechanisms (localStorage, sessionStorage) or retain challenges in shared mutable server memory without TTLs.
- Code SHOULD enforce a strict Time-To-Live (TTL) of at most 120 seconds for conditional UI challenges to limit the interception window.

## Bad vs Good Implementations
### WebAuthn Conditional UI Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is fetched without atomic deletion. A concurrent attacker or duplicate request can read the same challenge before it is cleared, enabling session hijacking and replay. Furthermore, failed verifications leave the challenge active in the database.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { Request, Response } from 'express';

// VULNERABLE: Reads challenge without atomic deletion and permits reuse
export async function verifyPasskeyAutofill(req: Request, res: Response) {
  const { sessionId, credential } = req.body;
  
  // Flaw 1: Session lookup does not invalidate the challenge
  const session = await db.session.findUnique({ where: { id: sessionId } });
  if (!session || !session.currentChallenge) {
    return res.status(400).json({ error: 'No challenge found' });
  }

  // Flaw 2: Race condition - concurrent requests can reuse session.currentChallenge
  const verification = await verifyAuthenticationResponse({
    response: credential,
    expectedChallenge: session.currentChallenge,
    expectedOrigin: 'https://example.com',
    expectedRPID: 'example.com',
    authenticator: session.authenticator,
  });

  if (verification.verified) {
    // Flaw 3: Challenge deleted only after success; failed attempts leave challenge open to hijack
    await db.session.update({
      where: { id: sessionId },
      data: { currentChallenge: null, authenticated: true },
    });
    return res.json({ verified: true });
  }

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

#### Production Standard (Correct)
> **Standard**: Uses Redis `GETDEL` to guarantee atomic, single-use consumption of the challenge regardless of verification outcome. Cryptographically couples challenge to an HttpOnly pre-auth cookie and rotates the session immediately upon success to eliminate session fixation.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { Request, Response } from 'express';
import { redis } from '../lib/redis';

export async function verifyPasskeyAutofill(req: Request, res: Response) {
  // Bind validation to authenticated HttpOnly pre-session cookie
  const preAuthSessionId = req.signedCookies['__Host-pre-auth-session'];
  if (!preAuthSessionId) {
    return res.status(401).json({ error: 'Pre-authentication session missing' });
  }

  const challengeKey = `webauthn:challenge:${preAuthSessionId}`;

  // INVARIANT: Atomic GETDEL ensures the challenge can only ever be consumed once
  const expectedChallenge = await redis.getdel(challengeKey);
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'Challenge expired, missing, or already consumed' });
  }

  const { credential } = req.body;
  const authenticator = await getAuthenticatorByCredentialId(credential.id);

  try {
    const verification = await verifyAuthenticationResponse({
      response: credential,
      expectedChallenge,
      expectedOrigin: process.env.AUTH_ORIGIN!,
      expectedRPID: process.env.AUTH_RPID!,
      authenticator: authenticator.publicKey,
      requireUserVerification: true,
    });

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

    // Rotate session identifier upon authentication to prevent session fixation
    const newSessionToken = await createEstablishedSession(authenticator.userId);
    res.cookie('__Host-session', newSessionToken, { secure: true, httpOnly: true, sameSite: 'strict' });
    res.clearCookie('__Host-pre-auth-session');

    return res.json({ verified: true });
  } catch (error) {
    // Challenge was already atomically consumed; replay is impossible
    return res.status(400).json({ error: 'Authentication verification rejected' });
  }
}
```

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 Single-Use Challenge and Session Binding

WebAuthn Conditional UI Single-Use Challenge and Session Binding defines an industrial-grade behavioral standard for security engineering. Enforces atomic, single-use cryptographically bound challenge validation for WebAuthn Conditional UI (autofill) interactions. Prevents race-condition authentication hijacking, replay attacks, and session fixation by requiring challenge consumption to be atomic and strictly bound to the initiating client session. 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: Reusing Challenges or Verifying Conditional UI Assertions Non-Atomically 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 DriftReusing Challenges or Verifying Conditional UI Assertions Non-AtomicallyCritical
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 consume WebAuthn challenges atomically using single-operation primitives (e.g., Redis GETDEL, SQL DELETE ... RETURNING, or transactional CAS) before starting signature verification.

Engineers MUST ALWAYS consume WebAuthn challenges atomically using single-operation primitives (e.g., Redis GETDEL, SQL DELETE ... RETURNING, or transactional CAS) before starting 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.
2

Engineers MUST NOT allow challenge reuse across multiple autofill cycles or fallback requests

Engineers MUST NOT allow challenge reuse across multiple autofill cycles or fallback requests; any failed verification MUST immediately invalidate the active 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.
3

Services MUST cryptographically bind the WebAuthn challenge to the caller's secure, HTTP-only ephemeral pre-auth session cookie or device fingerprint.

Services MUST cryptographically bind the WebAuthn challenge to the caller's secure, HTTP-only ephemeral pre-auth session cookie or device fingerprint.

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

Components NEVER expose raw challenges to client-side storage mechanisms (localStorage, sessionStorage) or retain challenges in shared mutable server memory without TTLs.

Components NEVER expose raw challenges to client-side storage mechanisms (localStorage, sessionStorage) or retain challenges in shared mutable server memory without TTLs.

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

Code SHOULD enforce a strict Time-To-Live (TTL) of at most 120 seconds for conditional UI challenges to limit the interception window.

Code SHOULD enforce a strict Time-To-Live (TTL) of at most 120 seconds for conditional UI challenges to limit the interception window.

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 Single-Use Challenge and Session Binding critical for AI coding assistants?

Enforces atomic, single-use cryptographically bound challenge validation for WebAuthn Conditional UI (autofill) interactions. Prevents race-condition authentication hijacking, replay attacks, and session fixation by requiring challenge consumption to be atomic and strictly bound to the initiating client session. 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 (Reusing Challenges or Verifying Conditional UI Assertions Non-Atomically) 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