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

WebAuthn Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail

Mandates cryptographic binding, atomic single-use consumption, and strict ephemeral rotation (TTL <= 60s) for FIDO hybrid cross-device authentication sessions. Enforces zero-trust QR payload generation tied directly to the initiator's TLS-bound session to neutralize MITM relay attacks and stale credential harvesting.

Prohibited Anti-Pattern: Long-Lived Static QR Codes and Unbound Hybrid WebAuthn Nonces Susceptible to Adversary Relay and Replay

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail - Mandates cryptographic binding, atomic single-use consumption, and strict ephemeral rotation (TTL <= 60s) for FIDO hybrid cross-device authentication sessions. Enforces zero-trust QR payload generation tied directly to the initiator's TLS-bound session to neutralize MITM relay attacks and stale credential harvesting.
globs: src/**/auth/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, src/**/fido/**/*.{ts,tsx}, src/**/session/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-hybrid-nonce-replay-guardrail"
---

# WebAuthn Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Long-Lived Static QR Codes and Unbound Hybrid WebAuthn Nonces Susceptible to Adversary Relay and Replay

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Passkey Hybrid Cross-Device Channel Replay Guardrail. Your mandate is to prevent Man-in-the-Middle (MITM) relay attacks during FIDO hybrid (caBLE) authentication by strictly enforcing ephemeral, cryptographically bound QR session nonces that rotate with TTL <= 60 seconds and are atomically consumed upon initiation.

## Strict Guidelines
- Engineers MUST ALWAYS bind the hybrid QR challenge cryptographically to the primary browser's active session ID using HMAC-SHA256 or HKDF.
- Engineers MUST NOT issue cross-device hybrid authentication challenges with a lifespan exceeding 60 seconds.
- Code MUST consume hybrid session nonces atomically (e.g., using Redis GETDEL, single-transaction CAS, or atomic Lua scripts) to guarantee strict single-use.
- Services MUST reject authentication handshakes if the QR session token does not match the active initiator session or if the nonce expiration window has lapsed.
- Components NEVER render long-lived or reusable QR codes for cross-device FIDO passkey enrollment or assertion without automatic visual and cryptographic polling rotation.

## Bad vs Good Implementations
### Hybrid Cross-Device Challenge Generation and Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example generates a challenge that is completely unlinked from the initiator's session, uses an excessively long 15-minute TTL, lacks atomic consumption (prone to race condition replays), and relies on a plain string comparison without cryptographic binding.
```typescript
import { randomUUID } from 'node:crypto';

interface SessionStore {
  [key: string]: { challenge: string; createdAt: number };
}

const inMemoryStore: SessionStore = {};

// ANTI-PATTERN: Static, unbound challenge with 15-minute expiration and non-atomic validation
export async function generateHybridQrCode(initiatorSessionId: string): Promise<string> {
  const qrSessionId = randomUUID();
  inMemoryStore[qrSessionId] = {
    challenge: randomUUID(),
    createdAt: Date.now(), // No connection to initiatorSessionId
  };
  // Lifespan is 15 minutes, allowing ample time for QR phishing and MITM relay
  return JSON.stringify({ qrSessionId, link: `fido://hybrid?token=${qrSessionId}` });
}

export async function verifyHybridChallenge(qrSessionId: string, challenge: string): Promise<boolean> {
  const session = inMemoryStore[qrSessionId];
  if (!session) return false;
  // Non-atomic read: vulnerable to race-condition replay
  const isExpired = Date.now() - session.createdAt > 15 * 60 * 1000;
  if (isExpired) return false;
  
  return session.challenge === challenge;
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation uses a 45-second TTL, binds the ephemeral nonce directly to the primary browser's session using HMAC-SHA256 with constant-time comparison, and utilizes Redis GETDEL for single-use atomic consumption to eliminate replay and relay vectors.
```typescript
import { randomBytes, createHmac, timingSafeEqual } from 'node:crypto';

interface RedisLikeClient {
  set(key: string, value: string, mode: string, durationSec: number): Promise<'OK' | null>;
  getdel(key: string): Promise<string | null>;
}

export interface HybridNoncePayload {
  qrNonceId: string;
  initiatorBindingHmac: string;
  expiresAt: number;
}

const HYBRID_NONCE_TTL_SECONDS = 45; // Strict TTL <= 60 seconds

export class HybridReplayGuard {
  constructor(
    private readonly redis: RedisLikeClient,
    private readonly hmacSecret: Buffer
  ) {}

  private computeBinding(initiatorSessionId: string, nonce: string): string {
    return createHmac('sha256', this.hmacSecret)
      .update(`${initiatorSessionId}:${nonce}`)
      .digest('hex');
  }

  public async issueEphemeralHybridChallenge(
    initiatorSessionId: string,
    webAuthnChallenge: string
  ): Promise<HybridNoncePayload> {
    const qrNonceId = randomBytes(32).toString('hex');
    const bindingHmac = this.computeBinding(initiatorSessionId, qrNonceId);
    const record = JSON.stringify({
      initiatorSessionId,
      webAuthnChallenge,
      bindingHmac,
    });

    const key = `fido:hybrid:nonce:${qrNonceId}`;
    await this.redis.set(key, record, 'EX', HYBRID_NONCE_TTL_SECONDS);

    return {
      qrNonceId,
      initiatorBindingHmac: bindingHmac,
      expiresAt: Date.now() + HYBRID_NONCE_TTL_SECONDS * 1000,
    };
  }

  public async consumeAndVerifyHybridNonce(
    qrNonceId: string,
    initiatorSessionId: string,
    providedChallenge: string
  ): Promise<boolean> {
    const key = `fido:hybrid:nonce:${qrNonceId}`;
    // Atomic read-and-delete prevents race-condition replay
    const rawRecord = await this.redis.getdel(key);
    if (!rawRecord) {
      return false; // Nonce does not exist, expired, or already consumed
    }

    const record = JSON.parse(rawRecord) as {
      initiatorSessionId: string;
      webAuthnChallenge: string;
      bindingHmac: string;
    };

    const expectedHmac = this.computeBinding(initiatorSessionId, qrNonceId);
    const isHmacValid = timingSafeEqual(
      Buffer.from(record.bindingHmac, 'hex'),
      Buffer.from(expectedHmac, 'hex')
    );

    const isSessionValid = record.initiatorSessionId === initiatorSessionId;
    const isChallengeValid = record.webAuthnChallenge === providedChallenge;

    return isHmacValid && isSessionValid && isChallengeValid;
  }
}
```

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 Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail

WebAuthn Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail defines an industrial-grade behavioral standard for security engineering. Mandates cryptographic binding, atomic single-use consumption, and strict ephemeral rotation (TTL <= 60s) for FIDO hybrid cross-device authentication sessions. Enforces zero-trust QR payload generation tied directly to the initiator's TLS-bound session to neutralize MITM relay attacks and stale credential harvesting. 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: Long-Lived Static QR Codes and Unbound Hybrid WebAuthn Nonces Susceptible to Adversary Relay and Replay 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 DriftLong-Lived Static QR Codes and Unbound Hybrid WebAuthn Nonces Susceptible to Adversary Relay and ReplayCritical
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 bind the hybrid QR challenge cryptographically to the primary browser's active session ID using HMAC-SHA256 or HKDF.

Engineers MUST ALWAYS bind the hybrid QR challenge cryptographically to the primary browser's active session ID using HMAC-SHA256 or HKDF.

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 issue cross-device hybrid authentication challenges with a lifespan exceeding 60 seconds.

Engineers MUST NOT issue cross-device hybrid authentication challenges with a lifespan exceeding 60 seconds.

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

Code MUST consume hybrid session nonces atomically (e.g., using Redis GETDEL, single-transaction CAS, or atomic Lua scripts) to guarantee strict single-use.

Code MUST consume hybrid session nonces atomically (e.g., using Redis GETDEL, single-transaction CAS, or atomic Lua scripts) to guarantee strict single-use.

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 reject authentication handshakes if the QR session token does not match the active initiator session or if the nonce expiration window has lapsed.

Services MUST reject authentication handshakes if the QR session token does not match the active initiator session or if the nonce expiration window has lapsed.

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 render long-lived or reusable QR codes for cross-device FIDO passkey enrollment or assertion without automatic visual and cryptographic polling rotation.

Components NEVER render long-lived or reusable QR codes for cross-device FIDO passkey enrollment or assertion without automatic visual and cryptographic polling rotation.

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 Hybrid Cross-Device Ephemeral Nonce & Session-Binding Replay Guardrail critical for AI coding assistants?

Mandates cryptographic binding, atomic single-use consumption, and strict ephemeral rotation (TTL <= 60s) for FIDO hybrid cross-device authentication sessions. Enforces zero-trust QR payload generation tied directly to the initiator's TLS-bound session to neutralize MITM relay attacks and stale credential harvesting. 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 (Long-Lived Static QR Codes and Unbound Hybrid WebAuthn Nonces Susceptible to Adversary Relay and Replay) 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