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

Hardware Enclave Keystore Bridging for Cryptographic Operations

Enforces strict delegation of authentication tokens and cryptographic operations to native platform hardware (iOS Secure Enclave and Android Hardware-backed Keystore / StrongBox) via Capacitor 7 bridges. Prevents persistent plaintext token storage or in-memory token reconstruction in the JavaScript runtime context where it remains vulnerable to heap inspection and XSS.

Prohibited Anti-Pattern: Persisting Refresh Tokens in Web Storage or Extracting Raw Secrets into the WebView Runtime Memory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware Enclave Keystore Bridging for Cryptographic Operations - Enforces strict delegation of authentication tokens and cryptographic operations to native platform hardware (iOS Secure Enclave and Android Hardware-backed Keystore / StrongBox) via Capacitor 7 bridges. Prevents persistent plaintext token storage or in-memory token reconstruction in the JavaScript runtime context where it remains vulnerable to heap inspection and XSS.
globs: src/services/auth/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-secure-enclave-keystore-bridging"
---

# Hardware Enclave Keystore Bridging for Cryptographic Operations

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Refresh Tokens in Web Storage or Extracting Raw Secrets into the WebView Runtime Memory

## System Constraints
You are a Principal Mobile Security Architect enforcing strict hardware-backed cryptographic signing boundaries in Capacitor 7 applications. You must ensure that high-entropy secrets and long-lived authentication credentials never traverse into the JavaScript heap or unencrypted storage layers.

## Strict Guidelines
- Engineers MUST NEVER store refresh tokens, session master keys, or private signing keys in localStorage, sessionStorage, IndexedDB, or standard unencrypted Preferences.
- Engineers MUST delegate cryptographic signature generation (such as DPoP or client assertion JWTs) directly across the native bridge into the iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore/StrongBox.
- Native plugins MUST enforce non-exportable key flags (e.g., KeyProperties.PURPOSE_SIGN for Android KeyStore, kSecAttrIsExtractable: false for iOS Keychain/Secure Enclave) during asymmetric key generation.
- Bridge methods MUST only return proof signatures, cryptographic assertions, or ephemeral access tokens; raw private keys and encrypted token buffers MUST NOT be exposed across the bridge into the web context.
- Services MUST implement challenge-response assertions where the server issues an ephemeral nonce and the native bridge signs it within the secure hardware boundary, eliminating persistent refresh tokens from client memory.

## Bad vs Good Implementations
### Anti-Pattern: Storing and Reading Raw Refresh Tokens in JavaScript Memory

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores long-lived credentials in Capacitor Preferences (unencrypted SQLite/SharedPreferences). The raw token is exposed in the JavaScript runtime heap, leaving it vulnerable to process memory scraping, WebView inspection, and XSS extraction.
```typescript
import { Preferences } from '@capacitor/preferences';
import axios from 'axios';

export class AuthService {
  // VULNERABLE: Refresh token is exposed to the WebView JS heap and unencrypted preferences
  async refreshSession(): Promise<string> {
    const { value: rawRefreshToken } = await Preferences.get({ key: 'auth_refresh_token' });
    if (!rawRefreshToken) throw new Error('Unauthenticated');

    const response = await axios.post('https://api.domain.com/v1/auth/token', {
      grant_type: 'refresh_token',
      refresh_token: rawRefreshToken,
    });

    await Preferences.set({ key: 'auth_refresh_token', value: response.data.refresh_token });
    return response.data.access_token;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations to the device hardware enclave. The private key material is physically non-exportable from the Secure Enclave / StrongBox, and only signed ephemeral challenges pass across the Capacitor bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

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

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

export class AuthService {
  // SECURE: Raw keys never enter JavaScript memory; hardware enclave signs proof-of-possession
  async refreshSession(challenge: string): Promise<string> {
    const { signature, keyId } = await SecureEnclave.signChallenge({
      challenge,
      keyAlias: 'auth_session_signing_key',
    });

    const response = await fetch('https://api.domain.com/v1/auth/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        grant_type: 'hardware_assertion',
        key_id: keyId,
        assertion: signature,
      }),
    });

    if (!response.ok) throw new Error('Hardware verification failed');
    const payload = await response.json();
    return payload.access_token;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware Enclave Keystore Bridging for Cryptographic Operations

Hardware Enclave Keystore Bridging for Cryptographic Operations defines an industrial-grade behavioral standard for mobile engineering. Enforces strict delegation of authentication tokens and cryptographic operations to native platform hardware (iOS Secure Enclave and Android Hardware-backed Keystore / StrongBox) via Capacitor 7 bridges. Prevents persistent plaintext token storage or in-memory token reconstruction in the JavaScript runtime context where it remains vulnerable to heap inspection and XSS. 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 Refresh Tokens in Web Storage or Extracting Raw Secrets into the WebView Runtime Memory 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 Refresh Tokens in Web Storage or Extracting Raw Secrets into the WebView Runtime MemoryCritical
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 NEVER store refresh tokens, session master keys, or private signing keys in localStorage, sessionStorage, IndexedDB, or standard unencrypted Preferences.

Engineers MUST NEVER store refresh tokens, session master keys, or private signing keys in localStorage, sessionStorage, IndexedDB, or standard unencrypted 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.
2

Engineers MUST delegate cryptographic signature generation (such as DPoP or client assertion JWTs) directly across the native bridge into the iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore/StrongBox.

Engineers MUST delegate cryptographic signature generation (such as DPoP or client assertion JWTs) directly across the native bridge into the iOS Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android KeyStore/StrongBox.

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 non-exportable key flags (e.g., KeyProperties.PURPOSE_SIGN for Android KeyStore, kSecAttrIsExtractable

Native plugins MUST enforce non-exportable key flags (e.g., KeyProperties.PURPOSE_SIGN for Android KeyStore, kSecAttrIsExtractable: false for iOS Keychain/Secure Enclave) during asymmetric key generation.

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

Bridge methods MUST only return proof signatures, cryptographic assertions, or ephemeral access tokens

Bridge methods MUST only return proof signatures, cryptographic assertions, or ephemeral access tokens; raw private keys and encrypted token buffers MUST NOT be exposed across the bridge into the web context.

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 implement challenge-response assertions where the server issues an ephemeral nonce and the native bridge signs it within the secure hardware boundary, eliminating persistent refresh tokens from client memory.

Services MUST implement challenge-response assertions where the server issues an ephemeral nonce and the native bridge signs it within the secure hardware boundary, eliminating persistent refresh tokens from client memory.

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 Enclave Keystore Bridging for Cryptographic Operations critical for AI coding assistants?

Enforces strict delegation of authentication tokens and cryptographic operations to native platform hardware (iOS Secure Enclave and Android Hardware-backed Keystore / StrongBox) via Capacitor 7 bridges. Prevents persistent plaintext token storage or in-memory token reconstruction in the JavaScript runtime context where it remains vulnerable to heap inspection and XSS. 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 Refresh Tokens in Web Storage or Extracting Raw Secrets into the WebView Runtime Memory) 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