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

WebAuthn Dynamic Attestation and Strict Origin-Binding Validation

Cryptographically enforces strict Relying Party ID (rpId) hashing, exact expected origin verification, and raw clientDataHash computation during WebAuthn registration and authentication ceremonies. Prevents credential-relay, subdomain manipulation, and Man-in-the-Middle (MITM) passkey replay attacks by mandating exact byte-level hashing of raw clientDataJSON and constant-time verification of session-bound cryptographic challenges.

Prohibited Anti-Pattern: Trusting Client-Supplied Origins and Deserializing clientDataJSON Prior to Hash Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Dynamic Attestation and Strict Origin-Binding Validation - Cryptographically enforces strict Relying Party ID (rpId) hashing, exact expected origin verification, and raw clientDataHash computation during WebAuthn registration and authentication ceremonies. Prevents credential-relay, subdomain manipulation, and Man-in-the-Middle (MITM) passkey replay attacks by mandating exact byte-level hashing of raw clientDataJSON and constant-time verification of session-bound cryptographic challenges.
globs: src/auth/**/*.{ts,js}, src/server/auth/**/*.{ts,js}, src/api/auth/**/*.{ts,js}, lib/auth/**/*.{ts,js}, **/*webauthn*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-dynamic-attestation-origin-binding-guardrail"
---

# WebAuthn Dynamic Attestation and Strict Origin-Binding Validation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting Client-Supplied Origins and Deserializing clientDataJSON Prior to Hash Verification

## System Constraints
You are a Principal Security Architect enforcing FIDO2/WebAuthn Level 3 specifications. Reject any implementation that performs loose origin checking, normalizes or re-encodes clientDataJSON prior to computing clientDataHash, accepts client-defined rpId values, or skips SHA-256 rpIdHash verification against authenticatorData. Mandate strict single-use challenge consumption, exact scheme-host-port origin verification, constant-time comparisons, and strict User Presence (UP) and User Verification (UV) flag checks.

## Strict Guidelines
- Engineers MUST ALWAYS compute `clientDataHash` directly from the raw incoming `clientDataJSON` byte buffer using SHA-256 rather than re-stringifying a parsed JSON object.
- Engineers MUST NOT permit wildcards, dynamic reflections of the HTTP `Host` header, or arbitrary subdomain matching when validating the `origin` field in `clientDataJSON`.
- Services MUST verify that `authenticatorData.rpIdHash` exactly matches `crypto.createHash('sha256').update(expectedRpId).digest()` using constant-time comparison.
- Services MUST atomically consume and invalidate the associated cryptographic challenge upon first verification attempt to prevent credential relay replay attacks.
- Components NEVER accept authentication assertions where the User Presence (`UP`) bit in `authenticatorData` flags is 0, and MUST enforce the User Verification (`UV`) bit when biometric/PIN verification is required.

## Bad vs Good Implementations
### WebAuthn Assertion Verification (Origin, rpIdHash, and clientDataHash)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example extracts clientDataJSON as a string, performs loose origin validation (allowing attacker-controlled domains like 'attacker-example.com'), omits rpIdHash validation against the authenticatorData buffer, and fails to invalidate the session challenge atomically.
```typescript
import { Request, Response } from 'express';

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

  // VULNERABLE: Parsing and re-encoding clientDataJSON changes byte representation
  const rawParsed = JSON.parse(Buffer.from(clientDataJSON, 'base64url').toString('utf8'));
  
  // VULNERABLE: Loose origin validation allowing arbitrary attacker subdomains or reflection
  if (!rawParsed.origin.includes('example.com')) {
    return res.status(400).json({ error: 'Invalid origin' });
  }

  // VULNERABLE: Challenge checked without single-use invalidation and with non-constant-time check
  if (rawParsed.challenge !== req.session.challenge) {
    return res.status(400).json({ error: 'Challenge mismatch' });
  }

  // VULNERABLE: Fails to verify rpIdHash in authenticatorData matches configured rpId
  // Signature verification omitted or flawed...
  return res.status(200).json({ verified: true });
}
```

#### Production Standard (Correct)
> **Standard**: Computes clientDataHash over raw input bytes, executes exact origin matching via strict set lookup, uses crypto.timingSafeEqual for challenge and rpIdHash comparisons, and verifies authenticatorData flags (UP/UV) according to the W3C WebAuthn Level 3 specification.
```typescript
import crypto from 'node:crypto';

interface VerifyAssertionParams {
  rawClientDataJSON: Buffer;
  rawAuthenticatorData: Buffer;
  signature: Buffer;
  expectedChallenge: string;
  expectedRpId: string;
  allowedOrigins: ReadonlySet<string>;
}

export function verifyPasskeyAssertion({
  rawClientDataJSON,
  rawAuthenticatorData,
  expectedChallenge,
  expectedRpId,
  allowedOrigins,
}: VerifyAssertionParams): { clientDataHash: Buffer; rpIdHashVerified: boolean } {
  // 1. Compute clientDataHash directly on raw bytes
  const clientDataHash = crypto.createHash('sha256').update(rawClientDataJSON).digest();

  // 2. Parse clientDataJSON safely for type, challenge, origin
  const clientData = JSON.parse(rawClientDataJSON.toString('utf8'));
  if (clientData.type !== 'webauthn.get') {
    throw new Error('Invalid assertion ceremony type');
  }

  // 3. Strict, exact origin verification (scheme + host + port)
  if (!allowedOrigins.has(clientData.origin)) {
    throw new SecurityError(`Origin mismatch: ${clientData.origin}`);
  }

  // 4. Constant-time challenge comparison
  const challengeBuf = Buffer.from(clientData.challenge, 'base64url');
  const expectedBuf = Buffer.from(expectedChallenge, 'base64url');
  if (challengeBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(challengeBuf, expectedBuf)) {
    throw new SecurityError('Cryptographic challenge mismatch');
  }

  // 5. Verify rpIdHash from authenticatorData bytes (first 32 bytes)
  if (rawAuthenticatorData.length < 37) {
    throw new SecurityError('Malformed authenticatorData');
  }
  const authDataRpIdHash = rawAuthenticatorData.subarray(0, 32);
  const expectedRpIdHash = crypto.createHash('sha256').update(expectedRpId).digest();

  if (!crypto.timingSafeEqual(authDataRpIdHash, expectedRpIdHash)) {
    throw new SecurityError('RP ID hash mismatch');
  }

  // 6. Verify User Presence (UP) bit 0 is set
  const flags = rawAuthenticatorData[32];
  const userPresence = (flags & 0x01) !== 0;
  if (!userPresence) {
    throw new SecurityError('User Presence (UP) flag not set');
  }

  return { clientDataHash, rpIdHashVerified: 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 Dynamic Attestation and Strict Origin-Binding Validation

WebAuthn Dynamic Attestation and Strict Origin-Binding Validation defines an industrial-grade behavioral standard for security engineering. Cryptographically enforces strict Relying Party ID (rpId) hashing, exact expected origin verification, and raw clientDataHash computation during WebAuthn registration and authentication ceremonies. Prevents credential-relay, subdomain manipulation, and Man-in-the-Middle (MITM) passkey replay attacks by mandating exact byte-level hashing of raw clientDataJSON and constant-time verification of session-bound cryptographic challenges. 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 and Deserializing clientDataJSON Prior to Hash 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 and Deserializing clientDataJSON Prior to Hash 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 compute `clientDataHash` directly from the raw incoming `clientDataJSON` byte buffer using SHA-256 rather than re-stringifying a parsed JSON object.

Engineers MUST ALWAYS compute `clientDataHash` directly from the raw incoming `clientDataJSON` byte buffer using SHA-256 rather than re-stringifying a parsed JSON object.

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 NOT permit wildcards, dynamic reflections of the HTTP `Host` header, or arbitrary subdomain matching when validating the `origin` field in `clientDataJSON`.

Engineers MUST NOT permit wildcards, dynamic reflections of the HTTP `Host` header, or arbitrary subdomain matching when validating the `origin` field in `clientDataJSON`.

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 that `authenticatorData.rpIdHash` exactly matches `crypto.createHash('sha256').update(expectedRpId).digest()` using constant-time comparison.

Services MUST verify that `authenticatorData.rpIdHash` exactly matches `crypto.createHash('sha256').update(expectedRpId).digest()` using constant-time 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.
4

Services MUST atomically consume and invalidate the associated cryptographic challenge upon first verification attempt to prevent credential relay replay attacks.

Services MUST atomically consume and invalidate the associated cryptographic challenge upon first verification attempt to prevent credential relay 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.
5

Components NEVER accept authentication assertions where the User Presence (`UP`) bit in `authenticatorData` flags is 0, and MUST enforce the User Verification (`UV`) bit when biometric/PIN verification is required.

Components NEVER accept authentication assertions where the User Presence (`UP`) bit in `authenticatorData` flags is 0, and MUST enforce the User Verification (`UV`) bit when biometric/PIN verification is 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is WebAuthn Dynamic Attestation and Strict Origin-Binding Validation critical for AI coding assistants?

Cryptographically enforces strict Relying Party ID (rpId) hashing, exact expected origin verification, and raw clientDataHash computation during WebAuthn registration and authentication ceremonies. Prevents credential-relay, subdomain manipulation, and Man-in-the-Middle (MITM) passkey replay attacks by mandating exact byte-level hashing of raw clientDataJSON and constant-time verification of session-bound cryptographic challenges. 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 and Deserializing clientDataJSON Prior to Hash 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

WebAuthn