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

Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard

Enforces zero-trust cryptographic isolation in Capacitor 7 hybrid applications by disallowing plaintext token or symmetric key persistence in the JavaScript WebView runtime. Mandates that cryptographic material and high-entropy authentication tokens are strictly bound to hardware-backed secure elements (Android StrongBox Keymaster/KeyMint and Apple Secure Enclave) via native bridging with mandatory remote key attestation.

Prohibited Anti-Pattern: Persisting Long-Lived Session Secrets and Private Keys in WebView LocalStorage, IndexedDB, or Unprotected Capacitor Preferences

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard - Enforces zero-trust cryptographic isolation in Capacitor 7 hybrid applications by disallowing plaintext token or symmetric key persistence in the JavaScript WebView runtime. Mandates that cryptographic material and high-entropy authentication tokens are strictly bound to hardware-backed secure elements (Android StrongBox Keymaster/KeyMint and Apple Secure Enclave) via native bridging with mandatory remote key attestation.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-strongbox-hardware-keystore-isolation-standard"
---

# Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Long-Lived Session Secrets and Private Keys in WebView LocalStorage, IndexedDB, or Unprotected Capacitor Preferences

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard. Your objective is to eliminate memory inspection, XSS token exfiltration, and physical extraction vulnerabilities in Capacitor hybrid mobile architectures. You must enforce that raw cryptographic keys and authentication refresh tokens never touch the JavaScript execution context in unencrypted form, mandating hardware-isolated cryptographic operations (Android StrongBox KeyMint and iOS Secure Enclave) accessed exclusively through authenticated native plugins.

## Strict Guidelines
- Engineers MUST ALWAYS store cryptographically sensitive tokens using hardware-isolated primitives (Android StrongBox/TEE Keystore and iOS Secure Enclave Keychain) via custom Capacitor plugins, never in browser-accessible storage.
- Engineers MUST NOT persist raw access tokens, refresh tokens, biometric session secrets, or private keys inside window.localStorage, window.sessionStorage, unencrypted IndexedDB, or standard @capacitor/preferences.
- Code SHOULD verify hardware attestation certificates on the backend during device enrollment using Android KeyStore Attestation (with StrongBox verification) and Apple App Attest / DeviceCheck before issuing session credentials.
- Services MUST execute all signature generation, key agreement, and decryption routines inside the native boundary, returning only signatures or ephemeral proof payloads across the Capacitor bridge.
- Components NEVER hold non-ephemeral authentication secrets in JavaScript memory longer than the lifecycle of a single atomic remote procedure call.

## Bad vs Good Implementations
### Hardware Keystore Isolation vs. Insecure Storage Token Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing refresh tokens and raw private keys in @capacitor/preferences or localStorage exposes them in plaintext files (e.g., SharedPreferences XML on Android or standard Plist/SQLite on iOS) and makes them directly accessible via WebView memory inspection, debugging bridges (chrome://inspect), or XSS.
```typescript
import { Preferences } from '@capacitor/preferences';

interface AuthSession {
  accessToken: string;
  refreshToken: string;
  signingPrivateKeyPem: string;
}

// CRITICAL FLAW: Sensitive keys and refresh tokens stored in cleartext XML/SQLite/localStorage
// Vulnerable to memory inspection, XSS exfiltration, and root-level physical extraction
export class SessionManager {
  async saveSession(session: AuthSession): Promise<void> {
    await Preferences.set({
      key: 'auth_session',
      value: JSON.stringify(session)
    });
    window.localStorage.setItem('access_token', session.accessToken);
  }

  async signPayload(payload: string): Promise<string> {
    const raw = await Preferences.get({ key: 'auth_session' });
    const { signingPrivateKeyPem } = JSON.parse(raw.value!);
    // Signing happens in JS runtime memory, exposing private key
    return window.crypto.subtle ? 'insecure-signature' : signingPrivateKeyPem;
  }
}
```

#### Production Standard (Correct)
> **Standard**: The private key is generated directly within Android StrongBox or the Apple Secure Enclave. Private key material cannot be extracted even with root or kernel-level compromises. All cryptographic operations occur in hardware, passing only attestation certificates and signatures across the Capacitor bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

interface HardwareVaultPlugin {
  generateHardwareKey(options: { alias: string; requireStrongBox: boolean }): Promise<{ attestationCertificateChain: string[] }>;
  signHardwarePayload(options: { alias: string; challengeSha256Base64: string }): Promise<{ signatureBase64: string }>;
  hasStrongBoxSupport(): Promise<{ isSupported: boolean }>;
}

const HardwareVault = registerPlugin<HardwareVaultPlugin>('HardwareVault');

export class SecureSessionManager {
  private static readonly KEY_ALIAS = 'app_auth_hardware_key';

  // Key generation occurs strictly in Android StrongBox (KeyMint) or iOS Secure Enclave
  // Private keys NEVER cross into the JS runtime or leave the secure hardware
  async initializeDeviceAttestation(serverEnrollmentChallenge: string): Promise<string[]> {
    const { isSupported } = await HardwareVault.hasStrongBoxSupport();
    
    const { attestationCertificateChain } = await HardwareVault.generateHardwareKey({
      alias: SecureSessionManager.KEY_ALIAS,
      requireStrongBox: isSupported
    });

    return attestationCertificateChain;
  }

  // Cryptographic operations are delegated to hardware; WebView handles only ephemeral digests
  async authenticateRequest(challengeBytesBase64: string): Promise<string> {
    const { signatureBase64 } = await HardwareVault.signHardwarePayload({
      alias: SecureSessionManager.KEY_ALIAS,
      challengeSha256Base64: challengeBytesBase64
    });
    return signatureBase64;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard

Capacitor 7 StrongBox Attestation and Hardware Keystore Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces zero-trust cryptographic isolation in Capacitor 7 hybrid applications by disallowing plaintext token or symmetric key persistence in the JavaScript WebView runtime. Mandates that cryptographic material and high-entropy authentication tokens are strictly bound to hardware-backed secure elements (Android StrongBox Keymaster/KeyMint and Apple Secure Enclave) via native bridging with mandatory remote key attestation. 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: Persisting Long-Lived Session Secrets and Private Keys in WebView LocalStorage, IndexedDB, or Unprotected Capacitor Preferences 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 DriftPersisting Long-Lived Session Secrets and Private Keys in WebView LocalStorage, IndexedDB, or Unprotected Capacitor PreferencesCritical
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 store cryptographically sensitive tokens using hardware-isolated primitives (Android StrongBox/TEE Keystore and iOS Secure Enclave Keychain) via custom Capacitor plugins, never in browser-accessible storage.

Engineers MUST ALWAYS store cryptographically sensitive tokens using hardware-isolated primitives (Android StrongBox/TEE Keystore and iOS Secure Enclave Keychain) via custom Capacitor plugins, never in browser-accessible storage.

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 persist raw access tokens, refresh tokens, biometric session secrets, or private keys inside window.localStorage, window.sessionStorage, unencrypted IndexedDB, or standard @capacitor/preferences.

Engineers MUST NOT persist raw access tokens, refresh tokens, biometric session secrets, or private keys inside window.localStorage, window.sessionStorage, unencrypted IndexedDB, or standard @capacitor/preferences.

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 verify hardware attestation certificates on the backend during device enrollment using Android KeyStore Attestation (with StrongBox verification) and Apple App Attest / DeviceCheck before issuing session credentials.

Code SHOULD verify hardware attestation certificates on the backend during device enrollment using Android KeyStore Attestation (with StrongBox verification) and Apple App Attest / DeviceCheck before issuing session credentials.

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 execute all signature generation, key agreement, and decryption routines inside the native boundary, returning only signatures or ephemeral proof payloads across the Capacitor bridge.

Services MUST execute all signature generation, key agreement, and decryption routines inside the native boundary, returning only signatures or ephemeral proof payloads across the Capacitor bridge.

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 hold non-ephemeral authentication secrets in JavaScript memory longer than the lifecycle of a single atomic remote procedure call.

Components NEVER hold non-ephemeral authentication secrets in JavaScript memory longer than the lifecycle of a single atomic remote procedure call.

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 StrongBox Attestation and Hardware Keystore Isolation Standard critical for AI coding assistants?

Enforces zero-trust cryptographic isolation in Capacitor 7 hybrid applications by disallowing plaintext token or symmetric key persistence in the JavaScript WebView runtime. Mandates that cryptographic material and high-entropy authentication tokens are strictly bound to hardware-backed secure elements (Android StrongBox Keymaster/KeyMint and Apple Secure Enclave) via native bridging with mandatory remote key attestation. 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 (Persisting Long-Lived Session Secrets and Private Keys in WebView LocalStorage, IndexedDB, or Unprotected Capacitor Preferences) 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