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

Capacitor 7 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail

Enforces strict origin validation, isolated context execution, and explicit Content Security Policy partitions on all native capability RPC invocations within Capacitor 7. Mitigates cross-context bridge hijacking and unauthorized native plugin execution by preventing wildcards in server hostnames, rejecting untrusted frame execution, and mandating cryptographic nonce validation for custom bridge protocols.

Prohibited Anti-Pattern: Wildcard Server Allowlisting and Unvalidated Native Bridge Invocations in WebViews

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail - Enforces strict origin validation, isolated context execution, and explicit Content Security Policy partitions on all native capability RPC invocations within Capacitor 7. Mitigates cross-context bridge hijacking and unauthorized native plugin execution by preventing wildcards in server hostnames, rejecting untrusted frame execution, and mandating cryptographic nonce validation for custom bridge protocols.
globs: capacitor.config.ts, android/app/src/main/res/xml/config.xml, ios/App/App/capacitor.config.json, src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-webview-bridge-origin-guardrail"
---

# Capacitor 7 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Wildcard Server Allowlisting and Unvalidated Native Bridge Invocations in WebViews

## System Constraints
You are a Principal Mobile Systems Architect enforcing the Capacitor 7 Isolated WebView Native Bridge Origin Guardrail. Your mandate is to prevent cross-context script injection, unauthenticated bridge invocation, and insecure webview hosting. Reject any configuration or implementation where native plugin bridges are exposed to untrusted external URLs, where Content Security Policies allow arbitrary script sources, or where RPC endpoints process commands lacking cryptographically verified origin headers.

## Strict Guidelines
- Engineers MUST ALWAYS configure `server.hostname` and `server.androidScheme` in `capacitor.config.ts` to strict, explicit internal origins (e.g., custom HTTPS domains or secure internal schemes) and NEVER use `localhost` or wildcards in production.
- Engineers MUST NOT configure `server.url` to point to external remote web servers unless `server.cleartext` is explicitly set to `false` and strict origin verification plugins intercept all bridge communications.
- Code MUST verify window hierarchy before executing native bridge calls by confirming `window.self === window.top` to prevent iframe context hijacking of native capabilities.
- Services invoking sensitive native bridge plugins (e.g., Biometrics, SecureStorage, Filesystem) MUST validate a runtime-generated cryptographic session nonce matching native state prior to dispatching RPC calls.
- HTML documents hosted within the WebView MUST declare a strict Content-Security-Policy meta tag restricting `default-src 'self'`, forbidding `unsafe-eval`, and strictly constraining `connect-src` and `script-src`.

## Bad vs Good Implementations
### Capacitor 7 Bridge Origin Configuration & RPC Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring remote URLs with wildcard navigation allowlists grants arbitrary web code direct access to the Capacitor native bridge. Calling the bridge without verifying window context (`window.self === window.top`) or origin integrity enables malicious iframes or XSS payloads to execute arbitrary native plugins.
```typescript
import { CapacitorConfig } from '@capacitor/cli';

// ANTI-PATTERN: Wildcard server URLs, cleartext allowed, and untrusted bridge dispatch
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'InsecureApp',
  webDir: 'dist',
  server: {
    url: 'https://staging.example.com', // Remote host with full native bridge exposure
    cleartext: true,
    allowNavigation: ['*'] // Wildcard allows untrusted origins to invoke native code
  }
};

export const callNativePlugin = async (pluginName: string, data: any) => {
  // Insecure: Executes directly from any frame or context without validation
  return (window as any).Capacitor.nativePromise(pluginName, 'execute', data);
};

export default config;
```

#### Production Standard (Correct)
> **Standard**: Restricts the Capacitor runtime to a specific internal HTTPS hostname and eliminates wildcard navigation. Enforces strict top-level execution checks (`window.self === window.top`), validates the origin identity, and appends cryptographic nonces to all native RPC payloads before invocation.
```typescript
import { CapacitorConfig } from '@capacitor/cli';

// PRODUCTION INVARIANT: Strict scheme isolation, deterministic origins, and context assertions
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'SecureApp',
  webDir: 'dist',
  server: {
    androidScheme: 'https',
    hostname: 'app.internal.secure',
    cleartext: false,
    allowNavigation: ['app.internal.secure']
  }
};

export class SecureBridgeGateway {
  private static readonly TRUSTED_ORIGIN = 'https://app.internal.secure';

  public static async invokeBridgeRPC<T, R>(
    pluginId: string,
    method: string,
    payload: T,
    bridgeNonce: string
  ): Promise<R> {
    // Enforce isolated context: bridge MUST NOT be callable from iframes
    if (window.self !== window.top) {
      throw new SecurityError('Native bridge execution blocked: Invocation from nested context.');
    }

    // Verify document origin matches expected isolated internal scheme
    if (window.location.origin !== this.TRUSTED_ORIGIN) {
      throw new SecurityError(`Native bridge execution blocked: Origin ${window.location.origin} is untrusted.`);
    }

    if (!bridgeNonce || typeof bridgeNonce !== 'string') {
      throw new SecurityError('Native bridge execution blocked: Cryptographic invocation nonce missing.');
    }

    const capacitorInstance = (window as unknown as { Capacitor?: { nativePromise: (p: string, m: string, d: unknown) => Promise<R> } }).Capacitor;
    if (!capacitorInstance?.nativePromise) {
      throw new Error('Capacitor bridge interface unavailable.');
    }

    return capacitorInstance.nativePromise(pluginId, method, {
      ...payload,
      __bridgeOriginSignature: window.location.origin,
      __bridgeNonce: bridgeNonce
    });
  }
}

export default config;
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail

Capacitor 7 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin validation, isolated context execution, and explicit Content Security Policy partitions on all native capability RPC invocations within Capacitor 7. Mitigates cross-context bridge hijacking and unauthorized native plugin execution by preventing wildcards in server hostnames, rejecting untrusted frame execution, and mandating cryptographic nonce validation for custom bridge protocols. 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: Wildcard Server Allowlisting and Unvalidated Native Bridge Invocations in WebViews 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 DriftWildcard Server Allowlisting and Unvalidated Native Bridge Invocations in WebViewsCritical
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 configure `server.hostname` and `server.androidScheme` in `capacitor.config.ts` to strict, explicit internal origins (e.g., custom HTTPS domains or secure internal schemes) and NEVER use `localhost` or wildcards in production.

Engineers MUST ALWAYS configure `server.hostname` and `server.androidScheme` in `capacitor.config.ts` to strict, explicit internal origins (e.g., custom HTTPS domains or secure internal schemes) and NEVER use `localhost` or wildcards in production.

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 configure `server.url` to point to external remote web servers unless `server.cleartext` is explicitly set to `false` and strict origin verification plugins intercept all bridge communications.

Engineers MUST NOT configure `server.url` to point to external remote web servers unless `server.cleartext` is explicitly set to `false` and strict origin verification plugins intercept all bridge communications.

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 window hierarchy before executing native bridge calls by confirming `window.self === window.top` to prevent iframe context hijacking of native capabilities.

Code MUST verify window hierarchy before executing native bridge calls by confirming `window.self === window.top` to prevent iframe context hijacking of 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 invoking sensitive native bridge plugins (e.g., Biometrics, SecureStorage, Filesystem) MUST validate a runtime-generated cryptographic session nonce matching native state prior to dispatching RPC calls.

Services invoking sensitive native bridge plugins (e.g., Biometrics, SecureStorage, Filesystem) MUST validate a runtime-generated cryptographic session nonce matching native state prior to dispatching RPC calls.

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

HTML documents hosted within the WebView MUST declare a strict Content-Security-Policy meta tag restricting `default-src 'self'`, forbidding `unsafe-eval`, and strictly constraining `connect-src` and `script-src`.

HTML documents hosted within the WebView MUST declare a strict Content-Security-Policy meta tag restricting `default-src 'self'`, forbidding `unsafe-eval`, and strictly constraining `connect-src` and `script-src`.

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 Isolated WebView Bridge Origin and Cryptographic RPC Guardrail critical for AI coding assistants?

Enforces strict origin validation, isolated context execution, and explicit Content Security Policy partitions on all native capability RPC invocations within Capacitor 7. Mitigates cross-context bridge hijacking and unauthorized native plugin execution by preventing wildcards in server hostnames, rejecting untrusted frame execution, and mandating cryptographic nonce validation for custom bridge protocols. 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 (Wildcard Server Allowlisting and Unvalidated Native Bridge Invocations in WebViews) 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