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

WebAuthn Conditional Mediation & Synced Passkey Assertion Invariants

Enforces strict cryptographic verification for WebAuthn conditional mediation (autofill) and multi-device synced passkeys. Mandates server-side cryptographic challenge generation, single-use binding to secure HTTP-only sessions, multi-device backup state evaluation, and absolute prohibition of zero-trust signature counter checks for synced credentials.

Prohibited Anti-Pattern: Blind Counter Verification and Unbound Challenge Consumption in Conditional Autofill Flows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional Mediation & Synced Passkey Assertion Invariants - Enforces strict cryptographic verification for WebAuthn conditional mediation (autofill) and multi-device synced passkeys. Mandates server-side cryptographic challenge generation, single-use binding to secure HTTP-only sessions, multi-device backup state evaluation, and absolute prohibition of zero-trust signature counter checks for synced credentials.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,js}, src/pages/api/auth/**/*.{ts,js}, src/components/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-synced-passkey-invariants"
---

# WebAuthn Conditional Mediation & Synced Passkey Assertion Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Blind Counter Verification and Unbound Challenge Consumption in Conditional Autofill Flows

## System Constraints
You are a Principal Security Architect enforcing WebAuthn L3 specifications, Conditional Mediation (Form Autofill), and Synced Passkey Assertion Invariants. You must ensure all authentication ceremonies use cryptographically secure, single-use, TTL-bound challenges tied to an ephemeral server session. You must prohibit hard failures on signature counters when authenticator data flags indicate multi-device backup eligibility (BE=1, BS=1), while strictly enforcing origin, rpId, user verification (UV), and clientDataJSON type checks.

## Strict Guidelines
- Engineers MUST ALWAYS verify the challenge from clientDataJSON against a cryptographically random, single-use nonce stored in an HTTP-only, secure, partitioned session or ephemeral cache with a strict TTL (<= 120s), consuming it immediately upon first verification to prevent replay attacks.
- Engineers MUST ALWAYS parse the authenticatorData flags: verify the User Presence (UP) bit is set (0x01) and User Verification (UV) bit is set (0x04) when `userVerification: 'required'` is mandated.
- Services MUST evaluate the Backup Eligibility (BE, 0x08) and Backup State (BS, 0x10) flags in authenticatorData; if BE is true (synced passkey), signCount MUST NOT be expected to increment monotonically, and counter rollback checks MUST NOT reject the assertion.
- Components MUST abort any active conditional mediation AbortController before initiating a modal WebAuthn ceremony to avoid concurrent ceremony lockups in user-agent credential managers.
- Engineers MUST NOT accept base64url deserialized responses directly without strictly validating that `clientDataJSON.type` matches `webauthn.get` and `clientDataJSON.origin` matches the exact authorized Fully Qualified Domain Name (FQDN) using secure scheme and port matching.

## Bad vs Good Implementations
### Conditional Mediation Client & Server Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The client triggers conditional mediation without AbortController management, risking UI lockouts. The server uses a predictable challenge, fails to consume it atomically, and strictly rejects any assertion where signCount does not increment. Synced passkeys (iCloud Keychain, Google Password Manager) typically keep signCount at 0 or non-monotonic, causing persistent authentication failures for legitimate users.
```typescript
import { Request, Response } from 'express';

// ANTI-PATTERN: Client-side unhandled controller conflict and server-side counter check failure on synced passkeys
export async function startAuth() {
  // Bad: Triggering conditional mediation without abort handling or feature detection
  const credential = await navigator.credentials.get({
    mediation: 'conditional',
    publicKey: { challenge: new Uint8Array([1, 2, 3, 4]) }
  });
  await fetch('/api/verify', { method: 'POST', body: JSON.stringify(credential) });
}

export async function verifyAssertion(req: Request, res: Response) {
  const { id, response } = req.body;
  const userPasskey = await db.passkeys.findById(id);
  
  // Bad: Fixed challenge, no replay protection, strict monotonic counter check rejects synced passkeys
  if (response.authenticatorData.signCount <= userPasskey.lastSignCount) {
    return res.status(401).json({ error: 'Replay detected or cloned authenticator' });
  }
  
  await db.passkeys.update(id, { lastSignCount: response.authenticatorData.signCount });
  return res.json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: Implements graceful AbortController handling for conditional mediation, atomic server challenge consumption against replay attacks, origin/RP ID cryptographic validation, and properly bifurcates signature counter verification based on the backup eligibility (BE) flag to fully support multi-device synced passkeys.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { isoUint8Array } from '@simplewebauthn/server/helpers';

// PRODUCTION INVARIANT: AbortController-managed autofill and sync-aware verification
export async function initConditionalAutofill(abortController: AbortController): Promise<void> {
  if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
    return;
  }
  const isAvailable = await PublicKeyCredential.isConditionalMediationAvailable();
  if (!isAvailable) return;

  const optsRes = await fetch('/api/auth/generate-options');
  const options = await optsRes.json();

  try {
    const credential = await navigator.credentials.get({
      mediation: 'conditional',
      publicKey: options,
      signal: abortController.signal
    });
    if (credential) {
      await fetch('/api/auth/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credential)
      });
    }
  } catch (err: unknown) {
    if (err instanceof DOMException && err.name === 'AbortError') return;
    throw err;
  }
}

export async function verifyAssertion(req: Request, res: Response): Promise<Response> {
  const session = req.session;
  const expectedChallenge = session?.currentChallenge;
  
  // Atomically consume challenge immediately to invalidate replays
  session.currentChallenge = null;
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'Expired or non-existent challenge.' });
  }

  const passkey = await db.passkeys.findById(req.body.id);
  if (!passkey) return res.status(404).json({ error: 'Passkey not found.' });

  const verification = await verifyAuthenticationResponse({
    response: req.body,
    expectedChallenge,
    expectedOrigin: process.env.AUTH_RP_ORIGIN!,
    expectedRPID: process.env.AUTH_RP_ID!,
    authenticator: {
      credentialPublicKey: isoUint8Array.fromBase64(passkey.publicKey, 'base64url'),
      credentialID: isoUint8Array.fromBase64(passkey.id, 'base64url'),
      counter: passkey.counter
    },
    requireUserVerification: true
  });

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

  const { newCounter, authenticationInfo } = verification;
  const isSyncedPasskey = authenticationInfo.authenticatorDataFlags.backupEligibility;

  // Handle counter verification only for hardware security keys (BE=0)
  if (!isSyncedPasskey && newCounter <= passkey.counter && passkey.counter > 0) {
    return res.status(401).json({ error: 'Hardware key signature counter did not increment.' });
  }

  await db.passkeys.update(passkey.id, {
    counter: newCounter,
    lastUsedAt: new Date()
  });

  return res.json({ verified: 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 Conditional Mediation & Synced Passkey Assertion Invariants

WebAuthn Conditional Mediation & Synced Passkey Assertion Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic verification for WebAuthn conditional mediation (autofill) and multi-device synced passkeys. Mandates server-side cryptographic challenge generation, single-use binding to secure HTTP-only sessions, multi-device backup state evaluation, and absolute prohibition of zero-trust signature counter checks for synced credentials. 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: Blind Counter Verification and Unbound Challenge Consumption in Conditional Autofill Flows 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 DriftBlind Counter Verification and Unbound Challenge Consumption in Conditional Autofill FlowsCritical
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 the challenge from clientDataJSON against a cryptographically random, single-use nonce stored in an HTTP-only, secure, partitioned session or ephemeral cache with a strict TTL (<= 120s), consuming it immediately upon first verification to prevent replay attacks.

Engineers MUST ALWAYS verify the challenge from clientDataJSON against a cryptographically random, single-use nonce stored in an HTTP-only, secure, partitioned session or ephemeral cache with a strict TTL (<= 120s), consuming it immediately upon first verification to prevent 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 ALWAYS parse the authenticatorData flags

Engineers MUST ALWAYS parse the authenticatorData flags: verify the User Presence (UP) bit is set (0x01) and User Verification (UV) bit is set (0x04) when `userVerification: 'required'` is mandated.

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 evaluate the Backup Eligibility (BE, 0x08) and Backup State (BS, 0x10) flags in authenticatorData

Services MUST evaluate the Backup Eligibility (BE, 0x08) and Backup State (BS, 0x10) flags in authenticatorData; if BE is true (synced passkey), signCount MUST NOT be expected to increment monotonically, and counter rollback checks MUST NOT reject the assertion.

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 MUST abort any active conditional mediation AbortController before initiating a modal WebAuthn ceremony to avoid concurrent ceremony lockups in user-agent credential managers.

Components MUST abort any active conditional mediation AbortController before initiating a modal WebAuthn ceremony to avoid concurrent ceremony lockups in user-agent credential managers.

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 accept base64url deserialized responses directly without strictly validating that `clientDataJSON.type` matches `webauthn.get` and `clientDataJSON.origin` matches the exact authorized Fully Qualified Domain Name (FQDN) using secure scheme and port matching.

Engineers MUST NOT accept base64url deserialized responses directly without strictly validating that `clientDataJSON.type` matches `webauthn.get` and `clientDataJSON.origin` matches the exact authorized Fully Qualified Domain Name (FQDN) using secure scheme and port 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.
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 & Synced Passkey Assertion Invariants critical for AI coding assistants?

Enforces strict cryptographic verification for WebAuthn conditional mediation (autofill) and multi-device synced passkeys. Mandates server-side cryptographic challenge generation, single-use binding to secure HTTP-only sessions, multi-device backup state evaluation, and absolute prohibition of zero-trust signature counter checks for synced credentials. 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 (Blind Counter Verification and Unbound Challenge Consumption in Conditional Autofill Flows) 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