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

Capacitor 7 Native IPC Bridge Structured Serialization Boundary

Enforces strict runtime schema validation and structured byte buffer handling across the Capacitor 7 WebView-to-native IPC bridge. Eliminates cross-origin bridge exploitation, bridge injection vectors, and prototype pollution by enforcing zero-copy binary streaming and strict origin and payload validation at the native dispatcher boundary.

Prohibited Anti-Pattern: Unvalidated JSON Serialization and Arbitrary Object Dispatch Across WebView Native Bridge

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native IPC Bridge Structured Serialization Boundary - Enforces strict runtime schema validation and structured byte buffer handling across the Capacitor 7 WebView-to-native IPC bridge. Eliminates cross-origin bridge exploitation, bridge injection vectors, and prototype pollution by enforcing zero-copy binary streaming and strict origin and payload validation at the native dispatcher boundary.
globs: src/**/*.{ts,tsx}, capacitor.config.ts, ios/App/App/**/*.swift, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-ipc-bridge-serialization-boundary"
---

# Capacitor 7 Native IPC Bridge Structured Serialization Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unvalidated JSON Serialization and Arbitrary Object Dispatch Across WebView Native Bridge

## System Constraints
You are a Principal Mobile Architect and Security Engineer enforcing strict Capacitor 7 Native IPC bridge invariants. Mandate exhaustive compile-time and runtime type validation, sanitize all bridge dispatches against cross-origin bridge invocation, forbid unvalidated JSON stringification across plugin interfaces, and mandate zero-copy byte buffers for binary transfers.

## Strict Guidelines
- Engineers MUST ALWAYS validate IPC bridge payloads at the web-to-native boundary using strict schema validation (e.g., Zod, ArkType) before invoking native bridge methods.
- Engineers MUST NEVER pass raw, unbounded base64 strings across the IPC bridge for binary transfers; use Capacitor 7 zero-copy TypedArray / ArrayBuffer transfers or streaming channels.
- Code MUST sanitize all incoming bridge options against prototype pollution vectors (__proto__, constructor, prototype) before marshaling to native runtime objects.
- Services MUST explicitly enforce origin verification inside native WebView bridge dispatch handlers to ensure commands originate solely from authorized application scheme origins (e.g., capacitor://localhost or https://localhost).
- Components NEVER invoke raw `(window as any).Capacitor.nativePromise()` or bypass typed `registerPlugin<T>()` declarations.

## Bad vs Good Implementations
### Unsafe IPC Bridge Invocation vs Type-Safe Binary IPC Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The untyped plugin definition allows unchecked input containing prototype pollution keys (__proto__, constructor) to traverse the IPC bridge. Additionally, serializing binary data via Base64 strings causes severe memory duplication, performance degradation, and leaves the native bridge vulnerable to payload injection.
```typescript
import { registerPlugin } from '@capacitor/core';

// ANTI-PATTERN: Untyped plugin bridge passing unsanitized base64 payloads
const UnsafeStorage = registerPlugin<any>('UnsafeStorage');

export async function writeSecurePayload(untrustedInput: any): Promise<void> {
  // Insecure: Passing unchecked objects with prototype pollution risks
  // and sending binary data as bloated, serialized base64 strings
  const rawBase64 = btoa(JSON.stringify(untrustedInput.data));
  
  await UnsafeStorage.writeData({
    key: untrustedInput.key,
    blob: rawBase64,
    metadata: untrustedInput.metadata
  });
}
```

#### Production Standard (Correct)
> **Standard**: The payload is strictly validated at runtime using Zod with explicit key format constraints, rejecting any prototype pollution vectors. It uses native ArrayBuffer typed transfers to ensure safe, performant zero-copy byte transport across the native IPC boundary.
```typescript
import { registerPlugin } from '@capacitor/core';
import { z } from 'zod';

const PayloadSchema = z.object({
  key: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),
  buffer: z.instanceof(Uint8Array),
  checksum: z.string().length(64)
}).strict();

export type PayloadInput = z.infer<typeof PayloadSchema>;

export interface SecureStoragePlugin {
  writeBuffer(options: { key: string; data: ArrayBuffer; checksum: string }): Promise<{ bytesWritten: number }>;
}

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

export async function writeSecurePayload(input: unknown): Promise<{ bytesWritten: number }> {
  const validated = PayloadSchema.parse(input);
  
  // Enforce zero-copy transferable ArrayBuffer across Capacitor 7 bridge
  return await SecureStorage.writeBuffer({
    key: validated.key,
    data: validated.buffer.buffer,
    checksum: validated.checksum
  });
}
```

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 IPC Bridge Structured Serialization Boundary

Capacitor 7 Native IPC Bridge Structured Serialization Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces strict runtime schema validation and structured byte buffer handling across the Capacitor 7 WebView-to-native IPC bridge. Eliminates cross-origin bridge exploitation, bridge injection vectors, and prototype pollution by enforcing zero-copy binary streaming and strict origin and payload validation at the native dispatcher boundary. 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 JSON Serialization and Arbitrary Object Dispatch Across WebView Native Bridge 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 JSON Serialization and Arbitrary Object Dispatch Across WebView Native BridgeCritical
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 IPC bridge payloads at the web-to-native boundary using strict schema validation (e.g., Zod, ArkType) before invoking native bridge methods.

Engineers MUST ALWAYS validate IPC bridge payloads at the web-to-native boundary using strict schema validation (e.g., Zod, ArkType) before invoking native bridge methods.

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 NEVER pass raw, unbounded base64 strings across the IPC bridge for binary transfers

Engineers MUST NEVER pass raw, unbounded base64 strings across the IPC bridge for binary transfers; use Capacitor 7 zero-copy TypedArray / ArrayBuffer transfers or streaming channels.

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 sanitize all incoming bridge options against prototype pollution vectors (__proto__, constructor, prototype) before marshaling to native runtime objects.

Code MUST sanitize all incoming bridge options against prototype pollution vectors (__proto__, constructor, prototype) before marshaling to native runtime objects.

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 explicitly enforce origin verification inside native WebView bridge dispatch handlers to ensure commands originate solely from authorized application scheme origins (e.g., capacitor

Services MUST explicitly enforce origin verification inside native WebView bridge dispatch handlers to ensure commands originate solely from authorized application scheme origins (e.g., capacitor://localhost or https://localhost).

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 raw `(window as any).Capacitor.nativePromise()` or bypass typed `registerPlugin<T>()` declarations.

Components NEVER invoke raw `(window as any).Capacitor.nativePromise()` or bypass typed `registerPlugin<T>()` declarations.

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 IPC Bridge Structured Serialization Boundary critical for AI coding assistants?

Enforces strict runtime schema validation and structured byte buffer handling across the Capacitor 7 WebView-to-native IPC bridge. Eliminates cross-origin bridge exploitation, bridge injection vectors, and prototype pollution by enforcing zero-copy binary streaming and strict origin and payload validation at the native dispatcher boundary. 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 JSON Serialization and Arbitrary Object Dispatch Across WebView Native Bridge) 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