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

Passkey Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant

Enforces cryptographic and architectural fencing for WebAuthn autofill (conditional mediation) flows to prevent relying-party origin reflection vulnerabilities. Verifies that the clientDataJSON origin and authenticatorData rpIdHash match immutable, cryptographically sealed whitelists rather than trusting incoming HTTP headers or permissive cross-origin delegations.

Prohibited Anti-Pattern: Reflecting Dynamic HTTP Origin/Host Headers into WebAuthn Assertion RP Verification

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Passkey Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant - Enforces cryptographic and architectural fencing for WebAuthn autofill (conditional mediation) flows to prevent relying-party origin reflection vulnerabilities. Verifies that the clientDataJSON origin and authenticatorData rpIdHash match immutable, cryptographically sealed whitelists rather than trusting incoming HTTP headers or permissive cross-origin delegations.
globs: src/**/auth/**/*.{ts,tsx,js,jsx}, src/**/webauthn/**/*.{ts,tsx,js,jsx}, src/**/api/**/*.{ts,tsx,js,jsx}, src/**/services/auth/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/passkey-conditional-mediation-origin-downgrade-fencing"
---

# Passkey Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Reflecting Dynamic HTTP Origin/Host Headers into WebAuthn Assertion RP Verification

## System Constraints
You are a Principal Security Architect enforcing cryptographic origin integrity and WebAuthn Conditional Mediation fencing. You must prevent cross-origin downgrade attacks, subdomain assertion hijacking, and HTTP header reflection during passkey autofill. Mandate strict cryptographic verification of `clientDataJSON.origin`, `clientDataJSON.crossOrigin`, and `authenticatorData.rpIdHash` against immutable, environment-sealed canonical identity bounds.

## Strict Guidelines
- Engineers MUST ALWAYS match clientDataJSON.origin against an immutable, hardcoded or environment-sealed set of fully qualified canonical origins.
- Engineers MUST NEVER reflect `req.headers.origin`, `req.headers.host`, or `X-Forwarded-Host` into the `expectedOrigin` or `expectedRPID` verification parameters.
- Code SHOULD inspect the `crossOrigin` boolean in `clientDataJSON` and explicitly reject assertion responses where `crossOrigin === true` unless multi-domain iframe delegation is cryptographically authorized and structurally isolated.
- Services MUST verify that `authenticatorData.rpIdHash` matches the SHA-256 hash of the canonical RP ID (e.g., `crypto.subtle.digest('SHA-256', canonicalRpId)`).
- Components NEVER trigger `navigator.credentials.get({ mediation: 'conditional' })` inside untrusted, cross-origin, or un-sandboxed iframes lacking explicit `publickey-credentials-get` Feature-Policy / Permissions-Policy declarations.

## Bad vs Good Implementations
### Vulnerable Dynamic Origin Reflection vs. Fenced Immutable RP Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Deriving expectedOrigin and expectedRPID dynamically from incoming HTTP headers (Origin/Host) permits origin reflection and cross-origin downgrade attacks. An attacker manipulating proxy headers or routing assertions through alternative endpoints can coerce verification against an unauthorized relying party context.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { Request, Response } from 'express';

export async function verifyPasskeyAssertion(req: Request, res: Response) {
  const { assertionResponse, challenge } = req.body;

  // CRITICAL SECURITY FLAW: Reflecting dynamic HTTP host/origin headers
  // Attacker on a compromised subdomain or malicious origin can spoof expectedOrigin/expectedRPID
  const clientOrigin = req.headers.origin || `https://${req.headers.host}`;
  const derivedRpId = new URL(clientOrigin).hostname;

  const verification = await verifyAuthenticationResponse({
    response: assertionResponse,
    expectedChallenge: challenge,
    expectedOrigin: clientOrigin,
    expectedRPID: derivedRpId,
    requireUserVerification: true,
  });

  if (!verification.verified) {
    return res.status(401).json({ error: 'Authentication failed' });
  }
  return res.json({ success: true });
}
```

#### Production Standard (Correct)
> **Standard**: Decodes and inspects clientDataJSON prior to crypto assertion, fences the origin against an immutable compile-time allowlist, verifies that crossOrigin downgrade flags are strictly rejected, and anchors expectedRPID to an unalterable canonical domain identifier.
```typescript
import { verifyAuthenticationResponse } from '@simplewebauthn/server';
import type { Request, Response } from 'express';

// Cryptographically sealed canonical relying party parameters
const CANONICAL_RP_ID = Object.freeze('identity.corp.example.com');
const TRUSTED_ORIGIN_SET = Object.freeze(new Set([
  'https://identity.corp.example.com',
  'https://login.corp.example.com'
]));

export async function verifyPasskeyAssertion(req: Request, res: Response) {
  const { assertionResponse, sessionChallenge } = req.body;

  // Decode clientDataJSON to evaluate structural security fields
  const rawClientData = Buffer.from(assertionResponse.response.clientDataJSON, 'base64url').toString('utf8');
  const clientData = JSON.parse(rawClientData);

  // 1. Verify exact operation intent
  if (clientData.type !== 'webauthn.get') {
    return res.status(400).json({ error: 'Invalid WebAuthn operation type' });
  }

  // 2. Fence origin strictly against sealed allowlist (reject header reflection)
  if (!TRUSTED_ORIGIN_SET.has(clientData.origin)) {
    return res.status(403).json({ error: 'Assertion origin not permitted by relying party fencing' });
  }

  // 3. Reject cross-origin autofill downgrades unless explicitly handled
  if (clientData.crossOrigin === true) {
    return res.status(403).json({ error: 'Cross-origin conditional mediation is explicitly rejected' });
  }

  const verification = await verifyAuthenticationResponse({
    response: assertionResponse,
    expectedChallenge: sessionChallenge,
    expectedOrigin: clientData.origin,
    expectedRPID: CANONICAL_RP_ID,
    requireUserVerification: true,
  });

  if (!verification.verified) {
    return res.status(401).json({ error: 'Cryptographic assertion verification failed' });
  }

  return res.json({ success: true });
}
```

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 Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant

Passkey Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant defines an industrial-grade behavioral standard for security engineering. Enforces cryptographic and architectural fencing for WebAuthn autofill (conditional mediation) flows to prevent relying-party origin reflection vulnerabilities. Verifies that the clientDataJSON origin and authenticatorData rpIdHash match immutable, cryptographically sealed whitelists rather than trusting incoming HTTP headers or permissive cross-origin delegations. 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: Reflecting Dynamic HTTP Origin/Host Headers into WebAuthn Assertion RP Verification 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 DriftReflecting Dynamic HTTP Origin/Host Headers into WebAuthn Assertion RP VerificationCritical
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 match clientDataJSON.origin against an immutable, hardcoded or environment-sealed set of fully qualified canonical origins.

Engineers MUST ALWAYS match clientDataJSON.origin against an immutable, hardcoded or environment-sealed set of fully qualified canonical origins.

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 NEVER reflect `req.headers.origin`, `req.headers.host`, or `X-Forwarded-Host` into the `expectedOrigin` or `expectedRPID` verification parameters.

Engineers MUST NEVER reflect `req.headers.origin`, `req.headers.host`, or `X-Forwarded-Host` into the `expectedOrigin` or `expectedRPID` verification parameters.

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

Code SHOULD inspect the `crossOrigin` boolean in `clientDataJSON` and explicitly reject assertion responses where `crossOrigin === true` unless multi-domain iframe delegation is cryptographically authorized and structurally isolated.

Code SHOULD inspect the `crossOrigin` boolean in `clientDataJSON` and explicitly reject assertion responses where `crossOrigin === true` unless multi-domain iframe delegation is cryptographically authorized and structurally isolated.

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 verify that `authenticatorData.rpIdHash` matches the SHA-256 hash of the canonical RP ID (e.g., `crypto.subtle.digest('SHA-256', canonicalRpId)`).

Services MUST verify that `authenticatorData.rpIdHash` matches the SHA-256 hash of the canonical RP ID (e.g., `crypto.subtle.digest('SHA-256', canonicalRpId)`).

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 trigger `navigator.credentials.get({ mediation

Components NEVER trigger `navigator.credentials.get({ mediation: 'conditional' })` inside untrusted, cross-origin, or un-sandboxed iframes lacking explicit `publickey-credentials-get` Feature-Policy / Permissions-Policy declarations.

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 Conditional Mediation Cross-Origin Downgrade Fencing & RP Binding Invariant critical for AI coding assistants?

Enforces cryptographic and architectural fencing for WebAuthn autofill (conditional mediation) flows to prevent relying-party origin reflection vulnerabilities. Verifies that the clientDataJSON origin and authenticatorData rpIdHash match immutable, cryptographically sealed whitelists rather than trusting incoming HTTP headers or permissive cross-origin delegations. 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 (Reflecting Dynamic HTTP Origin/Host Headers into WebAuthn Assertion RP Verification) 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