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

Capacitor 7 Native Bridge Isolation and Prototype Pollution Guardrail

Enforces strict runtime isolation, deep immutability, and prototype sanitation on Capacitor 7 native bridge interfaces inside hybrid WebViews. Restricts untrusted third-party scripts from hijacking bridge dispatchers or polluting Object prototypes to escalate privileges into native device capabilities.

Prohibited Anti-Pattern: Exposing Mutable Native Bridge Handlers and Unsanitized Plugin Registries to Untrusted WebView Execution Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Isolation and Prototype Pollution Guardrail - Enforces strict runtime isolation, deep immutability, and prototype sanitation on Capacitor 7 native bridge interfaces inside hybrid WebViews. Restricts untrusted third-party scripts from hijacking bridge dispatchers or polluting Object prototypes to escalate privileges into native device capabilities.
globs: src/**/*.{ts,tsx}, 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-isolated-bridge-guardrail-production-standard"
---

# Capacitor 7 Native Bridge Isolation and Prototype Pollution Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Mutable Native Bridge Handlers and Unsanitized Plugin Registries to Untrusted WebView Execution Contexts

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Isolated Content World Bridge Guardrails. Mandate absolute isolation of the window.Capacitor bridge, freeze plugin registries against prototype pollution, sanitize all arguments crossing to native platforms, and prevent untrusted third-party runtime script execution in the privileged WebView window context.

## Strict Guidelines
- Engineers MUST ALWAYS recursively freeze (`Object.freeze`) `window.Capacitor`, `window.Capacitor.Plugins`, and native dispatch conduits (`postToNative`, `toNative`) immediately after bridge initialization.
- Engineers MUST NOT expose the raw `window.Capacitor` object to untrusted third-party scripts, analytics libraries, or external DOM embeddings.
- Bridge serialization functions MUST validate and purge dangerous prototype pollution keys (`__proto__`, `constructor`, `prototype`) from payload arguments before invoking native handlers.
- Services MUST define native dispatch properties using `Object.defineProperty` with `writable: false`, `configurable: false`, and `enumerable: false` to prevent property shadowing and prototype tampering.
- Components NEVER execute untrusted remote scripts in the primary WebView window context; third-party integrations MUST run in isolated execution contexts or sandboxed iframes without native bridge bindings.

## Bad vs Good Implementations
### Capacitor 7 Native Bridge Hardening and Prototype Sanitization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The global `window.Capacitor` instance and plugin objects remain mutable. A malicious third-party script injected via compromised CDN, cross-site script, or embedded ad can rewrite `Capacitor.toNative`, intercept sensitive native tokens, or pollute `Object.prototype` to manipulate arguments passed to native bridge plugins.
```typescript
import { registerPlugin } from '@capacitor/core';

// VULNERABLE: Direct exposure of mutable bridge and plugin registration
export interface SecureStoragePlugin {
  getToken(): Promise<{ token: string }>;
  saveToken(options: { token: string }): Promise<void>;
}

// Exposed directly on global window without freezing or input sanitization
export const SecureStorage = registerPlugin<SecureStoragePlugin>('SecureStorage');

// Untrusted third-party script can mutate bridge dispatch or pollute prototype
export function dispatchNativeCall(pluginName: string, methodName: string, payload: any) {
  const cap = (window as any).Capacitor;
  if (cap && cap.toNative) {
    // Susceptible to Object.prototype pollution and toNative hijacking
    return cap.toNative(pluginName, methodName, payload);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Applies recursive immutability (`deepFreeze`) to `window.Capacitor` and plugin instances, sets non-writable and non-configurable descriptors to prevent prototype shadowing, and strictly strips prototype pollution keys (`__proto__`, `constructor`, `prototype`) prior to bridging to the native platform.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureStoragePlugin {
  getToken(): Promise<{ token: string }>;
  saveToken(options: { token: string }): Promise<void>;
}

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

function deepFreeze<T extends object>(obj: T): Readonly<T> {
  Object.freeze(obj);
  for (const key of Object.getOwnPropertyNames(obj)) {
    const value = (obj as any)[key];
    if (value && typeof value === 'object' && !Object.isFrozen(value)) {
      deepFreeze(value);
    }
  }
  return obj;
}

function sanitizeBridgePayload<T>(payload: T): T {
  return JSON.parse(JSON.stringify(payload, (key, value) => {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      return undefined;
    }
    return value;
  }));
}

// Wrap plugin proxy with strict validation and immutability
export const SecureStorage: SecureStoragePlugin = deepFreeze({
  async getToken(): Promise<{ token: string }> {
    return await RawSecureStorage.getToken();
  },
  async saveToken(options: { token: string }): Promise<void> {
    const sanitized = sanitizeBridgePayload(options);
    return await RawSecureStorage.saveToken(sanitized);
  }
});

// Enforce immutability and lockout on window.Capacitor if present in context
if (typeof window !== 'undefined' && (window as any).Capacitor) {
  const cap = (window as any).Capacitor;
  deepFreeze(cap.Plugins ?? {});
  Object.defineProperty(window, 'Capacitor', {
    value: deepFreeze(cap),
    writable: false,
    configurable: false,
    enumerable: false
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge Isolation and Prototype Pollution Guardrail

Capacitor 7 Native Bridge Isolation and Prototype Pollution Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict runtime isolation, deep immutability, and prototype sanitation on Capacitor 7 native bridge interfaces inside hybrid WebViews. Restricts untrusted third-party scripts from hijacking bridge dispatchers or polluting Object prototypes to escalate privileges into native device capabilities. 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: Exposing Mutable Native Bridge Handlers and Unsanitized Plugin Registries to Untrusted WebView Execution 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 DriftExposing Mutable Native Bridge Handlers and Unsanitized Plugin Registries to Untrusted WebView Execution 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 recursively freeze (`Object.freeze`) `window.Capacitor`, `window.Capacitor.Plugins`, and native dispatch conduits (`postToNative`, `toNative`) immediately after bridge initialization.

Engineers MUST ALWAYS recursively freeze (`Object.freeze`) `window.Capacitor`, `window.Capacitor.Plugins`, and native dispatch conduits (`postToNative`, `toNative`) immediately after bridge initialization.

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 the raw `window.Capacitor` object to untrusted third-party scripts, analytics libraries, or external DOM embeddings.

Engineers MUST NOT expose the raw `window.Capacitor` object to untrusted third-party scripts, analytics libraries, or external DOM embeddings.

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

Bridge serialization functions MUST validate and purge dangerous prototype pollution keys (`__proto__`, `constructor`, `prototype`) from payload arguments before invoking native handlers.

Bridge serialization functions MUST validate and purge dangerous prototype pollution keys (`__proto__`, `constructor`, `prototype`) from payload arguments before invoking native handlers.

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 define native dispatch properties using `Object.defineProperty` with `writable

Services MUST define native dispatch properties using `Object.defineProperty` with `writable: false`, `configurable: false`, and `enumerable: false` to prevent property shadowing and prototype tampering.

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 execute untrusted remote scripts in the primary WebView window context

Components NEVER execute untrusted remote scripts in the primary WebView window context; third-party integrations MUST run in isolated execution contexts or sandboxed iframes without native bridge bindings.

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 Isolation and Prototype Pollution Guardrail critical for AI coding assistants?

Enforces strict runtime isolation, deep immutability, and prototype sanitation on Capacitor 7 native bridge interfaces inside hybrid WebViews. Restricts untrusted third-party scripts from hijacking bridge dispatchers or polluting Object prototypes to escalate privileges into native device capabilities. 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 (Exposing Mutable Native Bridge Handlers and Unsanitized Plugin Registries to Untrusted WebView Execution 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.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor