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

WebAuthn Level 3 Conditional Mediation & Hardware Attestation Invariants

Enforces cryptographically rigorous FIDO2/WebAuthn Level 3 implementations across omnichannel entrypoints. Mandates client-side conditional UI mediation with explicit AbortController lifecycle management and server-side strict challenge-response verification against FIDO Metadata Service (MDS) hardware attestation roots, preventing credential stuffing, phishing, and replay attacks.

Prohibited Anti-Pattern: Unvalidated Client Assertions with Ephemeral Nonce Leakage and Missing Conditional Autofill Cleanup

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Conditional Mediation & Hardware Attestation Invariants - Enforces cryptographically rigorous FIDO2/WebAuthn Level 3 implementations across omnichannel entrypoints. Mandates client-side conditional UI mediation with explicit AbortController lifecycle management and server-side strict challenge-response verification against FIDO Metadata Service (MDS) hardware attestation roots, preventing credential stuffing, phishing, and replay attacks.
globs: src/auth/**/*.{ts,tsx}, src/pages/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,js}, api/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-passkeys-conditional-mediation-standard"
---

# WebAuthn Level 3 Conditional Mediation & Hardware Attestation Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unvalidated Client Assertions with Ephemeral Nonce Leakage and Missing Conditional Autofill Cleanup

## System Constraints
You are a Principal Security Architect enforcing strict FIDO2/WebAuthn Level 3 standards. You must reject any implementation that accepts unverified client assertions, trusts unvalidated AAGUIDs without FIDO MDS hardware attestation verification, neglects AbortController abort signals on conditional mediation calls, or persists WebAuthn challenge nonces in unencrypted or long-lived stores.

## Strict Guidelines
- Engineers MUST ALWAYS verify client assertions against exact expected rpId, origin, and cryptographic challenge on the server using a validated WebAuthn Level 3 library.
- Engineers MUST ALWAYS implement PublicKeyCredential.isConditionalMediationAvailable() checks before passing mediation: 'conditional' to navigator.credentials.get().
- Engineers MUST ALWAYS bind an AbortController signal to conditional mediation requests and abort in-flight requests when modal credentials or user interactions trigger alternative flows.
- Services MUST enforce server-side monotonic counter verification to detect cloned authenticators, immediately flagging accounts when counter regressions occur.
- Services MUST validate authenticator attestation statements (packed, tpm, or fido-u2f) against trusted root certificates from the FIDO Alliance Metadata Service (MDS3) when enterprise or hardware-backed tiering is required.
- Components NEVER store authentication challenge nonces in client-accessible storage (localStorage, sessionStorage, unencrypted cookies); challenges MUST be single-use, cryptographically random (minimum 32 bytes), and bound to an ephemeral server-side session with a TTL ≤ 120 seconds.

## Bad vs Good Implementations
### WebAuthn Conditional Autofill & Server-Side Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses a static, client-generated challenge instead of a cryptographic server nonce with strict TTL. Omits PublicKeyCredential.isConditionalMediationAvailable() check and AbortController signal. Accepts authentication on the server without verifying clientDataJSON, authenticatorData, signature, or sign counter.
```typescript
// BAD: Blind credential fetching without conditional mediation availability check,
// leaking in-flight requests, and performing zero server-side assertion verification.
export async function initiateLogin(username: string) {
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new TextEncoder().encode("static-client-challenge"),
      rpId: window.location.hostname,
      userVerification: "preferred",
    },
  }) as PublicKeyCredential;

  // Security Vulnerability: Sending raw ID without challenge, origin, or signature verification
  const res = await fetch("/api/login/complete", {
    method: "POST",
    body: JSON.stringify({ id: credential.id, rawId: credential.id }),
  });
  return res.json();
}
```

#### Production Standard (Correct)
> **Standard**: Validates conditional mediation availability, coordinates cancellation via AbortSignal to avoid DOM lockups, fetches an ephemeral server-side challenge, and invokes strict Level 3 server verification enforcing counter monotonic advancement, user verification, origin matching, and signature validation.
```typescript
// GOOD: Level 3 compliant conditional mediation with AbortController lifecycle and rigorous server-side verification
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { AuthenticationResponseJSON } from '@simplewebauthn/types';

// Client-side implementation
export async function initConditionalPasskey(signal: AbortSignal): Promise<AuthenticationResponseJSON | null> {
  const isAvailable = window.PublicKeyCredential &&
    await PublicKeyCredential.isConditionalMediationAvailable?.();
  if (!isAvailable) return null;

  const challengeRes = await fetch('/api/auth/challenge', { method: 'POST', signal });
  const options = await challengeRes.json();

  try {
    const assertion = await navigator.credentials.get({
      publicKey: options,
      mediation: 'conditional',
      signal,
    }) as PublicKeyCredential;
    return assertion ? (assertion.toJSON() as AuthenticationResponseJSON) : null;
  } catch (err: unknown) {
    if (err instanceof DOMException && err.name === 'AbortError') return null;
    throw err;
  }
}

// Server-side verification handler
export async function verifyPasskeyAssertion(
  session: { expectedChallenge: string; currentCounter: number; userPublicKey: Uint8Array },
  response: AuthenticationResponseJSON
) {
  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge: session.expectedChallenge,
    expectedOrigin: 'https://auth.company.internal',
    expectedRPID: 'company.internal',
    authenticator: {
      credentialPublicKey: session.userPublicKey,
      credentialID: response.rawId,
      counter: session.currentCounter,
    },
    requireUserVerification: true,
  });

  if (!verification.verified) {
    throw new Error('WebAuthn assertion failed verification');
  }
  return verification.authenticationInfo;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Level 3 Conditional Mediation & Hardware Attestation Invariants

WebAuthn Level 3 Conditional Mediation & Hardware Attestation Invariants defines an industrial-grade behavioral standard for security engineering. Enforces cryptographically rigorous FIDO2/WebAuthn Level 3 implementations across omnichannel entrypoints. Mandates client-side conditional UI mediation with explicit AbortController lifecycle management and server-side strict challenge-response verification against FIDO Metadata Service (MDS) hardware attestation roots, preventing credential stuffing, phishing, and replay attacks. 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: Unvalidated Client Assertions with Ephemeral Nonce Leakage and Missing Conditional Autofill Cleanup 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 DriftUnvalidated Client Assertions with Ephemeral Nonce Leakage and Missing Conditional Autofill CleanupCritical
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 verify client assertions against exact expected rpId, origin, and cryptographic challenge on the server using a validated WebAuthn Level 3 library.

Engineers MUST ALWAYS verify client assertions against exact expected rpId, origin, and cryptographic challenge on the server using a validated WebAuthn Level 3 library.

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 implement PublicKeyCredential.isConditionalMediationAvailable() checks before passing mediation

Engineers MUST ALWAYS implement PublicKeyCredential.isConditionalMediationAvailable() checks before passing mediation: 'conditional' to navigator.credentials.get().

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 ALWAYS bind an AbortController signal to conditional mediation requests and abort in-flight requests when modal credentials or user interactions trigger alternative flows.

Engineers MUST ALWAYS bind an AbortController signal to conditional mediation requests and abort in-flight requests when modal credentials or user interactions trigger alternative flows.

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 enforce server-side monotonic counter verification to detect cloned authenticators, immediately flagging accounts when counter regressions occur.

Services MUST enforce server-side monotonic counter verification to detect cloned authenticators, immediately flagging accounts when counter regressions occur.

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 validate authenticator attestation statements (packed, tpm, or fido-u2f) against trusted root certificates from the FIDO Alliance Metadata Service (MDS3) when enterprise or hardware-backed tiering is required.

Services MUST validate authenticator attestation statements (packed, tpm, or fido-u2f) against trusted root certificates from the FIDO Alliance Metadata Service (MDS3) when enterprise or hardware-backed tiering is required.

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 authentication challenge nonces in client-accessible storage (localStorage, sessionStorage, unencrypted cookies)

Components NEVER store authentication challenge nonces in client-accessible storage (localStorage, sessionStorage, unencrypted cookies); challenges MUST be single-use, cryptographically random (minimum 32 bytes), and bound to an ephemeral server-side session with a TTL ≤ 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.
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 & Hardware Attestation Invariants critical for AI coding assistants?

Enforces cryptographically rigorous FIDO2/WebAuthn Level 3 implementations across omnichannel entrypoints. Mandates client-side conditional UI mediation with explicit AbortController lifecycle management and server-side strict challenge-response verification against FIDO Metadata Service (MDS) hardware attestation roots, preventing credential stuffing, phishing, and replay attacks. 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 (Unvalidated Client Assertions with Ephemeral Nonce Leakage and Missing Conditional Autofill Cleanup) 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