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

Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning

Enforces strict implementation standards for WebAuthn Conditional UI (autofill) authentication and robust server-side cryptographic origin verification. Guarantees protection against reverse-proxy phishing and origin-spoofing attacks by pinning expected client origins and RP IDs against signed authenticator assertions.

Prohibited Anti-Pattern: Trusting Client-Supplied Origin Headers or Omitting Conditional Mediation Checks in WebAuthn Workflows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning - Enforces strict implementation standards for WebAuthn Conditional UI (autofill) authentication and robust server-side cryptographic origin verification. Guarantees protection against reverse-proxy phishing and origin-spoofing attacks by pinning expected client origins and RP IDs against signed authenticator assertions.
globs: src/**/*.{ts,tsx}, api/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-ui-origin-pinning"
---

# Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Trusting Client-Supplied Origin Headers or Omitting Conditional Mediation Checks in WebAuthn Workflows

## System Constraints
You are a Principal Security Engineer enforcing Passkey WebAuthn Conditional UI standards and Origin Cryptographic Pinning. You must ensure that client-side implementations verify platform support before requesting conditional mediation, abort stale requests cleanly, and configure autofill input attributes. On the server side, you must mandate that authenticator responses are verified against an immutable, cryptographically pinned expected origin and RP ID, rejecting any dynamic origin extraction from client request headers.

## Strict Guidelines
- Engineers MUST ALWAYS cryptographically verify clientDataJSON against a strictly whitelisted, statically configured origin and RP ID on the server, never reading the expected origin dynamically from the incoming request's 'Host' or 'Origin' header.
- Engineers MUST verify that `PublicKeyCredential.isConditionalMediationAvailable()` resolves to true before invoking `navigator.credentials.get({ mediation: 'conditional' })` on the client.
- Engineers MUST bind an `AbortController` signal to all conditional WebAuthn get requests and cancel pending credentials when the component unmounts or switches authentication modes.
- Engineers MUST mark targeted username inputs with `autocomplete="webauthn username"` to enable native browser credential autofill popups.
- Engineers MUST store challenges in a short-lived, replay-protected session or encrypted state and ensure single-use challenge consumption during signature verification.
- Engineers MUST NOT fallback to insecure origins or accept wildcard domains when validating `clientDataJSON.origin` on the backend.
- Engineers MUST NOT invoke modal WebAuthn requests while a conditional UI request is active without first aborting the conditional request via its `AbortSignal`.

## Bad vs Good Implementations
### Client-Side Conditional UI Initiation with Lifecycle Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to check `isConditionalMediationAvailable()`, risking runtime exceptions on unsupported platforms. Lacks an `AbortController` to cancel pending mediation during page transitions or modal triggers, and hardcodes raw non-cryptographic challenge bytes without tracking session context.
```typescript
export function initPasskeyLogin() {
  // VULNERABLE: Invokes conditional UI without capability check or AbortSignal
  navigator.credentials.get({
    publicKey: {
      challenge: new Uint8Array([1, 2, 3]),
      rpId: window.location.hostname
    },
    // Type assertion bypass without checking browser support
    mediation: 'conditional' as CredentialMediationRequirement
  });
}
```

#### Production Standard (Correct)
> **Standard**: Verifies that conditional mediation is supported by the platform before proceeding. Uses an external `AbortSignal` to cancel execution if the UI unmounts or transitions, and requests cryptographic challenge options dynamically from the server.
```typescript
export async function initPasskeyLogin(abortSignal: AbortSignal): Promise<Credential | null> {
  const isAvailable =
    window.PublicKeyCredential &&
    typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function' &&
    await window.PublicKeyCredential.isConditionalMediationAvailable();

  if (!isAvailable) {
    return null;
  }

  const res = await fetch('/api/auth/webauthn/assertion-options', { method: 'POST', signal: abortSignal });
  const options: PublicKeyCredentialRequestOptionsJSON = await res.json();

  return await navigator.credentials.get({
    publicKey: {
      ...options,
      challenge: Uint8Array.from(atob(options.challenge), (c) => c.charCodeAt(0))
    },
    mediation: 'conditional',
    signal: abortSignal
  });
}
```

### Server-Side Origin Cryptographic Pinning Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting the origin from client-supplied HTTP request headers destroys WebAuthn phishing resistance. A reverse-proxy or attacker-controlled domain can forward their own Host/Origin headers, fooling the verifier into accepting assertions signed for a rogue domain.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

export async function handleLogin(req: Request) {
  const body = await req.json();
  // CRITICAL VULNERABILITY: Derives expected origin dynamically from unauthenticated request headers
  const dynamicOrigin = req.headers.get('origin') || `https://${req.headers.get('host')}`;
  
  return await verifyAuthenticationResponse({
    response: body.credential,
    expectedChallenge: body.challenge,
    expectedOrigin: dynamicOrigin,
    expectedRPID: new URL(dynamicOrigin).hostname
  });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces origin cryptographic pinning by checking assertions strictly against an immutable list of trusted origins (`PINNED_ORIGINS`) and an explicit `PINNED_RP_ID`. Eliminates reliance on spoofable HTTP headers and verifies that session challenges match.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';

const PINNED_ORIGINS = new Set([
  'https://auth.company.internal',
  'https://login.company.com'
]);
const PINNED_RP_ID = 'company.com';

export async function handleLogin(req: Request, sessionChallenge: string) {
  const body = await req.json();
  
  const verification = await verifyAuthenticationResponse({
    response: body.credential,
    expectedChallenge: sessionChallenge,
    expectedOrigin: Array.from(PINNED_ORIGINS),
    expectedRPID: PINNED_RP_ID,
    requireUserVerification: true
  });

  if (!verification.verified) {
    throw new Error('WebAuthn cryptographic verification failed');
  }

  return verification;
}
```

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: Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning

Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning defines an industrial-grade behavioral standard for security engineering. Enforces strict implementation standards for WebAuthn Conditional UI (autofill) authentication and robust server-side cryptographic origin verification. Guarantees protection against reverse-proxy phishing and origin-spoofing attacks by pinning expected client origins and RP IDs against signed authenticator assertions. 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: Trusting Client-Supplied Origin Headers or Omitting Conditional Mediation Checks in WebAuthn Workflows 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 DriftTrusting Client-Supplied Origin Headers or Omitting Conditional Mediation Checks in WebAuthn WorkflowsCritical
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 cryptographically verify clientDataJSON against a strictly whitelisted, statically configured origin and RP ID on the server, never reading the expected origin dynamically from the incoming request's 'Host' or 'Origin' header.

Engineers MUST ALWAYS cryptographically verify clientDataJSON against a strictly whitelisted, statically configured origin and RP ID on the server, never reading the expected origin dynamically from the incoming request's 'Host' or 'Origin' header.

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 verify that `PublicKeyCredential.isConditionalMediationAvailable()` resolves to true before invoking `navigator.credentials.get({ mediation

Engineers MUST verify that `PublicKeyCredential.isConditionalMediationAvailable()` resolves to true before invoking `navigator.credentials.get({ mediation: 'conditional' })` on the client.

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

Engineers MUST bind an `AbortController` signal to all conditional WebAuthn get requests and cancel pending credentials when the component unmounts or switches authentication modes.

Engineers MUST bind an `AbortController` signal to all conditional WebAuthn get requests and cancel pending credentials when the component unmounts or switches authentication modes.

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

Engineers MUST mark targeted username inputs with `autocomplete="webauthn username"` to enable native browser credential autofill popups.

Engineers MUST mark targeted username inputs with `autocomplete="webauthn username"` to enable native browser credential autofill popups.

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

Engineers MUST store challenges in a short-lived, replay-protected session or encrypted state and ensure single-use challenge consumption during signature verification.

Engineers MUST store challenges in a short-lived, replay-protected session or encrypted state and ensure single-use challenge consumption during signature verification.

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 NOT fallback to insecure origins or accept wildcard domains when validating `clientDataJSON.origin` on the backend.

Engineers MUST NOT fallback to insecure origins or accept wildcard domains when validating `clientDataJSON.origin` on the backend.

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

Engineers MUST NOT invoke modal WebAuthn requests while a conditional UI request is active without first aborting the conditional request via its `AbortSignal`.

Engineers MUST NOT invoke modal WebAuthn requests while a conditional UI request is active without first aborting the conditional request via its `AbortSignal`.

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 Passkey WebAuthn Conditional UI with Origin Cryptographic Pinning critical for AI coding assistants?

Enforces strict implementation standards for WebAuthn Conditional UI (autofill) authentication and robust server-side cryptographic origin verification. Guarantees protection against reverse-proxy phishing and origin-spoofing attacks by pinning expected client origins and RP IDs against signed authenticator assertions. 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 (Trusting Client-Supplied Origin Headers or Omitting Conditional Mediation Checks in WebAuthn Workflows) 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

Passkey