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

Capacitor 7 Secure Enclave and StrongBox Hardware Key Attestation Invariant

Mandates that cryptographic authentication keys generated within Capacitor 7 hybrid runtimes are physically bound to hardware-isolated crypto co-processors (Apple Secure Enclave or Android StrongBox Keymaster/KeyMint). Enforces server-side hardware attestation verification and strict per-operation or tightly bounded biometric authentication timeouts.

Prohibited Anti-Pattern: Ephemeral WebCrypto key generation or software-backed keystore fallbacks lacking biometric access controls and hardware attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave and StrongBox Hardware Key Attestation Invariant - Mandates that cryptographic authentication keys generated within Capacitor 7 hybrid runtimes are physically bound to hardware-isolated crypto co-processors (Apple Secure Enclave or Android StrongBox Keymaster/KeyMint). Enforces server-side hardware attestation verification and strict per-operation or tightly bounded biometric authentication timeouts.
globs: src/**/*.{ts,tsx,js,jsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-hardware-attestation"
---

# Capacitor 7 Secure Enclave and StrongBox Hardware Key Attestation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Ephemeral WebCrypto key generation or software-backed keystore fallbacks lacking biometric access controls and hardware attestation

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust cryptographic invariants in Capacitor 7 hybrid applications. You must ensure that authentication credentials never reside in WebView memory, localStorage, or software-backed Android Keystores / iOS Keychain items. Every keypair generation must strictly mandate hardware-backed co-processors (Apple Secure Enclave via kSecAttrAccessControl with biometry, Android StrongBox KeyMint with setIsStrongBoxBacked(true)). Cryptographic operations must require explicit biometric authorization with an access timeout of 0 (per-use authentication) or a strictly verified window not exceeding 60 seconds. Attestation certificate chains must be sent to the backend for verification against Apple App Attest or Google Key Attestation root certificates prior to trust establishment.

## Strict Guidelines
- Engineers MUST ALWAYS isolate private key generation to native hardware co-processors (iOS Secure Enclave or Android StrongBox KeyMint) through native Capacitor plugins rather than using WebView WebCrypto.
- Engineers MUST NOT allow software fallback when hardware-backed key storage or StrongBox is unavailable; the application must throw a non-recoverable security exception or transition to a degraded safe mode.
- Code MUST require biometric authentication before accessing the private key, configuringsetUserAuthenticationRequired(true) with a duration <= 30 seconds on Android and kSecAccessControlBiometryCurrentSet on iOS.
- Services MUST extract the X.509 attestation certificate chain generated at key creation and transmit it to the backend for cryptographic leaf-to-root signature and extension verification.
- Components NEVER store private key material in JavaScript runtime memory, Capacitor Preferences, IndexedDB, or standard unencrypted SharedPreferences/UserDefaults.

## Bad vs Good Implementations
### Hardware-Backed Key Generation and Hardware Attestation via Capacitor Native Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating cryptographic credentials within WebView JavaScript exposes private key material to runtime memory dumping, XSS, and WebView vulnerabilities. LocalStorage lacks hardware isolation, StrongBox/Secure Enclave enforcement, attestation chains, and biometric access controls.
```typescript
// CRITICAL FLAW: Generating keys inside WebView WebCrypto or software-backed storage
// without hardware backing or biometric authentication gates.
export async function registerAuthKeyBad(userId: string): Promise<{ publicKey: string }> {
  // Key resides in V8/WebKit memory; extractable via XSS or WebView injection
  const keyPair = await window.crypto.subtle.generateKey(
    {
      name: 'ECDSA',
      namedCurve: 'P-256',
    },
    true,
    ['sign', 'verify']
  );

  const exportedPublic = await window.crypto.subtle.exportKey('spki', keyPair.publicKey);
  const exportedPrivate = await window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey);

  // Storing raw private key in insecure Capacitor Preferences (LocalStorage wrapper)
  localStorage.setItem(`key_${userId}`, JSON.stringify(Array.from(new Uint8Array(exportedPrivate))));

  return {
    publicKey: btoa(String.fromCharCode(...new Uint8Array(exportedPublic)))
  };
}
```

#### Production Standard (Correct)
> **Standard**: Invokes a native Capacitor 7 plugin that provisions non-extractable keys inside the Apple Secure Enclave or Android StrongBox KeyMint. Mandates per-use biometric authorization (authTimeoutSeconds: 0), prevents software fallback, and captures an X.509 attestation certificate chain for backend validation.
```typescript
// PRODUCTION STANDARD: Capacitor 7 Secure Enclave / StrongBox Enforced Native Bridge
import { registerPlugin } from '@capacitor/core';

export interface SecureHardwareKeyResult {
  alias: string;
  publicKeyPem: string;
  attestationChain: string[];
}

export interface HardwareKeyPlugin {
  generateHardwareKey(options: {
    alias: string;
    requireStrongBox: boolean;
    requireBiometric: boolean;
    authTimeoutSeconds: number;
    challenge: string;
  }): Promise<SecureHardwareKeyResult>;
  
  signHardwarePayload(options: {
    alias: string;
    payload: string;
    promptMessage: string;
  }): Promise<{ signature: string }>;
}

const HardwareKeyBridge = registerPlugin<HardwareKeyPlugin>('HardwareKeyBridge');

export async function registerHardwareBoundKey(userId: string, serverChallenge: string): Promise<SecureHardwareKeyResult> {
  try {
    // Delegates to native layer implementing:
    // Android: KeyGenParameterSpec.Builder with setIsStrongBoxBacked(true), setUserAuthenticationRequired(true)
    // iOS: kSecAttrTokenIDSecureEnclave, SecAccessControlCreateWithFlags (biometryCurrentSet)
    const result = await HardwareKeyBridge.generateHardwareKey({
      alias: `auth_key_${userId}`,
      requireStrongBox: true,
      requireBiometric: true,
      authTimeoutSeconds: 0, // Invariant: 0 forces per-signature biometric prompt
      challenge: serverChallenge,
    });

    if (!result.attestationChain || result.attestationChain.length === 0) {
      throw new Error('HARDWARE_ATTESTATION_FAILED: No hardware certificate chain returned.');
    }

    return result;
  } catch (error) {
    // Fail closed: Never downgrade to software keystore
    console.error('Fatal: Hardware-isolated key generation failed.', error);
    throw new Error('DEVICE_INTEGRITY_VIOLATION: Secure Enclave or StrongBox unavailable.');
  }
}
```

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: Capacitor 7 Secure Enclave and StrongBox Hardware Key Attestation Invariant

Capacitor 7 Secure Enclave and StrongBox Hardware Key Attestation Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates that cryptographic authentication keys generated within Capacitor 7 hybrid runtimes are physically bound to hardware-isolated crypto co-processors (Apple Secure Enclave or Android StrongBox Keymaster/KeyMint). Enforces server-side hardware attestation verification and strict per-operation or tightly bounded biometric authentication timeouts. 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: Ephemeral WebCrypto key generation or software-backed keystore fallbacks lacking biometric access controls and hardware 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 DriftEphemeral WebCrypto key generation or software-backed keystore fallbacks lacking biometric access controls and hardware 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 private key generation to native hardware co-processors (iOS Secure Enclave or Android StrongBox KeyMint) through native Capacitor plugins rather than using WebView WebCrypto.

Engineers MUST ALWAYS isolate private key generation to native hardware co-processors (iOS Secure Enclave or Android StrongBox KeyMint) through native Capacitor plugins rather than using WebView WebCrypto.

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 allow software fallback when hardware-backed key storage or StrongBox is unavailable

Engineers MUST NOT allow software fallback when hardware-backed key storage or StrongBox is unavailable; the application must throw a non-recoverable security exception or transition to a degraded safe mode.

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 require biometric authentication before accessing the private key, configuringsetUserAuthenticationRequired(true) with a duration <= 30 seconds on Android and kSecAccessControlBiometryCurrentSet on iOS.

Code MUST require biometric authentication before accessing the private key, configuringsetUserAuthenticationRequired(true) with a duration <= 30 seconds on Android and kSecAccessControlBiometryCurrentSet 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.
4

Services MUST extract the X.509 attestation certificate chain generated at key creation and transmit it to the backend for cryptographic leaf-to-root signature and extension verification.

Services MUST extract the X.509 attestation certificate chain generated at key creation and transmit it to the backend for cryptographic leaf-to-root signature and extension verification.

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 store private key material in JavaScript runtime memory, Capacitor Preferences, IndexedDB, or standard unencrypted SharedPreferences/UserDefaults.

Components NEVER store private key material in JavaScript runtime memory, Capacitor Preferences, IndexedDB, or standard unencrypted SharedPreferences/UserDefaults.

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 Secure Enclave and StrongBox Hardware Key Attestation Invariant critical for AI coding assistants?

Mandates that cryptographic authentication keys generated within Capacitor 7 hybrid runtimes are physically bound to hardware-isolated crypto co-processors (Apple Secure Enclave or Android StrongBox Keymaster/KeyMint). Enforces server-side hardware attestation verification and strict per-operation or tightly bounded biometric authentication timeouts. 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 (Ephemeral WebCrypto key generation or software-backed keystore fallbacks lacking biometric access controls and hardware 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