This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-webview-bridge-origin-isolation-guardrail

Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding

Enforces cryptographic origin binding and strict webview context isolation on the Capacitor 7 JavaScript-to-Native bridge. Prevents unauthorized native plugin invocation by rogue cross-origin iframes, malicious redirect targets, and injected third-party scripts through mutual token verification and strict origin assertion during bridge bootstrap.

Prohibited Anti-Pattern: Unvalidated Capacitor Bridge Exposure Allowing Arbitrary Cross-Origin Native Plugin Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding - Enforces cryptographic origin binding and strict webview context isolation on the Capacitor 7 JavaScript-to-Native bridge. Prevents unauthorized native plugin invocation by rogue cross-origin iframes, malicious redirect targets, and injected third-party scripts through mutual token verification and strict origin assertion during bridge bootstrap.
globs: src/**/*.{ts,tsx}, capacitor.config.ts, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-webview-bridge-origin-isolation-guardrail"
---

# Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unvalidated Capacitor Bridge Exposure Allowing Arbitrary Cross-Origin Native Plugin Execution

## System Constraints
You are a Principal Mobile Systems Architect and Application Security Engineer enforcing strict Capacitor 7 Native Bridge Origin-Isolation and Cryptographic Token Binding. Mandate invariants that restrict window.Capacitor access, assert web origin validity before native IPC invocation, strip native bridge primitives from untrusted child contexts, and implement cryptographic authorization headers on bridge exchanges.

## Strict Guidelines
- Engineers MUST ALWAYS validate the execution context origin against an immutable allowlist (e.g., capacitor://localhost or http://localhost) before invoking any Capacitor plugin.
- Engineers MUST NOT allow Capacitor bridge initialization or plugin dispatch within untrusted <iframe> elements, popups, or external webview redirects.
- Code SHOULD inject an ephemeral, high-entropy cryptographic session token generated by the native layer during webview bootstrap and require it in every native bridge payload.
- Services MUST reject bridge messages at the native plugin layer if the caller's origin does not match the configured application package scheme or if the session token is invalid/tampered with.
- Components NEVER expose raw Capacitor.toNative or Capacitor.nativePromise handles directly to global window scopes accessible by arbitrary third-party analytics or external CDNs.

## Bad vs Good Implementations
### Vulnerable Bridge Invocation vs Cryptographically Bound IPC Gateway

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native bridge is invoked without verifying that the current window context is the canonical webview root origin, nor does it pass cryptographic provenance tokens. If the web app is framed or compromised by third-party scripts, unauthorized native device operations can be triggered.
```typescript
import { Capacitor } from '@capacitor/core';
import { Camera } from '@capacitor/camera';

// ANTI-PATTERN: Blindly executing native plugin methods from any execution context
// Malicious script injected via XSS or untrusted iframe can invoke native device hardware
export async function capturePhoto(): Promise<string | undefined> {
  const photo = await Camera.getPhoto({
    quality: 90,
    allowEditing: false
  });
  return photo.webPath;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces iframe prevention (window.top === window.self), validates the runtime origin strictly against canonical internal scheme definitions, seals the global Capacitor handle, and requires an immutable runtime session token to execute native routines.
```typescript
import { Capacitor } from '@capacitor/core';
import { Camera, Photo } from '@capacitor/camera';

interface BridgeSessionContext {
  readonly canonicalOrigin: string;
  readonly sessionToken: string;
}

class SecureBridgeGateway {
  private static readonly ALLOWED_ORIGIN: string = 'capacitor://localhost';
  private static sessionContext: BridgeSessionContext | null = null;

  public static initialize(token: string): void {
    if (typeof window === 'undefined' || window.top !== window.self) {
      throw new Error('Security Violation: Bridge initialization in non-top frame prohibited.');
    }
    if (window.location.origin !== this.ALLOWED_ORIGIN) {
      throw new Error(`Security Violation: Origin ${window.location.origin} is unauthorized.`);
    }
    this.sessionContext = Object.freeze({ canonicalOrigin: this.ALLOWED_ORIGIN, sessionToken: token });
    Object.defineProperty(window, 'Capacitor', { configurable: false, writable: false });
  }

  public static async executeSecurely<T>(pluginCall: (token: string) => Promise<T>): Promise<T> {
    if (!this.sessionContext || window.location.origin !== this.sessionContext.canonicalOrigin) {
      throw new Error('Access Denied: Untrusted caller context detected.');
    }
    return await pluginCall(this.sessionContext.sessionToken);
  }
}

export async function capturePhotoSecurely(bridgeToken: string): Promise<string | undefined> {
  SecureBridgeGateway.initialize(bridgeToken);
  return await SecureBridgeGateway.executeSecurely(async () => {
    const photo: Photo = await Camera.getPhoto({ quality: 90, allowEditing: false });
    return photo.webPath;
  });
}
```

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: Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding

Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic origin binding and strict webview context isolation on the Capacitor 7 JavaScript-to-Native bridge. Prevents unauthorized native plugin invocation by rogue cross-origin iframes, malicious redirect targets, and injected third-party scripts through mutual token verification and strict origin assertion during bridge bootstrap. 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: Unvalidated Capacitor Bridge Exposure Allowing Arbitrary Cross-Origin Native Plugin Execution 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 DriftUnvalidated Capacitor Bridge Exposure Allowing Arbitrary Cross-Origin Native Plugin ExecutionCritical
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 the execution context origin against an immutable allowlist (e.g., capacitor

Engineers MUST ALWAYS validate the execution context origin against an immutable allowlist (e.g., capacitor://localhost or http://localhost) before invoking any Capacitor plugin.

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 allow Capacitor bridge initialization or plugin dispatch within untrusted <iframe> elements, popups, or external webview redirects.

Engineers MUST NOT allow Capacitor bridge initialization or plugin dispatch within untrusted <iframe> elements, popups, or external webview redirects.

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 inject an ephemeral, high-entropy cryptographic session token generated by the native layer during webview bootstrap and require it in every native bridge payload.

Code SHOULD inject an ephemeral, high-entropy cryptographic session token generated by the native layer during webview bootstrap and require it in every native bridge payload.

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 reject bridge messages at the native plugin layer if the caller's origin does not match the configured application package scheme or if the session token is invalid/tampered with.

Services MUST reject bridge messages at the native plugin layer if the caller's origin does not match the configured application package scheme or if the session token is invalid/tampered with.

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 raw Capacitor.toNative or Capacitor.nativePromise handles directly to global window scopes accessible by arbitrary third-party analytics or external CDNs.

Components NEVER expose raw Capacitor.toNative or Capacitor.nativePromise handles directly to global window scopes accessible by arbitrary third-party analytics or external CDNs.

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 Capacitor 7 Native Bridge Origin Isolation and IPC Cryptographic Token Binding critical for AI coding assistants?

Enforces cryptographic origin binding and strict webview context isolation on the Capacitor 7 JavaScript-to-Native bridge. Prevents unauthorized native plugin invocation by rogue cross-origin iframes, malicious redirect targets, and injected third-party scripts through mutual token verification and strict origin assertion during bridge bootstrap. 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 (Unvalidated Capacitor Bridge Exposure Allowing Arbitrary Cross-Origin Native Plugin Execution) 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.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor