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

Capacitor 7 Bridgeless Plugin Origin-Scoped Capability Sandboxing

Enforces strict origin-scoped capability manifests and sandbox barriers for Capacitor 7 web-to-native execution channels. Prevents cross-webview script injection, arbitrary native bridge calls from untrusted subframes or injected XSS payloads, and privilege escalation by binding plugin dispatch to cryptographically verified or origin-whitelisted execution contexts.

Prohibited Anti-Pattern: Unrestricted Global Native Bridge Exposure and Unvalidated Cross-Origin Plugin Invocation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Bridgeless Plugin Origin-Scoped Capability Sandboxing - Enforces strict origin-scoped capability manifests and sandbox barriers for Capacitor 7 web-to-native execution channels. Prevents cross-webview script injection, arbitrary native bridge calls from untrusted subframes or injected XSS payloads, and privilege escalation by binding plugin dispatch to cryptographically verified or origin-whitelisted execution contexts.
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-bridgeless-plugin-security-sandboxing"
---

# Capacitor 7 Bridgeless Plugin Origin-Scoped Capability Sandboxing

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unrestricted Global Native Bridge Exposure and Unvalidated Cross-Origin Plugin Invocation

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 bridgeless plugin security sandboxing and origin-scoped capability validation. Mandate invariants that restrict all web-to-native execution channels to pre-approved origin domains, prohibit exposing raw Capacitor bridge handles to arbitrary window contexts or iframes, and enforce capability isolation across all custom and official native plugins.

## Strict Guidelines
- Engineers MUST ALWAYS restrict Capacitor bridge invocation to explicitly configured origins using the `server.allowNavigation` and custom capability gates.
- Engineers MUST NOT expose raw `Capacitor.toNative` or unconstrained plugin references to `window` or cross-origin `iframe` environments.
- Code MUST verify current execution context (`window.isSecureContext`, origin validation, and `window.self === window.top`) before invoking high-privilege native capabilities.
- Services MUST implement capability-scoped broker wrappers that authenticate callers before proxying calls to native Capacitor 7 interfaces.
- Components NEVER invoke native bridge methods directly from untrusted rendered HTML or externally fetched content contexts.

## Bad vs Good Implementations
### Origin and Context-Restricted Plugin Invoker vs Raw Bridge Exposure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly registering and exposing native plugins to global scope or calling them without origin and frame boundary validation allows untrusted scripts (e.g., from XSS or injected iframes) to execute native methods with elevated device privileges.
```typescript
import { registerPlugin } from '@capacitor/core';

// ANTI-PATTERN: Direct global exposure of sensitive native plugin
// Any injected script, third-party iframe, or XSS vector can invoke biometrics directly
export interface SecureVaultPlugin {
  unlockVault(options: { keyId: string }): Promise<{ secret: string }>;
}

export const SecureVault = registerPlugin<SecureVaultPlugin>('SecureVault');

// Insecurely attached to window or called without origin/context assertions
(window as unknown as { SecureVault: SecureVaultPlugin }).SecureVault = SecureVault;

export async function executeUnlock(keyId: string) {
  return SecureVault.unlockVault({ keyId });
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation shields the native plugin using a SandboxedPluginBroker that validates execution context: confirming top-level window hierarchy, enforcing a cryptographic or secure context invariant, and checking against an authorized origin allowlist before dispatching to the native layer.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureVaultPlugin {
  unlockVault(options: { keyId: string; sessionToken: string }): Promise<{ secret: string }>;
}

const RawSecureVault = registerPlugin<SecureVaultPlugin>('SecureVault');

const TRUSTED_ORIGINS = new Set([
  'capacitor://localhost',
  'ionic://localhost',
  'http://localhost',
  'https://app.internal.domain'
]);

class SandboxedPluginBroker {
  private static validateExecutionContext(): void {
    // Invariant: Native calls must execute only within the top-level secure origin context
    if (typeof window === 'undefined' || !window.isSecureContext) {
      throw new Error('CapacitorSandboxViolation: Insecure execution context detected.');
    }
    if (window.self !== window.top) {
      throw new Error('CapacitorSandboxViolation: Embedded iframe invocation is forbidden.');
    }
    if (!TRUSTED_ORIGINS.has(window.location.origin)) {
      throw new Error(`CapacitorSandboxViolation: Origin '${window.location.origin}' is not authorized.`);
    }
  }

  public static async executeScopedCall<T>(
    capabilityName: string,
    fn: () => Promise<T>
  ): Promise<T> {
    this.validateExecutionContext();
    try {
      return await fn();
    } catch (error) {
      console.error(`Execution failed for sandboxed capability: ${capabilityName}`, error);
      throw error;
    }
  }
}

export async function executeUnlock(keyId: string, sessionToken: string): Promise<{ secret: string }> {
  return SandboxedPluginBroker.executeScopedCall('SecureVault.unlockVault', () =>
    RawSecureVault.unlockVault({ keyId, sessionToken })
  );
}
```

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 Bridgeless Plugin Origin-Scoped Capability Sandboxing

Capacitor 7 Bridgeless Plugin Origin-Scoped Capability Sandboxing defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin-scoped capability manifests and sandbox barriers for Capacitor 7 web-to-native execution channels. Prevents cross-webview script injection, arbitrary native bridge calls from untrusted subframes or injected XSS payloads, and privilege escalation by binding plugin dispatch to cryptographically verified or origin-whitelisted execution contexts. 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: Unrestricted Global Native Bridge Exposure and Unvalidated Cross-Origin Plugin Invocation 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 DriftUnrestricted Global Native Bridge Exposure and Unvalidated Cross-Origin Plugin InvocationCritical
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 restrict Capacitor bridge invocation to explicitly configured origins using the `server.allowNavigation` and custom capability gates.

Engineers MUST ALWAYS restrict Capacitor bridge invocation to explicitly configured origins using the `server.allowNavigation` and custom capability gates.

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 expose raw `Capacitor.toNative` or unconstrained plugin references to `window` or cross-origin `iframe` environments.

Engineers MUST NOT expose raw `Capacitor.toNative` or unconstrained plugin references to `window` or cross-origin `iframe` environments.

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 current execution context (`window.isSecureContext`, origin validation, and `window.self === window.top`) before invoking high-privilege native capabilities.

Code MUST verify current execution context (`window.isSecureContext`, origin validation, and `window.self === window.top`) before invoking high-privilege native capabilities.

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 implement capability-scoped broker wrappers that authenticate callers before proxying calls to native Capacitor 7 interfaces.

Services MUST implement capability-scoped broker wrappers that authenticate callers before proxying calls to native Capacitor 7 interfaces.

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 invoke native bridge methods directly from untrusted rendered HTML or externally fetched content contexts.

Components NEVER invoke native bridge methods directly from untrusted rendered HTML or externally fetched content contexts.

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 Bridgeless Plugin Origin-Scoped Capability Sandboxing critical for AI coding assistants?

Enforces strict origin-scoped capability manifests and sandbox barriers for Capacitor 7 web-to-native execution channels. Prevents cross-webview script injection, arbitrary native bridge calls from untrusted subframes or injected XSS payloads, and privilege escalation by binding plugin dispatch to cryptographically verified or origin-whitelisted execution contexts. 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 (Unrestricted Global Native Bridge Exposure and Unvalidated Cross-Origin Plugin Invocation) 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