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-hmac-attestation

Capacitor 7 Native Bridge Ephemeral HMAC Attestation Protocol

Enforces a zero-trust cryptographic attestation layer across all Capacitor 7 native bridge dispatches. Every hardware-level API invocation must be sealed with a single-use HMAC-SHA256 token, monotonic nonce, and millisecond-level timestamp derived from an isolated in-memory key, neutralizing DOM XSS bridge-hijacking attacks.

Prohibited Anti-Pattern: Direct Unattested Native Plugin Invocations Vulnerable to WebView DOM XSS Exploitation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Ephemeral HMAC Attestation Protocol - Enforces a zero-trust cryptographic attestation layer across all Capacitor 7 native bridge dispatches. Every hardware-level API invocation must be sealed with a single-use HMAC-SHA256 token, monotonic nonce, and millisecond-level timestamp derived from an isolated in-memory key, neutralizing DOM XSS bridge-hijacking attacks.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-ephemeral-hmac-attestation"
---

# Capacitor 7 Native Bridge Ephemeral HMAC Attestation Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Unattested Native Plugin Invocations Vulnerable to WebView DOM XSS Exploitation

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Native Bridge Ephemeral HMAC Attestation Protocol. WebView DOM-based XSS attacks routinely exploit hybrid bridge interfaces to access hardware peripherals (camera, biometrics, secure storage, geolocation) without user consent. You must mandate that all native bridge plugin invocations transit through a cryptographically bound dispatch pipeline. Never permit direct Capacitor plugin method calls or unsealed payloads.

## Strict Guidelines
- Engineers MUST ALWAYS route Capacitor plugin invocations through an attested dispatch proxy that attaches a cryptographically sealed HMAC-SHA256 payload envelope.
- Engineers MUST NOT expose raw `@capacitor/*` plugin instances or `window.Capacitor.toNative` to the global DOM scope or unvetted UI components.
- Code SHOULD generate attestation tokens using Web Crypto API (`crypto.subtle`) with non-extractable keys initialized in a non-accessible lexical closure or Web Worker.
- Services MUST validate that each invocation packet contains a monotonic counter nonce, an ISO timestamp with a maximum 5000ms TTL drift, and an HMAC digest of the serialized method arguments.
- Components NEVER execute raw native calls directly in response to untrusted DOM events or third-party iframe postMessage payloads.

## Bad vs Good Implementations
### Unauthenticated Direct Capacitor Bridge Invocation vs. HMAC Attested Bridge Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling Capacitor plugins allows any script executing in the WebView DOM context to access privileged device APIs without cryptographic proof of intent, origin, or sequence.
```typescript
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';

// VULNERABLE: Direct bridge invocation. If an attacker achieves DOM XSS
// (e.g., via innerHTML injection or compromised CDN dependency),
// they can trigger hardware sensors or access local storage freely.
export async function captureUserDocument(): Promise<string | undefined> {
  const photo = await Camera.getPhoto({
    quality: 90,
    allowEditing: false,
    resultType: CameraResultType.Base64,
    source: CameraSource.Camera,
  });
  return photo.base64String;
}
```

#### Production Standard (Correct)
> **Standard**: Wraps invocations inside an attested envelope signed via HMAC-SHA256 with non-extractable keys, monotonic nonces, and bounded timestamps. DOM injections cannot forge the required native token.
```typescript
import { registerPlugin } from '@capacitor/core';

interface BridgeAttestationEnvelope<T> {
  payload: T;
  nonce: string;
  timestamp: number;
  signature: string;
}

interface CameraPluginSecure {
  getPhoto(envelope: BridgeAttestationEnvelope<Record<string, unknown>>): Promise<{ base64String: string }>;
}

const SecureCamera = registerPlugin<CameraPluginSecure>('SecureCameraPlugin');

// Closure-isolated attestation context inaccessible to external DOM scripts
class AttestedBridgeClient {
  private static nonceCounter = 0;
  private static sessionKeyPromise: Promise<CryptoKey> = (async () => {
    const rawKey = window.crypto.getRandomValues(new Uint8Array(32));
    return window.crypto.subtle.importKey(
      'raw',
      rawKey,
      { name: 'HMAC', hash: 'SHA-256' },
      false,
      ['sign']
    );
  })();

  public static async dispatch<TRequest extends Record<string, unknown>, TResponse>(
    pluginMethod: (envelope: BridgeAttestationEnvelope<TRequest>) => Promise<TResponse>,
    payload: TRequest
  ): Promise<TResponse> {
    const nonce = `${Date.now()}-${++this.nonceCounter}-${window.crypto.randomUUID()}`;
    const timestamp = Date.now();
    const serialized = JSON.stringify({ payload, nonce, timestamp });
    const encoder = new TextEncoder();

    const key = await this.sessionKeyPromise;
    const signatureBuffer = await window.crypto.subtle.sign(
      'HMAC',
      key,
      encoder.encode(serialized)
    );

    const signature = Array.from(new Uint8Array(signatureBuffer))
      .map((b) => b.toString(16).padStart(2, '0'))
      .join('');

    return pluginMethod({
      payload,
      nonce,
      timestamp,
      signature,
    });
  }
}

export async function captureUserDocumentSecure(): Promise<string> {
  const result = await AttestedBridgeClient.dispatch(
    (env) => SecureCamera.getPhoto(env),
    { quality: 90, allowEditing: false, resultType: 'base64', source: 'camera' }
  );
  return result.base64String;
}
```

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 Ephemeral HMAC Attestation Protocol

Capacitor 7 Native Bridge Ephemeral HMAC Attestation Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces a zero-trust cryptographic attestation layer across all Capacitor 7 native bridge dispatches. Every hardware-level API invocation must be sealed with a single-use HMAC-SHA256 token, monotonic nonce, and millisecond-level timestamp derived from an isolated in-memory key, neutralizing DOM XSS bridge-hijacking attacks. 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: Direct Unattested Native Plugin Invocations Vulnerable to WebView DOM XSS Exploitation 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 DriftDirect Unattested Native Plugin Invocations Vulnerable to WebView DOM XSS ExploitationCritical
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 route Capacitor plugin invocations through an attested dispatch proxy that attaches a cryptographically sealed HMAC-SHA256 payload envelope.

Engineers MUST ALWAYS route Capacitor plugin invocations through an attested dispatch proxy that attaches a cryptographically sealed HMAC-SHA256 payload envelope.

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 expose raw `@capacitor/*` plugin instances or `window.Capacitor.toNative` to the global DOM scope or unvetted UI components.

Engineers MUST NOT expose raw `@capacitor/*` plugin instances or `window.Capacitor.toNative` to the global DOM scope or unvetted UI components.

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 generate attestation tokens using Web Crypto API (`crypto.subtle`) with non-extractable keys initialized in a non-accessible lexical closure or Web Worker.

Code SHOULD generate attestation tokens using Web Crypto API (`crypto.subtle`) with non-extractable keys initialized in a non-accessible lexical closure or Web Worker.

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 validate that each invocation packet contains a monotonic counter nonce, an ISO timestamp with a maximum 5000ms TTL drift, and an HMAC digest of the serialized method arguments.

Services MUST validate that each invocation packet contains a monotonic counter nonce, an ISO timestamp with a maximum 5000ms TTL drift, and an HMAC digest of the serialized method arguments.

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 native calls directly in response to untrusted DOM events or third-party iframe postMessage payloads.

Components NEVER execute raw native calls directly in response to untrusted DOM events or third-party iframe postMessage payloads.

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 HMAC Attestation Protocol critical for AI coding assistants?

Enforces a zero-trust cryptographic attestation layer across all Capacitor 7 native bridge dispatches. Every hardware-level API invocation must be sealed with a single-use HMAC-SHA256 token, monotonic nonce, and millisecond-level timestamp derived from an isolated in-memory key, neutralizing DOM XSS bridge-hijacking attacks. 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 (Direct Unattested Native Plugin Invocations Vulnerable to WebView DOM XSS Exploitation) 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