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

Strict WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation

Enforces deterministic validation of WebAuthn Level 3 assertions, requiring exact origin matching, atomic challenge revocation, user verification enforcement, and monotonic signature counter validation. Prevents cross-origin credential harvesting, authenticator cloning, and assertion replay attacks across federated microservices.

Prohibited Anti-Pattern: Lax Origin Validation, Ignored SignCount Monotonicity, and Client-Supplied RP ID Trust

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation - Enforces deterministic validation of WebAuthn Level 3 assertions, requiring exact origin matching, atomic challenge revocation, user verification enforcement, and monotonic signature counter validation. Prevents cross-origin credential harvesting, authenticator cloning, and assertion replay attacks across federated microservices.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/security/**/*.{ts,tsx}, services/**/identity/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-passkey-cryptographic-origin-attestation"
---

# Strict WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Lax Origin Validation, Ignored SignCount Monotonicity, and Client-Supplied RP ID Trust

## System Constraints
You are a Principal Security Architect enforcing W3C WebAuthn Level 3 and FIDO2 standards across federated enterprise microservices. You must ensure that authentication assertions strictly validate cryptographic client data, reject regex-based or sub-domain wildcards on expected origins, verify bitwise authenticator flags (User Presence and User Verification), atomically invalidate single-use challenges, and strictly verify signature counters to detect cloned authenticators.

## Strict Guidelines
- Engineers MUST ALWAYS validate clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins using exact byte-wise comparison.
- Engineers MUST NEVER use regex patterns, substring checks, or wildcard parsing (e.g., *.corp.internal) to validate clientDataJSON.origin or rpId.
- Services MUST atomically consume and delete the cryptographic challenge upon first verification attempt using transactional key-value operations with strict TTLs (maximum 120 seconds).
- Services MUST verify that authenticatorData flags have both UP (User Present, 0x01) and UV (User Verified, 0x04) bits asserted when UserVerificationRequirement is set to 'required'.
- Engineers MUST enforce monotonic incrementation of the signCount field: if current signCount <= stored signCount and signCount != 0, the credential MUST be disabled immediately as compromised (authenticator cloning detection).
- Components NEVER pass raw WebAuthn assertions down to upstream internal microservices; the authentication edge MUST terminate the assertion and issue cryptographically bound, ephemeral DPoP-compliant tokens.

## Bad vs Good Implementations
### WebAuthn Assertion Verification Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The implementation performs an unsafe substring check on clientData.origin (vulnerable to attacker-controlled origins like attacker-myenterprise.com), accepts challenges from the client body instead of server-controlled storage, lacks atomic invalidation of challenges, fails to inspect authenticatorData flags (UV/UP), and ignores monotonic signature counters.
```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'));

  // CRITICAL VULNERABILITY: Loose origin check allows cross-site origin spoofing
  if (!clientData.origin.includes('myenterprise.com')) {
    return res.status(403).json({ error: 'Invalid origin' });
  }

  // VULNERABILITY: Challenge check without atomic invalidation allows replay attacks
  if (clientData.challenge !== expectedChallenge) {
    return res.status(401).json({ error: 'Challenge mismatch' });
  }

  // VULNERABILITY: Ignores flags (UV/UP) and signCount (authenticator cloning ignored)
  return res.json({ authenticated: true });
}
```

#### Production Standard (Correct)
> **Standard**: The remediated standard enforces atomic challenge consumption (GETDEL), exact array-bound origin matching, required user verification (UV flag), and strict verification of the monotonic signature counter to halt cloned hardware tokens.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { Redis } from 'ioredis';

interface VerifyParams {
  response: any;
  userId: string;
  storedPublicKey: Uint8Array;
  storedSignCount: number;
  redisClient: Redis;
  expectedRpId: string;
  trustedOrigins: readonly string[];
}

export async function verifyPasskeyAssertion({
  response,
  userId,
  storedPublicKey,
  storedSignCount,
  redisClient,
  expectedRpId,
  trustedOrigins
}: VerifyParams) {
  const challengeKey = `webauthn:challenge:${userId}`;
  
  // Atomically retrieve and delete challenge to strictly prevent replay
  const expectedChallenge = await redisClient.getdel(challengeKey);
  if (!expectedChallenge) {
    throw new SecurityException('ERR_CHALLENGE_EXPIRED_OR_REPLAYED', 'Cryptographic challenge not found or expired.');
  }

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge,
    expectedOrigin: trustedOrigins as unknown as string[],
    expectedRPID: expectedRpId,
    credential: {
      id: response.id,
      publicKey: storedPublicKey,
      counter: storedSignCount,
    },
    requireUserVerification: true,
  });

  if (!verification.verified || !verification.authenticationInfo) {
    throw new SecurityException('ERR_ATTESTATION_FAILED', 'Cryptographic signature verification failed.');
  }

  const { newCounter } = verification.authenticationInfo;

  // Strict monotonic check for cloning detection
  if (storedSignCount > 0 && newCounter <= storedSignCount) {
    // Flag credential as cloned and lock account
    throw new SecurityException('ERR_AUTHENTICATOR_CLONED', 'Potential authenticator cloning detected. Monotonic signCount violation.');
  }

  return {
    verified: true,
    updatedSignCount: newCounter,
  };
}

class SecurityException extends Error {
  constructor(public code: string, message: string) {
    super(message);
    this.name = 'SecurityException';
  }
}
```

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: Strict WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation

Strict WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation defines an industrial-grade behavioral standard for security engineering. Enforces deterministic validation of WebAuthn Level 3 assertions, requiring exact origin matching, atomic challenge revocation, user verification enforcement, and monotonic signature counter validation. Prevents cross-origin credential harvesting, authenticator cloning, and assertion replay attacks across federated microservices. 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: Lax Origin Validation, Ignored SignCount Monotonicity, and Client-Supplied RP ID Trust 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 DriftLax Origin Validation, Ignored SignCount Monotonicity, and Client-Supplied RP ID TrustCritical
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 against an explicit, immutable allowlist of fully qualified origins using exact byte-wise comparison.

Engineers MUST ALWAYS validate clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins using exact byte-wise comparison.

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 NEVER use regex patterns, substring checks, or wildcard parsing (e.g., *.corp.internal) to validate clientDataJSON.origin or rpId.

Engineers MUST NEVER use regex patterns, substring checks, or wildcard parsing (e.g., *.corp.internal) to validate clientDataJSON.origin or rpId.

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 atomically consume and delete the cryptographic challenge upon first verification attempt using transactional key-value operations with strict TTLs (maximum 120 seconds).

Services MUST atomically consume and delete the cryptographic challenge upon first verification attempt using transactional key-value operations with strict TTLs (maximum 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.
4

Services MUST verify that authenticatorData flags have both UP (User Present, 0x01) and UV (User Verified, 0x04) bits asserted when UserVerificationRequirement is set to 'required'.

Services MUST verify that authenticatorData flags have both UP (User Present, 0x01) and UV (User Verified, 0x04) bits asserted when UserVerificationRequirement is set to '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

Engineers MUST enforce monotonic incrementation of the signCount field

Engineers MUST enforce monotonic incrementation of the signCount field: if current signCount <= stored signCount and signCount != 0, the credential MUST be disabled immediately as compromised (authenticator cloning detection).

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 pass raw WebAuthn assertions down to upstream internal microservices

Components NEVER pass raw WebAuthn assertions down to upstream internal microservices; the authentication edge MUST terminate the assertion and issue cryptographically bound, ephemeral DPoP-compliant tokens.

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 WebAuthn Level 3 Passkey Cryptographic Origin and Monotonic State Attestation critical for AI coding assistants?

Enforces deterministic validation of WebAuthn Level 3 assertions, requiring exact origin matching, atomic challenge revocation, user verification enforcement, and monotonic signature counter validation. Prevents cross-origin credential harvesting, authenticator cloning, and assertion replay attacks across federated microservices. 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 (Lax Origin Validation, Ignored SignCount Monotonicity, and Client-Supplied RP ID Trust) 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