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

Capacitor 7 Native Bridge Origin Isolation and Scheme Invariant Guardrail

Capacitor 7 native bridge invocations must be cryptographically bound to immutable custom schemes and verified origin domains. Failure to enforce origin checks and scheme invariants exposes native host plugins (Keychain, Keystore, Camera, Filesystem) to untrusted third-party script injection via DOM XSS, MITM webviews, or arbitrary remote navigations.

Prohibited Anti-Pattern: Permissive Remote Navigation with Unvalidated Native Bridge Invocations Across Arbitrary Origins

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Origin Isolation and Scheme Invariant Guardrail - Capacitor 7 native bridge invocations must be cryptographically bound to immutable custom schemes and verified origin domains. Failure to enforce origin checks and scheme invariants exposes native host plugins (Keychain, Keystore, Camera, Filesystem) to untrusted third-party script injection via DOM XSS, MITM webviews, or arbitrary remote navigations.
globs: capacitor.config.ts, android/app/src/main/**/*.kt, android/app/src/main/**/*.java, ios/App/App/**/*.swift, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-origin-isolation-scheme-invariant"
---

# Capacitor 7 Native Bridge Origin Isolation and Scheme Invariant Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Permissive Remote Navigation with Unvalidated Native Bridge Invocations Across Arbitrary Origins

## System Constraints
You are a Principal Mobile Systems Architect enforcing Capacitor 7 security boundaries. Mandate native bridge origin isolation and scheme invariants across all webview-to-native communication. Never allow wildcard navigations or unverified IPC message origins.

## Strict Guidelines
- Engineers MUST ALWAYS restrict `server.allowNavigation` in `capacitor.config.ts` to strictly bounded, explicit production domains and reject wildcards (`*`).
- Engineers MUST NOT permit arbitrary HTTP/HTTPS endpoints or remote origins to access the Capacitor native bridge runtime.
- Custom native plugins MUST verify the caller origin via the bridge's webview URL before executing privileged native operations (biometrics, secure storage, file I/O).
- Native configurations MUST enforce explicit secure scheme pairs (e.g., `androidScheme: 'https'` with custom hostname, or strictly validated custom app schemes) to guarantee Origin header immutability.
- Components NEVER execute raw `window.Capacitor.toNative()` or listen to unverified `window.postMessage` channels bypassing Capacitor's internal plugin registry.

## Bad vs Good Implementations
### Capacitor 7 Server Configuration and Scheme Hardening

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring allowNavigation to '*' and using cleartext HTTP enables any loaded remote resource or injected iframe to access window.Capacitor and invoke sensitive native APIs via the bridge.
```typescript
import { CapacitorConfig } from '@capacitor/cli';

// VULNERABLE: Wildcard navigation and unconstrained origins expose bridge
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'ExampleApp',
  webDir: 'dist',
  server: {
    // Anti-pattern: Wildcards allow malicious injected frames to call native bridge
    allowNavigation: ['*'],
    cleartext: true,
    androidScheme: 'http'
  }
};

export default config;
```

#### Production Standard (Correct)
> **Standard**: Restricts the webview runtime to a sealed, internal HTTPS origin (localapp.internal) and limits external navigations to explicitly enumerated production endpoints with cleartext disabled.
```typescript
import { CapacitorConfig } from '@capacitor/cli';

// HARDENED: Strict origin confinement and secure scheme enforcement
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'ExampleApp',
  webDir: 'dist',
  server: {
    // Invariant: Navigation is strictly restricted to trusted app origins
    androidScheme: 'https',
    hostname: 'localapp.internal',
    allowNavigation: [
      'https://api.example.com'
    ],
    cleartext: false
  }
};

export default config;
```

### Custom Plugin Origin Verification Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin does not verify caller provenance; any script running in the webview (including XSS payloads or third-party webview content) can invoke retrieveMasterKey.
```typescript
import { Plugin, PluginCall } from '@capacitor/core';

// VULNERABLE: Plugin executes without checking invoking origin
export class SecureVaultPlugin {
  async retrieveMasterKey(call: PluginCall): Promise<void> {
    // Anti-pattern: Blindly trusts any caller from the webview context
    const secret = await fetchSecureKeyFromHardware();
    call.resolve({ secret });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Validates the execution origin against the immutable trusted internal scheme before dispatching sensitive hardware-backed operations, preventing malicious web contexts from accessing the native boundary.
```typescript
import { Plugin, PluginCall } from '@capacitor/core';

const TRUSTED_ORIGIN = 'https://localapp.internal';

export class SecureVaultPlugin {
  async retrieveMasterKey(call: PluginCall): Promise<void> {
    // Invariant: Validate that call originated from the trusted scheme origin
    const callerUrl = (call as unknown as { _origin?: string })._origin || window.location.origin;
    
    if (callerUrl !== TRUSTED_ORIGIN) {
      call.reject('SecurityException: Bridge call rejected from unauthorized origin: ' + callerUrl);
      return;
    }

    const secret = await fetchSecureKeyFromHardware();
    call.resolve({ secret });
  }
}
```

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 Origin Isolation and Scheme Invariant Guardrail

Capacitor 7 Native Bridge Origin Isolation and Scheme Invariant Guardrail defines an industrial-grade behavioral standard for mobile engineering. Capacitor 7 native bridge invocations must be cryptographically bound to immutable custom schemes and verified origin domains. Failure to enforce origin checks and scheme invariants exposes native host plugins (Keychain, Keystore, Camera, Filesystem) to untrusted third-party script injection via DOM XSS, MITM webviews, or arbitrary remote navigations. 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: Permissive Remote Navigation with Unvalidated Native Bridge Invocations Across Arbitrary Origins 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 DriftPermissive Remote Navigation with Unvalidated Native Bridge Invocations Across Arbitrary OriginsCritical
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 `server.allowNavigation` in `capacitor.config.ts` to strictly bounded, explicit production domains and reject wildcards (`*`).

Engineers MUST ALWAYS restrict `server.allowNavigation` in `capacitor.config.ts` to strictly bounded, explicit production domains and reject wildcards (`*`).

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 permit arbitrary HTTP/HTTPS endpoints or remote origins to access the Capacitor native bridge runtime.

Engineers MUST NOT permit arbitrary HTTP/HTTPS endpoints or remote origins to access the Capacitor native bridge runtime.

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

Custom native plugins MUST verify the caller origin via the bridge's webview URL before executing privileged native operations (biometrics, secure storage, file I/O).

Custom native plugins MUST verify the caller origin via the bridge's webview URL before executing privileged native operations (biometrics, secure storage, file I/O).

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

Native configurations MUST enforce explicit secure scheme pairs (e.g., `androidScheme

Native configurations MUST enforce explicit secure scheme pairs (e.g., `androidScheme: 'https'` with custom hostname, or strictly validated custom app schemes) to guarantee Origin header immutability.

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 raw `window.Capacitor.toNative()` or listen to unverified `window.postMessage` channels bypassing Capacitor's internal plugin registry.

Components NEVER execute raw `window.Capacitor.toNative()` or listen to unverified `window.postMessage` channels bypassing Capacitor's internal plugin registry.

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 Origin Isolation and Scheme Invariant Guardrail critical for AI coding assistants?

Capacitor 7 native bridge invocations must be cryptographically bound to immutable custom schemes and verified origin domains. Failure to enforce origin checks and scheme invariants exposes native host plugins (Keychain, Keystore, Camera, Filesystem) to untrusted third-party script injection via DOM XSS, MITM webviews, or arbitrary remote navigations. 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 (Permissive Remote Navigation with Unvalidated Native Bridge Invocations Across Arbitrary Origins) 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