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

WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant

Cryptographically enforces adversary-in-the-middle (AiTM) session hijacking mitigation by binding continuous refresh-token rotations to hardware-backed platform authenticator assertions. Refresh token exchanges must require a fresh, server-issued cryptographic challenge signed by the registered WebAuthn credential keypair, strictly validating origin, RP ID, and signature counters before issuing subsequent credentials.

Prohibited Anti-Pattern: Decoupling Refresh Token Rotation from Hardware-Backed WebAuthn Cryptographic Signatures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant - Cryptographically enforces adversary-in-the-middle (AiTM) session hijacking mitigation by binding continuous refresh-token rotations to hardware-backed platform authenticator assertions. Refresh token exchanges must require a fresh, server-issued cryptographic challenge signed by the registered WebAuthn credential keypair, strictly validating origin, RP ID, and signature counters before issuing subsequent credentials.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/api/auth/**/*.{ts,tsx}, src/middleware/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-device-bound-session-assertion-invariant"
---

# WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Decoupling Refresh Token Rotation from Hardware-Backed WebAuthn Cryptographic Signatures

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant. You must reject any session refresh implementation that relies solely on bearer refresh tokens, ambient cookies, or unvalidated client metadata. Every session continuation or token rotation event MUST verify an asymmetric cryptographic proof produced by a registered platform authenticator against an ephemeral, single-use, server-stored challenge.

## Strict Guidelines
- Services MUST ALWAYS issue an ephemeral, single-use, cryptographically random challenge (minimum 32 bytes) tied to the active session ID prior to evaluating a refresh request.
- Services MUST verify the WebAuthn assertion signature using the enrolled public key, verifying that clientDataJSON.challenge matches the active challenge and clientDataJSON.origin matches the configured Relying Party origin exactly.
- Services MUST verify that authenticatorData flags have userPresence (UP) set and, if required by policy, userVerified (UV) set, rejecting assertions lacking required flags.
- Engineers MUST NOT allow silent token rotation or session extension on bearer tokens alone without verifying the corresponding hardware-bound credential assertion.
- Components NEVER store private WebAuthn keys in application memory, LocalStorage, or non-hardware-backed storage; assertions must originate directly from navigator.credentials.get via platform authenticators.
- Services MUST check and increment the stored signature counter (signCount); if the incoming signCount is non-zero and less than or equal to the recorded counter, the service MUST immediately invalidate the session and revoke the credential to neutralize cloned authenticators.

## Bad vs Good Implementations
### Device-Bound Refresh Token Rotation Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The endpoint treats the refresh token as a simple bearer secret. An AiTM adversary who proxies the initial login can steal the refresh token and replay it indefinitely on a different device without triggering authentication errors.
```typescript
import { Request, Response } from 'express';
import { db } from '../db';
import { signJwt } from '../jwt';

// VULNERABLE: Bearer refresh token accepted blindly without hardware-backed assertion.
// Reverse proxies (Evilginx) can capture and replay this token from anywhere.
export async function handleTokenRefresh(req: Request, res: Response) {
  const { refreshToken } = req.body;
  if (!refreshToken) {
    return res.status(400).json({ error: 'Missing refresh token' });
  }

  const session = await db.sessions.findUnique({ where: { token: refreshToken } });
  if (!session || session.expiresAt < new Date()) {
    return res.status(401).json({ error: 'Invalid or expired session' });
  }

  const newAccessToken = signJwt({ userId: session.userId }, '15m');
  const newRefreshToken = signJwt({ userId: session.userId }, '7d');
  await db.sessions.update({
    where: { id: session.id },
    data: { token: newRefreshToken }
  });

  return res.json({ accessToken: newAccessToken, refreshToken: newRefreshToken });
}
```

#### Production Standard (Correct)
> **Standard**: Binds rotation to WebAuthn asymmetric key verification. Challenges are single-use, RP origin and RP ID are checked against expected environment values, the authenticator's sign counter is verified against clone attacks, and the session cannot be refreshed without the physical hardware-backed authenticator.
```typescript
import { Request, Response } from 'express';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { db } from '../db';
import { signJwt } from '../jwt';
import crypto from 'node:crypto';

interface DeviceBoundRefreshBody {
  sessionId: string;
  assertionResponse: Parameters<typeof verifyAuthenticationResponse>[0]['response'];
}

export async function handleDeviceBoundRefresh(req: Request, res: Response) {
  const { sessionId, assertionResponse } = req.body as DeviceBoundRefreshBody;

  const session = await db.sessions.findUnique({
    where: { id: sessionId },
    include: { enrolledDeviceKey: true }
  });

  if (!session || !session.activeChallenge || session.expiresAt < new Date()) {
    return res.status(401).json({ error: 'Invalid or expired session context' });
  }

  const expectedChallenge = session.activeChallenge;
  // Invalidate challenge immediately to prevent replay
  await db.sessions.update({
    where: { id: session.id },
    data: { activeChallenge: null }
  });

  const verification = await verifyAuthenticationResponse({
    response: assertionResponse,
    expectedChallenge,
    expectedOrigin: process.env.AUTH_RP_ORIGIN!,
    expectedRPID: process.env.AUTH_RP_ID!,
    credential: {
      id: session.enrolledDeviceKey.credentialId,
      publicKey: Buffer.from(session.enrolledDeviceKey.publicKeyHex, 'hex'),
      counter: session.enrolledDeviceKey.counter
    },
    requireUserVerification: true
  });

  if (!verification.verified || !verification.authenticationInfo) {
    return res.status(403).json({ error: 'Device-bound assertion failed' });
  }

  const { newCounter } = verification.authenticationInfo;
  const nextChallenge = crypto.randomBytes(32).toString('base64url');

  await db.$transaction([
    db.enrolledDeviceKeys.update({
      where: { id: session.enrolledDeviceKey.id },
      data: { counter: newCounter }
    }),
    db.sessions.update({
      where: { id: session.id },
      data: {
        activeChallenge: nextChallenge,
        lastRefreshedAt: new Date()
      }
    })
  ]);

  const newAccessToken = signJwt({ userId: session.userId, deviceBound: true }, '15m');
  return res.json({
    accessToken: newAccessToken,
    nextChallenge
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant

WebAuthn Device-Bound Session Assertion (DBA) Re-Authentication Invariant defines an industrial-grade behavioral standard for security engineering. Cryptographically enforces adversary-in-the-middle (AiTM) session hijacking mitigation by binding continuous refresh-token rotations to hardware-backed platform authenticator assertions. Refresh token exchanges must require a fresh, server-issued cryptographic challenge signed by the registered WebAuthn credential keypair, strictly validating origin, RP ID, and signature counters before issuing subsequent credentials. 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: Decoupling Refresh Token Rotation from Hardware-Backed WebAuthn Cryptographic Signatures 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 DriftDecoupling Refresh Token Rotation from Hardware-Backed WebAuthn Cryptographic SignaturesCritical
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 ALWAYS issue an ephemeral, single-use, cryptographically random challenge (minimum 32 bytes) tied to the active session ID prior to evaluating a refresh request.

Services MUST ALWAYS issue an ephemeral, single-use, cryptographically random challenge (minimum 32 bytes) tied to the active session ID prior to evaluating a refresh request.

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 the WebAuthn assertion signature using the enrolled public key, verifying that clientDataJSON.challenge matches the active challenge and clientDataJSON.origin matches the configured Relying Party origin exactly.

Services MUST verify the WebAuthn assertion signature using the enrolled public key, verifying that clientDataJSON.challenge matches the active challenge and clientDataJSON.origin matches the configured Relying Party origin exactly.

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 flags have userPresence (UP) set and, if required by policy, userVerified (UV) set, rejecting assertions lacking required flags.

Services MUST verify that authenticatorData flags have userPresence (UP) set and, if required by policy, userVerified (UV) set, rejecting assertions lacking required 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.
4

Engineers MUST NOT allow silent token rotation or session extension on bearer tokens alone without verifying the corresponding hardware-bound credential assertion.

Engineers MUST NOT allow silent token rotation or session extension on bearer tokens alone without verifying the corresponding hardware-bound credential assertion.

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 store private WebAuthn keys in application memory, LocalStorage, or non-hardware-backed storage

Components NEVER store private WebAuthn keys in application memory, LocalStorage, or non-hardware-backed storage; assertions must originate directly from navigator.credentials.get via platform authenticators.

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 check and increment the stored signature counter (signCount)

Services MUST check and increment the stored signature counter (signCount); if the incoming signCount is non-zero and less than or equal to the recorded counter, the service MUST immediately invalidate the session and revoke the credential to neutralize cloned authenticators.

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 Device-Bound Session Assertion (DBA) Re-Authentication Invariant critical for AI coding assistants?

Cryptographically enforces adversary-in-the-middle (AiTM) session hijacking mitigation by binding continuous refresh-token rotations to hardware-backed platform authenticator assertions. Refresh token exchanges must require a fresh, server-issued cryptographic challenge signed by the registered WebAuthn credential keypair, strictly validating origin, RP ID, and signature counters before issuing subsequent credentials. 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 (Decoupling Refresh Token Rotation from Hardware-Backed WebAuthn Cryptographic Signatures) 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