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

WebAuthn Conditional Mediation Ephemeral Challenge Session-Binding Standard

Enforces strict cryptographic binding between WebAuthn conditional mediation (autofill) authentication challenges and ephemeral, single-use pre-session nonces. Prevents passkey assertion replay, cross-tab challenge hijacking, and session fixation vulnerabilities during passive credential autofill flows.

Prohibited Anti-Pattern: Global Challenge Pools, Unpinned Conditional Challenges, or Absent Post-Assertion Session Regeneration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional Mediation Ephemeral Challenge Session-Binding Standard - Enforces strict cryptographic binding between WebAuthn conditional mediation (autofill) authentication challenges and ephemeral, single-use pre-session nonces. Prevents passkey assertion replay, cross-tab challenge hijacking, and session fixation vulnerabilities during passive credential autofill flows.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/api/auth/**/*.{ts,tsx}, server/**/routes/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-session-binding-invariant"
---

# WebAuthn Conditional Mediation Ephemeral Challenge Session-Binding Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Global Challenge Pools, Unpinned Conditional Challenges, or Absent Post-Assertion Session Regeneration

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Conditional Mediation Session-Binding Invariant. In WebAuthn autofill (conditional mediation), passkey challenges are requested speculatively on page load. You must enforce that every assertion challenge is tied to an ephemeral, cryptographically signed pre-session state, consumed atomically, and verified against the identical origin and transport context before migrating the client into a fully authenticated session state with regenerated session identifiers.

## Strict Guidelines
- Services MUST cryptographically bind every generated WebAuthn challenge to an ephemeral, HttpOnly, SameSite=Strict pre-authentication token or cookie containing a unique nonce.
- Services MUST atomically invalidate and consume the ephemeral challenge upon first presentation (single-use guarantee via atomic delete/Redis EVAL/SQL transaction).
- Services MUST enforce an ephemeral challenge Time-To-Live (TTL) of at most 120 seconds to limit exposure during passive page residency.
- Services MUST regenerate all session identifiers immediately upon successful assertion verification to preclude session fixation attacks.
- Services MUST verify that clientDataJSON.challenge matches the specific challenge pinned to the requesting client's pre-session context, never querying by clientDataJSON.challenge alone.
- Components NEVER store or reuse conditional mediation challenges in shared or persistent user profiles prior to identity verification.
- Engineers MUST NOT allow challenge verification endpoints to fall back to unpinned challenge stores or unauthenticated memory caches.

## Bad vs Good Implementations
### Session-Unbound Conditional Mediation Challenge Verification vs Cryptographic Pre-Session Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is queried directly by the challenge string from the client payload rather than being bound to the caller's pre-session cookie. An attacker can initiate conditional UI, harvest challenges, or execute cross-session replays. Additionally, the existing session is not destroyed or regenerated upon successful elevation, causing session fixation.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { Request, Response } from 'express';

// VULNERABLE: In-memory global challenge map decoupled from requester context
const globalChallengeStore = new Map<string, { challenge: string; expiresAt: number }>();

export async function verifyPasskeyBad(req: Request, res: Response) {
  const { id, response } = req.body;
  const clientData = JSON.parse(Buffer.from(response.clientDataJSON, 'base64').toString());
  
  // Flaw 1: Lookup by user-controlled challenge string without requester binding
  const stored = globalChallengeStore.get(clientData.challenge);
  if (!stored || stored.expiresAt < Date.now()) {
    return res.status(400).json({ error: 'Invalid challenge' });
  }

  const verification = await verifyAuthenticationResponse({
    response: req.body,
    expectedChallenge: stored.challenge,
    expectedOrigin: 'https://example.com',
    expectedRPID: 'example.com',
    authenticator: getAuthenticator(id),
  });

  if (verification.verified) {
    // Flaw 2: Retaining current session context (Session Fixation)
    req.session.userId = verification.authenticationInfo.userId;
    return res.json({ success: true });
  }
  return res.status(401).json({ error: 'Verification failed' });
}
```

#### Production Standard (Correct)
> **Standard**: The challenge is generated alongside an ephemeral pre-auth nonce stored in an HttpOnly, SameSite=Strict cookie with a short 60s TTL. Atomic retrieval (`getdel`) guarantees challenges cannot be replayed. Verification enforces that the presented assertion matches the challenge bound strictly to that cookie context. Upon success, `req.session.regenerate()` prevents session fixation.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { randomBytes, timingSafeEqual } from 'crypto';
import type { Request, Response } from 'express';

const PRE_AUTH_COOKIE = '__Host-PreAuth-Challenge';
const CHALLENGE_TTL_MS = 60 * 1000; // 60 seconds strict TTL

export async function generateConditionalChallenge(req: Request, res: Response) {
  const nonce = randomBytes(32).toString('base64url');
  const challenge = randomBytes(32).toString('base64url');
  
  // Cryptographically bind ephemeral nonce to challenge in pre-session storage
  await req.redis.set(`preauth:${nonce}`, challenge, 'PX', CHALLENGE_TTL_MS);
  
  res.cookie(PRE_AUTH_COOKIE, nonce, {
    httpOnly: true,
    secure: true,
    sameSite: 'strict',
    maxAge: CHALLENGE_TTL_MS,
    path: '/api/auth'
  });

  return res.json({ challenge });
}

export async function verifyPasskeyGood(req: Request, res: Response) {
  const preAuthNonce = req.cookies[PRE_AUTH_COOKIE];
  if (!preAuthNonce) {
    return res.status(401).json({ error: 'Missing or expired pre-authentication context' });
  }

  // Invariant: Atomic single-use retrieval and deletion pinned strictly to nonce
  const expectedChallenge = await req.redis.getdel(`preauth:${preAuthNonce}`);
  res.clearCookie(PRE_AUTH_COOKIE, { path: '/api/auth' });

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

  const { id, response } = req.body;
  const verification = await verifyAuthenticationResponse({
    response: req.body,
    expectedChallenge,
    expectedOrigin: process.env.AUTH_RP_ORIGIN!,
    expectedRPID: process.env.AUTH_RP_ID!,
    authenticator: await getAuthenticatorById(id),
    requireUserVerification: true
  });

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

  // Invariant: Session fixation prevention via complete session regeneration
  await req.session.regenerate();
  req.session.userId = verification.authenticationInfo.userId;
  req.session.authenticatedAt = Date.now();
  
  return res.json({ success: 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 Ephemeral Challenge Session-Binding Standard

WebAuthn Conditional Mediation Ephemeral Challenge Session-Binding Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic binding between WebAuthn conditional mediation (autofill) authentication challenges and ephemeral, single-use pre-session nonces. Prevents passkey assertion replay, cross-tab challenge hijacking, and session fixation vulnerabilities during passive credential autofill flows. 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: Global Challenge Pools, Unpinned Conditional Challenges, or Absent Post-Assertion Session Regeneration 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 DriftGlobal Challenge Pools, Unpinned Conditional Challenges, or Absent Post-Assertion Session RegenerationCritical
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 cryptographically bind every generated WebAuthn challenge to an ephemeral, HttpOnly, SameSite=Strict pre-authentication token or cookie containing a unique nonce.

Services MUST cryptographically bind every generated WebAuthn challenge to an ephemeral, HttpOnly, SameSite=Strict pre-authentication token or cookie containing a unique nonce.

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 invalidate and consume the ephemeral challenge upon first presentation (single-use guarantee via atomic delete/Redis EVAL/SQL transaction).

Services MUST atomically invalidate and consume the ephemeral challenge upon first presentation (single-use guarantee via atomic delete/Redis EVAL/SQL transaction).

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 enforce an ephemeral challenge Time-To-Live (TTL) of at most 120 seconds to limit exposure during passive page residency.

Services MUST enforce an ephemeral challenge Time-To-Live (TTL) of at most 120 seconds to limit exposure during passive page residency.

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 regenerate all session identifiers immediately upon successful assertion verification to preclude session fixation attacks.

Services MUST regenerate all session identifiers immediately upon successful assertion verification to preclude session fixation 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.
5

Services MUST verify that clientDataJSON.challenge matches the specific challenge pinned to the requesting client's pre-session context, never querying by clientDataJSON.challenge alone.

Services MUST verify that clientDataJSON.challenge matches the specific challenge pinned to the requesting client's pre-session context, never querying by clientDataJSON.challenge alone.

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 store or reuse conditional mediation challenges in shared or persistent user profiles prior to identity verification.

Components NEVER store or reuse conditional mediation challenges in shared or persistent user profiles prior to identity 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.
7

Engineers MUST NOT allow challenge verification endpoints to fall back to unpinned challenge stores or unauthenticated memory caches.

Engineers MUST NOT allow challenge verification endpoints to fall back to unpinned challenge stores or unauthenticated memory caches.

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 Ephemeral Challenge Session-Binding Standard critical for AI coding assistants?

Enforces strict cryptographic binding between WebAuthn conditional mediation (autofill) authentication challenges and ephemeral, single-use pre-session nonces. Prevents passkey assertion replay, cross-tab challenge hijacking, and session fixation vulnerabilities during passive credential autofill flows. 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 (Global Challenge Pools, Unpinned Conditional Challenges, or Absent Post-Assertion Session Regeneration) 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