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

Capacitor 7 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol

Enforces hardware-backed cryptographic key isolation using Android StrongBox/TEE Keystore and iOS Secure Enclave for Capacitor 7 hybrid mobile applications. Prevents plaintext key exposure across the JavaScript-to-native bridge and guarantees hardware-bound biometric authentication lifecycles with explicit enrollment invalidation.

Prohibited Anti-Pattern: Software-Emulated Keystore Fallback and Plaintext Key Transit Over Web-Native Bridge

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol - Enforces hardware-backed cryptographic key isolation using Android StrongBox/TEE Keystore and iOS Secure Enclave for Capacitor 7 hybrid mobile applications. Prevents plaintext key exposure across the JavaScript-to-native bridge and guarantees hardware-bound biometric authentication lifecycles with explicit enrollment invalidation.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-keystore-enclave-bridge"
---

# Capacitor 7 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Software-Emulated Keystore Fallback and Plaintext Key Transit Over Web-Native Bridge

## System Constraints
You are a Principal Mobile Security Architect enforcing hardware-backed cryptographic guarantees in Capacitor 7 applications. Your mandate is to prevent reliance on software-backed keystores, unauthenticated SharedPreferences/UserDefaults storage, and insecure FFI transit of sensitive material. Ensure all asymmetric/symmetric keys are bound to Android StrongBox/TEE or Apple Secure Enclave with biometryCurrentSet / setInvalidatedByBiometricEnrollment, ensuring zero-knowledge cryptographic operations where raw keys never cross the WebKit/WebView JavaScript boundary.

## Strict Guidelines
- Engineers MUST ALWAYS verify native security evaluation via hardware-backed indicators (Android StrongBox or TEE KeyStore, iOS kSecAttrTokenIDSecureEnclave) prior to persisting high-entropy secrets.
- Engineers MUST NOT transmit raw cryptographic private or symmetric master keys across the Capacitor bridge into the JavaScript V8/JavaScriptCore runtime context.
- Native plugins MUST enforce biometric authorization at the hardware level using kSecAccessControlBiometryCurrentSet (iOS) or setUserAuthenticationRequired(true) with setInvalidatedByBiometricEnrollment(true) (Android).
- Bridge services MUST explicitly catch and classify cryptographic hardware invalidation events (e.g., KeyPermanentlyInvalidatedException or errSecAuthFailed) when new biometrics are enrolled, triggering a deterministic re-keying flow.
- Cryptographic operations (signing, decryption, cipher block generation) MUST occur strictly inside native hardware isolation boundaries, returning only ciphertexts, signatures, or ephemeral session tokens to the Web layer.
- Components NEVER store sensitive tokens or hardware-bound cryptographic aliases in Capacitor Preferences, localStorage, or unencrypted IndexedDB.

## Bad vs Good Implementations
### Hardware-Enclave Vault Bridge with Invalidation Detection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores sensitive keys using @capacitor/preferences which persists in plaintext XML/plist files. The raw key is exposed in the WebView JavaScript heap, bypasses hardware isolation (TEE/StrongBox/Secure Enclave), and lacks biometric gating or invalidation on biometric enrollment changes.
```typescript
import { Preferences } from '@capacitor/preferences';

// VULNERABLE: Soft storage fallback, plaintext keys in JS runtime,
// no biometric binding or hardware security verification.
export class VaultBridgeService {
  async storeSessionKey(keyAlias: string, rawKey: string): Promise<void> {
    // Plaintext key stored in unencrypted SharedPreferences/UserDefaults
    await Preferences.set({
      key: `vault_${keyAlias}`,
      value: rawKey,
    });
  }

  async getSessionKey(keyAlias: string): Promise<string | null> {
    const { value } = await Preferences.get({ key: `vault_${keyAlias}` });
    return value;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations directly to native hardware isolation boundaries through a dedicated bridge interface. Validates StrongBox/TEE/Secure Enclave availability, binds key lifecycle to biometric enrollment changes, avoids exposing raw symmetric master keys in JavaScript memory, and handles hardware key invalidation explicitly.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureStorageHardwareBridgePlugin {
  encryptPayload(options: {
    alias: string;
    plaintext: string;
    requireBiometric: boolean;
    invalidateOnBiometricChange?: boolean;
  }): Promise<{ ciphertext: string; hardwareSecurityLevel: 'STRONGBOX' | 'TEE' | 'SECURE_ENCLAVE' }>;

  decryptPayload(options: {
    alias: string;
    ciphertext: string;
    biometricPromptTitle: string;
  }): Promise<{ plaintext: string }>;

  isHardwareLevelSupported(): Promise<{
    hasSecureEnclaveOrStrongBox: boolean;
    enrolledBiometrics: boolean;
  }>;
}

export const SecureStorageBridge = registerPlugin<SecureStorageHardwareBridgePlugin>('SecureStorageHardwareBridge');

export class EnclaveBoundVaultService {
  public async secureStoreSecret(
    keyAlias: string,
    sensitiveData: string
  ): Promise<{ ciphertext: string }> {
    const hardware = await SecureStorageBridge.isHardwareLevelSupported();
    if (!hardware.hasSecureEnclaveOrStrongBox) {
      throw new Error('HARDWARE_SECURITY_VIOLATION: Device lacks isolated enclave/StrongBox execution environment.');
    }
    if (!hardware.enrolledBiometrics) {
      throw new Error('BIOMETRIC_NOT_ENROLLED: Hardware enclave requires registered biometric credentials.');
    }

    return await SecureStorageBridge.encryptPayload({
      alias: keyAlias,
      plaintext: sensitiveData,
      requireBiometric: true,
      invalidateOnBiometricChange: true,
    });
  }

  public async retrieveSecret(keyAlias: string, ciphertext: string): Promise<string> {
    try {
      const result = await SecureStorageBridge.decryptPayload({
        alias: keyAlias,
        ciphertext,
        biometricPromptTitle: 'Authenticate to access cryptographic enclave',
      });
      return result.plaintext;
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error);
      if (message.includes('KEY_INVALIDATED') || message.includes('errSecAuthFailed')) {
        throw new Error('CRYPTOGRAPHIC_ENCLAVE_REVOKED: Keys invalidated due to biometric state change.');
      }
      throw error;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol

Capacitor 7 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic key isolation using Android StrongBox/TEE Keystore and iOS Secure Enclave for Capacitor 7 hybrid mobile applications. Prevents plaintext key exposure across the JavaScript-to-native bridge and guarantees hardware-bound biometric authentication lifecycles with explicit enrollment invalidation. 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: Software-Emulated Keystore Fallback and Plaintext Key Transit Over Web-Native Bridge 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 DriftSoftware-Emulated Keystore Fallback and Plaintext Key Transit Over Web-Native BridgeCritical
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 verify native security evaluation via hardware-backed indicators (Android StrongBox or TEE KeyStore, iOS kSecAttrTokenIDSecureEnclave) prior to persisting high-entropy secrets.

Engineers MUST ALWAYS verify native security evaluation via hardware-backed indicators (Android StrongBox or TEE KeyStore, iOS kSecAttrTokenIDSecureEnclave) prior to persisting high-entropy secrets.

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 transmit raw cryptographic private or symmetric master keys across the Capacitor bridge into the JavaScript V8/JavaScriptCore runtime context.

Engineers MUST NOT transmit raw cryptographic private or symmetric master keys across the Capacitor bridge into the JavaScript V8/JavaScriptCore runtime context.

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

Native plugins MUST enforce biometric authorization at the hardware level using kSecAccessControlBiometryCurrentSet (iOS) or setUserAuthenticationRequired(true) with setInvalidatedByBiometricEnrollment(true) (Android).

Native plugins MUST enforce biometric authorization at the hardware level using kSecAccessControlBiometryCurrentSet (iOS) or setUserAuthenticationRequired(true) with setInvalidatedByBiometricEnrollment(true) (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

Bridge services MUST explicitly catch and classify cryptographic hardware invalidation events (e.g., KeyPermanentlyInvalidatedException or errSecAuthFailed) when new biometrics are enrolled, triggering a deterministic re-keying flow.

Bridge services MUST explicitly catch and classify cryptographic hardware invalidation events (e.g., KeyPermanentlyInvalidatedException or errSecAuthFailed) when new biometrics are enrolled, triggering a deterministic re-keying flow.

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

Cryptographic operations (signing, decryption, cipher block generation) MUST occur strictly inside native hardware isolation boundaries, returning only ciphertexts, signatures, or ephemeral session tokens to the Web layer.

Cryptographic operations (signing, decryption, cipher block generation) MUST occur strictly inside native hardware isolation boundaries, returning only ciphertexts, signatures, or ephemeral session tokens to the Web layer.

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 store sensitive tokens or hardware-bound cryptographic aliases in Capacitor Preferences, localStorage, or unencrypted IndexedDB.

Components NEVER store sensitive tokens or hardware-bound cryptographic aliases in Capacitor Preferences, localStorage, or unencrypted IndexedDB.

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 Hardware-Backed StrongBox and Secure Enclave Bridge Protocol critical for AI coding assistants?

Enforces hardware-backed cryptographic key isolation using Android StrongBox/TEE Keystore and iOS Secure Enclave for Capacitor 7 hybrid mobile applications. Prevents plaintext key exposure across the JavaScript-to-native bridge and guarantees hardware-bound biometric authentication lifecycles with explicit enrollment invalidation. 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 (Software-Emulated Keystore Fallback and Plaintext Key Transit Over Web-Native Bridge) 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