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

Capacitor 7 Hardware-Backed KeyStore & Biometric Zero-Plaintext Boundary

Enforces hardware-isolated asymmetric key generation within Android StrongBox Keymaster and iOS Secure Enclave, strictly prohibiting plaintext session tokens and symmetric secrets from residing in the hybrid WebView JavaScript memory, LocalStorage, or standard Capacitor Preferences. All session verifications must execute via hardware-attested cryptographic challenge signing with biometric gatekeeping at the native boundary.

Prohibited Anti-Pattern: Persisting Plaintext Bearer Tokens in Hybrid Storage or Leaking Symmetric Keys to JS Heap

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed KeyStore & Biometric Zero-Plaintext Boundary - Enforces hardware-isolated asymmetric key generation within Android StrongBox Keymaster and iOS Secure Enclave, strictly prohibiting plaintext session tokens and symmetric secrets from residing in the hybrid WebView JavaScript memory, LocalStorage, or standard Capacitor Preferences. All session verifications must execute via hardware-attested cryptographic challenge signing with biometric gatekeeping at the native boundary.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, 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-cryptographic-boundary"
---

# Capacitor 7 Hardware-Backed KeyStore & Biometric Zero-Plaintext Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Plaintext Bearer Tokens in Hybrid Storage or Leaking Symmetric Keys to JS Heap

## System Constraints
You are a Principal Mobile Security Architect enforcing cryptographic boundaries in Capacitor 7 hybrid applications. You MUST enforce hardware-backed asymmetric key pairs (NIST P-256 / secp256r1) bound to biometrics (iOS Secure Enclave kSecAccessControlBiometryCurrentSet and Android StrongBox/Keymaster KeyGenParameterSpec.Builder with setUserAuthenticationRequired(true)). Under NO circumstances may raw session tokens, symmetric master keys, or passwords be stored in capacitor Preferences, LocalStorage, IndexedDB, or held as long-lived strings in the JavaScript heap. Authentication MUST operate on asymmetric challenge-response paradigms where the native bridge exclusively returns digital signatures, never the private key or decrypted secrets.

## Strict Guidelines
- Engineers MUST ALWAYS isolate cryptographic private keys to hardware-backed modules (Android Keystore StrongBox or Apple Secure Enclave) via custom native plugins or certified Capacitor 7 FIPS-compliant providers.
- Engineers MUST NOT persist JWTs, session tokens, or API credentials in `@capacitor/preferences`, `localStorage`, `sessionStorage`, or IndexedDB.
- Code MUST mandate biometric user presence (`UserPresence` or `BiometryCurrentSet`) directly linked to the hardware key cryptographic signature operation.
- Services MUST implement challenge-response authentication workflows where the backend provides an ephemeral cryptographic nonce, and the native layer signs it using the hardware-isolated private key.
- Components NEVER hold decrypted credentials in memory; sensitive buffers received in native layers must be explicitly overwritten with zero bytes (`Arrays.fill(buffer, (byte) 0)` or `memset_s`) immediately post-use.
- Native plugins MUST reject key generation if hardware-backed security (TEE/StrongBox/Secure Enclave) is unavailable on the physical device.

## Bad vs Good Implementations
### Vulnerable: Persisting Plaintext Session Token in Capacitor Preferences

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Decoupling biometric checks from cryptographic hardware operations creates a false security boundary. Storing raw tokens in Capacitor Preferences persists sensitive session credentials in shared preference XML/NSUserDefaults in plaintext or software-encrypted files, vulnerable to WebView XSS, memory dumping, and backup extraction.
```typescript
import { Preferences } from '@capacitor/preferences';
import { BiometricAuth } from '@aparajita/capacitor-biometric-auth';

export async function authenticateSession(token: string): Promise<boolean> {
  // Anti-Pattern: Biometrics is decoupled from actual crypto operations,
  // and raw session tokens are stored in unencrypted/software-backed storage accessible to JS.
  const result = await BiometricAuth.verify({
    reason: 'Confirm identity to access your session'
  });

  if (result) {
    await Preferences.set({
      key: 'auth_bearer_token',
      value: token // Critical Leak: Plaintext token stored in bridge-accessible storage
    });
    return true;
  }
  return false;
}
```

#### Production Standard (Correct)
> **Standard**: Uses an asymmetric challenge-response pattern backed by hardware security. The private key remains completely inaccessible to the JS runtime inside the Secure Enclave / StrongBox. The biometric prompt is native and tied directly to the hardware key authorization window, ensuring zero-plaintext memory footprint in the hybrid runtime.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface HardwareKeyStorePlugin {
  generateHardwareBoundKeyPair(): Promise<{ publicKeyPem: string; isHardwareBacked: boolean }>;
  signSessionChallenge(options: { challenge: string; promptMessage: string }): Promise<{ signature: string }>;
}

const HardwareKeyStore = registerPlugin<HardwareKeyStorePlugin>('HardwareKeyStore');

export async function authenticateChallengeWithHardware(challengeNonce: string): Promise<string> {
  // Invariant: Hardware-backed signature strictly gated by biometrics in TEE/Secure Enclave.
  // Zero plaintext credentials or private keys ever transit to or reside within the JavaScript engine.
  const { signature } = await HardwareKeyStore.signSessionChallenge({
    challenge: challengeNonce,
    promptMessage: 'Authenticate to sign dynamic transaction nonce'
  });

  // Return only the cryptographic assertion to transmit to the identity provider
  return signature;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed KeyStore & Biometric Zero-Plaintext Boundary

Capacitor 7 Hardware-Backed KeyStore & Biometric Zero-Plaintext Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-isolated asymmetric key generation within Android StrongBox Keymaster and iOS Secure Enclave, strictly prohibiting plaintext session tokens and symmetric secrets from residing in the hybrid WebView JavaScript memory, LocalStorage, or standard Capacitor Preferences. All session verifications must execute via hardware-attested cryptographic challenge signing with biometric gatekeeping at the native boundary. 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 Plaintext Bearer Tokens in Hybrid Storage or Leaking Symmetric Keys to JS Heap 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 Plaintext Bearer Tokens in Hybrid Storage or Leaking Symmetric Keys to JS HeapCritical
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 cryptographic private keys to hardware-backed modules (Android Keystore StrongBox or Apple Secure Enclave) via custom native plugins or certified Capacitor 7 FIPS-compliant providers.

Engineers MUST ALWAYS isolate cryptographic private keys to hardware-backed modules (Android Keystore StrongBox or Apple Secure Enclave) via custom native plugins or certified Capacitor 7 FIPS-compliant providers.

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 JWTs, session tokens, or API credentials in `@capacitor/preferences`, `localStorage`, `sessionStorage`, or IndexedDB.

Engineers MUST NOT persist JWTs, session tokens, or API credentials in `@capacitor/preferences`, `localStorage`, `sessionStorage`, or 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.
3

Code MUST mandate biometric user presence (`UserPresence` or `BiometryCurrentSet`) directly linked to the hardware key cryptographic signature operation.

Code MUST mandate biometric user presence (`UserPresence` or `BiometryCurrentSet`) directly linked to the hardware key cryptographic signature operation.

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 challenge-response authentication workflows where the backend provides an ephemeral cryptographic nonce, and the native layer signs it using the hardware-isolated private key.

Services MUST implement challenge-response authentication workflows where the backend provides an ephemeral cryptographic nonce, and the native layer signs it using the hardware-isolated private key.

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 decrypted credentials in memory

Components NEVER hold decrypted credentials in memory; sensitive buffers received in native layers must be explicitly overwritten with zero bytes (`Arrays.fill(buffer, (byte) 0)` or `memset_s`) immediately post-use.

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

Native plugins MUST reject key generation if hardware-backed security (TEE/StrongBox/Secure Enclave) is unavailable on the physical device.

Native plugins MUST reject key generation if hardware-backed security (TEE/StrongBox/Secure Enclave) is unavailable on the physical device.

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 KeyStore & Biometric Zero-Plaintext Boundary critical for AI coding assistants?

Enforces hardware-isolated asymmetric key generation within Android StrongBox Keymaster and iOS Secure Enclave, strictly prohibiting plaintext session tokens and symmetric secrets from residing in the hybrid WebView JavaScript memory, LocalStorage, or standard Capacitor Preferences. All session verifications must execute via hardware-attested cryptographic challenge signing with biometric gatekeeping at the native boundary. 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 Plaintext Bearer Tokens in Hybrid Storage or Leaking Symmetric Keys to JS Heap) 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