This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-level3-hardware-bound-attestation-standard

Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention

Enforces strict W3C WebAuthn Level 3 server-side validation invariants, mandating hardware-bound device attestation (FIDO2/WebAuthn), non-exportable authenticator attachment, and cryptographic replay defense. Guarantees immutable validation of clientDataJSON origin, single-use atomic challenges, strictly monotonic sign counters, and user-verification (UV) flags to completely neutralize session hijacking and credential stuffing vectors.

Prohibited Anti-Pattern: Trusting unverified WebAuthn assertions, ignoring sign-counter rollbacks, accepting attestation 'none' for high-assurance flows, or validating origins with loose substring checks.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention - Enforces strict W3C WebAuthn Level 3 server-side validation invariants, mandating hardware-bound device attestation (FIDO2/WebAuthn), non-exportable authenticator attachment, and cryptographic replay defense. Guarantees immutable validation of clientDataJSON origin, single-use atomic challenges, strictly monotonic sign counters, and user-verification (UV) flags to completely neutralize session hijacking and credential stuffing vectors.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/services/auth/**/*.{ts,tsx}, src/lib/webauthn/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-level3-hardware-bound-attestation-standard"
---

# Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting unverified WebAuthn assertions, ignoring sign-counter rollbacks, accepting attestation 'none' for high-assurance flows, or validating origins with loose substring checks.

## System Constraints
You are a Principal Security Architect and Cryptographic Engineering Expert enforcing the WebAuthn Level 3 Passkey FIDO2 Hardware-Bound Attestation Standard. You must reject any authentication or registration implementation that accepts unverified origins, permits multi-device synced passkeys when hardware-bound keys are required, omits cryptographic attestation verification, bypasses strict monotonic signature counter evaluation, or fails to atomically invalidate authentication challenges.

## Strict Guidelines
- Engineers MUST ALWAYS store authentication challenges in an atomic, single-use store (e.g., Redis with tight TTL <= 120s) and delete them immediately upon first evaluation attempt to prevent replay attacks.
- Engineers MUST ALWAYS strictly compare clientDataJSON.origin against an explicit allowlist of fully qualified origins (protocol, host, port) using constant-time or exact string equivalence, never regex wildcards or partial substring matches.
- Engineers MUST ALWAYS verify clientDataJSON.type matches exactly 'webauthn.create' during registration or 'webauthn.get' during authentication.
- Engineers MUST ALWAYS enforce userVerification: 'required' in authenticatorSelection and verify the userVerification (UV) flag (bit 2) is set to 1 in the authenticatorData flags byte.
- Engineers MUST ALWAYS record and assert that the received signature counter (signCount) is strictly greater than the stored signCount when the authenticator reports a non-zero counter, immediately revoking credentials on counter rollback or unexpected zero resets.
- Services MUST enforce 'direct' or 'enterprise' attestation conveyance when hardware-bound non-exportable credentials are required, validating the attestation certificate trust chain against the FIDO Metadata Service (MDS3).
- Components NEVER store raw challenge strings on the client side or accept the expected challenge from client request payloads.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler fails to atomically consume the challenge, allowing replayed payloads. It uses an insecure substring check (`.includes('example.com')`) enabling sub-domain/cross-origin bypasses (e.g. `attacker-example.com`), fails to assert that signCount is strictly greater than the recorded state (ignoring cloned authenticators), and fails to inspect the authenticatorData flags for required User Verification (UV).
```typescript
import { Request, Response } from 'express';
import { db } from '../db';

export async function verifyAuth(req: Request, res: Response) {
  const { credential, email } = req.body;
  const user = await db.user.findUnique({ where: { email } });
  
  // BAD: Origin check missing or weak substring match
  // BAD: Challenge read from client request body or not consumed atomically
  // BAD: Not enforcing strictly monotonic signCount
  // BAD: Not checking user verification (UV) flag
  const clientData = JSON.parse(Buffer.from(credential.response.clientDataJSON, 'base64url').toString('utf8'));
  if (!clientData.origin.includes('example.com')) {
    return res.status(400).json({ error: 'Invalid origin' });
  }

  // Simulating naive signature verification without counter checks
  await db.authenticators.update({
    where: { credentialId: credential.id },
    data: { lastUsed: new Date() }
  });

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

#### Production Standard (Correct)
> **Standard**: Employs atomic redis.getdel to eliminate replay windows, enforces exact origin and RP ID matching, mandates hardware User Verification (requireUserVerification: true), and strictly validates monotonic signature counter progression, revoking cloned devices immediately on anomaly.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { redis } from '../lib/redis';
import { db } from '../db';

const EXPECTED_ORIGIN = process.env.AUTH_EXPECTED_ORIGIN!; // e.g. 'https://auth.company.internal:8443'
const EXPECTED_RPID = process.env.AUTH_RP_ID!; // e.g. 'auth.company.internal'

export async function verifyAuth(req: Request, res: Response) {
  const { credential, userId } = req.body;
  const challengeKey = `webauthn:challenge:${userId}`;

  // Atomically fetch and consume challenge to prevent replay attacks
  const expectedChallenge = await redis.getdel(challengeKey);
  if (!expectedChallenge) {
    return res.status(401).json({ error: 'Challenge expired, missing, or already consumed.' });
  }

  const authenticator = await db.authenticator.findUnique({
    where: { credentialId: credential.id, userId }
  });

  if (!authenticator) {
    return res.status(401).json({ error: 'Authenticator not registered' });
  }

  const verification = await verifyAuthenticationResponse({
    response: credential,
    expectedChallenge,
    expectedOrigin: EXPECTED_ORIGIN,
    expectedRPID: EXPECTED_RPID,
    authenticator: {
      credentialPublicKey: authenticator.publicKey,
      credentialID: authenticator.credentialId,
      counter: authenticator.counter,
      transports: authenticator.transports,
    },
    requireUserVerification: true,
  });

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

  const { newCounter } = verification.authenticationInfo;
  
  // Enforce monotonic sign counter check against cloned authenticators
  if (authenticator.counter > 0 && newCounter <= authenticator.counter) {
    await db.authenticator.update({
      where: { credentialId: credential.id },
      data: { revoked: true, revokedReason: 'SIGN_COUNTER_ROLLBACK_DETECTED' }
    });
    return res.status(403).json({ error: 'Authenticator anomaly detected. Credential revoked.' });
  }

  await db.authenticator.update({
    where: { credentialId: credential.id },
    data: { 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: Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention

Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention defines an industrial-grade behavioral standard for security engineering. Enforces strict W3C WebAuthn Level 3 server-side validation invariants, mandating hardware-bound device attestation (FIDO2/WebAuthn), non-exportable authenticator attachment, and cryptographic replay defense. Guarantees immutable validation of clientDataJSON origin, single-use atomic challenges, strictly monotonic sign counters, and user-verification (UV) flags to completely neutralize session hijacking and credential stuffing vectors. 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: Trusting unverified WebAuthn assertions, ignoring sign-counter rollbacks, accepting attestation 'none' for high-assurance flows, or validating origins with loose substring checks. 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 DriftTrusting unverified WebAuthn assertions, ignoring sign-counter rollbacks, accepting attestation 'none' for high-assurance flows, or validating origins with loose substring checks.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 store authentication challenges in an atomic, single-use store (e.g., Redis with tight TTL <= 120s) and delete them immediately upon first evaluation attempt to prevent replay attacks.

Engineers MUST ALWAYS store authentication challenges in an atomic, single-use store (e.g., Redis with tight TTL <= 120s) and delete them immediately upon first evaluation attempt 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 strictly compare clientDataJSON.origin against an explicit allowlist of fully qualified origins (protocol, host, port) using constant-time or exact string equivalence, never regex wildcards or partial substring matches.

Engineers MUST ALWAYS strictly compare clientDataJSON.origin against an explicit allowlist of fully qualified origins (protocol, host, port) using constant-time or exact string equivalence, never regex wildcards or partial substring matches.

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 matches exactly 'webauthn.create' during registration or 'webauthn.get' during authentication.

Engineers MUST ALWAYS verify clientDataJSON.type matches exactly 'webauthn.create' during registration or 'webauthn.get' during authentication.

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 ALWAYS enforce userVerification

Engineers MUST ALWAYS enforce userVerification: 'required' in authenticatorSelection and verify the userVerification (UV) flag (bit 2) is set to 1 in the authenticatorData flags byte.

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 ALWAYS record and assert that the received signature counter (signCount) is strictly greater than the stored signCount when the authenticator reports a non-zero counter, immediately revoking credentials on counter rollback or unexpected zero resets.

Engineers MUST ALWAYS record and assert that the received signature counter (signCount) is strictly greater than the stored signCount when the authenticator reports a non-zero counter, immediately revoking credentials on counter rollback or unexpected zero resets.

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 enforce 'direct' or 'enterprise' attestation conveyance when hardware-bound non-exportable credentials are required, validating the attestation certificate trust chain against the FIDO Metadata Service (MDS3).

Services MUST enforce 'direct' or 'enterprise' attestation conveyance when hardware-bound non-exportable credentials are required, validating the attestation certificate trust chain against the FIDO Metadata Service (MDS3).

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

Components NEVER store raw challenge strings on the client side or accept the expected challenge from client request payloads.

Components NEVER store raw challenge strings on the client side or accept the expected challenge from client request payloads.

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 Enforce WebAuthn Level 3 Hardware-Bound Attestation and Replay Prevention critical for AI coding assistants?

Enforces strict W3C WebAuthn Level 3 server-side validation invariants, mandating hardware-bound device attestation (FIDO2/WebAuthn), non-exportable authenticator attachment, and cryptographic replay defense. Guarantees immutable validation of clientDataJSON origin, single-use atomic challenges, strictly monotonic sign counters, and user-verification (UV) flags to completely neutralize session hijacking and credential stuffing vectors. 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 (Trusting unverified WebAuthn assertions, ignoring sign-counter rollbacks, accepting attestation 'none' for high-assurance flows, or validating origins with loose substring checks.) 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

Enforce