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

WebAuthn Level 3 Conditional Mediation & Passkey Autofill Sanitization

Enforces strict isolation, challenge lifecycle management, and AbortController synchronization during WebAuthn Level 3 Conditional UI mediation. Mitigates credential hijacking, replay vulnerabilities, and race conditions between autofill requests, modal biometric prompts, and hostile embedded webview contexts.

Prohibited Anti-Pattern: Uncoordinated navigator.credentials.get calls with unverified origins, shared AbortSignals, and dangling conditional UI promises.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Conditional Mediation & Passkey Autofill Sanitization - Enforces strict isolation, challenge lifecycle management, and AbortController synchronization during WebAuthn Level 3 Conditional UI mediation. Mitigates credential hijacking, replay vulnerabilities, and race conditions between autofill requests, modal biometric prompts, and hostile embedded webview contexts.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-l3-conditional-mediation-sanitization"
---

# WebAuthn Level 3 Conditional Mediation & Passkey Autofill Sanitization

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Uncoordinated navigator.credentials.get calls with unverified origins, shared AbortSignals, and dangling conditional UI promises.

## System Constraints
You are a Principal Security Architect enforcing WebAuthn Level 3 Conditional Mediation and Passkey Autofill Sanitization. You must strictly verify that conditional UI requests invoke an isolated AbortController, disallow un-scoped challenges, check for webview spoofing, sanitize autofill inputs, and serialize credential retrieval so that user-initiated interactive prompts abort any pending conditional queries cleanly.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate an isolated AbortController per mediation attempt and explicitly abort any active conditional mediation before dispatching a modal or interactive navigator.credentials.get() request.
- Engineers MUST ALWAYS verify window.PublicKeyCredential && PublicKeyCredential.isConditionalMediationAvailable() returns true before setting mediation: 'conditional'.
- Services MUST generate cryptographically secure, single-use, time-bounded challenges on the backend and bind them strictly to the validated client Origin and RP ID.
- Components MUST NEVER execute WebAuthn conditional mediation inside untrusted, non-isolated iframe contexts or embedded webviews lacking verified origin isolation.
- Code SHOULD sanitize form inputs and prevent DOM autofill state pollution by decoupling WebAuthn conditional assertion payloads from standard credential input element values.
- Engineers MUST handle AbortError exceptions gracefully and avoid leaking assertion states across concurrent authentication attempts.

## Bad vs Good Implementations
### Passkey Conditional Mediation Lifecycle and Interactive Request Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to verify conditional mediation support via PublicKeyCredential.isConditionalMediationAvailable(). Omits AbortController handling, leaving conditional requests dangling and triggering silent failures or race conditions when interactive login is concurrently invoked. Uses unvalidated client-side rpId strings vulnerable to subdomain hijacking.
```typescript
// Vulnerable: Shared or unmanaged lifecycle, no mediation pre-check, and race condition
export async function initiatePasskeyAutofill(challenge: string) {
  // Missing mediation availability check
  // Dangling promise without AbortController creates race condition with manual submit
  const credential = await navigator.credentials.get({
    mediation: 'conditional',
    publicKey: {
      challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
      rpId: window.location.hostname,
      userVerification: 'preferred'
    }
  });
  return credential;
}

export async function initiateInteractiveLogin(challenge: string) {
  // Concurrently calls get() without aborting active conditional mediation
  // Causes browser-dependent DOM exceptions or credential confusion
  return await navigator.credentials.get({
    publicKey: {
      challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
      rpId: window.location.hostname
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Guards availability with isConditionalMediationAvailable(), establishes an AbortController per conditional session, explicitly aborts conditional mediation before modal authentication to prevent WebAuthn race conditions, and correctly suppresses benign AbortError exceptions.
```typescript
// Production-grade: Isolated abort lifecycle, availability guards, and mutual exclusion
export class PasskeyMediationManager {
  private conditionalAbortController: AbortController | null = null;
  private isMediating = false;

  public async startConditionalAutofill(
    challengeBase64: string,
    expectedRpId: string
  ): Promise<PublicKeyCredential | null> {
    if (
      typeof window === 'undefined' ||
      !window.PublicKeyCredential ||
      !PublicKeyCredential.isConditionalMediationAvailable ||
      !(await PublicKeyCredential.isConditionalMediationAvailable())
    ) {
      return null;
    }

    this.abortConditionalMediation();
    this.conditionalAbortController = new AbortController();
    this.isMediating = true;

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

      return credential;
    } catch (error: unknown) {
      if (error instanceof DOMException && error.name === 'AbortError') {
        return null; // Gracefully handle expected cancellation
      }
      throw error;
    } finally {
      this.isMediating = false;
      this.conditionalAbortController = null;
    }
  }

  public async startInteractiveAssertion(
    challengeBase64: string,
    expectedRpId: string
  ): Promise<PublicKeyCredential | null> {
    this.abortConditionalMediation(); // Abort background mediation prior to explicit modal prompt

    const challengeBuffer = Uint8Array.from(atob(challengeBase64), (c) => c.charCodeAt(0));
    return (await navigator.credentials.get({
      publicKey: {
        challenge: challengeBuffer,
        rpId: expectedRpId,
        userVerification: 'required',
        timeout: 60000
      }
    })) as PublicKeyCredential | null;
  }

  public abortConditionalMediation(): void {
    if (this.isMediating && this.conditionalAbortController) {
      this.conditionalAbortController.abort();
      this.conditionalAbortController = null;
      this.isMediating = false;
    }
  }
}
```

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 Level 3 Conditional Mediation & Passkey Autofill Sanitization

WebAuthn Level 3 Conditional Mediation & Passkey Autofill Sanitization defines an industrial-grade behavioral standard for security engineering. Enforces strict isolation, challenge lifecycle management, and AbortController synchronization during WebAuthn Level 3 Conditional UI mediation. Mitigates credential hijacking, replay vulnerabilities, and race conditions between autofill requests, modal biometric prompts, and hostile embedded webview 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: Uncoordinated navigator.credentials.get calls with unverified origins, shared AbortSignals, and dangling conditional UI promises. 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 DriftUncoordinated navigator.credentials.get calls with unverified origins, shared AbortSignals, and dangling conditional UI promises.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 instantiate an isolated AbortController per mediation attempt and explicitly abort any active conditional mediation before dispatching a modal or interactive navigator.credentials.get() request.

Engineers MUST ALWAYS instantiate an isolated AbortController per mediation attempt and explicitly abort any active conditional mediation before dispatching a modal or interactive navigator.credentials.get() 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 ALWAYS verify window.PublicKeyCredential && PublicKeyCredential.isConditionalMediationAvailable() returns true before setting mediation

Engineers MUST ALWAYS verify window.PublicKeyCredential && PublicKeyCredential.isConditionalMediationAvailable() returns true before setting mediation: 'conditional'.

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 generate cryptographically secure, single-use, time-bounded challenges on the backend and bind them strictly to the validated client Origin and RP ID.

Services MUST generate cryptographically secure, single-use, time-bounded challenges on the backend and bind them strictly to the validated client Origin and RP ID.

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

Components MUST NEVER execute WebAuthn conditional mediation inside untrusted, non-isolated iframe contexts or embedded webviews lacking verified origin isolation.

Components MUST NEVER execute WebAuthn conditional mediation inside untrusted, non-isolated iframe contexts or embedded webviews lacking verified origin isolation.

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

Code SHOULD sanitize form inputs and prevent DOM autofill state pollution by decoupling WebAuthn conditional assertion payloads from standard credential input element values.

Code SHOULD sanitize form inputs and prevent DOM autofill state pollution by decoupling WebAuthn conditional assertion payloads from standard credential input element values.

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

Engineers MUST handle AbortError exceptions gracefully and avoid leaking assertion states across concurrent authentication attempts.

Engineers MUST handle AbortError exceptions gracefully and avoid leaking assertion states across concurrent authentication attempts.

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 Level 3 Conditional Mediation & Passkey Autofill Sanitization critical for AI coding assistants?

Enforces strict isolation, challenge lifecycle management, and AbortController synchronization during WebAuthn Level 3 Conditional UI mediation. Mitigates credential hijacking, replay vulnerabilities, and race conditions between autofill requests, modal biometric prompts, and hostile embedded webview 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 (Uncoordinated navigator.credentials.get calls with unverified origins, shared AbortSignals, and dangling conditional UI promises.) 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