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

Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Session Binding

Enforces strict cryptographic binding of hybrid web view session lifecycles to non-exportable, hardware-isolated asymmetric keypairs generated inside Apple's Secure Enclave or Android's StrongBox KeyStore. Eradicates web-layer session hijacking and token exfiltration vulnerabilities by restricting the web view context to ephemeral transaction payloads signed across the Capacitor 7 bridge via native biometric proof-of-possession.

Prohibited Anti-Pattern: Persisting Bearer Tokens in Hybrid Web Storage or Software-Emulated Keychains

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Session Binding - Enforces strict cryptographic binding of hybrid web view session lifecycles to non-exportable, hardware-isolated asymmetric keypairs generated inside Apple's Secure Enclave or Android's StrongBox KeyStore. Eradicates web-layer session hijacking and token exfiltration vulnerabilities by restricting the web view context to ephemeral transaction payloads signed across the Capacitor 7 bridge via native biometric proof-of-possession.
globs: src/**/*.{ts,tsx,js}, 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-hardware-key-attestation-enclave"
---

# Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Session Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Bearer Tokens in Hybrid Web Storage or Software-Emulated Keychains

## System Constraints
You are a Principal Mobile Security Architect enforcing Capacitor 7 Hardware-Backed Key Attestation standards. Hybrid web environments are susceptible to cross-site scripting (XSS), script injection via malformed deep links, and dynamic bridge abuse. To prevent compromise, you mandate that authentication never relies on raw bearer tokens held in the WebView (such as localStorage, IndexedDB, or WebKit memory). All session lifecycles must be authenticated using native hardware-backed ECDSA keypairs generated inside Apple Secure Enclave and Android StrongBox, leveraging DPoP (RFC 9449) or HTTP Message Signatures (RFC 9421) orchestrated across the Capacitor native boundary.

## Strict Guidelines
- Engineers MUST ALWAYS generate asymmetric ECDSA (P-256 / secp256r1) keypairs directly inside the hardware enclave using `kSecAccessControlTouchIDAny` / `kSecAccessControlBiometryAny` (iOS) or `KeyProperties.PURPOSE_SIGN` with `setIsStrongBoxBacked(true)` (Android).
- Engineers MUST NOT store long-lived bearer tokens, refresh tokens, or raw private keys in WebView-accessible storage (`localStorage`, `sessionStorage`, `IndexedDB`, or Capacitor `@capacitor/preferences`).
- Services MUST implement Demonstrating Proof-of-Possession (DPoP, RFC 9449) or HTTP Message Signatures (RFC 9421), where outgoing network payloads are signed by invoking the native Capacitor plugin bridge.
- The native bridge MUST enforce hardware-backed biometric verification (`LocalAuthentication` or `BiometricPrompt.CryptoObject`) prior to releasing private key signing operations for privileged transactions.
- Backend auth services MUST validate the native hardware attestation certificate chain (Apple App Attest / Android Key Attestation Extension) during device enrollment before trusting the enclave public key.
- Hybrid code MUST NEVER expose export methods or serialize private key material across the `CapacitorCustomPlugin` interface.

## Bad vs Good Implementations
### Vulnerable: Session Bearer Token Stored in WebView Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw bearer tokens are stored in the shared bridge preferences and injected directly into headers by the web view. An attacker exploiting an XSS vulnerability in the web application can trivially read the token via standard JavaScript or plugin bridge reflection and exfiltrate it off-device.
```typescript
import { Preferences } from '@capacitor/preferences';
import axios from 'axios';

// VULNERABLE: Direct access token storage in software preferences or localStorage
export async function executeAuthenticatedRequest(url: string, payload: unknown) {
  const { value: accessToken } = await Preferences.get({ key: 'auth_bearer_token' });
  
  // Any XSS vulnerability inside the Capacitor WebView can read 'auth_bearer_token'
  // and exfiltrate it to hijack the user's entire session.
  return axios.post(url, payload, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
    },
  });
}
```

#### Production Standard (Correct)
> **Standard**: The hybrid layer never sees or stores a bearer secret. It computes a hash of the transaction and delegates signature generation directly to the non-exportable hardware enclave via the Capacitor plugin. Even full DOM compromise cannot steal the private key.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  generateHardwareKey(options: { alias: string }): Promise<{ publicKeyJwk: string; attestationObject: string }>;
  signPayload(options: { alias: string; payloadHash: string }): Promise<{ signatureDerBase64: string }>;
}

const EnclaveAuth = registerPlugin<SecureEnclavePlugin>('SecureEnclaveAuth');

export async function executeSignedHardwareRequest(url: string, body: Record<string, unknown>) {
  const timestamp = Math.floor(Date.now() / 1000);
  const serializedBody = JSON.stringify(body);
  
  // Compute digest in web view
  const encoder = new TextEncoder();
  const data = encoder.encode(`${timestamp}:${url}:${serializedBody}`);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const payloadHash = Array.from(new Uint8Array(hashBuffer))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');

  // Delegate cryptographic signing exclusively to Apple Secure Enclave / Android StrongBox
  const { signatureDerBase64 } = await EnclaveAuth.signPayload({
    alias: 'primary_session_key',
    payloadHash,
  });

  // Non-exportable hardware key proof sent in headers; XSS cannot exfiltrate the private key
  return fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Key-Alias': 'primary_session_key',
      'X-Signature-Timestamp': timestamp.toString(),
      'X-Payload-Signature': signatureDerBase64,
    },
    body: serializedBody,
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Session Binding

Capacitor 7 Hardware-Backed Secure Enclave & StrongBox Session Binding defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cryptographic binding of hybrid web view session lifecycles to non-exportable, hardware-isolated asymmetric keypairs generated inside Apple's Secure Enclave or Android's StrongBox KeyStore. Eradicates web-layer session hijacking and token exfiltration vulnerabilities by restricting the web view context to ephemeral transaction payloads signed across the Capacitor 7 bridge via native biometric proof-of-possession. 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 Bearer Tokens in Hybrid Web Storage or Software-Emulated Keychains 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 Bearer Tokens in Hybrid Web Storage or Software-Emulated KeychainsCritical
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 generate asymmetric ECDSA (P-256 / secp256r1) keypairs directly inside the hardware enclave using `kSecAccessControlTouchIDAny` / `kSecAccessControlBiometryAny` (iOS) or `KeyProperties.PURPOSE_SIGN` with `setIsStrongBoxBacked(true)` (Android).

Engineers MUST ALWAYS generate asymmetric ECDSA (P-256 / secp256r1) keypairs directly inside the hardware enclave using `kSecAccessControlTouchIDAny` / `kSecAccessControlBiometryAny` (iOS) or `KeyProperties.PURPOSE_SIGN` with `setIsStrongBoxBacked(true)` (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 store long-lived bearer tokens, refresh tokens, or raw private keys in WebView-accessible storage (`localStorage`, `sessionStorage`, `IndexedDB`, or Capacitor `@capacitor/preferences`).

Engineers MUST NOT store long-lived bearer tokens, refresh tokens, or raw private keys in WebView-accessible storage (`localStorage`, `sessionStorage`, `IndexedDB`, or Capacitor `@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.
3

Services MUST implement Demonstrating Proof-of-Possession (DPoP, RFC 9449) or HTTP Message Signatures (RFC 9421), where outgoing network payloads are signed by invoking the native Capacitor plugin bridge.

Services MUST implement Demonstrating Proof-of-Possession (DPoP, RFC 9449) or HTTP Message Signatures (RFC 9421), where outgoing network payloads are signed by invoking the native Capacitor plugin 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.
4

The native bridge MUST enforce hardware-backed biometric verification (`LocalAuthentication` or `BiometricPrompt.CryptoObject`) prior to releasing private key signing operations for privileged transactions.

The native bridge MUST enforce hardware-backed biometric verification (`LocalAuthentication` or `BiometricPrompt.CryptoObject`) prior to releasing private key signing operations for privileged transactions.

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

Backend auth services MUST validate the native hardware attestation certificate chain (Apple App Attest / Android Key Attestation Extension) during device enrollment before trusting the enclave public key.

Backend auth services MUST validate the native hardware attestation certificate chain (Apple App Attest / Android Key Attestation Extension) during device enrollment before trusting the enclave public 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.
6

Hybrid code MUST NEVER expose export methods or serialize private key material across the `CapacitorCustomPlugin` interface.

Hybrid code MUST NEVER expose export methods or serialize private key material across the `CapacitorCustomPlugin` interface.

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 Secure Enclave & StrongBox Session Binding critical for AI coding assistants?

Enforces strict cryptographic binding of hybrid web view session lifecycles to non-exportable, hardware-isolated asymmetric keypairs generated inside Apple's Secure Enclave or Android's StrongBox KeyStore. Eradicates web-layer session hijacking and token exfiltration vulnerabilities by restricting the web view context to ephemeral transaction payloads signed across the Capacitor 7 bridge via native biometric proof-of-possession. 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 Bearer Tokens in Hybrid Web Storage or Software-Emulated Keychains) 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