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

Capacitor 7 Secure Enclave and Hardware KeyStore Boundary Isolation

Enforces cryptographic isolation between untrusted WebView execution contexts and host platform hardware security modules (Apple Secure Enclave, Android StrongBox/TEE KeyStore). Mandates zero-knowledge token handling, platform-side cryptographic signature verification, and direct biometric gatekeeping within native plugins to prevent credential exfiltration from DOM XSS vectors.

Prohibited Anti-Pattern: Exposing Raw Cryptographic Keys or Reusable Biometric Authorization Flags to the Hybrid WebView

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave and Hardware KeyStore Boundary Isolation - Enforces cryptographic isolation between untrusted WebView execution contexts and host platform hardware security modules (Apple Secure Enclave, Android StrongBox/TEE KeyStore). Mandates zero-knowledge token handling, platform-side cryptographic signature verification, and direct biometric gatekeeping within native plugins to prevent credential exfiltration from DOM XSS vectors.
globs: src/**/*.{ts,tsx,js,jsx}, 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-secure-enclave-boundary"
---

# Capacitor 7 Secure Enclave and Hardware KeyStore Boundary Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Cryptographic Keys or Reusable Biometric Authorization Flags to the Hybrid WebView

## System Constraints
You are a Principal Mobile Security Architect enforcing strict hardware-backed cryptographic boundaries in Capacitor 7 applications. The hybrid DOM/WebView context must be treated as hostile and fully untrusted. You must mandate that raw private keys, symmetric master keys, and long-lived authorization tokens are never instantiated within the JavaScript runtime, localStorage, or standard IndexedDB. All asymmetric key pairs must be generated inside the Apple Secure Enclave (`kSecAccessControlBiometryAny` / `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`) or Android KeyStore (`KeyProperties.PURPOSE_SIGN`, StrongBox / TEE backed) with hardware-enforced user authentication. The WebView must only initiate cryptographic challenge requests or receive short-lived, detached digital signatures, eliminating replay attacks and persistent token exfiltration.

## Strict Guidelines
- Engineers MUST ALWAYS isolate private key generation and storage inside native hardware (iOS Secure Enclave / Android StrongBox KeyStore) using custom or hardened Capacitor 7 native plugins.
- Engineers MUST NEVER return raw private keys, unwrapped symmetric keys, or plain boolean biometric authentication outcomes to the WebView layer for client-side authorization bypass.
- Code MUST sign an ephemeral, server-issued cryptographic nonce directly in native hardware during biometric prompt execution rather than handling passwords or bearer tokens in JavaScript.
- Services MUST enforce `setUserAuthenticationRequired(true)` with zero timeout on Android and `.userPresence` or `.biometryCurrentSet` access controls on iOS to invalidate keys upon enrollment changes.
- Components NEVER store credentials, biometric state flags, or cryptographic secrets in `localStorage`, `sessionStorage`, cookies, or unencrypted Capacitor Preferences.

## Bad vs Good Implementations
### Biometric Authentication: Boolean Auth Flag vs Hardware Challenge-Response Signature

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The hybrid runtime evaluates a primitive boolean ('success: true') from the native bridge and retrieves a static bearer token from Preferences. An attacker injecting malicious JavaScript into the WebView can patch the NativeBiometric object, bypass the check, and exfiltrate the stored credentials.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { Preferences } from '@capacitor/preferences';

export async function authenticateAndAuthorize(apiEndpoint: string): Promise<void> {
  // Flaw: Untrusted JavaScript asks native layer if biometric matched.
  // An attacker with XSS or DOM control can spoof this boolean entirely.
  const result = await NativeBiometric.verifyIdentity({
    reason: 'Please authenticate to sign transaction',
    title: 'Biometric Login',
  });

  if (result.success) {
    // Flaw: Storing or reading static bearer token inside insecure storage
    const { value: bearerToken } = await Preferences.get({ key: 'auth_token' });
    await fetch(apiEndpoint, {
      method: 'POST',
      headers: { Authorization: `Bearer ${bearerToken}` },
      body: JSON.stringify({ action: 'transfer', amount: 5000 }),
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Private keys never leave the Secure Enclave or StrongBox. The native plugin requests user presence via biometrics directly at the hardware gate before the key will compute an ECDSA/P-256 signature over the server-issued challenge. XSS injection cannot forge signatures or steal private keys.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface SecureEnclavePlugin {
  signChallenge(options: { challenge: string; prompt: string }): Promise<{ signature: string; keyId: string }>;
}

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

export async function authenticateAndAuthorize(apiEndpoint: string, serverChallenge: string): Promise<Response> {
  // The JavaScript layer only passes an ephemeral nonce down to native code.
  // The native plugin signs the payload within Secure Enclave / KeyStore.
  // If biometric validation fails or is tampered with, hardware refuses to release the private key.
  const { signature, keyId } = await SecureEnclave.signChallenge({
    challenge: serverChallenge,
    prompt: 'Authorize high-value transfer',
  });

  // Transmit the cryptographic signature to the backend for verification.
  // No raw key or persistent secret ever enters the WebView runtime.
  return await fetch(apiEndpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      challenge: serverChallenge,
      signature,
      keyId,
      action: 'transfer',
      amount: 5000,
    }),
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave and Hardware KeyStore Boundary Isolation

Capacitor 7 Secure Enclave and Hardware KeyStore Boundary Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic isolation between untrusted WebView execution contexts and host platform hardware security modules (Apple Secure Enclave, Android StrongBox/TEE KeyStore). Mandates zero-knowledge token handling, platform-side cryptographic signature verification, and direct biometric gatekeeping within native plugins to prevent credential exfiltration from DOM XSS vectors. 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: Exposing Raw Cryptographic Keys or Reusable Biometric Authorization Flags to the Hybrid WebView 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 DriftExposing Raw Cryptographic Keys or Reusable Biometric Authorization Flags to the Hybrid WebViewCritical
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 and storage inside native hardware (iOS Secure Enclave / Android StrongBox KeyStore) using custom or hardened Capacitor 7 native plugins.

Engineers MUST ALWAYS isolate private key generation and storage inside native hardware (iOS Secure Enclave / Android StrongBox KeyStore) using custom or hardened Capacitor 7 native 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.
2

Engineers MUST NEVER return raw private keys, unwrapped symmetric keys, or plain boolean biometric authentication outcomes to the WebView layer for client-side authorization bypass.

Engineers MUST NEVER return raw private keys, unwrapped symmetric keys, or plain boolean biometric authentication outcomes to the WebView layer for client-side authorization bypass.

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 sign an ephemeral, server-issued cryptographic nonce directly in native hardware during biometric prompt execution rather than handling passwords or bearer tokens in JavaScript.

Code MUST sign an ephemeral, server-issued cryptographic nonce directly in native hardware during biometric prompt execution rather than handling passwords or bearer tokens in JavaScript.

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 enforce `setUserAuthenticationRequired(true)` with zero timeout on Android and `.userPresence` or `.biometryCurrentSet` access controls on iOS to invalidate keys upon enrollment changes.

Services MUST enforce `setUserAuthenticationRequired(true)` with zero timeout on Android and `.userPresence` or `.biometryCurrentSet` access controls on iOS to invalidate keys upon enrollment changes.

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 credentials, biometric state flags, or cryptographic secrets in `localStorage`, `sessionStorage`, cookies, or unencrypted Capacitor Preferences.

Components NEVER store credentials, biometric state flags, or cryptographic secrets in `localStorage`, `sessionStorage`, cookies, or unencrypted 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.
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 Hardware KeyStore Boundary Isolation critical for AI coding assistants?

Enforces cryptographic isolation between untrusted WebView execution contexts and host platform hardware security modules (Apple Secure Enclave, Android StrongBox/TEE KeyStore). Mandates zero-knowledge token handling, platform-side cryptographic signature verification, and direct biometric gatekeeping within native plugins to prevent credential exfiltration from DOM XSS vectors. 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 (Exposing Raw Cryptographic Keys or Reusable Biometric Authorization Flags to the Hybrid WebView) 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