This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-passkey-device-binding-downgrade-prevention

WebAuthn Bound Device-State Verification & Downgrade Prevention

Enforces strict server-side validation of WebAuthn authenticator data bitwise flags (User Presence, User Verification, Backup State) during step-up and high-assurance transactions. Prohibits silent downgrade or exception-driven fallback to phishing-susceptible legacy factors (e.g., SMS OTP, standard TOTP) once a bound credential has been enrolled.

Prohibited Anti-Pattern: Silent Fallback to Phishing-Susceptible Factors and Unchecked Authenticator Flag Bitmasks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Bound Device-State Verification & Downgrade Prevention - Enforces strict server-side validation of WebAuthn authenticator data bitwise flags (User Presence, User Verification, Backup State) during step-up and high-assurance transactions. Prohibits silent downgrade or exception-driven fallback to phishing-susceptible legacy factors (e.g., SMS OTP, standard TOTP) once a bound credential has been enrolled.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, server/src/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-passkey-device-binding-downgrade-prevention"
---

# WebAuthn Bound Device-State Verification & Downgrade Prevention

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Silent Fallback to Phishing-Susceptible Factors and Unchecked Authenticator Flag Bitmasks

## System Constraints
You are a Principal Security Architect enforcing WebAuthn / FIDO2 device-binding verification and downgrade prevention invariants. You must mandate strict bitwise parsing of authenticatorData (UP, UV, BE, BS flags), verify signature counters to detect credential cloning, and reject any code paths that allow silent or client-driven fallback to legacy authentication mechanisms (SMS, email OTP, TOTP) when a passkey or hardware-bound credential is required.

## Strict Guidelines
- Servers MUST verify the User Presence (UP, bit 0) and User Verification (UV, bit 2) flags directly from the raw authenticatorData buffer using bitwise operations (UP: 0x01, UV: 0x04).
- Services MUST evaluate the Backup Eligibility (BE, bit 3) and Backup State (BS, bit 4) flags to distinguish between synced multi-device passkeys and non-exportable hardware-bound credentials when high-assurance policies mandate device-bound storage.
- Engineers MUST NOT implement catch blocks that automatically trigger legacy secondary factors (e.g., SMS OTP, email magic links) upon WebAuthn authentication failures or client cancellations.
- Authentication handlers MUST track and validate the monotonic signature counter (`signCount`) to detect cloned authenticators, raising an immediate security alert if `signCount <= previousSignCount` (unless `signCount == 0` for authenticators that omit counter support).
- Code MUST require cryptographic proof of origin and challenge matching, preventing cross-origin relay attacks and challenge replay across separate operational sessions.

## Bad vs Good Implementations
### WebAuthn Assertion Verification with Downgrade Prevention and Bitmask Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code fails to inspect authenticatorData bitmask flags (UP, UV, BE, BS), omits signCount verification against replay/cloning, and provides a silent downgrade mechanism to SMS OTP when WebAuthn fails or is canceled.
```typescript
import { Request, Response } from 'express';

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

  try {
    // VULNERABLE: Shallow validation, does not inspect bitwise flags
    const isValid = await verifyWebAuthnSignature(credentialId, clientDataJSON, signature);
    if (!isValid) {
      throw new Error('WebAuthn signature invalid');
    }
    return res.json({ status: 'success' });
  } catch (error) {
    // VULNERABLE: Silent fallback to phishing-prone SMS OTP upon failure/cancellation
    console.warn('WebAuthn failed, falling back to SMS OTP', error);
    await sendSmsOtp(userId);
    return res.status(200).json({ status: 'fallback', factor: 'sms_otp' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: The code extracts and enforces the UP and UV bitmask flags, blocks multi-device backups when device-bound keys are required, validates counter increments to stop cloning, and terminates on failure without allowing silent fallback to SMS.
```typescript
import { Request, Response } from 'express';
import crypto from 'crypto';

const FLAG_UP = 0x01; // Bit 0: User Presence
const FLAG_UV = 0x04; // Bit 2: User Verification
const FLAG_BE = 0x08; // Bit 3: Backup Eligibility
const FLAG_BS = 0x10; // Bit 4: Backup State

interface StoredCredential {
  publicKeyPem: string;
  signCount: number;
  requiresDeviceBound: boolean;
}

export async function verifyStepUpAuth(
  req: Request,
  res: Response,
  getCredential: (id: string) => Promise<StoredCredential | null>,
  expectedChallenge: string,
  expectedOrigin: string
) {
  const { credentialId, clientDataJSON, authenticatorData, signature } = req.body;

  const clientData = JSON.parse(Buffer.from(clientDataJSON, 'base64url').toString('utf8'));
  if (clientData.type !== 'webauthn.get' || clientData.challenge !== expectedChallenge || clientData.origin !== expectedOrigin) {
    return res.status(401).json({ error: 'Origin or challenge mismatch' });
  }

  const authDataBuffer = Buffer.from(authenticatorData, 'base64url');
  if (authDataBuffer.length < 37) {
    return res.status(400).json({ error: 'Malformed authenticator data' });
  }

  const flags = authDataBuffer[32];
  const isUp = (flags & FLAG_UP) !== 0;
  const isUv = (flags & FLAG_UV) !== 0;
  const isBe = (flags & FLAG_BE) !== 0;
  const isBs = (flags & FLAG_BS) !== 0;

  if (!isUp || !isUv) {
    return res.status(403).json({ error: 'User Presence and User Verification flags required' });
  }

  const credential = await getCredential(credentialId);
  if (!credential) {
    return res.status(404).json({ error: 'Credential not registered' });
  }

  if (credential.requiresDeviceBound && (isBe || isBs)) {
    return res.status(403).json({ error: 'High-assurance action mandates non-exportable device-bound credential' });
  }

  const signCount = authDataBuffer.readUInt32BE(33);
  if (signCount > 0 && signCount <= credential.signCount) {
    // Detected potential cloned authenticator
    return res.status(403).json({ error: 'Authenticator counter rollback detected' });
  }

  const clientDataHash = crypto.createHash('sha256').update(Buffer.from(clientDataJSON, 'base64url')).digest();
  const verifyPayload = Buffer.concat([authDataBuffer, clientDataHash]);
  const isSigValid = crypto.createVerify('SHA256')
    .update(verifyPayload)
    .verify(credential.publicKeyPem, Buffer.from(signature, 'base64url'));

  if (!isSigValid) {
    // NEVER fall back to legacy SMS/OTP factors; abort strictly
    return res.status(401).json({ error: 'Cryptographic assertion verification failed' });
  }

  return res.json({ status: 'verified', updatedSignCount: signCount });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Bound Device-State Verification & Downgrade Prevention

WebAuthn Bound Device-State Verification & Downgrade Prevention defines an industrial-grade behavioral standard for security engineering. Enforces strict server-side validation of WebAuthn authenticator data bitwise flags (User Presence, User Verification, Backup State) during step-up and high-assurance transactions. Prohibits silent downgrade or exception-driven fallback to phishing-susceptible legacy factors (e.g., SMS OTP, standard TOTP) once a bound credential has been enrolled. 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: Silent Fallback to Phishing-Susceptible Factors and Unchecked Authenticator Flag Bitmasks 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 DriftSilent Fallback to Phishing-Susceptible Factors and Unchecked Authenticator Flag BitmasksCritical
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

Servers MUST verify the User Presence (UP, bit 0) and User Verification (UV, bit 2) flags directly from the raw authenticatorData buffer using bitwise operations (UP

Servers MUST verify the User Presence (UP, bit 0) and User Verification (UV, bit 2) flags directly from the raw authenticatorData buffer using bitwise operations (UP: 0x01, UV: 0x04).

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 evaluate the Backup Eligibility (BE, bit 3) and Backup State (BS, bit 4) flags to distinguish between synced multi-device passkeys and non-exportable hardware-bound credentials when high-assurance policies mandate device-bound storage.

Services MUST evaluate the Backup Eligibility (BE, bit 3) and Backup State (BS, bit 4) flags to distinguish between synced multi-device passkeys and non-exportable hardware-bound credentials when high-assurance policies mandate device-bound storage.

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 NOT implement catch blocks that automatically trigger legacy secondary factors (e.g., SMS OTP, email magic links) upon WebAuthn authentication failures or client cancellations.

Engineers MUST NOT implement catch blocks that automatically trigger legacy secondary factors (e.g., SMS OTP, email magic links) upon WebAuthn authentication failures or client cancellations.

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

Authentication handlers MUST track and validate the monotonic signature counter (`signCount`) to detect cloned authenticators, raising an immediate security alert if `signCount <= previousSignCount` (unless `signCount == 0` for authenticators that omit counter support).

Authentication handlers MUST track and validate the monotonic signature counter (`signCount`) to detect cloned authenticators, raising an immediate security alert if `signCount <= previousSignCount` (unless `signCount == 0` for authenticators that omit counter support).

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

Code MUST require cryptographic proof of origin and challenge matching, preventing cross-origin relay attacks and challenge replay across separate operational sessions.

Code MUST require cryptographic proof of origin and challenge matching, preventing cross-origin relay attacks and challenge replay across separate operational sessions.

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 Bound Device-State Verification & Downgrade Prevention critical for AI coding assistants?

Enforces strict server-side validation of WebAuthn authenticator data bitwise flags (User Presence, User Verification, Backup State) during step-up and high-assurance transactions. Prohibits silent downgrade or exception-driven fallback to phishing-susceptible legacy factors (e.g., SMS OTP, standard TOTP) once a bound credential has been enrolled. 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 (Silent Fallback to Phishing-Susceptible Factors and Unchecked Authenticator Flag Bitmasks) 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