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

WebAuthn Level 3 Conditional UI & Device-Bound Assertion Invariant Guardrail

Enforces strict WebAuthn Level 3 conditional UI orchestration and server-side device-bound passkey assertion verification. Prevents race conditions and credential hijacking by mandating AbortController-managed autofill mediation, user-verification enforcement, and cryptographic validation of authenticatorData flags.

Prohibited Anti-Pattern: Unmanaged Conditional UI Autofill Collisions and Flawed User Verification Enforcement in Passkey Assertions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Level 3 Conditional UI & Device-Bound Assertion Invariant Guardrail - Enforces strict WebAuthn Level 3 conditional UI orchestration and server-side device-bound passkey assertion verification. Prevents race conditions and credential hijacking by mandating AbortController-managed autofill mediation, user-verification enforcement, and cryptographic validation of authenticatorData flags.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}, app/**/*.{ts,tsx}, lib/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-level3-conditional-ui-assertion-guardrail"
---

# WebAuthn Level 3 Conditional UI & Device-Bound Assertion Invariant Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unmanaged Conditional UI Autofill Collisions and Flawed User Verification Enforcement in Passkey Assertions

## System Constraints
You are a Principal Security Architect enforcing WebAuthn Level 3 specifications, Conditional UI (Passkey Autofill) lifecycle standards, and cryptographic device-bound assertion validation. You MUST mandate non-colliding AbortController lifecycle management for autofill mediation, strict 'userVerification: required' policies, and bitwise verification of authenticatorData flags (UP, UV, BE, BS) on the server.

## Strict Guidelines
- Clients MUST ALWAYS query `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation: 'conditional'` to `navigator.credentials.get()`.
- Clients MUST manage conditional UI requests with an explicit `AbortController` and MUST abort active autofill promises before initiating user-driven modal assertions.
- Inputs supporting passkey autofill MUST include `autocomplete="username webauthn"` or `autocomplete="webauthn"` attributes.
- Assertion options MUST ALWAYS set `userVerification: 'required'` to prevent phishing and unauthorized access via unverified biometrics/PINs.
- Servers MUST verify clientDataJSON `origin` against a strictly allowlisted fully-qualified origin, verify `type === 'webauthn.get'`, and validate the signed cryptographic challenge in constant time.
- Servers MUST parse `authenticatorData` flags and verify bit 0 (User Present / UP) is 1 and bit 2 (User Verified / UV) is 1.
- When enterprise policy mandates device-bound credentials (non-synced hardware keys), servers MUST enforce that the Backup Eligibility (BE) flag (bit 3) is 0, or verify hardware attestation roots.

## Bad vs Good Implementations
### Client-Side Conditional UI Lifecycle & Modal Fallback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to verify conditional mediation availability, uses 'userVerification: preferred' which degrades enterprise phishing resistance, and omits AbortController handling, leading to unhandled promise rejections and collisions when a user clicks a manual sign-in button.
```typescript
async function startAuth() {
  // Anti-pattern: No availability check, unmanaged AbortController,
  // lax userVerification, and unhandled AbortError causing race conditions.
  const credential = await navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array([1, 2, 3]),
      userVerification: 'preferred' // Flaw: Allows non-biometric bypass
    },
    mediation: 'conditional' // Flaw: Throws if browser lacks support; no abort signal
  });
  await sendToServer(credential);
}
```

#### Production Standard (Correct)
> **Standard**: Checks browser capability via `PublicKeyCredential.isConditionalMediationAvailable()`, tracks lifecycle with `AbortController` to prevent collisions, enforces `userVerification: 'required'`, and swallows intended `AbortError` instances safely.
```typescript
class PasskeyClient {
  private abortController: AbortController | null = null;

  public async initializeConditionalUI(challengeBytes: Uint8Array): Promise<void> {
    if (
      typeof window === 'undefined' ||
      !window.PublicKeyCredential ||
      !PublicKeyCredential.isConditionalMediationAvailable ||
      !(await PublicKeyCredential.isConditionalMediationAvailable())
    ) {
      return; // Gracefully degrade if conditional UI is unsupported
    }

    this.abortCurrentMediation();
    this.abortController = new AbortController();

    try {
      const credential = await navigator.credentials.get({
        publicKey: {
          challenge: challengeBytes,
          timeout: 60000,
          userVerification: 'required',
          rpId: window.location.hostname
        },
        mediation: 'conditional',
        signal: this.abortController.signal
      }) as PublicKeyCredential | null;

      if (credential) {
        await this.submitAssertion(credential);
      }
    } catch (err: unknown) {
      if (err instanceof DOMException && err.name === 'AbortError') {
        return; // Normal cleanup cancellation
      }
      throw err;
    }
  }

  public abortCurrentMediation(): void {
    if (this.abortController) {
      this.abortController.abort();
      this.abortController = null;
    }
  }

  private async submitAssertion(cred: PublicKeyCredential): Promise<void> {
    // Serialized dispatch to verification endpoint
  }
}
```

### Server-Side AuthenticatorData Bitwise Flag & Origin Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepts assertions without validating origin, leaves challenges vulnerable to timing attacks, and ignores authenticatorData flags (User Present, User Verified, and Backup Eligibility).
```typescript
import { Request, Response } from 'express';

export async function verifyAssertion(req: Request, res: Response) {
  const { clientDataJSON, authenticatorData } = req.body;
  const clientData = JSON.parse(Buffer.from(clientDataJSON, 'base64url').toString());
  
  // Anti-pattern: Missing origin check, missing constant-time challenge check,
  // and complete absence of authenticatorData flag validation.
  if (clientData.type !== 'webauthn.get') {
    return res.status(400).send('Invalid type');
  }
  
  res.status(200).send({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: Validates JSON structure, enforces strict origin matching, employs constant-time buffer comparison for challenges, and parses binary flags at byte offset 32 to guarantee User Presence, User Verification, and device-bound status.
```typescript
import { crypto } from 'node:crypto';

interface AssertionVerificationParams {
  authDataBuffer: Buffer;
  clientDataJSON: Buffer;
  expectedChallenge: string;
  expectedOrigin: string;
  requireDeviceBound: boolean;
}

export function verifyAssertionSecurityFlags({
  authDataBuffer,
  clientDataJSON,
  expectedChallenge,
  expectedOrigin,
  requireDeviceBound
}: AssertionVerificationParams): void {
  const clientData = JSON.parse(clientDataJSON.toString('utf-8'));

  if (clientData.type !== 'webauthn.get') {
    throw new Error('Invalid assertion type');
  }

  if (clientData.origin !== expectedOrigin) {
    throw new Error(`Origin mismatch: expected ${expectedOrigin}, got ${clientData.origin}`);
  }

  const challengeMatch = crypto.timingSafeEqual(
    Buffer.from(clientData.challenge, 'base64url'),
    Buffer.from(expectedChallenge, 'base64url')
  );
  if (!challengeMatch) {
    throw new Error('Challenge verification failed');
  }

  if (authDataBuffer.length < 37) {
    throw new Error('Authenticator data is malformed: length < 37 bytes');
  }

  const flags = authDataBuffer[32];
  const isUserPresent = (flags & 0x01) !== 0;      // Bit 0: UP
  const isUserVerified = (flags & 0x04) !== 0;     // Bit 2: UV
  const isBackupEligible = (flags & 0x08) !== 0;   // Bit 3: BE

  if (!isUserPresent) {
    throw new Error('User Present (UP) flag must be set');
  }

  if (!isUserVerified) {
    throw new Error('User Verified (UV) flag must be set for Level 3 assurance');
  }

  if (requireDeviceBound && isBackupEligible) {
    throw new Error('Credential must be device-bound; synced passkeys rejected');
  }
}
```

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 UI & Device-Bound Assertion Invariant Guardrail

WebAuthn Level 3 Conditional UI & Device-Bound Assertion Invariant Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict WebAuthn Level 3 conditional UI orchestration and server-side device-bound passkey assertion verification. Prevents race conditions and credential hijacking by mandating AbortController-managed autofill mediation, user-verification enforcement, and cryptographic validation of authenticatorData flags. 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: Unmanaged Conditional UI Autofill Collisions and Flawed User Verification Enforcement in Passkey Assertions 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 DriftUnmanaged Conditional UI Autofill Collisions and Flawed User Verification Enforcement in Passkey AssertionsCritical
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

Clients MUST ALWAYS query `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation

Clients MUST ALWAYS query `PublicKeyCredential.isConditionalMediationAvailable()` before passing `mediation: 'conditional'` to `navigator.credentials.get()`.

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

Clients MUST manage conditional UI requests with an explicit `AbortController` and MUST abort active autofill promises before initiating user-driven modal assertions.

Clients MUST manage conditional UI requests with an explicit `AbortController` and MUST abort active autofill promises before initiating user-driven modal assertions.

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

Inputs supporting passkey autofill MUST include `autocomplete="username webauthn"` or `autocomplete="webauthn"` attributes.

Inputs supporting passkey autofill MUST include `autocomplete="username webauthn"` or `autocomplete="webauthn"` attributes.

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

Assertion options MUST ALWAYS set `userVerification

Assertion options MUST ALWAYS set `userVerification: 'required'` to prevent phishing and unauthorized access via unverified biometrics/PINs.

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

Servers MUST verify clientDataJSON `origin` against a strictly allowlisted fully-qualified origin, verify `type === 'webauthn.get'`, and validate the signed cryptographic challenge in constant time.

Servers MUST verify clientDataJSON `origin` against a strictly allowlisted fully-qualified origin, verify `type === 'webauthn.get'`, and validate the signed cryptographic challenge in constant time.

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

Servers MUST parse `authenticatorData` flags and verify bit 0 (User Present / UP) is 1 and bit 2 (User Verified / UV) is 1.

Servers MUST parse `authenticatorData` flags and verify bit 0 (User Present / UP) is 1 and bit 2 (User Verified / UV) is 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.
7

When enterprise policy mandates device-bound credentials (non-synced hardware keys), servers MUST enforce that the Backup Eligibility (BE) flag (bit 3) is 0, or verify hardware attestation roots.

When enterprise policy mandates device-bound credentials (non-synced hardware keys), servers MUST enforce that the Backup Eligibility (BE) flag (bit 3) is 0, or verify hardware attestation roots.

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 UI & Device-Bound Assertion Invariant Guardrail critical for AI coding assistants?

Enforces strict WebAuthn Level 3 conditional UI orchestration and server-side device-bound passkey assertion verification. Prevents race conditions and credential hijacking by mandating AbortController-managed autofill mediation, user-verification enforcement, and cryptographic validation of authenticatorData flags. 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 (Unmanaged Conditional UI Autofill Collisions and Flawed User Verification Enforcement in Passkey Assertions) 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