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

FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants

Enforces strict origin validation, cryptographically random single-use ephemeral challenges, monotonic signature counter tracking for clone detection, and hardware-attested user verification for high-privilege step-up operations. Prevents credential phishing, replay attacks, token cloning, and cross-origin relay vulnerabilities.

Prohibited Anti-Pattern: Accepting Untrusted Origins, Reusing Challenges, or Bypassing Monotonic SignCount Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants - Enforces strict origin validation, cryptographically random single-use ephemeral challenges, monotonic signature counter tracking for clone detection, and hardware-attested user verification for high-privilege step-up operations. Prevents credential phishing, replay attacks, token cloning, and cross-origin relay vulnerabilities.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-fido2-device-bound-attestation-invariants"
---

# FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Accepting Untrusted Origins, Reusing Challenges, or Bypassing Monotonic SignCount Checks

## System Constraints
You are a Principal Security Architect enforcing FIDO2/WebAuthn L3 standards. You must ensure all passkey registration, authentication, and step-up flows are strictly bound to cryptographic origin policies, employ single-use ephemeral challenges with bounded lifetimes, enforce user verification flags, and detect credential cloning via monotonic signature counters.

## Strict Guidelines
- Services MUST generate cryptographically secure, random challenges (minimum 32 bytes) with an ephemeral TTL (maximum 120 seconds) stored in server-side session state.
- Services MUST atomicaly invalidate challenges immediately upon first consumption to prevent replay attacks, irrespective of verification outcome.
- Engineers MUST ALWAYS validate 'clientDataJSON.origin' against an exact server-side allowlist of fully qualified canonical origins (scheme, host, port); wildcards and client-supplied origins are strictly forbidden.
- Engineers MUST verify that the SHA-256 hash of the expected 'rpId' matches the 'rpIdHash' present in the authenticator data.
- Services MUST verify that the 'flags.up' (User Present) and 'flags.uv' (User Verified) bits are set to true for sensitive and step-up transactions ('userVerification: required').
- Services MUST verify authenticator 'signCount' monotonically increases relative to the stored counter (unless both are 0); if 'signCount <= storedSignCount' and 'storedSignCount > 0', the service MUST revoke the credential immediately and alert security on cloned authenticator detection.
- Components NEVER store or transmit raw attestation certificates or clientDataJSON as plain strings without cryptographic signature and trust chain validation (e.g., against FIDO Metadata Service / MDS).

## Bad vs Good Implementations
### WebAuthn Authentication & Step-Up Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on client-provided origin header (enabling cross-origin relay and phishing), does not invalidate the challenge immediately, ignores monotonic counter regression allowing cloned passkeys, and fails to mandate User Verification (`requireUserVerification: false`).
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

export async function verifyAuth(req: Request, res: Response) {
  const { body, session } = req;
  const credential = await getCredentialFromDb(body.id);

  // ANTI-PATTERN: Client-derived origin, non-ephemeral challenge, missing signCount check,
  // and ignoring User Verification (UV) flags for privileged actions.
  const verification = await verifyAuthenticationResponse({
    response: body,
    expectedChallenge: session.challenge,
    expectedOrigin: req.headers.origin as string, // VULNERABILITY: Phishing & cross-origin relay
    expectedRPID: 'example.com',
    authenticator: {
      credentialPublicKey: credential.publicKey,
      credentialID: credential.id,
      counter: credential.counter,
    },
    requireUserVerification: false, // VULNERABILITY: Bypasses biometric/PIN hardware validation
  });

  if (verification.verified) {
    return res.json({ status: 'ok' });
  }
  return res.status(401).send('Unauthorized');
}
```

#### Production Standard (Correct)
> **Standard**: Strictly isolates and invalidates challenges upon receipt, enforces exact canonical server-configured origin, mandates biometric/PIN User Verification (`requireUserVerification: true`), and validates monotonic signature counters to detect and revoke cloned passkeys immediately.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

const EXPECTED_ORIGIN = process.env.NODE_ENV === 'production' 
  ? 'https://auth.enterprise.com' 
  : 'http://localhost:3000';
const EXPECTED_RP_ID = process.env.NODE_ENV === 'production' 
  ? 'auth.enterprise.com' 
  : 'localhost';

export async function verifyStepUpAuth(req: Request, res: Response) {
  const { body, session } = req;
  const challenge = session.webauthnChallenge;

  // INVARIANT: Consume and destroy challenge immediately to prevent replay attacks
  delete session.webauthnChallenge;
  await req.session.save();

  if (!challenge) {
    return res.status(400).json({ error: 'CHALLENGE_EXPIRED_OR_MISSING' });
  }

  const credential = await getCredentialFromDb(body.id);
  if (!credential || credential.isRevoked) {
    return res.status(401).json({ error: 'CREDENTIAL_INVALID' });
  }

  const verification = await verifyAuthenticationResponse({
    response: body,
    expectedChallenge: challenge,
    expectedOrigin: EXPECTED_ORIGIN,
    expectedRPID: EXPECTED_RP_ID,
    authenticator: {
      credentialPublicKey: credential.publicKey,
      credentialID: credential.id,
      counter: credential.counter,
    },
    requireUserVerification: true, // INVARIANT: Hardware-bound biometric or PIN required
  });

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

  const { newCounter } = verification.authenticationInfo;

  // INVARIANT: Detect cloned authenticator via monotonic signature counter
  if (credential.counter > 0 && newCounter <= credential.counter) {
    await revokeCredential(credential.id, 'CLONED_AUTHENTICATOR_DETECTED');
    await emitSecurityAlert('CLONED_PASSKEY_DETECTED', { userId: credential.userId, credentialId: credential.id });
    return res.status(403).json({ error: 'SECURITY_VIOLATION_PASSKEY_CLONED' });
  }

  await updateCredentialCounter(credential.id, newCounter);
  return res.json({ verified: true, stepUpToken: generateScopedStepUpJwt(credential.userId) });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants

FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants defines an industrial-grade behavioral standard for security engineering. Enforces strict origin validation, cryptographically random single-use ephemeral challenges, monotonic signature counter tracking for clone detection, and hardware-attested user verification for high-privilege step-up operations. Prevents credential phishing, replay attacks, token cloning, and cross-origin relay vulnerabilities. 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 Origins, Reusing Challenges, or Bypassing Monotonic SignCount 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 DriftAccepting Untrusted Origins, Reusing Challenges, or Bypassing Monotonic SignCount ChecksCritical
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, random challenges (minimum 32 bytes) with an ephemeral TTL (maximum 120 seconds) stored in server-side session state.

Services MUST generate cryptographically secure, random challenges (minimum 32 bytes) with an ephemeral TTL (maximum 120 seconds) stored in server-side session state.

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 atomicaly invalidate challenges immediately upon first consumption to prevent replay attacks, irrespective of verification outcome.

Services MUST atomicaly invalidate challenges immediately upon first consumption to prevent replay attacks, irrespective of verification outcome.

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 validate 'clientDataJSON.origin' against an exact server-side allowlist of fully qualified canonical origins (scheme, host, port)

Engineers MUST ALWAYS validate 'clientDataJSON.origin' against an exact server-side allowlist of fully qualified canonical origins (scheme, host, port); wildcards and client-supplied origins are strictly forbidden.

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 the SHA-256 hash of the expected 'rpId' matches the 'rpIdHash' present in the authenticator data.

Engineers MUST verify that the SHA-256 hash of the expected 'rpId' matches the 'rpIdHash' present in the authenticator data.

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 verify that the 'flags.up' (User Present) and 'flags.uv' (User Verified) bits are set to true for sensitive and step-up transactions ('userVerification

Services MUST verify that the 'flags.up' (User Present) and 'flags.uv' (User Verified) bits are set to true for sensitive and step-up transactions ('userVerification: 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.
6

Services MUST verify authenticator 'signCount' monotonically increases relative to the stored counter (unless both are 0)

Services MUST verify authenticator 'signCount' monotonically increases relative to the stored counter (unless both are 0); if 'signCount <= storedSignCount' and 'storedSignCount > 0', the service MUST revoke the credential immediately and alert security on 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

Components NEVER store or transmit raw attestation certificates or clientDataJSON as plain strings without cryptographic signature and trust chain validation (e.g., against FIDO Metadata Service / MDS).

Components NEVER store or transmit raw attestation certificates or clientDataJSON as plain strings without cryptographic signature and trust chain validation (e.g., against FIDO Metadata Service / MDS).

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 FIDO2 / WebAuthn Device-Bound Attestation and Step-Up Invariants critical for AI coding assistants?

Enforces strict origin validation, cryptographically random single-use ephemeral challenges, monotonic signature counter tracking for clone detection, and hardware-attested user verification for high-privilege step-up operations. Prevents credential phishing, replay attacks, token cloning, and cross-origin relay vulnerabilities. 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 Origins, Reusing Challenges, or Bypassing Monotonic SignCount 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

FIDO2