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

WebAuthn L3 Conditional Mediation & Cross-Device Tunnel Guardrail

Enforces strict implementation standards for WebAuthn Level 3 conditional UI (autofill) and hybrid transport (caBLE/cross-device) authentication flows. Guarantees non-blocking asynchronous mediation initialization paired with robust AbortController lifecycle management and server-side origin/RP ID binding to eliminate credential friction and prevent tunnel-hijacking phishing vectors.

Prohibited Anti-Pattern: Unmediated Modal-Locking Credential Requests and Race-Prone Abort Signals in Hybrid Passkey Flows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn L3 Conditional Mediation & Cross-Device Tunnel Guardrail - Enforces strict implementation standards for WebAuthn Level 3 conditional UI (autofill) and hybrid transport (caBLE/cross-device) authentication flows. Guarantees non-blocking asynchronous mediation initialization paired with robust AbortController lifecycle management and server-side origin/RP ID binding to eliminate credential friction and prevent tunnel-hijacking phishing vectors.
globs: src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-conditional-mediation-guardrail"
---

# WebAuthn L3 Conditional Mediation & Cross-Device Tunnel Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unmediated Modal-Locking Credential Requests and Race-Prone Abort Signals in Hybrid Passkey Flows

## System Constraints
You are a Principal Security Architect enforcing FIDO2/WebAuthn Level 3 specifications. Your task is to mandate non-blocking conditional mediation (autofill) with proper AbortController orchestration, strict verification of cross-device hybrid flows, and zero credential-prompt friction. Ensure modal fallback requests cleanly abort active conditional mediation signals and verify origin/RP ID bindings immutably on both client and server.

## Strict Guidelines
- Engineers MUST ALWAYS feature-detect conditional mediation support via PublicKeyCredential.isConditionalMediationAvailable() before dispatching an autofill request.
- Engineers MUST instantiate a dedicated AbortController for conditional mediation requests and abort it cleanly prior to launching a user-initiated modal authentication flow.
- Code MUST NEVER trigger blocking modal WebAuthn prompts on page load; conditional requests MUST set mediation: 'conditional' and bind to an input element with autocomplete='username webauthn'.
- Services MUST validate the clientDataJSON origin against an immutable allowlist and reject any mismatch between the expected Relying Party ID (rpId) and the effective top-level domain plus one (eTLD+1).
- Components NEVER store or reuse cryptographic challenges across conditional and modal authentication requests; fresh single-use cryptographically random challenges MUST be fetched per request initiation.
- Services MUST ensure authenticatorAttachment is left unspecified or dynamically negotiated when supporting hybrid transport (cross-device/caBLE) alongside platform passkeys.

## Bad vs Good Implementations
### Conditional Mediation vs. Modal Fallback with AbortController Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to verify conditional mediation availability, omitting mediation: 'conditional'. This forces a blocking modal sheet on page load, destroys the autofill experience, and lacks an AbortController to cancel lingering requests when users fall back to standard form submission.
```typescript
// Anti-pattern: Blocking modal on load, shared abort controller, missing conditional check
export async function initPasskeyLogin(options: CredentialRequestOptions) {
  // Anti-pattern: No isConditionalMediationAvailable check
  // Anti-pattern: Missing mediation: 'conditional', locks UI immediately
  try {
    const credential = await navigator.credentials.get({
      publicKey: options.publicKey
    });
    await verifyOnServer(credential);
  } catch (err) {
    console.error('Auth failed', err);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Correctly checks PublicKeyCredential.isConditionalMediationAvailable(), passes mediation: 'conditional', and binds an AbortController signal. Cleanly cancels any pending conditional passkey request prior to launching an explicit modal fallback.
```typescript
// Production standard: Dual-track conditional autofill with explicit abort lifecycle
export class PasskeyAuthenticator {
  private conditionalAbortController: AbortController | null = null;

  async initConditionalAutofill(fetchOptions: () => Promise<CredentialRequestOptions>): Promise<void> {
    if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
      return;
    }

    const isAvailable = await PublicKeyCredential.isConditionalMediationAvailable();
    if (!isAvailable) return;

    this.conditionalAbortController?.abort();
    this.conditionalAbortController = new AbortController();

    try {
      const authOptions = await fetchOptions();
      const credential = await navigator.credentials.get({
        publicKey: authOptions.publicKey,
        mediation: 'conditional',
        signal: this.conditionalAbortController.signal,
      });

      if (credential) {
        await this.verifyOnServer(credential);
      }
    } catch (err: unknown) {
      if (err instanceof DOMException && err.name === 'AbortError') {
        return; // Expected teardown on modal switch or component unmount
      }
      throw err;
    }
  }

  async triggerModalFallback(options: CredentialRequestOptions): Promise<Credential | null> {
    // Abort pending conditional autofill before launching modal
    if (this.conditionalAbortController) {
      this.conditionalAbortController.abort();
      this.conditionalAbortController = null;
    }

    return navigator.credentials.get({
      publicKey: options.publicKey,
      mediation: 'optional'
    });
  }

  private async verifyOnServer(credential: Credential): Promise<void> {
    await fetch('/api/auth/webauthn/verify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credential)
    });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn L3 Conditional Mediation & Cross-Device Tunnel Guardrail

WebAuthn L3 Conditional Mediation & Cross-Device Tunnel Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict implementation standards for WebAuthn Level 3 conditional UI (autofill) and hybrid transport (caBLE/cross-device) authentication flows. Guarantees non-blocking asynchronous mediation initialization paired with robust AbortController lifecycle management and server-side origin/RP ID binding to eliminate credential friction and prevent tunnel-hijacking phishing vectors. 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: Unmediated Modal-Locking Credential Requests and Race-Prone Abort Signals in Hybrid Passkey Flows 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 DriftUnmediated Modal-Locking Credential Requests and Race-Prone Abort Signals in Hybrid Passkey FlowsCritical
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 feature-detect conditional mediation support via PublicKeyCredential.isConditionalMediationAvailable() before dispatching an autofill request.

Engineers MUST ALWAYS feature-detect conditional mediation support via PublicKeyCredential.isConditionalMediationAvailable() before dispatching an autofill 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

Engineers MUST instantiate a dedicated AbortController for conditional mediation requests and abort it cleanly prior to launching a user-initiated modal authentication flow.

Engineers MUST instantiate a dedicated AbortController for conditional mediation requests and abort it cleanly prior to launching a user-initiated modal authentication flow.

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 NEVER trigger blocking modal WebAuthn prompts on page load

Code MUST NEVER trigger blocking modal WebAuthn prompts on page load; conditional requests MUST set mediation: 'conditional' and bind to an input element with autocomplete='username webauthn'.

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 validate the clientDataJSON origin against an immutable allowlist and reject any mismatch between the expected Relying Party ID (rpId) and the effective top-level domain plus one (eTLD+1).

Services MUST validate the clientDataJSON origin against an immutable allowlist and reject any mismatch between the expected Relying Party ID (rpId) and the effective top-level domain plus one (eTLD+1).

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 or reuse cryptographic challenges across conditional and modal authentication requests

Components NEVER store or reuse cryptographic challenges across conditional and modal authentication requests; fresh single-use cryptographically random challenges MUST be fetched per request initiation.

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 ensure authenticatorAttachment is left unspecified or dynamically negotiated when supporting hybrid transport (cross-device/caBLE) alongside platform passkeys.

Services MUST ensure authenticatorAttachment is left unspecified or dynamically negotiated when supporting hybrid transport (cross-device/caBLE) alongside platform passkeys.

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 L3 Conditional Mediation & Cross-Device Tunnel Guardrail critical for AI coding assistants?

Enforces strict implementation standards for WebAuthn Level 3 conditional UI (autofill) and hybrid transport (caBLE/cross-device) authentication flows. Guarantees non-blocking asynchronous mediation initialization paired with robust AbortController lifecycle management and server-side origin/RP ID binding to eliminate credential friction and prevent tunnel-hijacking phishing vectors. 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 (Unmediated Modal-Locking Credential Requests and Race-Prone Abort Signals in Hybrid Passkey Flows) 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