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-standard

Capacitor 7 Hardware-Backed Key Attestation & Enclave Binding Standard

Enforces non-exportable, hardware-enclave cryptographic key pairs (Apple Secure Enclave and Android StrongBox/TEE) for Capacitor 7 hybrid mobile applications. Mandates backend server-nonce attestation verification and hardware-backed signing to eliminate token replay, device impersonation, and memory-dump tampering.

Prohibited Anti-Pattern: Generating Software-Synthesized Cryptographic Keys in the WebView or Storing Unattested Credentials in LocalStorage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Attestation & Enclave Binding Standard - Enforces non-exportable, hardware-enclave cryptographic key pairs (Apple Secure Enclave and Android StrongBox/TEE) for Capacitor 7 hybrid mobile applications. Mandates backend server-nonce attestation verification and hardware-backed signing to eliminate token replay, device impersonation, and memory-dump tampering.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.swift, android/app/src/main/java/**/*.java, android/app/src/main/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-key-attestation-standard"
---

# Capacitor 7 Hardware-Backed Key Attestation & Enclave Binding Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Generating Software-Synthesized Cryptographic Keys in the WebView or Storing Unattested Credentials in LocalStorage

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Hardware-Backed Key Attestation Standard. Reject all implementations that rely on software-based cryptography (WebCrypto/SubtleCrypto in the WebView) for sensitive session identity or device integrity. Mandate hardware-isolated non-exportable keys via Apple App Attest / Secure Enclave and Android StrongBox Keymaster/KeyMint with remote attestation verification.

## Strict Guidelines
- Engineers MUST ALWAYS generate cryptographic signing keys within isolated hardware (iOS Secure Enclave with DCAppAttestService or kSecAttrTokenIDSecureEnclave; Android Keystore with setIsStrongBoxBacked(true)).
- Engineers MUST NOT generate, store, or export asymmetric private keys within the WebView execution context (WebCrypto, IndexedDB, or Capacitor Preferences).
- Services MUST enforce server-driven challenge-response flows by providing a high-entropy, short-lived nonce for key attestation and payload signing.
- Engineers MUST verify the X.509 attestation certificate chain (KeyStore Attestation or Apple App Attest CBOR receipt) on the backend before trusting any client-asserted public key.
- Hybrid bridges MUST pass only raw, pre-hashed digests or high-level transaction metadata to the native enclave plugin, receiving only the detached signature.
- Components NEVER execute sensitive administrative actions without binding the request payload to an ephemeral hardware-enclave signature.

## Bad vs Good Implementations
### Hardware Enclave Attestation vs Software WebCrypto Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating extractable keys via WebCrypto exposes the private key directly to DOM-based XSS, WebView memory dumps, and backup extraction. It lacks cryptographic proof that the key was generated in a secure hardware chip (TEE/Secure Enclave), allowing attackers to clone and replay tokens.
```typescript
// BAD: Software-backed asymmetric key in WebView context; vulnerable to XSS and memory dumping
import { Preferences } from '@capacitor/preferences';

export async function authenticateSession(userId: string): Promise<string> {
  const keyPair = await window.crypto.subtle.generateKey(
    { name: 'ECDSA', namedCurve: 'P-256' },
    true, // Extractable private key allows exfiltration
    ['sign', 'verify']
  );

  const exportedKey = await window.crypto.subtle.exportKey('jwk', keyPair.privateKey);
  await Preferences.set({ key: `priv_${userId}`, value: JSON.stringify(exportedKey) });

  const payload = new TextEncoder().encode(JSON.stringify({ userId, timestamp: Date.now() }));
  const signature = await window.crypto.subtle.sign(
    { name: 'ECDSA', hash: { name: 'SHA-256' } },
    keyPair.privateKey,
    payload
  );

  return btoa(String.fromCharCode(...new Uint8Array(signature)));
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations across the Capacitor 7 bridge to native StrongBox (Android) and Secure Enclave (iOS). The private key is non-exportable and never enters the JavaScript runtime. Remote attestation chains allow backend verification of authentic physical hardware.
```typescript
// GOOD: Hardware-enclave generated, non-exportable key bound via Capacitor 7 Native Bridge
import { registerPlugin } from '@capacitor/core';

export interface AttestationPlugin {
  generateHardwareKey(options: { keyAlias: string; serverNonce: string }): Promise<{
    publicKeyDer: string;
    attestationChain: string[];
  }>;
  signDigest(options: {
    keyAlias: string;
    digestSha256Base64: string;
  }): Promise<{ signatureBase64: string }>;
}

const EnclaveAttestation = registerPlugin<AttestationPlugin>('EnclaveAttestation');

export async function initializeHardwareSession(userId: string, serverNonce: string): Promise<{
  publicKeyDer: string;
  attestationChain: string[];
}> {
  // Key generation strictly delegated to native StrongBox / Secure Enclave
  const result = await EnclaveAttestation.generateHardwareKey({
    keyAlias: `user_enclave_${userId}`,
    serverNonce,
  });

  return result;
}

export async function signSessionPayload(userId: string, payload: Record<string, unknown>): Promise<string> {
  const data = new TextEncoder().encode(JSON.stringify(payload));
  const hashBuffer = await window.crypto.subtle.digest('SHA-256', data);
  const digestSha256Base64 = btoa(String.fromCharCode(...new Uint8Array(hashBuffer)));

  const { signatureBase64 } = await EnclaveAttestation.signDigest({
    keyAlias: `user_enclave_${userId}`,
    digestSha256Base64,
  });

  return signatureBase64;
}
```

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 Hardware-Backed Key Attestation & Enclave Binding Standard

Capacitor 7 Hardware-Backed Key Attestation & Enclave Binding Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces non-exportable, hardware-enclave cryptographic key pairs (Apple Secure Enclave and Android StrongBox/TEE) for Capacitor 7 hybrid mobile applications. Mandates backend server-nonce attestation verification and hardware-backed signing to eliminate token replay, device impersonation, and memory-dump tampering. 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: Generating Software-Synthesized Cryptographic Keys in the WebView or Storing Unattested Credentials in LocalStorage 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 DriftGenerating Software-Synthesized Cryptographic Keys in the WebView or Storing Unattested Credentials in LocalStorageCritical
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 cryptographic signing keys within isolated hardware (iOS Secure Enclave with DCAppAttestService or kSecAttrTokenIDSecureEnclave

Engineers MUST ALWAYS generate cryptographic signing keys within isolated hardware (iOS Secure Enclave with DCAppAttestService or kSecAttrTokenIDSecureEnclave; Android Keystore with setIsStrongBoxBacked(true)).

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 generate, store, or export asymmetric private keys within the WebView execution context (WebCrypto, IndexedDB, or Capacitor Preferences).

Engineers MUST NOT generate, store, or export asymmetric private keys within the WebView execution context (WebCrypto, IndexedDB, or 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 enforce server-driven challenge-response flows by providing a high-entropy, short-lived nonce for key attestation and payload signing.

Services MUST enforce server-driven challenge-response flows by providing a high-entropy, short-lived nonce for key attestation and payload signing.

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

Engineers MUST verify the X.509 attestation certificate chain (KeyStore Attestation or Apple App Attest CBOR receipt) on the backend before trusting any client-asserted public key.

Engineers MUST verify the X.509 attestation certificate chain (KeyStore Attestation or Apple App Attest CBOR receipt) on the backend before trusting any client-asserted 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.
5

Hybrid bridges MUST pass only raw, pre-hashed digests or high-level transaction metadata to the native enclave plugin, receiving only the detached signature.

Hybrid bridges MUST pass only raw, pre-hashed digests or high-level transaction metadata to the native enclave plugin, receiving only the detached signature.

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

Components NEVER execute sensitive administrative actions without binding the request payload to an ephemeral hardware-enclave signature.

Components NEVER execute sensitive administrative actions without binding the request payload to an ephemeral hardware-enclave signature.

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 Key Attestation & Enclave Binding Standard critical for AI coding assistants?

Enforces non-exportable, hardware-enclave cryptographic key pairs (Apple Secure Enclave and Android StrongBox/TEE) for Capacitor 7 hybrid mobile applications. Mandates backend server-nonce attestation verification and hardware-backed signing to eliminate token replay, device impersonation, and memory-dump tampering. 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 (Generating Software-Synthesized Cryptographic Keys in the WebView or Storing Unattested Credentials in LocalStorage) 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