This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: webauthn-cross-device-hybrid-replay-guardrail

WebAuthn Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention

Mandates cryptographically bound ephemeral session identifiers, atomic challenge consumption, and strict origin/cross-origin validation during FIDO2/WebAuthn hybrid transport (caBLE) flows. Prevents QR-code phishing, cross-origin assertion forwarding, and race-condition replay attacks across disparate client contexts.

Prohibited Anti-Pattern: Decoupled Hybrid Authentication Challenges and Non-Atomic Origin Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention - Mandates cryptographically bound ephemeral session identifiers, atomic challenge consumption, and strict origin/cross-origin validation during FIDO2/WebAuthn hybrid transport (caBLE) flows. Prevents QR-code phishing, cross-origin assertion forwarding, and race-condition replay attacks across disparate client contexts.
globs: src/auth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,js}, src/api/auth/**/*.ts, src/services/passkey/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-cross-device-hybrid-replay-guardrail"
---

# WebAuthn Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Decoupled Hybrid Authentication Challenges and Non-Atomic Origin Verification

## System Constraints
You are a Principal Security Architect enforcing zero-trust WebAuthn Level 3 specifications. When implementing or reviewing cross-device hybrid authentication (QR code/caBLE), you must mandate that challenges are cryptographically bound to ephemeral browser sessions, consumed atomically prior to cryptographic verification, and strictly verified against RP origins and cross-origin flags.

## Strict Guidelines
- Engineers MUST ALWAYS atomically consume (burn-on-read via GETDEL or atomic transaction) the WebAuthn challenge before executing cryptographic signature verification to prevent replay race conditions.
- Engineers MUST ALWAYS cryptographically bind the WebAuthn challenge to the specific ephemeral session ID (e.g., WebSocket channel or polling token) initialized during the QR code generation handshake.
- Engineers MUST NOT accept assertions where clientDataJSON.crossOrigin is true unless an explicit, authenticated cross-origin federation allowlist matches the exact origin.
- Services MUST verify that clientDataJSON.origin matches the exact expected scheme, fully qualified domain name, and port of the Relying Party.
- Components NEVER store hybrid session credentials or challenges in shared, un-namespaced caches without explicit TTLs (maximum 120 seconds for hybrid exchanges).

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The challenge is read non-atomically and deleted only after signature verification, opening a race window for concurrent assertion replay. It also fails to inspect crossOrigin flags and does not verify that the ephemeral hybrid session context matches the client that requested the QR code.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { Request, Response } from 'express';
import { db } from '../db';

export async function handleHybridVerify(req: Request, res: Response) {
  const { sessionId, response } = req.body;

  // BAD: Non-atomic challenge retrieval allows replay race conditions
  const session = await db.sessions.findById(sessionId);
  if (!session || !session.expectedChallenge) {
    return res.status(400).json({ error: 'Session expired' });
  }

  // BAD: Ignores crossOrigin flag and lacks cryptographic session binding
  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge: session.expectedChallenge,
    expectedOrigin: 'https://example.com',
    expectedRPID: 'example.com',
    credential: session.userCredential,
  });

  if (verification.verified) {
    // BAD: Deleting challenge after verification leaves a race window
    await db.sessions.update(sessionId, { expectedChallenge: null });
    return res.json({ success: true });
  }
  return res.status(401).json({ error: 'Verification failed' });
}
```

#### Production Standard (Correct)
> **Standard**: Employs an atomic GETDEL to invalidate the challenge before processing, validates an ephemeral session secret via constant-time comparison, strictly rejects clientDataJSON crossOrigin assertions, and verifies credential ownership against the bound user context.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import { Request, Response } from 'express';
import { redis } from '../services/redis';
import { db } from '../db';
import crypto from 'node:crypto';

interface StoredChallengeContext {
  challenge: string;
  sessionBindingHash: string;
  userId: string;
}

export async function handleHybridVerify(req: Request, res: Response) {
  const { sessionId, response } = req.body;
  const clientSessionSecret = req.headers['x-hybrid-session-secret'];

  if (typeof clientSessionSecret !== 'string' || !sessionId) {
    return res.status(400).json({ error: 'Malformed hybrid verification context' });
  }

  // GOOD: Atomically fetch and delete challenge to enforce single-use execution
  const rawContext = await redis.getdel(`hybrid_challenge:${sessionId}`);
  if (!rawContext) {
    return res.status(400).json({ error: 'Challenge expired or already consumed' });
  }

  const context: StoredChallengeContext = JSON.parse(rawContext);

  // GOOD: Verify ephemeral cryptographic session binding
  const computedHash = crypto.createHash('sha256').update(clientSessionSecret).digest('hex');
  if (!crypto.timingSafeEqual(Buffer.from(computedHash), Buffer.from(context.sessionBindingHash))) {
    return res.status(403).json({ error: 'Hybrid session binding mismatch' });
  }

  // GOOD: Strict inspection of clientDataJSON parameters including crossOrigin
  const clientData = JSON.parse(Buffer.from(response.clientDataJSON, 'base64url').toString('utf-8'));
  if (clientData.crossOrigin === true) {
    return res.status(403).json({ error: 'Cross-origin assertions strictly prohibited for hybrid flow' });
  }

  const userCredential = await db.credentials.findByCredentialId(response.id);
  if (!userCredential || userCredential.userId !== context.userId) {
    return res.status(401).json({ error: 'Credential ownership mismatch' });
  }

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge: context.challenge,
    expectedOrigin: process.env.RP_ORIGIN!,
    expectedRPID: process.env.RP_ID!,
    credential: userCredential,
    requireUserVerification: true,
  });

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

  return res.json({ success: true, userId: context.userId });
}
```

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 Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention

WebAuthn Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention defines an industrial-grade behavioral standard for security engineering. Mandates cryptographically bound ephemeral session identifiers, atomic challenge consumption, and strict origin/cross-origin validation during FIDO2/WebAuthn hybrid transport (caBLE) flows. Prevents QR-code phishing, cross-origin assertion forwarding, and race-condition replay attacks across disparate client contexts. 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: Decoupled Hybrid Authentication Challenges and Non-Atomic 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 DriftDecoupled Hybrid Authentication Challenges and Non-Atomic 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 atomically consume (burn-on-read via GETDEL or atomic transaction) the WebAuthn challenge before executing cryptographic signature verification to prevent replay race conditions.

Engineers MUST ALWAYS atomically consume (burn-on-read via GETDEL or atomic transaction) the WebAuthn challenge before executing cryptographic signature verification to prevent replay race conditions.

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 ALWAYS cryptographically bind the WebAuthn challenge to the specific ephemeral session ID (e.g., WebSocket channel or polling token) initialized during the QR code generation handshake.

Engineers MUST ALWAYS cryptographically bind the WebAuthn challenge to the specific ephemeral session ID (e.g., WebSocket channel or polling token) initialized during the QR code generation handshake.

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 accept assertions where clientDataJSON.crossOrigin is true unless an explicit, authenticated cross-origin federation allowlist matches the exact origin.

Engineers MUST NOT accept assertions where clientDataJSON.crossOrigin is true unless an explicit, authenticated cross-origin federation allowlist matches the exact origin.

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 verify that clientDataJSON.origin matches the exact expected scheme, fully qualified domain name, and port of the Relying Party.

Services MUST verify that clientDataJSON.origin matches the exact expected scheme, fully qualified domain name, and port 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.
5

Components NEVER store hybrid session credentials or challenges in shared, un-namespaced caches without explicit TTLs (maximum 120 seconds for hybrid exchanges).

Components NEVER store hybrid session credentials or challenges in shared, un-namespaced caches without explicit TTLs (maximum 120 seconds for hybrid exchanges).

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 Cross-Device Hybrid Transport Ephemeral Binding and Replay Prevention critical for AI coding assistants?

Mandates cryptographically bound ephemeral session identifiers, atomic challenge consumption, and strict origin/cross-origin validation during FIDO2/WebAuthn hybrid transport (caBLE) flows. Prevents QR-code phishing, cross-origin assertion forwarding, and race-condition replay attacks across disparate client contexts. 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 (Decoupled Hybrid Authentication Challenges and Non-Atomic 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

WebAuthn