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

Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys

Production implementations of WebAuthn Conditional UI (autofill passkeys) must enforce cryptographic challenge verification, exact origin and Relying Party (RP) ID matching, and mandatory User Verification (`uv=required`) across both client mediation requests and server assertion verifications. Failing to enforce strict origin binding or permitting `discouraged` user verification allows malicious reverse proxies or compromised browser sessions to conduct MitM phishing and bypass biometrics on multi-device synced passkeys.

Prohibited Anti-Pattern: Permissive Origin Parsing and Weak User Verification in Autofill Passkey Assertion Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys - Production implementations of WebAuthn Conditional UI (autofill passkeys) must enforce cryptographic challenge verification, exact origin and Relying Party (RP) ID matching, and mandatory User Verification (`uv=required`) across both client mediation requests and server assertion verifications. Failing to enforce strict origin binding or permitting `discouraged` user verification allows malicious reverse proxies or compromised browser sessions to conduct MitM phishing and bypass biometrics on multi-device synced passkeys.
globs: src/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,js}, src/server/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-ui-passkey-attestation-guardrails"
---

# Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive Origin Parsing and Weak User Verification in Autofill Passkey Assertion Handlers

## System Constraints
You are a Principal Security Architect enforcing WebAuthn Conditional UI & Synced Passkey Attestation Guardrails. Mandate strict cryptographic challenge validation, exact origin/RP-ID matching, mandatory user verification (`uv=required`), and defensive token replay countermeasures across client mediation flows and server assertion handlers.

## Strict Guidelines
- Engineers MUST ALWAYS enforce `userVerification: 'required'` in both client `navigator.credentials.get` calls and server-side verification options (`verifyAuthenticationResponse`).
- Services MUST enforce strict, immutable origin matching against an explicit, trusted whitelist of fully-qualified domain origins (schema + host + port); dynamic reflection of the request `Host` or `Origin` header is strictly prohibited.
- Engineers MUST ALWAYS verify clientDataJSON `type` equals `webauthn.get` during authentication and that the decoded challenge exactly matches a cryptographically random, ephemeral challenge tied to the active session.
- Components MUST verify `PublicKeyCredential.isConditionalMediationAvailable()` before invoking `navigator.credentials.get({ mediation: 'conditional' })` and attach an `AbortController` to cancel pending mediation loops upon unmount or fallback.
- Services MUST verify the credential's `authenticatorData` flags to ensure the User Verified (`UV`) bit (bit 2) is explicitly set to 1, rejecting assertions where only User Presence (`UP`) is satisfied.
- Engineers MUST NEVER permit unauthenticated or unverified credential registration updates during Conditional UI login flows.

## Bad vs Good Implementations
### Server-Side Passkey Assertion Verification Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Deriving `expectedOrigin` and `expectedRPID` dynamically from request headers allows MitM reverse proxies (e.g., Evilginx) to proxy assertions effortlessly. Setting `requireUserVerification: false` violates the FIDO2 biometric guarantee, allowing synced passkeys to authenticate with weak user presence.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { AuthenticationResponseJSON } from '@simplewebauthn/types';
import type { Request, Response } from 'express';

export async function handlePasskeyLogin(req: Request, res: Response) {
  const response: AuthenticationResponseJSON = req.body.response;
  // Flaw 1: Deriving expectedOrigin dynamically from untrusted incoming headers
  const origin = req.headers.origin as string;
  // Flaw 2: Missing session binding check for ephemeral challenge
  const expectedChallenge = req.session.challenge;

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge,
    expectedOrigin: origin,
    expectedRPID: req.hostname,
    requireUserVerification: false // Flaw 3: Allows bypassing biometric/device PIN on synced passkeys
  });

  if (verification.verified) {
    return res.json({ success: true });
  }
  return res.status(401).json({ error: 'Unauthorized' });
}
```

#### Production Standard (Correct)
> **Standard**: Validates challenges against single-use session storage, matches origins against an explicit strict allowlist, mandates `requireUserVerification: true` to require device biometric/PIN presence, and increments assertion counters to identify cloned credentials.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { AuthenticationResponseJSON } from '@simplewebauthn/types';
import type { Request, Response } from 'express';

const TRUSTED_ORIGINS = new Set([
  'https://auth.company.internal',
  'https://login.company.internal'
]);
const TRUSTED_RP_ID = 'company.internal';

export async function handlePasskeyLogin(req: Request, res: Response) {
  const response: AuthenticationResponseJSON = req.body.response;
  const expectedChallenge = req.session.passkeyChallenge;

  // Invariant 1: Ensure challenge exists and immediately invalidate to prevent replay
  if (!expectedChallenge) {
    return res.status(400).json({ error: 'Missing or expired authentication challenge' });
  }
  delete req.session.passkeyChallenge;

  // Invariant 2: Look up credential and strictly validate static origin
  const userPasskey = await getPasskeyById(response.id);
  if (!userPasskey) {
    return res.status(404).json({ error: 'Passkey not registered' });
  }

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge,
    expectedOrigin: Array.from(TRUSTED_ORIGINS),
    expectedRPID: TRUSTED_RP_ID,
    authenticator: {
      credentialPublicKey: userPasskey.publicKey,
      credentialID: userPasskey.credentialId,
      counter: userPasskey.counter,
    },
    requireUserVerification: true // Invariant 3: Cryptographic UV enforcement required
  });

  if (!verification.verified || !verification.authenticationInfo.userVerified) {
    return res.status(401).json({ error: 'Passkey user verification failed' });
  }

  // Invariant 4: Persist incremented counter for clone detection
  await updatePasskeyCounter(response.id, verification.authenticationInfo.newCounter);
  return res.json({ success: true, userId: userPasskey.userId });
}
```

### Client-Side Conditional UI Invocation Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking conditional mediation without checking `PublicKeyCredential.isConditionalMediationAvailable()` throws unhandled DOMExceptions on unsupported browsers and does not supply an `AbortController` to cancel dangling background prompts.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';

export async function initConditionalUI(options: any) {
  // Flaw 1: Initiating Conditional UI without capability detection
  // Flaw 2: No abort controller; can leak or collide with standard auth attempts
  const authResponse = await startAuthentication({
    optionsJSON: options,
    useBrowserAutofill: true,
  });

  await fetch('/api/auth/verify', {
    method: 'POST',
    body: JSON.stringify({ response: authResponse }),
  });
}
```

#### Production Standard (Correct)
> **Standard**: Performs feature detection with `isConditionalMediationAvailable()`, wires up `AbortSignal` for clean unmounting/lifecycle termination, and verifies the autofill input contract safely.
```typescript
import { startAuthentication } from '@simplewebauthn/browser';
import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types';

export async function initConditionalUI(
  optionsJSON: PublicKeyCredentialRequestOptionsJSON,
  abortSignal: AbortSignal
): Promise<void> {
  // Invariant 1: Check browser platform capability prior to invocation
  const isAvailable =
    window.PublicKeyCredential &&
    typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function' &&
    await window.PublicKeyCredential.isConditionalMediationAvailable();

  if (!isAvailable) {
    return;
  }

  try {
    // Invariant 2: Bind abort signal and trigger autofill assertion
    const authResponse = await startAuthentication({
      optionsJSON,
      useBrowserAutofill: true,
      verifyBrowserAutofillInput: true
    });

    if (abortSignal.aborted) return;

    const response = await fetch('/api/auth/verify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ response: authResponse }),
      signal: abortSignal,
    });

    if (!response.ok) {
      throw new Error(`Authentication verification failed: ${response.statusText}`);
    }
  } catch (err: unknown) {
    if (err instanceof DOMException && err.name === 'AbortError') {
      return; // Cleanly handle component unmount/cancellation
    }
    throw err;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys

Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys defines an industrial-grade behavioral standard for security engineering. Production implementations of WebAuthn Conditional UI (autofill passkeys) must enforce cryptographic challenge verification, exact origin and Relying Party (RP) ID matching, and mandatory User Verification (`uv=required`) across both client mediation requests and server assertion verifications. Failing to enforce strict origin binding or permitting `discouraged` user verification allows malicious reverse proxies or compromised browser sessions to conduct MitM phishing and bypass biometrics on multi-device synced passkeys. 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: Permissive Origin Parsing and Weak User Verification in Autofill Passkey Assertion Handlers 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 DriftPermissive Origin Parsing and Weak User Verification in Autofill Passkey Assertion HandlersCritical
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 enforce `userVerification

Engineers MUST ALWAYS enforce `userVerification: 'required'` in both client `navigator.credentials.get` calls and server-side verification options (`verifyAuthenticationResponse`).

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 enforce strict, immutable origin matching against an explicit, trusted whitelist of fully-qualified domain origins (schema + host + port)

Services MUST enforce strict, immutable origin matching against an explicit, trusted whitelist of fully-qualified domain origins (schema + host + port); dynamic reflection of the request `Host` or `Origin` header is strictly prohibited.

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 verify clientDataJSON `type` equals `webauthn.get` during authentication and that the decoded challenge exactly matches a cryptographically random, ephemeral challenge tied to the active session.

Engineers MUST ALWAYS verify clientDataJSON `type` equals `webauthn.get` during authentication and that the decoded challenge exactly matches a cryptographically random, ephemeral challenge tied to the active session.

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 verify `PublicKeyCredential.isConditionalMediationAvailable()` before invoking `navigator.credentials.get({ mediation

Components MUST verify `PublicKeyCredential.isConditionalMediationAvailable()` before invoking `navigator.credentials.get({ mediation: 'conditional' })` and attach an `AbortController` to cancel pending mediation loops upon unmount or fallback.

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 the credential's `authenticatorData` flags to ensure the User Verified (`UV`) bit (bit 2) is explicitly set to 1, rejecting assertions where only User Presence (`UP`) is satisfied.

Services MUST verify the credential's `authenticatorData` flags to ensure the User Verified (`UV`) bit (bit 2) is explicitly set to 1, rejecting assertions where only User Presence (`UP`) is satisfied.

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

Engineers MUST NEVER permit unauthenticated or unverified credential registration updates during Conditional UI login flows.

Engineers MUST NEVER permit unauthenticated or unverified credential registration updates during Conditional UI login 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Strict Origin, Challenge, and User Verification Guardrails for WebAuthn Conditional UI Passkeys critical for AI coding assistants?

Production implementations of WebAuthn Conditional UI (autofill passkeys) must enforce cryptographic challenge verification, exact origin and Relying Party (RP) ID matching, and mandatory User Verification (`uv=required`) across both client mediation requests and server assertion verifications. Failing to enforce strict origin binding or permitting `discouraged` user verification allows malicious reverse proxies or compromised browser sessions to conduct MitM phishing and bypass biometrics on multi-device synced passkeys. 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 (Permissive Origin Parsing and Weak User Verification in Autofill Passkey Assertion Handlers) 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

Strict