This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-device-bound-assertion-replay-guardrail

WebAuthn & Passkey Device-Bound Assertion & Replay Protection Invariants

Enforces strict server-side validation of WebAuthn authenticator data, cryptographic challenge-response binding, client data origin validation, and signature counter monotonicity. Prevents cross-origin adversary-in-the-middle (AiTM) proxy attacks, credential replay, and challenge exhaustion across distributed authentication microservices.

Prohibited Anti-Pattern: Accepting Untrusted Origin Hashes, Ephemeral Challenge Re-use, or Unchecked Signature Counters

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn & Passkey Device-Bound Assertion & Replay Protection Invariants - Enforces strict server-side validation of WebAuthn authenticator data, cryptographic challenge-response binding, client data origin validation, and signature counter monotonicity. Prevents cross-origin adversary-in-the-middle (AiTM) proxy attacks, credential replay, and challenge exhaustion across distributed authentication microservices.
globs: src/auth/**/*.{ts,js,py,go}, src/server/auth/**/*.{ts,js,py,go}, src/services/passkey/**/*.{ts,js,py,go}, src/api/auth/**/*.{ts,js,py,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-device-bound-assertion-replay-guardrail"
---

# WebAuthn & Passkey Device-Bound Assertion & Replay Protection Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Untrusted Origin Hashes, Ephemeral Challenge Re-use, or Unchecked Signature Counters

## System Constraints
You are a Principal Security Architect enforcing WebAuthn / Passkey cryptographic invariants. Mandate strict adherence to RFC 9153 and FIDO2 specifications: challenge values must be cryptographically random, short-lived, single-use, and bound to the session context; clientDataJSON.origin and rpId must match the exact server-configured origin; authenticatorData flags (User Presence 'UP', User Verification 'UV') must be strictly checked; and signature counter (signCount) values must be monotonically increasing to detect cloned authenticators.

## Strict Guidelines
- Services MUST generate cryptographically secure (CSPRN) challenges with minimum 32 bytes of entropy stored in a stateful, single-use store (e.g., Redis with atomic GETDEL and <= 120s TTL).
- Services MUST verify that clientDataJSON.type strictly equals 'webauthn.get' for authentication assertions or 'webauthn.create' for registrations.
- Services MUST verify clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins (protocol, host, port) and NEVER allow wildcard prefixes or unvalidated reverse proxy headers.
- Services MUST compute the SHA-256 hash of the expected Relying Party ID (rpId) and ensure byte-for-byte equality with the first 32 bytes of authenticatorData (rpIdHash).
- Services MUST enforce the User Presence (UP) bit (bit 0) and, where required by policy, the User Verification (UV) bit (bit 2) within authenticatorData flags.
- Services MUST verify that authenticatorData.signCount is strictly greater than the stored credential signCount when signCount > 0, immediately invalidating the credential if zero or decremented (cloned authenticator detection).
- Engineers MUST NOT rely on client-reported RP IDs, origins, or bypass signature verification using mock credentials outside of isolated hermetic test harnesses.

## Bad vs Good Implementations
### Server-side WebAuthn Assertion Verification with Replay and Origin Invariants

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler accepts any origin containing 'example.com' (allowing attacker origins like example.com.evil.com), fails to consume challenges atomically (enabling replay attacks), ignores the Relying Party ID hash in authenticatorData, does not assert User Presence (UP) or User Verification (UV) flags, and skips monotonic signCount validation which fails to detect cloned authenticators.
```typescript
import { Request, Response } from 'express';
import { verifySignature } from './crypto';
import { db } from './db';

export async function verifyAssertion(req: Request, res: Response) {
  const { credentialId, clientDataJSON, authenticatorData, signature } = req.body;
  
  // VULNERABILITY 1: Parsing client data without checking consumed challenge in cache
  const clientData = JSON.parse(Buffer.from(clientDataJSON, 'base64url').toString('utf8'));
  
  // VULNERABILITY 2: Origin accepted from payload without canonical strict check
  if (!clientData.origin.includes('example.com')) {
    return res.status(400).json({ error: 'Invalid origin' });
  }

  const credential = await db.credentials.findUnique({ where: { id: credentialId } });
  if (!credential) return res.status(404).json({ error: 'Unknown credential' });

  // VULNERABILITY 3: Skipping UP/UV bit checking and signCount monotonicity check
  const isValid = verifySignature(credential.publicKey, clientDataJSON, authenticatorData, signature);
  if (!isValid) return res.status(401).json({ error: 'Signature mismatch' });

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

#### Production Standard (Correct)
> **Standard**: Applies all primary FIDO2 invariants: atomic single-use challenge consumption using Redis GETDEL, exact origin equality to block AiTM proxies, timing-safe rpIdHash comparison, bitwise verification of UP and UV flags, strict monotonic signCount verification with auto-revocation on clone detection, and cryptographic signature validation over authenticatorData || sha256(clientDataJSON).
```typescript
import { Request, Response } from 'express';
import crypto from 'node:crypto';
import { redis } from './redis';
import { db } from './db';
import { verifyWebAuthnSignature } from './crypto';

const EXPECTED_ORIGIN = 'https://auth.example.com';
const EXPECTED_RP_ID = 'example.com';
const EXPECTED_RP_ID_HASH = crypto.createHash('sha256').update(EXPECTED_RP_ID).digest();

export async function verifyAssertion(req: Request, res: Response) {
  const { credentialId, clientDataJSON, authenticatorData, signature, sessionId } = req.body;

  // INVARIANT 1: Atomic single-use challenge consumption (anti-replay)
  const challengeKey = `webauthn:challenge:${sessionId}`;
  const expectedChallenge = await redis.getdel(challengeKey);
  if (!expectedChallenge) {
    return res.status(401).json({ error: 'Challenge expired or already consumed' });
  }

  // INVARIANT 2: Strict ClientData validation
  const rawClientData = Buffer.from(clientDataJSON, 'base64url');
  const clientData = JSON.parse(rawClientData.toString('utf8'));
  
  if (clientData.type !== 'webauthn.get') {
    return res.status(400).json({ error: 'Invalid assertion operation type' });
  }
  if (clientData.origin !== EXPECTED_ORIGIN) {
    return res.status(403).json({ error: 'Origin mismatch: possible AiTM phishing' });
  }
  if (clientData.challenge !== expectedChallenge) {
    return res.status(401).json({ error: 'Cryptographic challenge mismatch' });
  }

  // INVARIANT 3: Authenticator Data rpIdHash & Flag validation
  const authDataBuffer = Buffer.from(authenticatorData, 'base64url');
  const rpIdHash = authDataBuffer.subarray(0, 32);
  if (!crypto.timingSafeEqual(rpIdHash, EXPECTED_RP_ID_HASH)) {
    return res.status(403).json({ error: 'RP ID hash does not match relying party' });
  }

  const flags = authDataBuffer[32];
  const userPresent = (flags & 0x01) !== 0;
  const userVerified = (flags & 0x04) !== 0;
  if (!userPresent || !userVerified) {
    return res.status(400).json({ error: 'User presence and verification required' });
  }

  // INVARIANT 4: Monotonic signCount validation (clone detection)
  const signCount = authDataBuffer.readUInt32BE(33);
  const credential = await db.credentials.findUnique({ where: { id: credentialId } });
  if (!credential) return res.status(404).json({ error: 'Credential not found' });

  if (credential.signCount !== 0 && signCount <= credential.signCount) {
    await db.credentials.update({ where: { id: credentialId }, data: { isRevoked: true } });
    return res.status(401).json({ error: 'Cloned authenticator detected; credential revoked' });
  }

  // INVARIANT 5: Signature verification over authenticatorData || sha256(clientDataJSON)
  const clientDataHash = crypto.createHash('sha256').update(rawClientData).digest();
  const verified = verifyWebAuthnSignature({
    publicKey: credential.publicKey,
    signature: Buffer.from(signature, 'base64url'),
    signedData: Buffer.concat([authDataBuffer, clientDataHash])
  });

  if (!verified) return res.status(401).json({ error: 'Invalid assertion signature' });

  await db.credentials.update({
    where: { id: credentialId },
    data: { signCount, lastUsedAt: new Date() }
  });

  return res.json({ success: 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: WebAuthn & Passkey Device-Bound Assertion & Replay Protection Invariants

WebAuthn & Passkey Device-Bound Assertion & Replay Protection Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict server-side validation of WebAuthn authenticator data, cryptographic challenge-response binding, client data origin validation, and signature counter monotonicity. Prevents cross-origin adversary-in-the-middle (AiTM) proxy attacks, credential replay, and challenge exhaustion across distributed authentication 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: Accepting Untrusted Origin Hashes, Ephemeral Challenge Re-use, or Unchecked Signature Counters 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 Untrusted Origin Hashes, Ephemeral Challenge Re-use, or Unchecked Signature CountersCritical
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

Services MUST generate cryptographically secure (CSPRN) challenges with minimum 32 bytes of entropy stored in a stateful, single-use store (e.g., Redis with atomic GETDEL and <= 120s TTL).

Services MUST generate cryptographically secure (CSPRN) challenges with minimum 32 bytes of entropy stored in a stateful, single-use store (e.g., Redis with atomic GETDEL and <= 120s TTL).

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 verify that clientDataJSON.type strictly equals 'webauthn.get' for authentication assertions or 'webauthn.create' for registrations.

Services MUST verify that clientDataJSON.type strictly equals 'webauthn.get' for authentication assertions or 'webauthn.create' for registrations.

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 clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins (protocol, host, port) and NEVER allow wildcard prefixes or unvalidated reverse proxy headers.

Services MUST verify clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins (protocol, host, port) and NEVER allow wildcard prefixes or unvalidated reverse proxy headers.

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 compute the SHA-256 hash of the expected Relying Party ID (rpId) and ensure byte-for-byte equality with the first 32 bytes of authenticatorData (rpIdHash).

Services MUST compute the SHA-256 hash of the expected Relying Party ID (rpId) and ensure byte-for-byte equality with the first 32 bytes of authenticatorData (rpIdHash).

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 enforce the User Presence (UP) bit (bit 0) and, where required by policy, the User Verification (UV) bit (bit 2) within authenticatorData flags.

Services MUST enforce the User Presence (UP) bit (bit 0) and, where required by policy, the User Verification (UV) bit (bit 2) within authenticatorData flags.

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 authenticatorData.signCount is strictly greater than the stored credential signCount when signCount > 0, immediately invalidating the credential if zero or decremented (cloned authenticator detection).

Services MUST verify that authenticatorData.signCount is strictly greater than the stored credential signCount when signCount > 0, immediately invalidating the credential if zero or decremented (cloned authenticator 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.
7

Engineers MUST NOT rely on client-reported RP IDs, origins, or bypass signature verification using mock credentials outside of isolated hermetic test harnesses.

Engineers MUST NOT rely on client-reported RP IDs, origins, or bypass signature verification using mock credentials outside of isolated hermetic test harnesses.

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 & Passkey Device-Bound Assertion & Replay Protection Invariants critical for AI coding assistants?

Enforces strict server-side validation of WebAuthn authenticator data, cryptographic challenge-response binding, client data origin validation, and signature counter monotonicity. Prevents cross-origin adversary-in-the-middle (AiTM) proxy attacks, credential replay, and challenge exhaustion across distributed authentication 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 (Accepting Untrusted Origin Hashes, Ephemeral Challenge Re-use, or Unchecked Signature Counters) 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