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

Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows

Defends WebAuthn conditional mediation (passkey autofill) against ambient replay attacks, cross-origin credential harvesting, and concurrent AbortSignal race conditions. Mandates single-flight AbortController orchestration, ephemeral challenge-session binding, and atomic challenge invalidation on verification.

Prohibited Anti-Pattern: Unbounded conditional mediation invocations sharing static challenges or omitting abort controller lifecycle governance

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows - Defends WebAuthn conditional mediation (passkey autofill) against ambient replay attacks, cross-origin credential harvesting, and concurrent AbortSignal race conditions. Mandates single-flight AbortController orchestration, ephemeral challenge-session binding, and atomic challenge invalidation on verification.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-ambient-replay-firewall"
---

# Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded conditional mediation invocations sharing static challenges or omitting abort controller lifecycle governance

## System Constraints
You are a Principal Security Architect enforcing strict WebAuthn Conditional Mediation invariants. Ambient passkey requests (mediation: 'conditional') run continuously in the background and are susceptible to cross-origin harvesting, autofill race conditions, and replay attacks unless bound to single-use, time-delimited cryptographic challenges and managed via mutually exclusive AbortControllers.

## Strict Guidelines
- Engineers MUST ALWAYS tie every WebAuthn challenge directly to an ephemeral, cryptographically secure server session token with a time-to-live (TTL) not exceeding 120 seconds.
- Engineers MUST ALWAYS abort any in-flight conditional mediation request using an explicit AbortController before initiating a modal WebAuthn prompt or when unmounting the credential input view.
- Services MUST atomically consume and invalidate challenges upon first presentation (CAS / delete-on-read) prior to cryptographic signature verification to prevent replay attacks.
- Services MUST strictly verify that the clientDataJSON origin matches the expected fully qualified domain and scheme (exact match, no suffix/subdomain wildcards).
- Components NEVER execute navigator.credentials.get without inspecting PublicKeyCredential.isConditionalMediationAvailable() availability first.
- Code SHOULD isolate conditional mediation listeners so multiple input components never spawn competing, concurrent credentials.get() calls.

## Bad vs Good Implementations
### Passkey Conditional Mediation Lifecycle and Atomic Challenge Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Lacks conditional mediation feature detection, fails to govern lifecycle with an AbortController causing autofill race conditions upon re-render, and uses an unbound challenge that exposes the ambient authentication flow to replay attacks.
```typescript
import React, { useEffect } from 'react';

export const LoginForm = () => {
  useEffect(() => {
    // VULNERABLE: No feature detection, no AbortController cleanup,
    // and static/unbound challenge allows replay and race conditions.
    async function startAutofill() {
      const response = await fetch('/api/auth/challenge');
      const { challenge } = await response.json();

      const credential = await navigator.credentials.get({
        mediation: 'conditional',
        publicKey: {
          challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
          rpId: window.location.hostname,
          userVerification: 'preferred'
        }
      });

      await fetch('/api/auth/verify', {
        method: 'POST',
        body: JSON.stringify(credential)
      });
    }
    startAutofill();
  }, []);

  return <input type="text" name="username" autoComplete="username webauthn" />;
};
```

#### Production Standard (Correct)
> **Standard**: Implements strict feature gating with PublicKeyCredential.isConditionalMediationAvailable(), manages concurrent interactions using an AbortController with unmount cleanup, binds challenge retrieval to ephemeral session context, and gracefully handles abort states.
```typescript
import React, { useEffect, useRef } from 'react';

export const LoginForm: React.FC = () => {
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    let isMounted = true;

    async function initConditionalPasskey() {
      const isAvailable = 
        typeof window.PublicKeyCredential !== 'undefined' &&
        typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function' &&
        await window.PublicKeyCredential.isConditionalMediationAvailable();

      if (!isAvailable || !isMounted) return;

      // Abort any prior in-flight ambient requests
      abortControllerRef.current?.abort('REPLACED_BY_NEW_FLOW');
      const controller = new AbortController();
      abortControllerRef.current = controller;

      try {
        // Challenge is tied to an ephemeral HTTP-only session cookie (state token)
        const challengeRes = await fetch('/api/auth/conditional-challenge', {
          signal: controller.signal
        });
        if (!challengeRes.ok) return;
        const { challengeBase64, rpId } = await challengeRes.json();

        const credential = await navigator.credentials.get({
          mediation: 'conditional',
          signal: controller.signal,
          publicKey: {
            challenge: Uint8Array.from(atob(challengeBase64), c => c.charCodeAt(0)),
            rpId,
            userVerification: 'preferred',
            timeout: 120000
          }
        }) as PublicKeyCredential | null;

        if (!credential || !isMounted) return;

        // Atomic verification: backend verifies and burns the ephemeral challenge
        const verifyRes = await fetch('/api/auth/conditional-verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: credential.id,
            rawId: btoa(String.fromCharCode(...new Uint8Array(credential.rawId))),
            response: {
              clientDataJSON: btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).clientDataJSON))),
              authenticatorData: btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).authenticatorData))),
              signature: btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).signature))),
              userHandle: (credential.response as AuthenticatorAssertionResponse).userHandle
                ? btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).userHandle!)))
                : null
            }
          })
        });

        if (verifyRes.ok) {
          window.location.assign('/dashboard');
        }
      } catch (err: unknown) {
        if (err instanceof DOMException && err.name === 'AbortError') {
          return; // Expected cancellation
        }
        console.error('Ambient mediation failure:', err);
      }
    }

    initConditionalPasskey();

    return () => {
      isMounted = false;
      abortControllerRef.current?.abort('COMPONENT_UNMOUNTED');
    };
  }, []);

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <input
        type="text"
        name="username"
        autoComplete="username webauthn"
        aria-label="Username or Passkey Autofill"
      />
    </form>
  );
};
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows

Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows defines an industrial-grade behavioral standard for security engineering. Defends WebAuthn conditional mediation (passkey autofill) against ambient replay attacks, cross-origin credential harvesting, and concurrent AbortSignal race conditions. Mandates single-flight AbortController orchestration, ephemeral challenge-session binding, and atomic challenge invalidation on verification. 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: Unbounded conditional mediation invocations sharing static challenges or omitting abort controller lifecycle governance 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 DriftUnbounded conditional mediation invocations sharing static challenges or omitting abort controller lifecycle governanceCritical
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 tie every WebAuthn challenge directly to an ephemeral, cryptographically secure server session token with a time-to-live (TTL) not exceeding 120 seconds.

Engineers MUST ALWAYS tie every WebAuthn challenge directly to an ephemeral, cryptographically secure server session token with a time-to-live (TTL) not exceeding 120 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.
2

Engineers MUST ALWAYS abort any in-flight conditional mediation request using an explicit AbortController before initiating a modal WebAuthn prompt or when unmounting the credential input view.

Engineers MUST ALWAYS abort any in-flight conditional mediation request using an explicit AbortController before initiating a modal WebAuthn prompt or when unmounting the credential input view.

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 invalidate challenges upon first presentation (CAS / delete-on-read) prior to cryptographic signature verification to prevent replay attacks.

Services MUST atomically consume and invalidate challenges upon first presentation (CAS / delete-on-read) prior to cryptographic signature verification to prevent replay attacks.

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 strictly verify that the clientDataJSON origin matches the expected fully qualified domain and scheme (exact match, no suffix/subdomain wildcards).

Services MUST strictly verify that the clientDataJSON origin matches the expected fully qualified domain and scheme (exact match, no suffix/subdomain wildcards).

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 execute navigator.credentials.get without inspecting PublicKeyCredential.isConditionalMediationAvailable() availability first.

Components NEVER execute navigator.credentials.get without inspecting PublicKeyCredential.isConditionalMediationAvailable() availability first.

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

Code SHOULD isolate conditional mediation listeners so multiple input components never spawn competing, concurrent credentials.get() calls.

Code SHOULD isolate conditional mediation listeners so multiple input components never spawn competing, concurrent credentials.get() calls.

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 Enforce Strict Challenge Invalidation and Origin Binding for WebAuthn Conditional Mediation Flows critical for AI coding assistants?

Defends WebAuthn conditional mediation (passkey autofill) against ambient replay attacks, cross-origin credential harvesting, and concurrent AbortSignal race conditions. Mandates single-flight AbortController orchestration, ephemeral challenge-session binding, and atomic challenge invalidation on verification. 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 (Unbounded conditional mediation invocations sharing static challenges or omitting abort controller lifecycle governance) 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

Enforce