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

WebAuthn L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard

Enforces strict WebAuthn Level 3 server-side validation invariants for passkey registration and authentication ceremonies. Mandates precise clientDataJSON origin/RP ID matching, monotonic sign-count inspection to detect cloned authenticators, user verification enforcement, and complete sandboxing against cross-origin iframe token-relay attacks.

Prohibited Anti-Pattern: Accepting unverified clientDataJSON origins, omitting sign-count regression checks, and permitting un-sandboxed passkey delegation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard - Enforces strict WebAuthn Level 3 server-side validation invariants for passkey registration and authentication ceremonies. Mandates precise clientDataJSON origin/RP ID matching, monotonic sign-count inspection to detect cloned authenticators, user verification enforcement, and complete sandboxing against cross-origin iframe token-relay attacks.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/passkey/**/*.{ts,tsx}, src/server/api/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-passkey-assertion-standard"
---

# WebAuthn L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting unverified clientDataJSON origins, omitting sign-count regression checks, and permitting un-sandboxed passkey delegation

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Level 3 Passkey Cryptographic Origin-Bound Assertion Standard. You must mandate strict byte-for-byte clientDataJSON parsing, immutable origin and RP ID validation against authoritative server configurations, cryptographic signature verification using authentic public keys, strict sign-count monotonicity checks to mitigate authenticator cloning, and complete elimination of un-sandboxed iframe passkey invocations.

## Strict Guidelines
- Engineers MUST ALWAYS verify that clientDataJSON.origin exactly matches the authoritative server origin (scheme, host, and port) with strict equality, never regex wildcards.
- Engineers MUST ALWAYS hash the expected RP ID using SHA-256 and assert exact byte-for-byte equality against the rpIdHash extracted from authData.
- Services MUST enforce strict sign-count monotonicity: if authData.signCount > 0 and storedSignCount > 0, authData.signCount MUST be strictly greater than storedSignCount; otherwise, immediately revoke the credential and raise an authenticator cloning alert.
- Engineers MUST verify the userVerification (UV) flag (bit 2 of authData.flags) is set when the ceremony mandates User Verification (required), rather than silently defaulting to userPresence (UP) alone.
- Components NEVER execute WebAuthn ceremonies inside iframes without explicit Permissions-Policy='publickey-credentials-create *; publickey-credentials-get *' and explicit cross-origin origin boundaries validated by the RP server.
- Services MUST ensure that challenge tokens are single-use, cryptographically random (minimum 32 bytes), TTL-bounded (<120 seconds), and stored server-side under an authenticated session or non-forgeable signed token.

## Bad vs Good Implementations
### Server-Side Passkey Assertion Verification with Origin & Monotonic Sign-Count Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Performs insecure substring origin verification vulnerable to subdomain/phishing bypasses, neglects SHA-256 rpIdHash verification against authData, ignores the User Verification flag, and fails to check sign-count monotonicity, permitting cloned authenticator replay attacks.
```typescript
import { Request, Response } from 'express';

export async function verifyAssertion(req: Request, res: Response) {
  const { credential, expectedChallenge } = req.body;
  const clientData = JSON.parse(Buffer.from(credential.response.clientDataJSON, 'base64url').toString('utf8'));
  
  // INSECURE: Loose challenge and origin checks
  if (!clientData.origin.includes('example.com')) {
    return res.status(400).send('Invalid origin');
  }
  if (clientData.challenge !== expectedChallenge) {
    return res.status(400).send('Invalid challenge');
  }
  
  // INSECURE: Ignores rpIdHash, UV bit, and signCount cloning detection
  const storedCred = await db.credentials.findUnique({ where: { id: credential.id } });
  return res.json({ success: true, userId: storedCred.userId });
}
```

#### Production Standard (Correct)
> **Standard**: Implements strict Level 3 WebAuthn assertion verification: verifies exact origin matching, constant-time challenge comparison, byte-level rpIdHash validation, mandatory UP/UV flag bits, monotonic sign-count check to detect cloning, and verifies the digital signature across concatenated authData and clientDataHash.
```typescript
import { createHash, timingSafeEqual } from 'crypto';
import { verifySignature } from './crypto-utils';

interface AssertionPayload {
  id: string;
  rawId: string;
  response: {
    clientDataJSON: string;
    authenticatorData: string;
    signature: string;
    userHandle?: string;
  };
}

export async function verifyAssertionStrict(
  payload: AssertionPayload,
  expectedChallenge: string,
  expectedOrigin: string,
  expectedRpId: string,
  storedCredential: { publicKeyPem: string; signCount: number; userId: string }
): Promise<{ valid: boolean; newSignCount: number }> {
  const clientDataRaw = Buffer.from(payload.response.clientDataJSON, 'base64url');
  const clientData = JSON.parse(clientDataRaw.toString('utf8'));

  if (clientData.type !== 'webauthn.get') {
    throw new Error('Invalid assertion type');
  }

  // Constant-time challenge verification
  const challengeMatch = timingSafeEqual(
    Buffer.from(clientData.challenge),
    Buffer.from(expectedChallenge)
  );
  if (!challengeMatch || clientData.origin !== expectedOrigin) {
    throw new Error('Origin or challenge validation failed');
  }

  const authData = Buffer.from(payload.response.authenticatorData, 'base64url');
  if (authData.length < 37) {
    throw new Error('Malformed authenticatorData');
  }

  // Verify rpIdHash (bytes 0..31)
  const expectedRpIdHash = createHash('sha256').update(expectedRpId).digest();
  const actualRpIdHash = authData.subarray(0, 32);
  if (!timingSafeEqual(expectedRpIdHash, actualRpIdHash)) {
    throw new Error('RP ID mismatch');
  }

  // Flags: Bit 0 = UP (User Presence), Bit 2 = UV (User Verification)
  const flags = authData[32];
  const isUp = (flags & 0x01) !== 0;
  const isUv = (flags & 0x04) !== 0;
  if (!isUp || !isUv) {
    throw new Error('User presence and user verification flags required');
  }

  // Sign-count monotonic increment check (bytes 33..36)
  const currentSignCount = authData.readUInt32BE(33);
  if (currentSignCount !== 0 || storedCredential.signCount !== 0) {
    if (currentSignCount <= storedCredential.signCount) {
      throw new Error('Authenticator cloning detected: signCount regression');
    }
  }

  // Cryptographic signature verification over authData || hash(clientDataJSON)
  const clientDataHash = createHash('sha256').update(clientDataRaw).digest();
  const signedPayload = Buffer.concat([authData, clientDataHash]);
  const sigBuffer = Buffer.from(payload.response.signature, 'base64url');

  const isSigValid = verifySignature(signedPayload, sigBuffer, storedCredential.publicKeyPem);
  if (!isSigValid) {
    throw new Error('Cryptographic signature verification failed');
  }

  return { valid: true, newSignCount: currentSignCount };
}
```

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 L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard

WebAuthn L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict WebAuthn Level 3 server-side validation invariants for passkey registration and authentication ceremonies. Mandates precise clientDataJSON origin/RP ID matching, monotonic sign-count inspection to detect cloned authenticators, user verification enforcement, and complete sandboxing against cross-origin iframe token-relay 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: Accepting unverified clientDataJSON origins, omitting sign-count regression checks, and permitting un-sandboxed passkey delegation 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 unverified clientDataJSON origins, omitting sign-count regression checks, and permitting un-sandboxed passkey delegationCritical
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 that clientDataJSON.origin exactly matches the authoritative server origin (scheme, host, and port) with strict equality, never regex wildcards.

Engineers MUST ALWAYS verify that clientDataJSON.origin exactly matches the authoritative server origin (scheme, host, and port) with strict equality, never regex wildcards.

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 hash the expected RP ID using SHA-256 and assert exact byte-for-byte equality against the rpIdHash extracted from authData.

Engineers MUST ALWAYS hash the expected RP ID using SHA-256 and assert exact byte-for-byte equality against the rpIdHash extracted from authData.

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 strict sign-count monotonicity

Services MUST enforce strict sign-count monotonicity: if authData.signCount > 0 and storedSignCount > 0, authData.signCount MUST be strictly greater than storedSignCount; otherwise, immediately revoke the credential and raise an authenticator cloning alert.

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

Engineers MUST verify the userVerification (UV) flag (bit 2 of authData.flags) is set when the ceremony mandates User Verification (required), rather than silently defaulting to userPresence (UP) alone.

Engineers MUST verify the userVerification (UV) flag (bit 2 of authData.flags) is set when the ceremony mandates User Verification (required), rather than silently defaulting to userPresence (UP) 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.
5

Components NEVER execute WebAuthn ceremonies inside iframes without explicit Permissions-Policy='publickey-credentials-create *

Components NEVER execute WebAuthn ceremonies inside iframes without explicit Permissions-Policy='publickey-credentials-create *; publickey-credentials-get *' and explicit cross-origin origin boundaries validated by the RP 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.
6

Services MUST ensure that challenge tokens are single-use, cryptographically random (minimum 32 bytes), TTL-bounded (<120 seconds), and stored server-side under an authenticated session or non-forgeable signed token.

Services MUST ensure that challenge tokens are single-use, cryptographically random (minimum 32 bytes), TTL-bounded (<120 seconds), and stored server-side under an authenticated session or non-forgeable signed token.

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 L3 Cryptographic Origin-Bound Assertion & Monotonic Verification Standard critical for AI coding assistants?

Enforces strict WebAuthn Level 3 server-side validation invariants for passkey registration and authentication ceremonies. Mandates precise clientDataJSON origin/RP ID matching, monotonic sign-count inspection to detect cloned authenticators, user verification enforcement, and complete sandboxing against cross-origin iframe token-relay 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 (Accepting unverified clientDataJSON origins, omitting sign-count regression checks, and permitting un-sandboxed passkey delegation) 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