This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: fido2-webauthn-hybrid-relay-defense-standard

FIDO2 WebAuthn Hybrid Transport Cross-Device Relay Defense

Enforces strict origin-bound assertion verification, atomic single-use challenge consumption, and hybrid transport validation in WebAuthn servers. Defeats proximity-spoofed cross-device relay attacks (caBLE / QR-code phishing) by validating exact canonical origins, denying cross-origin iframe context, and enforcing short-lived hybrid challenge lifetimes.

Prohibited Anti-Pattern: Permissive origin matching, non-atomic challenge checks, or missing crossOrigin flags during hybrid WebAuthn assertion verification.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FIDO2 WebAuthn Hybrid Transport Cross-Device Relay Defense - Enforces strict origin-bound assertion verification, atomic single-use challenge consumption, and hybrid transport validation in WebAuthn servers. Defeats proximity-spoofed cross-device relay attacks (caBLE / QR-code phishing) by validating exact canonical origins, denying cross-origin iframe context, and enforcing short-lived hybrid challenge lifetimes.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/server/auth/**/*.ts, src/api/auth/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fido2-webauthn-hybrid-relay-defense-standard"
---

# FIDO2 WebAuthn Hybrid Transport Cross-Device Relay Defense

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive origin matching, non-atomic challenge checks, or missing crossOrigin flags during hybrid WebAuthn assertion verification.

## System Constraints
You are a Principal Security Architect enforcing FIDO2/WebAuthn L3 Hybrid Transport Relay Defenses. You must mandate strict canonical origin-binding, explicit crossOrigin verification, atomic challenge invalidation, and tight lifetime limits for cross-device hybrid handshakes to prevent proximity-spoofed relay attacks.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict canonical origin validation against an immutable allowlist using exact string equality, never substring, regex wildcard, or loose protocol-agnostic checks.
- Engineers MUST NOT permit assertions where clientDataJSON.crossOrigin evaluates to true during hybrid/cross-device ceremonies unless explicitly operating an authenticated RP federation tunnel.
- Services MUST atomically consume and delete the WebAuthn challenge in a single transactional step (e.g., Redis GETDEL) before cryptographic verification begins to prevent concurrent relay replay.
- Services MUST enforce a maximum TTL of 60 seconds on challenges generated for hybrid (cross-device QR code/BLE) authentication ceremonies.
- Components NEVER trust client-reported authenticator attachment flags without cryptographically verifying that authenticatorData.rpIdHash strictly matches the SHA-256 digest of the expected rpId.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler validates the origin using a weak substring search (`includes('bank.com')`), allowing phishing domains like `evil-bank.com` to pass. It also fails to atomically consume the challenge via GETDEL, allowing race-condition relay attacks, and ignores the WebAuthn Level 3 `crossOrigin` property.
```typescript
import { Request, Response } from 'express';
import { cache } from '../lib/cache';
import crypto from 'node:crypto';

export async function verifyHybridAssertion(req: Request, res: Response) {
  const { id, rawId, response } = req.body;
  const clientData = JSON.parse(Buffer.from(response.clientDataJSON, 'base64url').toString('utf-8'));

  // VULNERABLE: Loose origin matching permits cross-device relay via attacker proxy (e.g. evil-bank.com)
  if (!clientData.origin.includes('bank.com')) {
    return res.status(401).json({ error: 'Untrusted origin' });
  }

  // VULNERABLE: Non-atomic read allows concurrent relay window; does not verify crossOrigin flag
  const storedChallenge = await cache.get(`auth:challenge:${clientData.challenge}`);
  if (!storedChallenge) {
    return res.status(401).json({ error: 'Challenge expired or invalid' });
  }

  // Challenge deleted after work or neglected entirely, enabling window of replay
  await cache.del(`auth:challenge:${clientData.challenge}`);
  return res.json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces origin-bound security: consumes challenges atomically via `getdel`, explicitly validates `clientData.origin` against an immutable Set of exact origins, verifies `clientData.crossOrigin !== true`, and cryptographically confirms user verification and RP ID hash matches.
```typescript
import { Request, Response } from 'express';
import { redisClient } from '../lib/redis';
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import crypto from 'node:crypto';

const CANONICAL_ORIGINS: ReadonlySet<string> = new Set([
  'https://auth.bank.example.com',
  'https://bank.example.com'
]);
const EXPECTED_RP_ID = 'bank.example.com';
const EXPECTED_RP_ID_HASH = crypto.createHash('sha256').update(EXPECTED_RP_ID).digest();

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

  // Atomic single-use challenge consumption prevents replay and concurrency races
  const challengeKey = `webauthn:challenge:${sessionId}`;
  const expectedChallenge = await redisClient.getdel(challengeKey);
  if (!expectedChallenge) {
    return res.status(401).json({ error: 'Invalid, expired, or replayed challenge session' });
  }

  const clientData = JSON.parse(
    Buffer.from(assertionResponse.response.clientDataJSON, 'base64url').toString('utf-8')
  );

  // Enforce strict canonical origin check
  if (!CANONICAL_ORIGINS.has(clientData.origin)) {
    return res.status(403).json({ error: 'Origin-bound assertion check failed' });
  }

  // Reject cross-origin framing/relays for hybrid/passkey assertions
  if (clientData.crossOrigin === true) {
    return res.status(403).json({ error: 'Cross-origin hybrid relay rejected' });
  }

  // Verify SHA-256 RP ID binding and cryptographic signatures
  const verification = await verifyAuthenticationResponse({
    response: assertionResponse,
    expectedChallenge,
    expectedOrigin: Array.from(CANONICAL_ORIGINS),
    expectedRPID: EXPECTED_RP_ID,
    requireUserVerification: true,
  });

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

  return res.status(200).json({ success: true });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FIDO2 WebAuthn Hybrid Transport Cross-Device Relay Defense

FIDO2 WebAuthn Hybrid Transport Cross-Device Relay Defense defines an industrial-grade behavioral standard for security engineering. Enforces strict origin-bound assertion verification, atomic single-use challenge consumption, and hybrid transport validation in WebAuthn servers. Defeats proximity-spoofed cross-device relay attacks (caBLE / QR-code phishing) by validating exact canonical origins, denying cross-origin iframe context, and enforcing short-lived hybrid challenge lifetimes. 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: Permissive origin matching, non-atomic challenge checks, or missing crossOrigin flags during hybrid WebAuthn assertion 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 DriftPermissive origin matching, non-atomic challenge checks, or missing crossOrigin flags during hybrid WebAuthn assertion verification.Critical
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 enforce strict canonical origin validation against an immutable allowlist using exact string equality, never substring, regex wildcard, or loose protocol-agnostic checks.

Engineers MUST ALWAYS enforce strict canonical origin validation against an immutable allowlist using exact string equality, never substring, regex wildcard, or loose protocol-agnostic checks.

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 assertions where clientDataJSON.crossOrigin evaluates to true during hybrid/cross-device ceremonies unless explicitly operating an authenticated RP federation tunnel.

Engineers MUST NOT permit assertions where clientDataJSON.crossOrigin evaluates to true during hybrid/cross-device ceremonies unless explicitly operating an authenticated RP federation tunnel.

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 atomically consume and delete the WebAuthn challenge in a single transactional step (e.g., Redis GETDEL) before cryptographic verification begins to prevent concurrent relay replay.

Services MUST atomically consume and delete the WebAuthn challenge in a single transactional step (e.g., Redis GETDEL) before cryptographic verification begins to prevent concurrent relay replay.

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 enforce a maximum TTL of 60 seconds on challenges generated for hybrid (cross-device QR code/BLE) authentication ceremonies.

Services MUST enforce a maximum TTL of 60 seconds on challenges generated for hybrid (cross-device QR code/BLE) authentication ceremonies.

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 trust client-reported authenticator attachment flags without cryptographically verifying that authenticatorData.rpIdHash strictly matches the SHA-256 digest of the expected rpId.

Components NEVER trust client-reported authenticator attachment flags without cryptographically verifying that authenticatorData.rpIdHash strictly matches the SHA-256 digest of the expected rpId.

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 Hybrid Transport Cross-Device Relay Defense critical for AI coding assistants?

Enforces strict origin-bound assertion verification, atomic single-use challenge consumption, and hybrid transport validation in WebAuthn servers. Defeats proximity-spoofed cross-device relay attacks (caBLE / QR-code phishing) by validating exact canonical origins, denying cross-origin iframe context, and enforcing short-lived hybrid challenge lifetimes. 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 (Permissive origin matching, non-atomic challenge checks, or missing crossOrigin flags during hybrid WebAuthn assertion 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

FIDO2