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

Capacitor 7 Native-to-WebView IPC Deserialization & Payload Validation Guardrail

Enforces strict runtime type validation, prototype pollution defense, and payload byte-size bounds on all Capacitor 7 bridge notifications and method return values crossing from native runtimes (Swift/Kotlin) into the WebView JavaScript execution context. Prevents prototype pollution, arbitrary property injection, and memory exhaustion from compromised native bridge boundaries.

Prohibited Anti-Pattern: Unchecked Native-to-JS Bridge Casts and Raw Event Stream Deserialization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native-to-WebView IPC Deserialization & Payload Validation Guardrail - Enforces strict runtime type validation, prototype pollution defense, and payload byte-size bounds on all Capacitor 7 bridge notifications and method return values crossing from native runtimes (Swift/Kotlin) into the WebView JavaScript execution context. Prevents prototype pollution, arbitrary property injection, and memory exhaustion from compromised native bridge boundaries.
globs: src/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-to-webview-ipc-deserialization-schema-guardrail"
---

# Capacitor 7 Native-to-WebView IPC Deserialization & Payload Validation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Native-to-JS Bridge Casts and Raw Event Stream Deserialization

## System Constraints
You are a Principal Mobile Architect enforcing strict zero-trust boundary validation across Capacitor 7 Native-to-WebView bridge interfaces. Mandate that every payload received from native bridge methods, custom plugins, or push/event listeners undergoes byte-size verification, prototype pollution stripping, and strict runtime schema parsing before reaching internal application state.

## Strict Guidelines
- Engineers MUST ALWAYS parse incoming Capacitor plugin return values and event listener streams through an immutable runtime schema validator (e.g., Zod, Valibot) before passing data into state stores or DOM sinks.
- Engineers MUST NOT cast raw bridge payloads using TypeScript assertion operators (e.g., `await Plugin.method() as ExpectedType` or `addListener(..., (data: ExpectedType) => ...)`).
- Services MUST sanitize all incoming bridge payloads against prototype pollution by discarding payloads containing `__proto__`, `constructor`, or `prototype` keys.
- Components NEVER consume unvalidated event streams directly; bridge communications must be encapsulated in typed gateway services that emit validated domain events or throw explicit boundary errors.
- Engineers MUST enforce a maximum payload size threshold (e.g., 2MB) on native serialization boundaries to prevent out-of-memory (OOM) crashes in the WebView V8/WebKit engine.

## Bad vs Good Implementations
### Bridge Listener Deserialization Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly trusting bridge payloads via `any` or TypeScript assertions exposes the WebView context to unexpected types, prototype pollution attacks, or UI crashes if the native layer sends malformed data or is intercepted by malicious native components.
```typescript
import { Plugins } from '@capacitor/core';
const { BlePlugin } = Plugins;

// ANTI-PATTERN: Blindly trusting bridge payload with unsafe casting
export function registerBleReceiver(onDeviceFound: (device: { id: string; rssi: number }) => void) {
  BlePlugin.addListener('deviceDiscovered', (rawPayload: any) => {
    // Vulnerable to prototype pollution, unexpected schema drift, and payload-based DoS
    const device = rawPayload as { id: string; rssi: number };
    onDeviceFound(device);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Applies a strict zero-trust boundary check: sanitizes against prototype poisoning, verifies payload structure via a strict Zod schema, rejects schema drift, and confines failures without crashing the application runtime.
```typescript
import { registerPlugin, PluginListenerHandle } from '@capacitor/core';
import { z } from 'zod';

const BleDeviceSchema = z.object({
  id: z.string().uuid(),
  rssi: z.number().int().min(-120).max(0),
  advertisementData: z.record(z.string(), z.unknown()).optional()
}).strict();

export type BleDevice = z.infer<typeof BleDeviceSchema>;

interface CustomBlePluginInterface {
  addListener(eventName: 'deviceDiscovered', listenerFunc: (payload: unknown) => void): Promise<PluginListenerHandle>;
}

const CustomBle = registerPlugin<CustomBlePluginInterface>('BlePlugin');

function sanitizeBridgePayload(payload: unknown): unknown {
  if (typeof payload === 'object' && payload !== null) {
    if ('__proto__' in payload || 'constructor' in payload || 'prototype' in payload) {
      throw new SecurityError('Prototype pollution attempt detected in bridge payload');
    }
  }
  return payload;
}

export async function registerBleReceiver(
  onDeviceFound: (device: BleDevice) => void,
  onError: (error: Error) => void
): Promise<PluginListenerHandle> {
  return CustomBle.addListener('deviceDiscovered', (rawPayload: unknown) => {
    try {
      const sanitized = sanitizeBridgePayload(rawPayload);
      const validatedDevice = BleDeviceSchema.parse(sanitized);
      onDeviceFound(validatedDevice);
    } catch (err) {
      onError(err instanceof Error ? err : new Error('Invalid bridge payload'));
    }
  });
}
```

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-to-WebView IPC Deserialization & Payload Validation Guardrail

Capacitor 7 Native-to-WebView IPC Deserialization & Payload Validation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict runtime type validation, prototype pollution defense, and payload byte-size bounds on all Capacitor 7 bridge notifications and method return values crossing from native runtimes (Swift/Kotlin) into the WebView JavaScript execution context. Prevents prototype pollution, arbitrary property injection, and memory exhaustion from compromised native bridge boundaries. 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: Unchecked Native-to-JS Bridge Casts and Raw Event Stream Deserialization 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 DriftUnchecked Native-to-JS Bridge Casts and Raw Event Stream DeserializationCritical
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 parse incoming Capacitor plugin return values and event listener streams through an immutable runtime schema validator (e.g., Zod, Valibot) before passing data into state stores or DOM sinks.

Engineers MUST ALWAYS parse incoming Capacitor plugin return values and event listener streams through an immutable runtime schema validator (e.g., Zod, Valibot) before passing data into state stores or DOM sinks.

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 cast raw bridge payloads using TypeScript assertion operators (e.g., `await Plugin.method() as ExpectedType` or `addListener(..., (data

Engineers MUST NOT cast raw bridge payloads using TypeScript assertion operators (e.g., `await Plugin.method() as ExpectedType` or `addListener(..., (data: ExpectedType) => ...)`).

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

Services MUST sanitize all incoming bridge payloads against prototype pollution by discarding payloads containing `__proto__`, `constructor`, or `prototype` keys.

Services MUST sanitize all incoming bridge payloads against prototype pollution by discarding payloads containing `__proto__`, `constructor`, or `prototype` keys.

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

Components NEVER consume unvalidated event streams directly

Components NEVER consume unvalidated event streams directly; bridge communications must be encapsulated in typed gateway services that emit validated domain events or throw explicit boundary errors.

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

Engineers MUST enforce a maximum payload size threshold (e.g., 2MB) on native serialization boundaries to prevent out-of-memory (OOM) crashes in the WebView V8/WebKit engine.

Engineers MUST enforce a maximum payload size threshold (e.g., 2MB) on native serialization boundaries to prevent out-of-memory (OOM) crashes in the WebView V8/WebKit engine.

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-to-WebView IPC Deserialization & Payload Validation Guardrail critical for AI coding assistants?

Enforces strict runtime type validation, prototype pollution defense, and payload byte-size bounds on all Capacitor 7 bridge notifications and method return values crossing from native runtimes (Swift/Kotlin) into the WebView JavaScript execution context. Prevents prototype pollution, arbitrary property injection, and memory exhaustion from compromised native bridge boundaries. 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 (Unchecked Native-to-JS Bridge Casts and Raw Event Stream Deserialization) 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