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

Capacitor 7 Native Bridge Ephemeral Token Exchange Protocol Guardrail

Enforces a cryptographically bound ephemeral token handshake between Capacitor 7 WebView runtimes and native platform plugins. Prevents unauthorized cross-origin execution, bridge hijacking from malicious third-party frames, and IPC token replay attacks by binding single-use dynamic nonces to every native dispatch.

Prohibited Anti-Pattern: Unauthenticated Global Bridge Invocation and Static Secret Replay in Native IPC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Ephemeral Token Exchange Protocol Guardrail - Enforces a cryptographically bound ephemeral token handshake between Capacitor 7 WebView runtimes and native platform plugins. Prevents unauthorized cross-origin execution, bridge hijacking from malicious third-party frames, and IPC token replay attacks by binding single-use dynamic nonces to every native dispatch.
globs: src/**/plugins/**/*.{ts,tsx}, src/**/bridge/**/*.{ts,tsx}, src/**/services/native/**/*.{ts,tsx}, android/app/src/main/java/**/plugins/**/*.java, ios/App/App/Plugins/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-ephemeral-token-protocol"
---

# Capacitor 7 Native Bridge Ephemeral Token Exchange Protocol Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unauthenticated Global Bridge Invocation and Static Secret Replay in Native IPC

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Native Bridge Ephemeral Token Exchange Protocol. You must reject any direct, unauthenticated invocations of native plugin bridges, exposure of persistent keys in web-accessible scopes, or stateless IPC execution without single-use cryptographically bound nonces. Enforce origin verification, dynamic nonce rotation, and atomic token invalidation across the bridge boundary.

## Strict Guidelines
- Engineers MUST ALWAYS exchange an ephemeral, single-use token signed with a session-derived secret before dispatching sensitive native bridge operations.
- Engineers MUST NOT invoke native plugin methods with static pre-shared keys or persistent authentication tokens stored in localStorage, document cookies, or global window objects.
- Bridge middleware MUST enforce a strict origin check ensuring dispatches originate exclusively from the declared Capacitor host scheme (e.g., 'capacitor://localhost' on iOS or 'http://localhost' on Android).
- Native plugins MUST atomically consume and invalidate each transaction nonce upon first receipt to eliminate IPC replay attacks.
- Services MUST reject IPC payloads containing timestamps older than a 5000-millisecond skew tolerance relative to the native monotonic clock.
- Components NEVER trigger direct calls via raw `Capacitor.toNative()` or unshielded `registerPlugin` handles without routing through the Ephemeral Token Bridge Gateway.

## Bad vs Good Implementations
### Vulnerable Direct Native Bridge Call vs. Ephemeral Token Handshake Protocol

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct plugin registration allows any script executing within the WebView context to trigger sensitive native APIs without proof of session freshness, execution context integrity, or token validity. It is completely susceptible to cross-site script invocation and bridge replay.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureVaultPlugin {
  exportKeys(options: { masterKeyId: string }): Promise<{ privateKey: string }>;
}

// ANTI-PATTERN: Direct exposure of native interface without origin or replay protection.
// Malicious scripts or hijacked iframes can freely invoke this method.
const SecureVault = registerPlugin<SecureVaultPlugin>('SecureVault');

export async function retrieveKey(keyId: string): Promise<string> {
  const result = await SecureVault.exportKeys({ masterKeyId: keyId });
  return result.privateKey;
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the native call in a challenge-response handshake with a dynamic nonce, monotonic timestamp check, and HMAC signature generated via SubtleCrypto. The native layer consumes the challenge exactly once, rejecting replayed, expired, or origin-mismatched requests.
```typescript
import { registerPlugin } from '@capacitor/core';

interface AuthenticatedPayload<T> {
  payload: T;
  token: string;
  nonce: string;
  timestamp: number;
}

interface SecureVaultPlugin {
  requestChallenge(): Promise<{ challenge: string }>;
  exportKeys(signedPayload: AuthenticatedPayload<{ masterKeyId: string }>): Promise<{ privateKey: string }>;
}

const RawVaultPlugin = registerPlugin<SecureVaultPlugin>('SecureVault');

export class EphemeralBridgeGateway {
  private static async generateHmac(message: string, secret: CryptoKey): Promise<string> {
    const encoder = new TextEncoder();
    const signature = await window.crypto.subtle.sign('HMAC', secret, encoder.encode(message));
    return Array.from(new Uint8Array(signature)).map(b => b.toString(16).padStart(2, '0')).join('');
  }

  public static async executeSecureDispatch<TInput, TOutput>(
    keyId: string,
    sessionSecret: CryptoKey,
    action: (payload: AuthenticatedPayload<{ masterKeyId: string }>) => Promise<TOutput>
  ): Promise<TOutput> {
    // 1. Acquire dynamic challenge from native side
    const { challenge } = await RawVaultPlugin.requestChallenge();
    
    // 2. Synthesize cryptographically strong nonce & timestamp
    const nonce = window.crypto.randomUUID();
    const timestamp = Date.now();
    const message = `${challenge}:${nonce}:${timestamp}:${keyId}`;
    
    // 3. Compute ephemeral authentication token bound to this specific execution
    const token = await this.generateHmac(message, sessionSecret);

    // 4. Dispatch with atomic single-use credentials
    return await action({
      payload: { masterKeyId: keyId },
      token,
      nonce,
      timestamp
    });
  }
}

export async function retrieveKey(keyId: string, sessionSecret: CryptoKey): Promise<string> {
  const result = await EphemeralBridgeGateway.executeSecureDispatch(
    keyId,
    sessionSecret,
    (signedPayload) => RawVaultPlugin.exportKeys(signedPayload)
  );
  return (result as { privateKey: string }).privateKey;
}
```

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 Ephemeral Token Exchange Protocol Guardrail

Capacitor 7 Native Bridge Ephemeral Token Exchange Protocol Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces a cryptographically bound ephemeral token handshake between Capacitor 7 WebView runtimes and native platform plugins. Prevents unauthorized cross-origin execution, bridge hijacking from malicious third-party frames, and IPC token replay attacks by binding single-use dynamic nonces to every native dispatch. 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: Unauthenticated Global Bridge Invocation and Static Secret Replay in Native IPC 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 DriftUnauthenticated Global Bridge Invocation and Static Secret Replay in Native IPCCritical
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 exchange an ephemeral, single-use token signed with a session-derived secret before dispatching sensitive native bridge operations.

Engineers MUST ALWAYS exchange an ephemeral, single-use token signed with a session-derived secret before dispatching sensitive native bridge operations.

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 invoke native plugin methods with static pre-shared keys or persistent authentication tokens stored in localStorage, document cookies, or global window objects.

Engineers MUST NOT invoke native plugin methods with static pre-shared keys or persistent authentication tokens stored in localStorage, document cookies, or global window objects.

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

Bridge middleware MUST enforce a strict origin check ensuring dispatches originate exclusively from the declared Capacitor host scheme (e.g., 'capacitor

Bridge middleware MUST enforce a strict origin check ensuring dispatches originate exclusively from the declared Capacitor host scheme (e.g., 'capacitor://localhost' on iOS or 'http://localhost' on Android).

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 plugins MUST atomically consume and invalidate each transaction nonce upon first receipt to eliminate IPC replay attacks.

Native plugins MUST atomically consume and invalidate each transaction nonce upon first receipt to eliminate IPC replay attacks.

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

Services MUST reject IPC payloads containing timestamps older than a 5000-millisecond skew tolerance relative to the native monotonic clock.

Services MUST reject IPC payloads containing timestamps older than a 5000-millisecond skew tolerance relative to the native monotonic clock.

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

Components NEVER trigger direct calls via raw `Capacitor.toNative()` or unshielded `registerPlugin` handles without routing through the Ephemeral Token Bridge Gateway.

Components NEVER trigger direct calls via raw `Capacitor.toNative()` or unshielded `registerPlugin` handles without routing through the Ephemeral Token Bridge Gateway.

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 Ephemeral Token Exchange Protocol Guardrail critical for AI coding assistants?

Enforces a cryptographically bound ephemeral token handshake between Capacitor 7 WebView runtimes and native platform plugins. Prevents unauthorized cross-origin execution, bridge hijacking from malicious third-party frames, and IPC token replay attacks by binding single-use dynamic nonces to every native dispatch. 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 (Unauthenticated Global Bridge Invocation and Static Secret Replay in Native IPC) 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