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

Strict WebAuthn/FIDO2 Origin Binding, Attestation, and Replay Protection

Enforces strict cryptographic verification of WebAuthn and FIDO2 passkey assertions and registrations. Guarantees immutable clientDataJSON origin validation, exact challenge-response replay matching with single-use eviction, RP ID boundary enforcement, and authenticator counter regression checks to defeat reverse-proxy adversary-in-the-middle (AiTM) phishing.

Prohibited Anti-Pattern: Trusting Client-Supplied Origins, Non-Atomic Challenges, or Skipping Cryptographic Counter & Origin Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict WebAuthn/FIDO2 Origin Binding, Attestation, and Replay Protection - Enforces strict cryptographic verification of WebAuthn and FIDO2 passkey assertions and registrations. Guarantees immutable clientDataJSON origin validation, exact challenge-response replay matching with single-use eviction, RP ID boundary enforcement, and authenticator counter regression checks to defeat reverse-proxy adversary-in-the-middle (AiTM) phishing.
globs: src/**/auth/**/*.{ts,js}, src/**/webauthn/**/*.{ts,js}, src/**/fido2/**/*.{ts,js}, src/**/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-origin-binding-attestation-guardrail"
---

# Strict WebAuthn/FIDO2 Origin Binding, Attestation, and Replay Protection

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting Client-Supplied Origins, Non-Atomic Challenges, or Skipping Cryptographic Counter & Origin Verification

## System Constraints
You are a Principal Security Architect enforcing FIDO2 WebAuthn cryptographic invariants. You must prevent reverse-proxy (AiTM) phishing, replay attacks, and credential tampering by mandating exact origin matching against server configuration, single-use cryptographically random challenges, monotonic sign-count enforcement, and valid authenticator/clientDataJSON deserialization. Reject any PR that uses client-supplied Host headers, omits RP ID checks, or allows challenge reuse.

## Strict Guidelines
- Engineers MUST ALWAYS validate clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins (protocol, domain, port) configured server-side, never trusting HTTP Request headers (e.g., Host, X-Forwarded-Host).
- Engineers MUST atomically consume and delete the WebAuthn challenge from server-side storage (e.g., Redis session or signed ephemeral cookie) immediately upon receipt to prevent replay attacks.
- Engineers MUST enforce strict RP ID hashing invariants (SHA-256 of rpId matching authenticatorData.rpIdHash), ensuring rpId conforms to the exact registrable domain of the relying party.
- Engineers MUST verify that authenticatorData.flags has the User Present (UP) bit set for all operations, and User Verified (UV) bit set whenever required by authentication policy.
- Engineers MUST compare the received signCount against the stored credential counter; if received signCount is non-zero and less than or equal to stored signCount, the authenticator MUST be marked as cloned and the session aborted immediately.
- Engineers MUST NOT rely on client-side parsing or validation of attestation/assertion objects; cryptographic signatures MUST be verified using canonical public keys (COSE/WebCrypto) on the backend server.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Vulnerable to AiTM reverse proxying and replay attacks. It accepts req.headers.origin dynamically, fails to evict the challenge immediately (allowing reuse), skips RP ID hash checking, and ignores signCount verification, which allows cloned authenticators to authenticate undetected.
```typescript
import { Request, Response } from 'express';

export async function verifyAssertion(req: Request, res: Response) {
  const { credential, userId } = req.body;
  const user = await db.users.findById(userId);
  const storedChallenge = await cache.get(`challenge:${userId}`);

  // VULNERABILITIES: Uses client-provided origin, does not atomically delete challenge,
  // ignores signature counter regression (cloned authenticator detection), and omits rpId checks.
  const clientData = JSON.parse(Buffer.from(credential.response.clientDataJSON, 'base64').toString('utf8'));

  if (clientData.challenge !== storedChallenge) {
    return res.status(400).send('Invalid challenge');
  }

  // Insecure dynamic origin verification allowing reverse proxies
  if (clientData.origin !== req.headers.origin) {
    return res.status(400).send('Origin mismatch');
  }

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

#### Production Standard (Correct)
> **Standard**: Atomic get-and-delete eliminates replay attacks. Verification enforces expectedRPID and a strict, hard-coded ALLOWED_ORIGINS tuple to prevent AiTM reverse proxies. The monotonic signCount is verified and updated, detecting and rejecting cloned authenticators.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { EXPECTED_RP_ID, ALLOWED_ORIGINS } from '../config/auth';

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

  // 1. Atomic challenge consumption to prevent replay
  const challengeKey = `webauthn:challenge:${userId}`;
  const expectedChallenge = await cache.getAndDelete(challengeKey);
  if (!expectedChallenge) {
    return res.status(403).json({ error: 'Challenge expired or already consumed' });
  }

  const passkey = await db.passkeys.findUnique({
    where: { credentialId: credential.id, userId },
  });
  if (!passkey) {
    return res.status(404).json({ error: 'Passkey not registered' });
  }

  try {
    // 2. Cryptographic verification against strict server-side invariants
    const verification = await verifyAuthenticationResponse({
      response: credential,
      expectedChallenge,
      expectedOrigin: ALLOWED_ORIGINS,
      expectedRPID: EXPECTED_RP_ID,
      authenticator: {
        credentialPublicKey: passkey.publicKey,
        credentialID: passkey.credentialId,
        counter: passkey.counter,
        transports: passkey.transports,
      },
      requireUserVerification: true,
    });

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

    // 3. Monotonic counter update to catch authenticator cloning
    await db.passkeys.update({
      where: { credentialId: credential.id },
      data: { counter: verification.authenticationInfo.newCounter },
    });

    return res.json({ success: true });
  } catch (error) {
    return res.status(400).json({ error: 'Verification failed' });
  }
}
```

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/FIDO2 Origin Binding, Attestation, and Replay Protection

Strict WebAuthn/FIDO2 Origin Binding, Attestation, and Replay Protection defines an industrial-grade behavioral standard for security engineering. Enforces strict cryptographic verification of WebAuthn and FIDO2 passkey assertions and registrations. Guarantees immutable clientDataJSON origin validation, exact challenge-response replay matching with single-use eviction, RP ID boundary enforcement, and authenticator counter regression checks to defeat reverse-proxy adversary-in-the-middle (AiTM) phishing. 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 Client-Supplied Origins, Non-Atomic Challenges, or Skipping Cryptographic Counter & Origin Verification 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 Client-Supplied Origins, Non-Atomic Challenges, or Skipping Cryptographic Counter & Origin VerificationCritical
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 (protocol, domain, port) configured server-side, never trusting HTTP Request headers (e.g., Host, X-Forwarded-Host).

Engineers MUST ALWAYS validate clientDataJSON.origin against an explicit, immutable allowlist of fully qualified origins (protocol, domain, port) configured server-side, never trusting HTTP Request headers (e.g., Host, X-Forwarded-Host).

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 atomically consume and delete the WebAuthn challenge from server-side storage (e.g., Redis session or signed ephemeral cookie) immediately upon receipt to prevent replay attacks.

Engineers MUST atomically consume and delete the WebAuthn challenge from server-side storage (e.g., Redis session or signed ephemeral cookie) immediately upon receipt 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.
3

Engineers MUST enforce strict RP ID hashing invariants (SHA-256 of rpId matching authenticatorData.rpIdHash), ensuring rpId conforms to the exact registrable domain of the relying party.

Engineers MUST enforce strict RP ID hashing invariants (SHA-256 of rpId matching authenticatorData.rpIdHash), ensuring rpId conforms to the exact registrable domain of the relying party.

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 that authenticatorData.flags has the User Present (UP) bit set for all operations, and User Verified (UV) bit set whenever required by authentication policy.

Engineers MUST verify that authenticatorData.flags has the User Present (UP) bit set for all operations, and User Verified (UV) bit set whenever required by authentication policy.

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 compare the received signCount against the stored credential counter

Engineers MUST compare the received signCount against the stored credential counter; if received signCount is non-zero and less than or equal to stored signCount, the authenticator MUST be marked as cloned and the session aborted immediately.

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

Engineers MUST NOT rely on client-side parsing or validation of attestation/assertion objects

Engineers MUST NOT rely on client-side parsing or validation of attestation/assertion objects; cryptographic signatures MUST be verified using canonical public keys (COSE/WebCrypto) on the backend 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Strict WebAuthn/FIDO2 Origin Binding, Attestation, and Replay Protection critical for AI coding assistants?

Enforces strict cryptographic verification of WebAuthn and FIDO2 passkey assertions and registrations. Guarantees immutable clientDataJSON origin validation, exact challenge-response replay matching with single-use eviction, RP ID boundary enforcement, and authenticator counter regression checks to defeat reverse-proxy adversary-in-the-middle (AiTM) phishing. 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 Client-Supplied Origins, Non-Atomic Challenges, or Skipping Cryptographic Counter & Origin Verification) 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