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

Capacitor 7 StrongBox Hardware Keystore Attestation & Encryption Invariant

Enforces hardware-backed encryption key derivation using Android StrongBox Keymaster and Apple Secure Enclave in Capacitor 7 hybrid mobile architectures. Guarantees that local persistent SQLite and key-value database keys are bound to cryptographic enclave hardware and verified through remote device attestation before storage unlocks, preventing extraction on compromised, rooted, or hooked runtimes.

Prohibited Anti-Pattern: Deriving Local Storage Keys in Software Without StrongBox Hardware Enclave Attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 StrongBox Hardware Keystore Attestation & Encryption Invariant - Enforces hardware-backed encryption key derivation using Android StrongBox Keymaster and Apple Secure Enclave in Capacitor 7 hybrid mobile architectures. Guarantees that local persistent SQLite and key-value database keys are bound to cryptographic enclave hardware and verified through remote device attestation before storage unlocks, preventing extraction on compromised, rooted, or hooked runtimes.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, 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-attestation-invariant"
---

# Capacitor 7 StrongBox Hardware Keystore Attestation & Encryption Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Deriving Local Storage Keys in Software Without StrongBox Hardware Enclave Attestation

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 StrongBox Hardware Keystore Attestation Invariant. You must reject any client-side key derivation, obfuscated string literals, plain SharedPreferences/UserDefaults storage of encryption passphrases, or unverified hardware access. You mandate hardware-backed master encryption keys isolated in Android StrongBox (FEATURE_STRONGBOX_KEYSTORE) and iOS Secure Enclave, coupled with zero-trust cryptographic attestation verification before exposing database encryption interfaces to the webview runtime.

## Strict Guidelines
- Engineers MUST ALWAYS isolate database encryption key generation within the hardware security module using KeyGenParameterSpec with setIsStrongBoxBacked(true) on Android and kSecAttrTokenIDSecureEnclave on iOS.
- Engineers MUST NOT persist raw encryption passphrases or derived intermediate keys in the Capacitor webview bridge, LocalStorage, IndexedDB, or standard unencrypted Key-Value plugins.
- Code SHOULD verify hardware root-of-trust certificates via backend challenge-response attestation before unsealing database encryption keys during cold-start authentication.
- Services MUST implement graceful fallback rejection (terminating database initialization with fatal security status) when StrongBox or Secure Enclave hardware is missing, untrusted, or modified.
- Components NEVER expose decrypted SQLite file handles, raw PRAGMA key directives, or plaintext keys over the Capacitor JavaScript-to-Native bridge window scope.

## Bad vs Good Implementations
### Database Master Key Derivation & Enclave Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Derives the encryption passphrase using soft client secrets or software-backed persistence. Attackers with root, Frida hooks, or memory dumps can trivially extract the static secret or memory-resident key without triggering hardware tamper mechanisms.
```typescript
import { Plugins } from '@capacitor/core';
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

// Anti-pattern: Hardcoded salt/passphrase or pure software Key-Value bridge storage
export async function initDatabase(): Promise<void> {
  const sqlite = new SQLiteConnection(CapacitorSQLite);
  const fallbackSecret = 'HardcodedSoftwareSalt_987321#'; // Insecure software secret
  
  const db = await sqlite.createConnection(
    'secure_vault.db',
    true, // encrypted
    'secret',
    1,
    false
  );
  
  // Directly unsealing without checking hardware tampering or StrongBox guarantees
  await db.open();
}
```

#### Production Standard (Correct)
> **Standard**: Mandates StrongBox Keymaster hardware backing on Android and Secure Enclave on iOS. Cryptographic keys are anchored in hardware tamper-resistant silicon, requiring explicit server-verified attestation challenges before exposing ephemeral references to the database layer.
```typescript
import { registerPlugin } from '@capacitor/core';
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

export interface SecureEnclavePlugin {
  generateAttestedKey(options: { challenge: string; requireStrongBox: boolean }): Promise<{ attestationChain: string[] }>;
  unsealDatabaseKey(options: { challenge: string; signature: string }): Promise<{ ephemeralKeyRef: string }>;
}

const EnclaveBridge = registerPlugin<SecureEnclavePlugin>('SecureEnclaveBridge');

export async function initHardwareProtectedDatabase(authChallenge: string, serverVerificationToken: string): Promise<void> {
  const sqlite = new SQLiteConnection(CapacitorSQLite);
  
  // Require dedicated Android StrongBox / Apple Secure Enclave execution
  const { attestationChain } = await EnclaveBridge.generateAttestedKey({
    challenge: authChallenge,
    requireStrongBox: true,
  });

  if (!attestationChain || attestationChain.length === 0) {
    throw new Error('HARDWARE_SECURITY_INVARIANT_VIOLATION: StrongBox not available');
  }

  // Ephemeral reference resolved inside native enclave wrapper; raw key bytes never cross the bridge
  const { ephemeralKeyRef } = await EnclaveBridge.unsealDatabaseKey({
    challenge: authChallenge,
    signature: serverVerificationToken,
  });

  const db = await sqlite.createConnection(
    'hardware_vault.db',
    true,
    ephemeralKeyRef, // Native-mapped alias verified by StrongBox hardware session
    1,
    false
  );

  await db.open();
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 StrongBox Hardware Keystore Attestation & Encryption Invariant

Capacitor 7 StrongBox Hardware Keystore Attestation & Encryption Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed encryption key derivation using Android StrongBox Keymaster and Apple Secure Enclave in Capacitor 7 hybrid mobile architectures. Guarantees that local persistent SQLite and key-value database keys are bound to cryptographic enclave hardware and verified through remote device attestation before storage unlocks, preventing extraction on compromised, rooted, or hooked runtimes. 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: Deriving Local Storage Keys in Software Without StrongBox Hardware Enclave Attestation 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 DriftDeriving Local Storage Keys in Software Without StrongBox Hardware Enclave AttestationCritical
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 isolate database encryption key generation within the hardware security module using KeyGenParameterSpec with setIsStrongBoxBacked(true) on Android and kSecAttrTokenIDSecureEnclave on iOS.

Engineers MUST ALWAYS isolate database encryption key generation within the hardware security module using KeyGenParameterSpec with setIsStrongBoxBacked(true) on Android and kSecAttrTokenIDSecureEnclave on iOS.

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 encryption passphrases or derived intermediate keys in the Capacitor webview bridge, LocalStorage, IndexedDB, or standard unencrypted Key-Value plugins.

Engineers MUST NOT persist raw encryption passphrases or derived intermediate keys in the Capacitor webview bridge, LocalStorage, IndexedDB, or standard unencrypted Key-Value plugins.

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 root-of-trust certificates via backend challenge-response attestation before unsealing database encryption keys during cold-start authentication.

Code SHOULD verify hardware root-of-trust certificates via backend challenge-response attestation before unsealing database encryption keys during cold-start authentication.

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 implement graceful fallback rejection (terminating database initialization with fatal security status) when StrongBox or Secure Enclave hardware is missing, untrusted, or modified.

Services MUST implement graceful fallback rejection (terminating database initialization with fatal security status) when StrongBox or Secure Enclave hardware is missing, untrusted, or modified.

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 expose decrypted SQLite file handles, raw PRAGMA key directives, or plaintext keys over the Capacitor JavaScript-to-Native bridge window scope.

Components NEVER expose decrypted SQLite file handles, raw PRAGMA key directives, or plaintext keys over the Capacitor JavaScript-to-Native bridge window scope.

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 Hardware Keystore Attestation & Encryption Invariant critical for AI coding assistants?

Enforces hardware-backed encryption key derivation using Android StrongBox Keymaster and Apple Secure Enclave in Capacitor 7 hybrid mobile architectures. Guarantees that local persistent SQLite and key-value database keys are bound to cryptographic enclave hardware and verified through remote device attestation before storage unlocks, preventing extraction on compromised, rooted, or hooked runtimes. 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 (Deriving Local Storage Keys in Software Without StrongBox Hardware Enclave Attestation) 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