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

Capacitor 7 Strict Native Bridge Sandboxing and Origin-Capability Isolation

Enforces strict origin-capability tagging and execution boundaries on the Capacitor 7 JavaScript-to-Native bridge. Prevents Cross-Site Scripting (XSS) payloads and untrusted third-party DOM scripts from invoking high-privilege native device interfaces (Filesystem, Biometrics, SecureStorage, Geolocation) through global bridge escalation.

Prohibited Anti-Pattern: Global Window Bridge Exposure Permitting XSS-Driven Native Privilege Escalation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Strict Native Bridge Sandboxing and Origin-Capability Isolation - Enforces strict origin-capability tagging and execution boundaries on the Capacitor 7 JavaScript-to-Native bridge. Prevents Cross-Site Scripting (XSS) payloads and untrusted third-party DOM scripts from invoking high-privilege native device interfaces (Filesystem, Biometrics, SecureStorage, Geolocation) through global bridge escalation.
globs: capacitor.config.ts, src/**/*.{ts,tsx}, ios/App/App/capacitor.config.json, android/app/src/main/assets/capacitor.config.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-strict-native-bridge-sandboxing"
---

# Capacitor 7 Strict Native Bridge Sandboxing and Origin-Capability Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Global Window Bridge Exposure Permitting XSS-Driven Native Privilege Escalation

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Strict Native Bridge Sandboxing. Your mandate is to eliminate all direct, unmediated access to `window.Capacitor` or `@capacitor/*` plugins from untrusted execution contexts, dynamic DOM scripts, and third-party dependencies. You enforce strict origin-capability gating, lock down capacitor configuration navigation boundaries, seal bridge facades against runtime tampering, and mandate defense-in-depth Content Security Policies (CSP) to isolate the native runtime from web-layer exploits.

## Strict Guidelines
- Engineers MUST NEVER permit direct invocation of `@capacitor/core` or `Capacitor.Plugins` inside arbitrary UI components, third-party libraries, or analytics callbacks.
- Engineers MUST wrap all native invocations behind a hardened, singleton Bridge Mediator that validates execution origin, context state, and capability entitlement tokens before dispatch.
- Configuration files (`capacitor.config.ts`) MUST explicitly lock down `server.allowNavigation` to approved, cryptographically validated subdomains and NEVER use wildcard `'*'` patterns.
- Code MUST `Object.freeze` and `Object.seal` all in-memory native bridge wrappers and gatekeepers to prevent DOM prototype pollution and script-level monkey-patching.
- Web applications MUST define a strict Content Security Policy (CSP) in `index.html` disallowing `unsafe-eval` and unauthorized script sources that could compromise the bridge namespace.
- Services interacting with native hardware (Biometrics, SecureStorage, Camera, Keychain) MUST require explicit user-initiated interaction invariants (transient user activation) prior to execution.

## Bad vs Good Implementations
### Unrestricted Capacitor Bridge Configuration and Direct Plugin Access

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring allowNavigation to '*' permits third-party websites or malicious redirects within the WebView to execute arbitrary native bridge methods. Furthermore, directly invoking plugin methods without sandboxing, token authorization, or origin isolation allows injected DOM scripts (via XSS or supply chain dependencies) to extract sensitive credentials directly from native storage.
```typescript
import { CapacitorConfig } from '@capacitor/cli';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

// ANTI-PATTERN: Wildcard navigation and unsealed global plugin access
export const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'VulnerableApp',
  webDir: 'dist',
  server: {
    // DANGEROUS: Permitting any external navigation allows malicious origins to inherit bridge
    allowNavigation: ['*'],
    cleartext: true,
  },
};

// Directly called from arbitrary UI layer or third-party context
export async function getAuthSecret(key: string): Promise<string> {
  // Attacker exploiting XSS can easily invoke this native bridge call:
  // window.Capacitor.Plugins.SecureStoragePlugin.get({ key: 'jwt' })
  const result = await SecureStoragePlugin.get({ key });
  return result.value;
}
```

#### Production Standard (Correct)
> **Standard**: Locks down the Capacitor config navigation permissions strictly to approved enterprise domains. Enforces a sealed `NativeBridgeGatekeeper` facade requiring origin verification, capability verification tokens, and trusted user events (`isTrusted: true`), preventing automated XSS payloads and untrusted DOM scripts from executing privileged native hardware operations.
```typescript
import { CapacitorConfig } from '@capacitor/cli';
import { registerPlugin } from '@capacitor/core';

// PRODUCTION INVARIANT: Restrict navigation boundaries and freeze bridge interfaces
export const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'HardenedApp',
  webDir: 'dist',
  server: {
    androidScheme: 'https',
    iosScheme: 'ionic',
    allowNavigation: ['auth.internal.example.com'],
    cleartext: false,
  },
  plugins: {
    CapacitorCookies: { enabled: true },
  },
};

interface SecureStorageCustomPlugin {
  get(options: { key: string }): Promise<{ value: string }>;
}

const RawSecureStorage = registerPlugin<SecureStorageCustomPlugin>('SecureStoragePlugin');

// Strict Capability Boundary Token
type CapabilityToken = 'CAPABILITY_READ_SECURE_VAULT';
const TRUSTED_ORIGIN = window.location.origin;

class NativeBridgeGatekeeper {
  private static instance: NativeBridgeGatekeeper;

  private constructor() {
    Object.freeze(this);
  }

  public static getInstance(): NativeBridgeGatekeeper {
    if (!NativeBridgeGatekeeper.instance) {
      NativeBridgeGatekeeper.instance = new NativeBridgeGatekeeper();
    }
    return NativeBridgeGatekeeper.instance;
  }

  public async accessSecureVault(
    token: CapabilityToken,
    key: string,
    callerEvent: UIEvent
  ): Promise<string> {
    // Invariant 1: Assert execution origin
    if (window.location.origin !== TRUSTED_ORIGIN) {
      throw new SecurityError('Unauthorized origin for native capability.');
    }

    // Invariant 2: Require transient user interaction to defeat automated script payloads
    if (!callerEvent.isTrusted) {
      throw new SecurityError('Capability invocation requires trusted user activation.');
    }

    // Invariant 3: Capability entitlement check
    if (token !== 'CAPABILITY_READ_SECURE_VAULT') {
      throw new SecurityError('Invalid capability token.');
    }

    const result = await RawSecureStorage.get({ key });
    return result.value;
  }
}

export const bridgeGatekeeper = Object.freeze(NativeBridgeGatekeeper.getInstance());
```

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 Strict Native Bridge Sandboxing and Origin-Capability Isolation

Capacitor 7 Strict Native Bridge Sandboxing and Origin-Capability Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin-capability tagging and execution boundaries on the Capacitor 7 JavaScript-to-Native bridge. Prevents Cross-Site Scripting (XSS) payloads and untrusted third-party DOM scripts from invoking high-privilege native device interfaces (Filesystem, Biometrics, SecureStorage, Geolocation) through global bridge escalation. 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: Global Window Bridge Exposure Permitting XSS-Driven Native Privilege Escalation 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 DriftGlobal Window Bridge Exposure Permitting XSS-Driven Native Privilege EscalationCritical
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 NEVER permit direct invocation of `@capacitor/core` or `Capacitor.Plugins` inside arbitrary UI components, third-party libraries, or analytics callbacks.

Engineers MUST NEVER permit direct invocation of `@capacitor/core` or `Capacitor.Plugins` inside arbitrary UI components, third-party libraries, or analytics callbacks.

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 wrap all native invocations behind a hardened, singleton Bridge Mediator that validates execution origin, context state, and capability entitlement tokens before dispatch.

Engineers MUST wrap all native invocations behind a hardened, singleton Bridge Mediator that validates execution origin, context state, and capability entitlement tokens before dispatch.

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

Configuration files (`capacitor.config.ts`) MUST explicitly lock down `server.allowNavigation` to approved, cryptographically validated subdomains and NEVER use wildcard `'*'` patterns.

Configuration files (`capacitor.config.ts`) MUST explicitly lock down `server.allowNavigation` to approved, cryptographically validated subdomains and NEVER use wildcard `'*'` patterns.

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 MUST `Object.freeze` and `Object.seal` all in-memory native bridge wrappers and gatekeepers to prevent DOM prototype pollution and script-level monkey-patching.

Code MUST `Object.freeze` and `Object.seal` all in-memory native bridge wrappers and gatekeepers to prevent DOM prototype pollution and script-level monkey-patching.

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

Web applications MUST define a strict Content Security Policy (CSP) in `index.html` disallowing `unsafe-eval` and unauthorized script sources that could compromise the bridge namespace.

Web applications MUST define a strict Content Security Policy (CSP) in `index.html` disallowing `unsafe-eval` and unauthorized script sources that could compromise the bridge namespace.

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

Services interacting with native hardware (Biometrics, SecureStorage, Camera, Keychain) MUST require explicit user-initiated interaction invariants (transient user activation) prior to execution.

Services interacting with native hardware (Biometrics, SecureStorage, Camera, Keychain) MUST require explicit user-initiated interaction invariants (transient user activation) prior to execution.

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 Strict Native Bridge Sandboxing and Origin-Capability Isolation critical for AI coding assistants?

Enforces strict origin-capability tagging and execution boundaries on the Capacitor 7 JavaScript-to-Native bridge. Prevents Cross-Site Scripting (XSS) payloads and untrusted third-party DOM scripts from invoking high-privilege native device interfaces (Filesystem, Biometrics, SecureStorage, Geolocation) through global bridge escalation. 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 (Global Window Bridge Exposure Permitting XSS-Driven Native Privilege Escalation) 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