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

Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7

Enforces strict cryptographic key residency within native Android StrongBox Keymaster and iOS Secure Enclave chips across Capacitor 7 bridges. Mandates that asymmetric key pairs are generated on-chip, private keys remain permanently non-exportable, and the WebView interface only transfers digests, public keys, and cryptographic attestations.

Prohibited Anti-Pattern: Bridging Raw Key Material or Software-Emulating Key Storage Across Capacitor WebView Interfaces

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7 - Enforces strict cryptographic key residency within native Android StrongBox Keymaster and iOS Secure Enclave chips across Capacitor 7 bridges. Mandates that asymmetric key pairs are generated on-chip, private keys remain permanently non-exportable, and the WebView interface only transfers digests, public keys, and cryptographic attestations.
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-isolation"
---

# Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridging Raw Key Material or Software-Emulating Key Storage Across Capacitor WebView Interfaces

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer enforcing strict hardware-backed key isolation in Capacitor 7 hybrid applications. You must reject any architecture or implementation that exposes raw asymmetric key material, uses software-backed cryptographic fallbacks, or executes private key operations in the JavaScript WebView runtime.

## Strict Guidelines
- Engineers MUST ALWAYS enforce hardware key generation on native platforms (kSecAttrTokenIDSecureEnclave on iOS; setIsStrongBoxBacked(true) with fallback to Trusted Execution Environment on Android).
- Engineers MUST NOT expose or transmit private key bytes, raw seed phrases, or PKCS#8 structures over the Capacitor JavaScript-to-Native bridge under any circumstance.
- Native plugins MUST enforce kSecAccessControlPrivateKeyUsage and Biometric/Device Authentication policies directly within the platform Keymaster/Security framework prior to signing operations.
- Web runtime code MUST interact with keys solely via opaque string identifiers (key aliases) and pass only the target payload hash or signing challenge across the bridge.
- Services MUST verify hardware attestation certificates (Apple DeviceCheck / App Attest or Android KeyStore Key Attestation records) before trusting public keys generated by the client.
- Plugins MUST explicitly configure key algorithms to secure asymmetric standards (e.g., NIST P-256 / secp256r1 ECDSA) natively supported by Secure Enclave and StrongBox silicon.

## Bad vs Good Implementations
### Hardware-Attested Signature Generation vs. Web-Side Software Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw private key material is retained in Web memory (and localStorage), then serialized over the Capacitor bridge. If the WebView suffers an XSS injection or memory dump, the non-repudiation property is invalidated and the key is permanently compromised.
```typescript
// ANTI-PATTERN: Generating keys in JS and sending raw private key across Capacitor bridge
import { registerPlugin } from '@capacitor/core';

interface LegacyCryptoPlugin {
  storeKey(options: { alias: string; privateKeyHex: string }): Promise<void>;
  signData(options: { privateKeyHex: string; data: string }): Promise<{ signature: string }>;
}

const LegacyCrypto = registerPlugin<LegacyCryptoPlugin>('LegacyCrypto');

export async function signPayload(payload: string): Promise<string> {
  // VULNERABLE: Private key resides in Chromium/WebKit JS heap and localStorage
  const rawPrivateKey = localStorage.getItem('user_priv_key')!;
  
  // Transmitting raw private key across IPC bridge exposes it to XSS and memory dumps
  const result = await LegacyCrypto.signData({
    privateKeyHex: rawPrivateKey,
    data: btoa(payload)
  });
  
  return result.signature;
}
```

#### Production Standard (Correct)
> **Standard**: The private key never leaves the hardware security module (Secure Enclave on iOS, StrongBox on Android). Only the key alias and the digest to sign are passed over the Capacitor bridge. Signing occurs entirely within isolated silicon.
```typescript
// PRODUCTION STANDARD: Hardware-isolated key pair with native Enclave signing
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  generateAttestedKeyPair(options: {
    alias: string;
    requireBiometrics: boolean;
  }): Promise<{ publicKeyDer: string; attestationChain: string[] }>;
  
  signWithHardwareKey(options: {
    alias: string;
    payloadSha256: string;
  }): Promise<{ signatureDer: string }>;
}

const SecureEnclave = registerPlugin<SecureEnclavePlugin>('SecureEnclave');

export async function signPayloadSecurely(keyAlias: string, payload: Uint8Array): Promise<string> {
  // 1. Hash the payload inside Web Crypto API
  const digestBuffer = await crypto.subtle.digest('SHA-256', payload);
  const digestArray = Array.from(new Uint8Array(digestBuffer));
  const payloadSha256 = digestArray.map((b) => b.toString(16).padStart(2, '0')).join('');

  // 2. Request native signature; private key NEVER leaves the Secure Enclave/StrongBox
  const { signatureDer } = await SecureEnclave.signWithHardwareKey({
    alias: keyAlias,
    payloadSha256
  });

  return signatureDer;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7

Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cryptographic key residency within native Android StrongBox Keymaster and iOS Secure Enclave chips across Capacitor 7 bridges. Mandates that asymmetric key pairs are generated on-chip, private keys remain permanently non-exportable, and the WebView interface only transfers digests, public keys, and cryptographic attestations. 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: Bridging Raw Key Material or Software-Emulating Key Storage Across Capacitor WebView Interfaces 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 DriftBridging Raw Key Material or Software-Emulating Key Storage Across Capacitor WebView InterfacesCritical
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 enforce hardware key generation on native platforms (kSecAttrTokenIDSecureEnclave on iOS

Engineers MUST ALWAYS enforce hardware key generation on native platforms (kSecAttrTokenIDSecureEnclave on iOS; setIsStrongBoxBacked(true) with fallback to Trusted Execution Environment on 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.
2

Engineers MUST NOT expose or transmit private key bytes, raw seed phrases, or PKCS#8 structures over the Capacitor JavaScript-to-Native bridge under any circumstance.

Engineers MUST NOT expose or transmit private key bytes, raw seed phrases, or PKCS#8 structures over the Capacitor JavaScript-to-Native bridge under any circumstance.

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 kSecAccessControlPrivateKeyUsage and Biometric/Device Authentication policies directly within the platform Keymaster/Security framework prior to signing operations.

Native plugins MUST enforce kSecAccessControlPrivateKeyUsage and Biometric/Device Authentication policies directly within the platform Keymaster/Security framework prior to signing operations.

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

Web runtime code MUST interact with keys solely via opaque string identifiers (key aliases) and pass only the target payload hash or signing challenge across the bridge.

Web runtime code MUST interact with keys solely via opaque string identifiers (key aliases) and pass only the target payload hash or signing challenge across the 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

Services MUST verify hardware attestation certificates (Apple DeviceCheck / App Attest or Android KeyStore Key Attestation records) before trusting public keys generated by the client.

Services MUST verify hardware attestation certificates (Apple DeviceCheck / App Attest or Android KeyStore Key Attestation records) before trusting public keys generated by the client.

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

Plugins MUST explicitly configure key algorithms to secure asymmetric standards (e.g., NIST P-256 / secp256r1 ECDSA) natively supported by Secure Enclave and StrongBox silicon.

Plugins MUST explicitly configure key algorithms to secure asymmetric standards (e.g., NIST P-256 / secp256r1 ECDSA) natively supported by Secure Enclave and StrongBox silicon.

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 Hardware-Attested Key Isolation & Cryptographic Signing in Capacitor 7 critical for AI coding assistants?

Enforces strict cryptographic key residency within native Android StrongBox Keymaster and iOS Secure Enclave chips across Capacitor 7 bridges. Mandates that asymmetric key pairs are generated on-chip, private keys remain permanently non-exportable, and the WebView interface only transfers digests, public keys, and cryptographic attestations. 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 (Bridging Raw Key Material or Software-Emulating Key Storage Across Capacitor WebView Interfaces) 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

Hardware-Attested