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

Capacitor 7 Custom Scheme and Native Bridge Origin Pinning Isolation

Mandates deterministic origin validation and custom scheme isolation within Capacitor 7 architectures. Restricts WebView-to-native IPC bridge invocations strictly to internally pinned origin namespaces, neutralizing cross-context script execution, bridge hijacking, and untrusted iframe privilege escalation.

Prohibited Anti-Pattern: Permissive WebView Navigation and Unpinned Origin Bridge Exposure

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Custom Scheme and Native Bridge Origin Pinning Isolation - Mandates deterministic origin validation and custom scheme isolation within Capacitor 7 architectures. Restricts WebView-to-native IPC bridge invocations strictly to internally pinned origin namespaces, neutralizing cross-context script execution, bridge hijacking, and untrusted iframe privilege escalation.
globs: capacitor.config.ts, capacitor.config.json, src/**/*.{ts,tsx}, android/app/src/main/res/xml/config.xml, ios/App/App/capacitor.config.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-custom-scheme-bridge-isolation-standard"
---

# Capacitor 7 Custom Scheme and Native Bridge Origin Pinning Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Permissive WebView Navigation and Unpinned Origin Bridge Exposure

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Custom Scheme Bridge Isolation Standard. Native WebView bridges grant web code direct access to device-level APIs (Filesystem, Biometrics, Keystore). You must strictly ensure that native bridge access is isolated to immutable, verified origin schemes (e.g., `https` with pinned internal hostnames or custom app schemes), and that wildcard `allowNavigation` or multi-tenant remote URL loading never exposes native plugins to malicious injection.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly define `server.androidScheme` (e.g., `https`) and an authoritative internal `server.hostname` (e.g., `app.internal`) in `capacitor.config.ts` rather than defaulting to insecure generic schemes.
- Engineers MUST NOT permit wildcard patterns (`*`, `*://*/*`, or external third-party origins) inside `server.allowNavigation` under any production configuration.
- Code SHOULD sanitize runtime bridge calls by verifying `window.isSecureContext` and comparing `window.location.origin` against the application's compiled internal origin manifest before invoking plugins.
- Services MUST route external authentication and remote web content through isolated browser sessions (`InAppBrowser` or `Browser.open` with ephemeral contexts) rather than navigating the primary Capacitor root WebView.
- Components NEVER execute native plugin methods from within dynamic `iframe` embeddings or after unauthorized cross-origin navigation redirects.

## Bad vs Good Implementations
### Capacitor 7 Secure Bridge Origin Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring `allowNavigation: ['*']` exposes the native Capacitor bridge to any external URL navigated to or framed within the WebView. If an external URL is loaded or injected, scripts running on that domain gain full privilege to call native Capacitor APIs directly.
```typescript
import type { CapacitorConfig } from '@capacitor/cli';

// VULNERABLE: Wildcard allowNavigation exposes native plugins
// to arbitrary external scripts if the WebView navigates or embeds remotes.
const config: CapacitorConfig = {
  appId: 'com.enterprise.app',
  appName: 'EnterpriseApp',
  webDir: 'dist',
  server: {
    // Insecure: Allows native bridge exposure across arbitrary web domains
    allowNavigation: ['*'],
    cleartext: true,
  },
};

export default config;
```

#### Production Standard (Correct)
> **Standard**: Pinning `androidScheme: 'https'` with an internal host `secure-app.internal` ensures standard web security policies (CORS, Secure Cookies) apply while restricting native bridge access strictly to code bundled and served from the immutable internal origin.
```typescript
import type { CapacitorConfig } from '@capacitor/cli';

const APP_HOSTNAME = 'secure-app.internal';

const config: CapacitorConfig = {
  appId: 'com.enterprise.app',
  appName: 'EnterpriseApp',
  webDir: 'dist',
  server: {
    // PINNED: Custom isolated scheme and internal origin namespace
    androidScheme: 'https',
    hostname: APP_HOSTNAME,
    iosScheme: 'capacitor',
    // Bridge restricted exclusively to the internal app authority
    allowNavigation: [
      APP_HOSTNAME,
    ],
    cleartext: false,
  },
  plugins: {
    CapacitorCookies: {
      enabled: true,
    },
  },
};

export default config;
```

### Runtime Bridge Invariant and Origin Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing native plugins without verifying execution context allows cross-origin scripts or hijacked frames to invoke sensitive hardware APIs if bridge isolation rules are bypassed.
```typescript
import { Camera, CameraResultType } from '@capacitor/camera';

// VULNERABLE: Invokes native subsystem without runtime origin verification
export async function captureUserDocument(): Promise<string | undefined> {
  const photo = await Camera.getPhoto({
    quality: 90,
    allowEditing: false,
    resultType: CameraResultType.Uri,
  });
  return photo.webPath;
}
```

#### Production Standard (Correct)
> **Standard**: The runtime invariant asserts that the executing frame is top-level (`window.self === window.top`), runs within a cryptographically secure context, and strictly matches the whitelisted application origin before dispatching calls to native device drivers.
```typescript
import { Camera, CameraResultType } from '@capacitor/camera';
import { Capacitor } from '@capacitor/core';

const TRUSTED_ORIGIN = 'https://secure-app.internal';

function assertBridgeOrigin(): void {
  if (!Capacitor.isNativePlatform()) return;
  
  const isTrustedOrigin = window.location.origin === TRUSTED_ORIGIN ||
    window.location.origin === 'capacitor://localhost';

  if (!window.isSecureContext || !isTrustedOrigin || window.self !== window.top) {
    throw new SecurityError(
      `IPC Bridge violation: Native invocation blocked from untrusted origin [${window.location.origin}]`
    );
  }
}

export async function captureUserDocument(): Promise<string | undefined> {
  assertBridgeOrigin();
  
  const photo = await Camera.getPhoto({
    quality: 90,
    allowEditing: false,
    resultType: CameraResultType.Uri,
  });
  return photo.webPath;
}
```

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 Custom Scheme and Native Bridge Origin Pinning Isolation

Capacitor 7 Custom Scheme and Native Bridge Origin Pinning Isolation defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic origin validation and custom scheme isolation within Capacitor 7 architectures. Restricts WebView-to-native IPC bridge invocations strictly to internally pinned origin namespaces, neutralizing cross-context script execution, bridge hijacking, and untrusted iframe privilege escalation. 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 WebView Navigation and Unpinned Origin Bridge Exposure 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 WebView Navigation and Unpinned Origin Bridge ExposureCritical
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 explicitly define `server.androidScheme` (e.g., `https`) and an authoritative internal `server.hostname` (e.g., `app.internal`) in `capacitor.config.ts` rather than defaulting to insecure generic schemes.

Engineers MUST ALWAYS explicitly define `server.androidScheme` (e.g., `https`) and an authoritative internal `server.hostname` (e.g., `app.internal`) in `capacitor.config.ts` rather than defaulting to insecure generic schemes.

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 wildcard patterns (`*`, `*

Engineers MUST NOT permit wildcard patterns (`*`, `*://*/*`, or external third-party origins) inside `server.allowNavigation` under any production configuration.

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 SHOULD sanitize runtime bridge calls by verifying `window.isSecureContext` and comparing `window.location.origin` against the application's compiled internal origin manifest before invoking plugins.

Code SHOULD sanitize runtime bridge calls by verifying `window.isSecureContext` and comparing `window.location.origin` against the application's compiled internal origin manifest before invoking plugins.

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 route external authentication and remote web content through isolated browser sessions (`InAppBrowser` or `Browser.open` with ephemeral contexts) rather than navigating the primary Capacitor root WebView.

Services MUST route external authentication and remote web content through isolated browser sessions (`InAppBrowser` or `Browser.open` with ephemeral contexts) rather than navigating the primary Capacitor root WebView.

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 native plugin methods from within dynamic `iframe` embeddings or after unauthorized cross-origin navigation redirects.

Components NEVER execute native plugin methods from within dynamic `iframe` embeddings or after unauthorized cross-origin navigation redirects.

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 Custom Scheme and Native Bridge Origin Pinning Isolation critical for AI coding assistants?

Mandates deterministic origin validation and custom scheme isolation within Capacitor 7 architectures. Restricts WebView-to-native IPC bridge invocations strictly to internally pinned origin namespaces, neutralizing cross-context script execution, bridge hijacking, and untrusted iframe privilege escalation. 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 WebView Navigation and Unpinned Origin Bridge Exposure) 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