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

WebAuthn Conditional Mediation Top-Level Browsing Context Guardrail

Enforces strict top-level browsing context boundaries during WebAuthn ambient passkey autofill (conditional mediation). Ambient credential requests in unvalidated or embedded contexts expose users to credential harvesting, iframe overlays, and clickjacking attacks.

Prohibited Anti-Pattern: Executing WebAuthn Conditional Mediation Inside Nested or Embedded Frame Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAuthn Conditional Mediation Top-Level Browsing Context Guardrail - Enforces strict top-level browsing context boundaries during WebAuthn ambient passkey autofill (conditional mediation). Ambient credential requests in unvalidated or embedded contexts expose users to credential harvesting, iframe overlays, and clickjacking attacks.
globs: src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webauthn-conditional-mediation-top-level-context-guardrail"
---

# WebAuthn Conditional Mediation Top-Level Browsing Context Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing WebAuthn Conditional Mediation Inside Nested or Embedded Frame Contexts

## System Constraints
You are a Principal Security Architect enforcing zero-trust browser boundaries for WebAuthn passkey autofill. WebAuthn conditional mediation (`mediation: 'conditional'`) initiates silent credential discovery during document initialization. You must ensure that conditional mediation is never executed inside iframes, unverified nested browsing contexts, or non-secure contexts, eliminating cross-origin credential harvesting and UI redressing vectors. Mandate strict top-level checks (`window.self === window.top`), modern feature detection via `PublicKeyCredential.isConditionalMediationAvailable()`, and lifecycle cancellation via `AbortController`.

## Strict Guidelines
- Engineers MUST ALWAYS verify that execution occurs strictly within the top-level browsing context (`window.self === window.top`) before invoking `navigator.credentials.get({ mediation: 'conditional' })`.
- Engineers MUST NOT initialize WebAuthn conditional mediation inside any iframe or embedded subframe, regardless of Permissions-Policy or allow attributes.
- Code MUST verify `window.isSecureContext` is `true` before attempting any WebAuthn ceremony.
- Services MUST link an `AbortSignal` to all conditional mediation calls to cancel dangling ambient queries on component unmount, navigation, or fallback modal trigger.
- Components NEVER trigger `navigator.credentials.get` with conditional mediation before confirming availability via `PublicKeyCredential.isConditionalMediationAvailable()`.

## Bad vs Good Implementations
### Passkey Conditional Autofill with Top-Level Frame Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to verify `window.self === window.top` and `window.isSecureContext`. An attacker embedding the login surface within an iframe could silently prompt for credentials or layer clickjacking overlays over passkey UI prompts. It also omits AbortSignal cleanup.
```typescript
import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types';

export async function startPasskeyAutofill(
  options: PublicKeyCredentialRequestOptionsJSON
): Promise<Credential | null> {
  // VULNERABLE: Lacks top-level context validation and lifecycle abort signal.
  // If embedded in an iframe via clickjacking or rogue third-party script,
  // ambient passkeys can be harvested or phished via UI overlays.
  if (window.PublicKeyCredential && PublicKeyCredential.isConditionalMediationAvailable) {
    const available = await PublicKeyCredential.isConditionalMediationAvailable();
    if (available) {
      return await navigator.credentials.get({
        publicKey: options as unknown as PublicKeyCredentialCreationOptions['publicKey'],
        mediation: 'conditional',
      });
    }
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: Strictly verifies `window.self === window.top`, asserts `window.isSecureContext`, safely verifies conditional mediation support, and binds the ceremony to an `AbortSignal` with explicit handling for `AbortError`.
```typescript
import type { PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types';

export interface AutofillConfig {
  options: PublicKeyCredentialRequestOptionsJSON;
  signal?: AbortSignal;
}

export async function startPasskeyAutofill({
  options,
  signal,
}: AutofillConfig): Promise<Credential | null> {
  // Invariant 1: Disallow execution in non-browser environments
  if (typeof window === 'undefined') {
    return null;
  }

  // Invariant 2: Strict Top-Level Context Guardrail against iframe harvesting
  if (window.self !== window.top) {
    console.warn(
      '[WebAuthn Guardrail] Conditional mediation blocked: execution attempted in an embedded frame.'
    );
    return null;
  }

  // Invariant 3: Verify cryptographic transport security context
  if (!window.isSecureContext) {
    throw new SecurityError('Passkey operations require a valid Secure Context (HTTPS).');
  }

  // Invariant 4: Guardrail against missing WebAuthn conditional UI capabilities
  const hasConditionalSupport =
    typeof window.PublicKeyCredential !== 'undefined' &&
    typeof window.PublicKeyCredential.isConditionalMediationAvailable === 'function';

  if (!hasConditionalSupport) {
    return null;
  }

  const isAvailable = await window.PublicKeyCredential.isConditionalMediationAvailable();
  if (!isAvailable) {
    return null;
  }

  try {
    return await navigator.credentials.get({
      publicKey: options as unknown as PublicKeyCredentialCreationOptions['publicKey'],
      mediation: 'conditional',
      signal,
    });
  } catch (err: unknown) {
    if (err instanceof DOMException && err.name === 'AbortError') {
      return null; // Intentional lifecycle cancellation
    }
    throw err;
  }
}
```

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 Top-Level Browsing Context Guardrail

WebAuthn Conditional Mediation Top-Level Browsing Context Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict top-level browsing context boundaries during WebAuthn ambient passkey autofill (conditional mediation). Ambient credential requests in unvalidated or embedded contexts expose users to credential harvesting, iframe overlays, and clickjacking attacks. 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 Mediation Inside Nested or Embedded Frame Contexts 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 Mediation Inside Nested or Embedded Frame ContextsCritical
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 execution occurs strictly within the top-level browsing context (`window.self === window.top`) before invoking `navigator.credentials.get({ mediation

Engineers MUST ALWAYS verify that execution occurs strictly within the top-level browsing context (`window.self === window.top`) before invoking `navigator.credentials.get({ mediation: 'conditional' })`.

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 initialize WebAuthn conditional mediation inside any iframe or embedded subframe, regardless of Permissions-Policy or allow attributes.

Engineers MUST NOT initialize WebAuthn conditional mediation inside any iframe or embedded subframe, regardless of Permissions-Policy or allow 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.
3

Code MUST verify `window.isSecureContext` is `true` before attempting any WebAuthn ceremony.

Code MUST verify `window.isSecureContext` is `true` before attempting any WebAuthn ceremony.

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 link an `AbortSignal` to all conditional mediation calls to cancel dangling ambient queries on component unmount, navigation, or fallback modal trigger.

Services MUST link an `AbortSignal` to all conditional mediation calls to cancel dangling ambient queries on component unmount, navigation, or fallback modal trigger.

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` with conditional mediation before confirming availability via `PublicKeyCredential.isConditionalMediationAvailable()`.

Components NEVER trigger `navigator.credentials.get` with conditional mediation before confirming availability via `PublicKeyCredential.isConditionalMediationAvailable()`.

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 Top-Level Browsing Context Guardrail critical for AI coding assistants?

Enforces strict top-level browsing context boundaries during WebAuthn ambient passkey autofill (conditional mediation). Ambient credential requests in unvalidated or embedded contexts expose users to credential harvesting, iframe overlays, and clickjacking attacks. 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 Mediation Inside Nested or Embedded Frame Contexts) 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