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

Capacitor 7 Native Bridge Origin Attestation and Secure Scheme Hardening

Enforces strict origin validation, explicit custom schemes, and restrictive Content Security Policies across the Capacitor 7 JavaScript-to-Native bridge. Prevents untrusted remote contexts and injected scripts from accessing high-privilege native device plugins via window.Capacitor.toNative. Mandates hardened server configuration and verified navigation boundaries to eliminate privilege escalation vectors.

Prohibited Anti-Pattern: Wildcard Navigation Whitelisting and Insecure Scheme Binding Exposing Native APIs to Untrusted Origins

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Origin Attestation and Secure Scheme Hardening - Enforces strict origin validation, explicit custom schemes, and restrictive Content Security Policies across the Capacitor 7 JavaScript-to-Native bridge. Prevents untrusted remote contexts and injected scripts from accessing high-privilege native device plugins via window.Capacitor.toNative. Mandates hardened server configuration and verified navigation boundaries to eliminate privilege escalation vectors.
globs: capacitor.config.ts, capacitor.config.json, index.html, src/index.html, src/main.ts, src/App.tsx
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-bridge-integrity-origin-attestation"
---

# Capacitor 7 Native Bridge Origin Attestation and Secure Scheme Hardening

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Wildcard Navigation Whitelisting and Insecure Scheme Binding Exposing Native APIs to Untrusted Origins

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Native Bridge Integrity and Origin Attestation. Mandate strict WebView configuration, explicit androidScheme/iosScheme declarations, zero-trust navigation boundaries, and bulletproof Content Security Policy (CSP) configurations to guarantee that arbitrary web content cannot invoke native device capabilities.

## Strict Guidelines
- Engineers MUST ALWAYS configure `androidScheme: 'https'` and define an explicit, attested local `hostname` (e.g., `'localhost'`) in `capacitor.config.ts`.
- Engineers MUST NOT configure wildcard entries (e.g., `'*'`, `'http://*'`, `'https://*'`) in `server.allowNavigation`.
- Engineers MUST declare a strict `Content-Security-Policy` meta tag in `index.html` restricting `script-src` to self and trusted cryptographic hashes, disallowing `unsafe-eval` in production.
- Services invoking Capacitor bridge methods MUST verify that execution context matches the expected native application origin before triggering sensitive hardware APIs (Biometrics, Secure Storage, Camera).
- Components NEVER load external web content directly into the primary application WebView; external URLs MUST be delegated to the InAppBrowser or system default browser with bridge isolation.
- Code SHOULD leverage Capacitor 7 plugin permission checks alongside runtime origin verification to reject cross-origin messaging attacks via `window.postMessage`.

## Bad vs Good Implementations
### Capacitor 7 Configuration Bridge Hardening

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring allowNavigation with wildcards combined with a remote server URL exposes window.Capacitor directly to third-party web content, enabling full native privilege escalation via simple XSS or malicious redirects.
```typescript
import type { CapacitorConfig } from '@capacitor/cli';

// INSECURE: Wildcard navigation and unpinned remote schemes grant arbitrary domains bridge access
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'VulnerableApp',
  webDir: 'dist',
  server: {
    url: 'https://staging.example.com', // Dynamic remote bundle allows MitM / takeover
    cleartext: true,
    allowNavigation: ['*'] // Flaw: Any iframe or redirected site can execute native plugins
  }
};

export default config;
```

#### Production Standard (Correct)
> **Standard**: Standardizes the scheme to https on Android and capacitor on iOS with an explicit localhost hostname, strictly scoping bridge injection to the local webDir and explicitly pinned OAuth domains.
```typescript
import type { CapacitorConfig } from '@capacitor/cli';

// SECURE: Enforces origin attestation, standard secure schemes, and strict navigation bounds
const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'HardenedApp',
  webDir: 'dist',
  server: {
    androidScheme: 'https',
    iosScheme: 'capacitor',
    hostname: 'localhost',
    cleartext: false,
    // Only allow verified authentication providers; external links must use InAppBrowser
    allowNavigation: [
      'auth.example.com'
    ]
  },
  plugins: {
    CapacitorCookies: {
      enabled: true
    }
  }
};

export default config;
```

### Runtime Native Bridge Origin Attestation & CSP Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking sensitive native plugins without verifying window.isSecureContext or attesting that the executing window matches the trusted local scheme allows embedded contexts or hijacked frames to execute native routines.
```typescript
import { Capacitor } from '@capacitor/core';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

// INSECURE: Directly triggers sensitive native API without verifying origin or execution domain
export async function authenticateUser(): Promise<void> {
  // Can be triggered by malicious postMessage or unauthorized framed contexts
  await BiometricAuth.authenticate({
    reason: 'Confirm transaction'
  });
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees that the native bridge call originates from top-level execution within an attested local scheme and throws immediately if executed within a framing or unverified external context.
```typescript
import { Capacitor } from '@capacitor/core';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

const TRUSTED_ORIGINS = new Set([
  'https://localhost',
  'capacitor://localhost'
]);

function assertBridgeOrigin(): void {
  if (!window.isSecureContext) {
    throw new Error('Bridge execution denied: Insecure context');
  }
  
  if (window.self !== window.top) {
    throw new Error('Bridge execution denied: Frame hijacking detected');
  }

  const currentOrigin = window.location.origin;
  if (Capacitor.isNativePlatform() && !TRUSTED_ORIGINS.has(currentOrigin)) {
    throw new Error(`Bridge execution denied: Untrusted origin ${currentOrigin}`);
  }
}

// SECURE: Enforces origin verification and boundary checks before bridging to native
export async function authenticateUser(): Promise<void> {
  assertBridgeOrigin();
  
  await BiometricAuth.authenticate({
    reason: 'Confirm transaction'
  });
}
```

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 Bridge Origin Attestation and Secure Scheme Hardening

Capacitor 7 Native Bridge Origin Attestation and Secure Scheme Hardening defines an industrial-grade behavioral standard for mobile engineering. Enforces strict origin validation, explicit custom schemes, and restrictive Content Security Policies across the Capacitor 7 JavaScript-to-Native bridge. Prevents untrusted remote contexts and injected scripts from accessing high-privilege native device plugins via window.Capacitor.toNative. Mandates hardened server configuration and verified navigation boundaries to eliminate privilege escalation vectors. 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 Navigation Whitelisting and Insecure Scheme Binding Exposing Native APIs to Untrusted 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 DriftWildcard Navigation Whitelisting and Insecure Scheme Binding Exposing Native APIs to Untrusted 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 configure `androidScheme

Engineers MUST ALWAYS configure `androidScheme: 'https'` and define an explicit, attested local `hostname` (e.g., `'localhost'`) in `capacitor.config.ts`.

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 wildcard entries (e.g., `'*'`, `'http

Engineers MUST NOT configure wildcard entries (e.g., `'*'`, `'http://*'`, `'https://*'`) in `server.allowNavigation`.

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

Engineers MUST declare a strict `Content-Security-Policy` meta tag in `index.html` restricting `script-src` to self and trusted cryptographic hashes, disallowing `unsafe-eval` in production.

Engineers MUST declare a strict `Content-Security-Policy` meta tag in `index.html` restricting `script-src` to self and trusted cryptographic hashes, disallowing `unsafe-eval` 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.
4

Services invoking Capacitor bridge methods MUST verify that execution context matches the expected native application origin before triggering sensitive hardware APIs (Biometrics, Secure Storage, Camera).

Services invoking Capacitor bridge methods MUST verify that execution context matches the expected native application origin before triggering sensitive hardware APIs (Biometrics, Secure Storage, Camera).

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 load external web content directly into the primary application WebView

Components NEVER load external web content directly into the primary application WebView; external URLs MUST be delegated to the InAppBrowser or system default browser with bridge isolation.

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.
6

Code SHOULD leverage Capacitor 7 plugin permission checks alongside runtime origin verification to reject cross-origin messaging attacks via `window.postMessage`.

Code SHOULD leverage Capacitor 7 plugin permission checks alongside runtime origin verification to reject cross-origin messaging attacks via `window.postMessage`.

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 Attestation and Secure Scheme Hardening critical for AI coding assistants?

Enforces strict origin validation, explicit custom schemes, and restrictive Content Security Policies across the Capacitor 7 JavaScript-to-Native bridge. Prevents untrusted remote contexts and injected scripts from accessing high-privilege native device plugins via window.Capacitor.toNative. Mandates hardened server configuration and verified navigation boundaries to eliminate privilege escalation vectors. 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 Navigation Whitelisting and Insecure Scheme Binding Exposing Native APIs to Untrusted 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