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

Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation

Enforces strict origin and top-origin cryptographic binding during WebAuthn conditional mediation (autofill passkey) exchanges. Mitigates silent credential harvesting, cross-origin assertion relay, and iframe credential substitution attacks by strictly verifying clientDataJSON against immutable session contexts. Mandates strict validation of RP ID, challenge nonce lifecycle, and conditional mediation assertion integrity on relying party servers.

Prohibited Anti-Pattern: Permissive Origin Validation or Loose Challenge Scoping in Passkey Autofill Handshakes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation - Enforces strict origin and top-origin cryptographic binding during WebAuthn conditional mediation (autofill passkey) exchanges. Mitigates silent credential harvesting, cross-origin assertion relay, and iframe credential substitution attacks by strictly verifying clientDataJSON against immutable session contexts. Mandates strict validation of RP ID, challenge nonce lifecycle, and conditional mediation assertion integrity on relying party servers.
globs: src/**/auth/**/*.{ts,tsx}, src/**/passkey/**/*.{ts,tsx}, src/**/webauthn/**/*.{ts,tsx}, server/**/auth/**/*.{ts,js}, api/**/auth/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-cross-origin-binding"
---

# Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Permissive Origin Validation or Loose Challenge Scoping in Passkey Autofill Handshakes

## System Constraints
You are a Principal Security Architect enforcing strict cryptographic boundaries on WebAuthn Level 3 Conditional Mediation (autofill passkey) authentication flows. You must ensure all relying party implementations rigorously validate clientDataJSON origins, topOrigins, rpIds, and single-use challenge bindings to prevent token injection, credential relay, and cross-origin substitution attacks.

## Strict Guidelines
- Engineers MUST ALWAYS validate 'clientDataJSON.origin' against an exact, fully qualified canonical origin (protocol, host, port) strictly matching the origin recorded in the authenticated session.
- Engineers MUST NOT permit wildcard subdomains, loose regex matches, or arbitrary client-supplied origin headers during WebAuthn assertion verification.
- Services MUST verify the 'crossOrigin' flag and 'topOrigin' property in 'clientDataJSON' whenever conditional mediation requests execute within embedded cross-origin contexts or iframes.
- Services MUST enforce atomic, single-use challenge consumption: challenges MUST be deleted or invalidated immediately upon retrieval before cryptographic verification completes to prevent replay.
- Components NEVER expose conditional UI triggers ('mediation: conditional') in cross-origin iframes without an explicit 'publickey-credentials-get' Permissions-Policy delegation.
- Code SHOULD enforce strict RP ID equality against an immutable backend configuration or tenant-scoped authority, forbidding fallback to broader parent domains unless explicitly configured.

## Bad vs Good Implementations
### Server-Side Conditional Mediation Assertion Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example uses a permissive substring match for origin validation (`origin.includes('example.com')`), allowing malicious origins like `attacker-example.com` or compromised subdomains. It fails to invalidate the challenge atomically, exposing the endpoint to replay attacks, and completely ignores the WebAuthn L3 `crossOrigin` and `topOrigin` attributes.
```typescript
import { Request, Response } from 'express';

interface StoredSession {
  challenge?: string;
}

export async function verifyPasskeyAssertion(req: Request, res: Response): Promise<void> {
  const session = req.session as unknown as StoredSession;
  const { clientDataJSON, authenticatorData, signature, id } = req.body;

  const clientData = JSON.parse(Buffer.from(clientDataJSON, 'base64url').toString('utf-8'));

  // VULNERABILITY 1: Loose origin validation permits sibling subdomain takeover
  if (!clientData.origin.includes('example.com')) {
    res.status(400).send('Invalid origin');
    return;
  }

  // VULNERABILITY 2: Challenge is not consumed atomically prior to cryptographic verification
  if (clientData.challenge !== session.challenge) {
    res.status(400).send('Invalid challenge');
    return;
  }

  // VULNERABILITY 3: Ignores crossOrigin and topOrigin checks entirely
  // Allows cross-origin frame relay attacks via conditional mediation autofill
  res.status(200).json({ status: 'verified', credentialId: id });
}
```

#### Production Standard (Correct)
> **Standard**: The good example atomically deletes the challenge prior to verification, uses constant-time comparison for the challenge, validates the operation type strictly (`webauthn.get`), enforces exact canonical origin matching against immutable session state, and explicitly inspects `crossOrigin` and `topOrigin` fields.
```typescript
import { Request, Response } from 'express';
import crypto from 'node:crypto';

interface SecureAuthSession {
  expectedChallenge: string;
  expectedOrigin: string;
  expectedRpId: string;
  challengeExpiresAt: number;
}

interface ClientDataJSON {
  type: string;
  challenge: string;
  origin: string;
  crossOrigin?: boolean;
  topOrigin?: string;
}

export async function verifyPasskeyAssertion(req: Request, res: Response): Promise<void> {
  const session = req.session as unknown as Partial<SecureAuthSession>;

  if (!session.expectedChallenge || !session.expectedOrigin || !session.expectedRpId) {
    res.status(401).json({ error: 'Missing active authentication challenge' });
    return;
  }

  // ATOMIC CONSUMPTION: Invalidate challenge immediately to prevent race conditions & replays
  const { expectedChallenge, expectedOrigin, expectedRpId, challengeExpiresAt } = session as SecureAuthSession;
  delete session.expectedChallenge;
  delete session.challengeExpiresAt;

  if (Date.now() > challengeExpiresAt) {
    res.status(401).json({ error: 'Authentication challenge expired' });
    return;
  }

  const rawClientData = Buffer.from(req.body.clientDataJSON, 'base64url').toString('utf-8');
  const clientData: ClientDataJSON = JSON.parse(rawClientData);

  // Strict invariant: assertion type must strictly match WebAuthn get
  if (clientData.type !== 'webauthn.get') {
    res.status(400).json({ error: 'Unexpected clientData type' });
    return;
  }

  // Constant-time challenge comparison to mitigate timing attacks
  const expectedBuf = Buffer.from(expectedChallenge, 'base64url');
  const actualBuf = Buffer.from(clientData.challenge, 'base64url');
  if (expectedBuf.length !== actualBuf.length || !crypto.timingSafeEqual(expectedBuf, actualBuf)) {
    res.status(401).json({ error: 'Challenge mismatch' });
    return;
  }

  // STRICT ORIGIN BINDING: Canonical equality check against session origin
  if (clientData.origin !== expectedOrigin) {
    res.status(403).json({ error: 'Origin binding verification failed' });
    return;
  }

  // CROSS-ORIGIN ISOLATION: Reject unexpected cross-origin assertion embedding
  if (clientData.crossOrigin === true) {
    if (!clientData.topOrigin || clientData.topOrigin !== expectedOrigin) {
      res.status(403).json({ error: 'Untrusted cross-origin assertion context' });
      return;
    }
  }

  // Proceed to cryptographic signature & authenticatorData RP ID hash verification
  res.status(200).json({ status: 'verified', rpId: expectedRpId });
}
```

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: Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation

Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation defines an industrial-grade behavioral standard for security engineering. Enforces strict origin and top-origin cryptographic binding during WebAuthn conditional mediation (autofill passkey) exchanges. Mitigates silent credential harvesting, cross-origin assertion relay, and iframe credential substitution attacks by strictly verifying clientDataJSON against immutable session contexts. Mandates strict validation of RP ID, challenge nonce lifecycle, and conditional mediation assertion integrity on relying party servers. 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: Permissive Origin Validation or Loose Challenge Scoping in Passkey Autofill Handshakes 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 DriftPermissive Origin Validation or Loose Challenge Scoping in Passkey Autofill HandshakesCritical
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 validate 'clientDataJSON.origin' against an exact, fully qualified canonical origin (protocol, host, port) strictly matching the origin recorded in the authenticated session.

Engineers MUST ALWAYS validate 'clientDataJSON.origin' against an exact, fully qualified canonical origin (protocol, host, port) strictly matching the origin recorded in the authenticated session.

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 NOT permit wildcard subdomains, loose regex matches, or arbitrary client-supplied origin headers during WebAuthn assertion verification.

Engineers MUST NOT permit wildcard subdomains, loose regex matches, or arbitrary client-supplied origin headers during WebAuthn assertion 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.
3

Services MUST verify the 'crossOrigin' flag and 'topOrigin' property in 'clientDataJSON' whenever conditional mediation requests execute within embedded cross-origin contexts or iframes.

Services MUST verify the 'crossOrigin' flag and 'topOrigin' property in 'clientDataJSON' whenever conditional mediation requests execute within embedded cross-origin contexts or iframes.

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 enforce atomic, single-use challenge consumption

Services MUST enforce atomic, single-use challenge consumption: challenges MUST be deleted or invalidated immediately upon retrieval before cryptographic verification completes to prevent replay.

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 expose conditional UI triggers ('mediation

Components NEVER expose conditional UI triggers ('mediation: conditional') in cross-origin iframes without an explicit 'publickey-credentials-get' Permissions-Policy delegation.

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 enforce strict RP ID equality against an immutable backend configuration or tenant-scoped authority, forbidding fallback to broader parent domains unless explicitly configured.

Code SHOULD enforce strict RP ID equality against an immutable backend configuration or tenant-scoped authority, forbidding fallback to broader parent domains unless explicitly configured.

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 Strict Origin-Bound Cryptographic Validation for WebAuthn Conditional Mediation critical for AI coding assistants?

Enforces strict origin and top-origin cryptographic binding during WebAuthn conditional mediation (autofill passkey) exchanges. Mitigates silent credential harvesting, cross-origin assertion relay, and iframe credential substitution attacks by strictly verifying clientDataJSON against immutable session contexts. Mandates strict validation of RP ID, challenge nonce lifecycle, and conditional mediation assertion integrity on relying party servers. 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 (Permissive Origin Validation or Loose Challenge Scoping in Passkey Autofill Handshakes) 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

Strict