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

WebAuthn Level 3 Passkey Attestation, Exact Origin Binding, and UV Enforcement

Enforces strict W3C WebAuthn Level 3 verification invariants during passkey registration and assertion. Mandates exact match comparisons against expected fully qualified origins (FQDN, scheme, port), hardware-backed User Verification (UV flag) enforcement, monotonic sign counter validation, and single-use cryptographic challenge invalidation to eliminate Adversary-in-the-Middle (AitM) phishing and credential cloning.

Prohibited Anti-Pattern: Accepting Spoofed Reverse-Proxy Origins, Regex Origin Wildcards, or Bypassing Hardware User Verification (UV)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Passkey Attestation, Exact Origin Binding, and UV Enforcement - Enforces strict W3C WebAuthn Level 3 verification invariants during passkey registration and assertion. Mandates exact match comparisons against expected fully qualified origins (FQDN, scheme, port), hardware-backed User Verification (UV flag) enforcement, monotonic sign counter validation, and single-use cryptographic challenge invalidation to eliminate Adversary-in-the-Middle (AitM) phishing and credential cloning.
globs: src/auth/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/server/webauthn/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-passkey-attestation-origin-binding"
---

# WebAuthn Level 3 Passkey Attestation, Exact Origin Binding, and UV Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Spoofed Reverse-Proxy Origins, Regex Origin Wildcards, or Bypassing Hardware User Verification (UV)

## System Constraints
You are a Principal Security Architect enforcing W3C WebAuthn Level 3 invariants and FIDO2 standards. Reject any implementation that derives expected origins from untrusted HTTP request headers, allows loose regex matching on clientDataJSON.origin, fails to mandate the User Verification (UV) flag (bit 2 of authenticator data flags), ignores single-use challenge consumption, or skips monotonic sign counter validation against credential cloning.

## Strict Guidelines
- Engineers MUST ALWAYS validate `clientDataJSON.origin` with constant-time exact byte equality against a deterministic server-side whitelist containing scheme, fully qualified domain, and explicit port (e.g., 'https://auth.example.com:443').
- Engineers MUST NOT derive the expected origin or RP ID from untrusted request headers such as `Host`, `X-Forwarded-Host`, `Referer`, or query parameters.
- Services MUST verify that bit 2 (User Verification, UV) in the authenticator data flags byte (`flags & 0x04 !== 0`) is explicitly set for all primary and step-up passkey assertions.
- Services MUST NOT accept User Presence (`flags & 0x01 !== 0`) alone as a substitute for User Verification (`UV`) when user verification is configured as 'required'.
- Services MUST consume and invalidate the authentication challenge immediately upon lookup in server-side session storage to prevent replay attacks, checking expiration within a maximum TTL of 120 seconds.
- Services MUST verify that `authData.rpIdHash` exactly matches the SHA-256 hash of the canonical Relying Party ID configured on the server.
- Services MUST enforce monotonic sign counter progression: if `newSignCount <= storedSignCount` and both values are greater than 0, the server MUST mark the passkey credential as cloned, revoke the credential, and terminate the session.
- Engineers MUST decode base64url payloads using secure constant-time parsers and enforce strict schema parsing on `clientDataJSON` and `authenticatorData` binary buffers.

## Bad vs Good Implementations
### Vulnerable vs. Hardened WebAuthn Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Deriving origin from `req.headers.host` allows proxy bypass, substring origin matching enables phishing subdomains (e.g., `attacker-example.com`), challenge is not invalidated atomically leading to race conditions, User Verification (UV) is ignored, and monotonic sign count checking is completely absent.
```typescript
import { Request, Response } from 'express';

export async function verifyAssertion(req: Request, res: Response) {
  const { credential, challengeSessionId } = req.body;
  const session = await getSession(challengeSessionId);

  // CRITICAL FLAW 1: Origin extracted dynamically from untrusted Host header
  const expectedOrigin = `https://${req.headers.host}`;

  const clientData = JSON.parse(Buffer.from(credential.response.clientDataJSON, 'base64url').toString('utf8'));

  // CRITICAL FLAW 2: Loose origin check allows AitM phishing domains
  if (!clientData.origin.includes('example.com')) {
    return res.status(401).json({ error: 'Origin mismatch' });
  }

  // CRITICAL FLAW 3: Challenge not revoked before processing (replay window open)
  if (clientData.challenge !== session.challenge) {
    return res.status(401).json({ error: 'Invalid challenge' });
  }

  const authDataBuffer = Buffer.from(credential.response.authenticatorData, 'base64url');
  const flags = authDataBuffer[32];

  // CRITICAL FLAW 4: Only checking UP (User Presence 0x01), ignoring UV (User Verification 0x04)
  if ((flags & 0x01) === 0) {
    return res.status(401).json({ error: 'User presence required' });
  }

  // CRITICAL FLAW 5: Missing sign counter validation allows cloned authenticators
  return res.json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict canonical origin verification with constant-time equality against an immutable environment constant, consumes the challenge atomically before parsing, validates both UP and UV bitwise flags, checks the SHA-256 RP ID hash, and detects cloned authenticators by strictly enforcing monotonic sign counter increments.
```typescript
import crypto from 'node:crypto';
import { Request, Response } from 'express';

const CANONICAL_ORIGIN = process.env.AUTH_EXPECTED_ORIGIN!; // e.g. 'https://auth.example.com'
const EXPECTED_RP_ID = process.env.AUTH_EXPECTED_RP_ID!;     // e.g. 'example.com'
const EXPECTED_RP_ID_HASH = crypto.createHash('sha256').update(EXPECTED_RP_ID).digest();

const FLAG_USER_PRESENT = 0x01;
const FLAG_USER_VERIFIED = 0x04;

export async function verifyAssertion(req: Request, res: Response) {
  const { credential, challengeSessionId } = req.body;

  // ATOMIC CONSUMPTION: Challenge immediately consumed and invalidated
  const session = await consumeAndInvalidateSessionChallenge(challengeSessionId);
  if (!session || Date.now() > session.challengeExpiresAt) {
    return res.status(401).json({ error: 'Invalid or expired challenge' });
  }

  const clientData = JSON.parse(Buffer.from(credential.response.clientDataJSON, 'base64url').toString('utf8'));

  // INVARIANT 1: Client data type must strictly be authentication assertion
  if (clientData.type !== 'webauthn.get') {
    return res.status(400).json({ error: 'Unexpected clientData type' });
  }

  // INVARIANT 2: Exact constant-time origin verification
  const originMatches = crypto.timingSafeEqual(
    Buffer.from(clientData.origin, 'utf8'),
    Buffer.from(CANONICAL_ORIGIN, 'utf8')
  );
  if (!originMatches) {
    return res.status(401).json({ error: 'Origin verification failed' });
  }

  // INVARIANT 3: Cryptographic challenge timing-safe match
  const challengeMatches = crypto.timingSafeEqual(
    Buffer.from(clientData.challenge, 'base64url'),
    Buffer.from(session.challenge, 'base64url')
  );
  if (!challengeMatches) {
    return res.status(401).json({ error: 'Challenge verification failed' });
  }

  const authData = Buffer.from(credential.response.authenticatorData, 'base64url');
  if (authData.length < 37) {
    return res.status(400).json({ error: 'Malformed authenticatorData length' });
  }

  // INVARIANT 4: RP ID Hash matching
  const rpIdHash = authData.subarray(0, 32);
  if (!crypto.timingSafeEqual(rpIdHash, EXPECTED_RP_ID_HASH)) {
    return res.status(401).json({ error: 'RP ID Hash mismatch' });
  }

  // INVARIANT 5: Explicit User Verification (UV) and User Presence (UP) flags
  const flags = authData[32];
  const isUserPresent = (flags & FLAG_USER_PRESENT) !== 0;
  const isUserVerified = (flags & FLAG_USER_VERIFIED) !== 0;

  if (!isUserPresent || !isUserVerified) {
    return res.status(401).json({ error: 'Hardware User Verification (UV) required' });
  }

  // INVARIANT 6: Monotonic sign counter validation to detect cloned authenticators
  const signCounter = authData.readUInt32BE(33);
  const storedPasskey = await getPasskeyCredential(credential.id);

  if (signCounter > 0 || storedPasskey.counter > 0) {
    if (signCounter <= storedPasskey.counter) {
      await revokePasskeyCredential(storedPasskey.id, 'Cloned credential detected');
      return res.status(403).json({ error: 'Credential cloning detected. Revoked.' });
    }
    await updatePasskeyCounter(storedPasskey.id, signCounter);
  }

  // Complete cryptographic signature verification using the stored public key
  const isSignatureValid = verifyCredentialSignature(storedPasskey.publicKey, authData, clientData, credential.response.signature);
  if (!isSignatureValid) {
    return res.status(401).json({ error: 'Invalid authenticator signature' });
  }

  return res.json({ success: true, userId: storedPasskey.userId });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Level 3 Passkey Attestation, Exact Origin Binding, and UV Enforcement

WebAuthn Level 3 Passkey Attestation, Exact Origin Binding, and UV Enforcement defines an industrial-grade behavioral standard for security engineering. Enforces strict W3C WebAuthn Level 3 verification invariants during passkey registration and assertion. Mandates exact match comparisons against expected fully qualified origins (FQDN, scheme, port), hardware-backed User Verification (UV flag) enforcement, monotonic sign counter validation, and single-use cryptographic challenge invalidation to eliminate Adversary-in-the-Middle (AitM) phishing and credential cloning. 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: Accepting Spoofed Reverse-Proxy Origins, Regex Origin Wildcards, or Bypassing Hardware User Verification (UV) 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 DriftAccepting Spoofed Reverse-Proxy Origins, Regex Origin Wildcards, or Bypassing Hardware User Verification (UV)Critical
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 validate `clientDataJSON.origin` with constant-time exact byte equality against a deterministic server-side whitelist containing scheme, fully qualified domain, and explicit port (e.g., 'https

Engineers MUST ALWAYS validate `clientDataJSON.origin` with constant-time exact byte equality against a deterministic server-side whitelist containing scheme, fully qualified domain, and explicit port (e.g., 'https://auth.example.com:443').

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 derive the expected origin or RP ID from untrusted request headers such as `Host`, `X-Forwarded-Host`, `Referer`, or query parameters.

Engineers MUST NOT derive the expected origin or RP ID from untrusted request headers such as `Host`, `X-Forwarded-Host`, `Referer`, or query parameters.

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 verify that bit 2 (User Verification, UV) in the authenticator data flags byte (`flags & 0x04 !== 0`) is explicitly set for all primary and step-up passkey assertions.

Services MUST verify that bit 2 (User Verification, UV) in the authenticator data flags byte (`flags & 0x04 !== 0`) is explicitly set for all primary and step-up passkey assertions.

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 NOT accept User Presence (`flags & 0x01 !== 0`) alone as a substitute for User Verification (`UV`) when user verification is configured as 'required'.

Services MUST NOT accept User Presence (`flags & 0x01 !== 0`) alone as a substitute for User Verification (`UV`) when user verification is configured as '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.
5

Services MUST consume and invalidate the authentication challenge immediately upon lookup in server-side session storage to prevent replay attacks, checking expiration within a maximum TTL of 120 seconds.

Services MUST consume and invalidate the authentication challenge immediately upon lookup in server-side session storage to prevent replay attacks, checking expiration within a maximum TTL of 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.
6

Services MUST verify that `authData.rpIdHash` exactly matches the SHA-256 hash of the canonical Relying Party ID configured on the server.

Services MUST verify that `authData.rpIdHash` exactly matches the SHA-256 hash of the canonical Relying Party ID configured on the server.

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

Services MUST enforce monotonic sign counter progression

Services MUST enforce monotonic sign counter progression: if `newSignCount <= storedSignCount` and both values are greater than 0, the server MUST mark the passkey credential as cloned, revoke the credential, and terminate the 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.
8

Engineers MUST decode base64url payloads using secure constant-time parsers and enforce strict schema parsing on `clientDataJSON` and `authenticatorData` binary buffers.

Engineers MUST decode base64url payloads using secure constant-time parsers and enforce strict schema parsing on `clientDataJSON` and `authenticatorData` binary buffers.

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 Passkey Attestation, Exact Origin Binding, and UV Enforcement critical for AI coding assistants?

Enforces strict W3C WebAuthn Level 3 verification invariants during passkey registration and assertion. Mandates exact match comparisons against expected fully qualified origins (FQDN, scheme, port), hardware-backed User Verification (UV flag) enforcement, monotonic sign counter validation, and single-use cryptographic challenge invalidation to eliminate Adversary-in-the-Middle (AitM) phishing and credential cloning. 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 (Accepting Spoofed Reverse-Proxy Origins, Regex Origin Wildcards, or Bypassing Hardware User Verification (UV)) 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