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-partitioning-guardrail

WebAuthn Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant

Enforces strict top-level origin isolation, explicit Permissions-Policy sandboxing, and cryptographic origin-binding during WebAuthn conditional mediation (passkey autofill) within micro-frontend federation layouts. Prevents cross-origin credential leakage, autofill hijacking, and federated session poisoning caused by unpartitioned credential mediation across untrusted remotes.

Prohibited Anti-Pattern: Executing WebAuthn Conditional Autofill Inside Embedded Remotes or Relaying Assertions Across Cross-Origin Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant - Enforces strict top-level origin isolation, explicit Permissions-Policy sandboxing, and cryptographic origin-binding during WebAuthn conditional mediation (passkey autofill) within micro-frontend federation layouts. Prevents cross-origin credential leakage, autofill hijacking, and federated session poisoning caused by unpartitioned credential mediation across untrusted remotes.
globs: src/**/*.{ts,tsx}, apps/**/*.{ts,tsx}, packages/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-cross-origin-partitioning-guardrail"
---

# WebAuthn Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing WebAuthn Conditional Autofill Inside Embedded Remotes or Relaying Assertions Across Cross-Origin Boundaries

## System Constraints
You are a Principal Security Architect enforcing the WebAuthn Conditional Mediation Cross-Origin Partitioning Invariant. Passkey autofill (`navigator.credentials.get({ mediation: 'conditional' })`) in federated micro-frontend architectures presents critical attack surfaces: cross-frame passkey interception, credential relay attacks, and session poisoning. You must guarantee that conditional mediation is only ever initiated in the canonical top-level browsing context, child iframes strictly restrict `publickey-credentials-get` via Permissions-Policy, WebAuthn assertion payloads are validated against the exact RP ID and origin, and credential assertions are never transferred over unpartitioned event buses or wildcard `postMessage` channels.

## Strict Guidelines
- Engineers MUST ALWAYS verify that `window === window.top` before invoking `navigator.credentials.get({ mediation: 'conditional', ... })` to prevent embedded remote micro-frontends from triggering or hijacking silent autofill flows.
- Engineers MUST ALWAYS bind an `AbortController` to the conditional mediation lifecycle and abort outstanding requests immediately upon component unmount, route transition, or explicit user credential submission.
- Engineers MUST NOT broadcast raw or serialized `PublicKeyCredential` assertions across micro-frontend boundaries via `window.postMessage('*')`, global event buses, or shared web workers.
- Code SHOULD enforce strict RP ID scoping matching the canonical top-level domain (`window.location.hostname`) and reject any attempts by federated subdomains or micro-app contexts to substitute alternative RP IDs.
- Services MUST validate that the clientDataJSON `origin` matches the exact authorized top-level canonical origin on the server before mutating any session state or issuing authentication tokens.
- Components NEVER embed micro-frontend iframes with wildcard `allow="publickey-credentials-get *"`; iframes MUST either omit this permission or restrict it strictly to `allow="publickey-credentials-get 'self'"`.

## Bad vs Good Implementations
### Conditional Mediation in Federated Micro-Frontend Layout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The component runs conditional mediation regardless of whether it is rendered in an embedded cross-origin iframe. It fails to manage request lifecycle via AbortController, exposes the raw passkey assertion across frame boundaries via wildcard window.postMessage('*'), and allows remote federated consumers to poison parent session states.
```typescript
import React, { useEffect } from 'react';

// VULNERABLE: Invokes conditional mediation without checking top-level context,
// uses hardcoded/unvalidated rpId, doesn't abort on route change, and broadcasts
// assertion through wildcard postMessage to federated remotes.
export const FederatedPasskeyAutofill: React.FC = () => {
  useEffect(() => {
    async function startAutofill() {
      if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
        return;
      }

      const available = await PublicKeyCredential.isConditionalMediationAvailable();
      if (!available) return;

      const challengeResponse = await fetch('/api/auth/challenge');
      const { challenge } = await challengeResponse.json();

      // Flaw: No frame boundary check, no AbortController, weak rpId check
      const credential = await navigator.credentials.get({
        mediation: 'conditional',
        publicKey: {
          challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
          rpId: window.location.hostname,
          userVerification: 'preferred'
        }
      });

      if (credential) {
        // Flaw: Leaking credential assertion across micro-frontend federation bus
        window.parent.postMessage({ type: 'PASSKEY_ASSERTION', credential }, '*');
      }
    }

    startAutofill();
  }, []);

  return <input type="text" name="username" autoComplete="username webauthn" />;
};
```

#### Production Standard (Correct)
> **Standard**: This implementation enforces complete context isolation: it verifies `window === window.top`, validates that the hostname matches the configured `allowedRpId`, bounds the execution to an `AbortController` signal, handles verification directly with the authoritative backend without publishing credentials across federated boundaries, and cancels pending requests upon unmount.
```typescript
import React, { useEffect, useRef } from 'react';

interface PasskeyAutofillProps {
  onAssertionSuccess: (sessionId: string) => void;
  allowedRpId: string;
}

// HARDENED: Strictly restricts conditional mediation to the canonical top-level
// context, encapsulates assertion exchange within the trusted host, and aborts cleanly.
export const PartitionedPasskeyAutofill: React.FC<PasskeyAutofillProps> = ({
  onAssertionSuccess,
  allowedRpId
}) => {
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // Invariant 1: Block conditional mediation in nested iframes/micro-frontends
    if (window !== window.top) {
      console.error('[WebAuthn Security] Conditional mediation disallowed in embedded frame.');
      return;
    }

    // Invariant 2: Host origin validation against allowed RP ID
    if (window.location.hostname !== allowedRpId) {
      console.error('[WebAuthn Security] Hostname does not match canonical RP ID.');
      return;
    }

    const abortController = new AbortController();
    abortControllerRef.current = abortController;

    async function runConditionalMediation() {
      try {
        if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
          return;
        }

        const isAvailable = await PublicKeyCredential.isConditionalMediationAvailable();
        if (!isAvailable || abortController.signal.aborted) return;

        const response = await fetch('/api/auth/webauthn/challenge', {
          signal: abortController.signal,
          headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        if (!response.ok) return;
        const { challenge, sessionNonce } = await response.json();

        const credential = await navigator.credentials.get({
          mediation: 'conditional',
          signal: abortController.signal,
          publicKey: {
            challenge: Uint8Array.from(atob(challenge), c => c.charCodeAt(0)),
            rpId: allowedRpId,
            userVerification: 'preferred'
          }
        }) as PublicKeyCredential | null;

        if (!credential || abortController.signal.aborted) return;

        // Invariant 3: Direct canonical verification; avoid federated postMessage transport
        const verifyRes = await fetch('/api/auth/webauthn/verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          signal: abortController.signal,
          body: JSON.stringify({
            sessionNonce,
            id: credential.id,
            rawId: btoa(String.fromCharCode(...new Uint8Array(credential.rawId))),
            response: {
              clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(credential.response.clientDataJSON))),
              authenticatorData: btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).authenticatorData))),
              signature: btoa(String.fromCharCode(...new Uint8Array((credential.response as AuthenticatorAssertionResponse).signature)))
            }
          })
        });

        if (verifyRes.ok) {
          const data = await verifyRes.json();
          onAssertionSuccess(data.sessionId);
        }
      } catch (err: unknown) {
        if ((err as Error).name !== 'AbortError') {
          console.error('[WebAuthn Security] Conditional mediation failed:', err);
        }
      }
    }

    runConditionalMediation();

    return () => {
      abortController.abort();
      abortControllerRef.current = null;
    };
  }, [allowedRpId, onAssertionSuccess]);

  return (
    <input
      type="text"
      id="passkey-autofill-username"
      name="username"
      autoComplete="username webauthn"
      aria-label="Username or Passkey"
    />
  );
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebAuthn Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant

WebAuthn Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces strict top-level origin isolation, explicit Permissions-Policy sandboxing, and cryptographic origin-binding during WebAuthn conditional mediation (passkey autofill) within micro-frontend federation layouts. Prevents cross-origin credential leakage, autofill hijacking, and federated session poisoning caused by unpartitioned credential mediation across untrusted remotes. 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: Executing WebAuthn Conditional Autofill Inside Embedded Remotes or Relaying Assertions Across Cross-Origin Boundaries 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 DriftExecuting WebAuthn Conditional Autofill Inside Embedded Remotes or Relaying Assertions Across Cross-Origin BoundariesCritical
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 verify that `window === window.top` before invoking `navigator.credentials.get({ mediation

Engineers MUST ALWAYS verify that `window === window.top` before invoking `navigator.credentials.get({ mediation: 'conditional', ... })` to prevent embedded remote micro-frontends from triggering or hijacking silent autofill flows.

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 bind an `AbortController` to the conditional mediation lifecycle and abort outstanding requests immediately upon component unmount, route transition, or explicit user credential submission.

Engineers MUST ALWAYS bind an `AbortController` to the conditional mediation lifecycle and abort outstanding requests immediately upon component unmount, route transition, or explicit user credential submission.

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 NOT broadcast raw or serialized `PublicKeyCredential` assertions across micro-frontend boundaries via `window.postMessage('*')`, global event buses, or shared web workers.

Engineers MUST NOT broadcast raw or serialized `PublicKeyCredential` assertions across micro-frontend boundaries via `window.postMessage('*')`, global event buses, or shared web workers.

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

Code SHOULD enforce strict RP ID scoping matching the canonical top-level domain (`window.location.hostname`) and reject any attempts by federated subdomains or micro-app contexts to substitute alternative RP IDs.

Code SHOULD enforce strict RP ID scoping matching the canonical top-level domain (`window.location.hostname`) and reject any attempts by federated subdomains or micro-app contexts to substitute alternative RP IDs.

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

Services MUST validate that the clientDataJSON `origin` matches the exact authorized top-level canonical origin on the server before mutating any session state or issuing authentication tokens.

Services MUST validate that the clientDataJSON `origin` matches the exact authorized top-level canonical origin on the server before mutating any session state or issuing authentication tokens.

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

Components NEVER embed micro-frontend iframes with wildcard `allow="publickey-credentials-get *"`

Components NEVER embed micro-frontend iframes with wildcard `allow="publickey-credentials-get *"`; iframes MUST either omit this permission or restrict it strictly to `allow="publickey-credentials-get 'self'"`.

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 Conditional Mediation Cross-Origin Partitioning & Session Isolation Invariant critical for AI coding assistants?

Enforces strict top-level origin isolation, explicit Permissions-Policy sandboxing, and cryptographic origin-binding during WebAuthn conditional mediation (passkey autofill) within micro-frontend federation layouts. Prevents cross-origin credential leakage, autofill hijacking, and federated session poisoning caused by unpartitioned credential mediation across untrusted remotes. 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 (Executing WebAuthn Conditional Autofill Inside Embedded Remotes or Relaying Assertions Across Cross-Origin Boundaries) 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