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

Capacitor 7 Secure Hardware Keystore and Key Attestation Bridge Invariant

Enforces non-exportable hardware-backed key isolation across the Capacitor 7 JavaScript-to-Native bridge. Mandates that private cryptographic keys residing in Android Keystore (StrongBox/TEE) and Apple Secure Enclave are strictly non-extractable, exposing only opaque key aliases, cryptographic challenges, and public attestation certificate chains to the WebView JavaScript runtime.

Prohibited Anti-Pattern: Exposing Raw Private Keys or Symmetric Secrets Across the Capacitor Bridge to the WebView Context

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Hardware Keystore and Key Attestation Bridge Invariant - Enforces non-exportable hardware-backed key isolation across the Capacitor 7 JavaScript-to-Native bridge. Mandates that private cryptographic keys residing in Android Keystore (StrongBox/TEE) and Apple Secure Enclave are strictly non-extractable, exposing only opaque key aliases, cryptographic challenges, and public attestation certificate chains to the WebView JavaScript runtime.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.kt, 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-7-hardware-keystore-attestation-bridge-invariant"
---

# Capacitor 7 Secure Hardware Keystore and Key Attestation Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Private Keys or Symmetric Secrets Across the Capacitor Bridge to the WebView Context

## System Constraints
You are a Principal Mobile Security Architect enforcing the Capacitor 7 Hardware-Backed Key Attestation Bridge Invariant. You must reject any code that transmits raw private keys, unencrypted symmetric seed material, or non-attested key references across the Capacitor JavaScript bridge. All signing and decryption operations MUST occur exclusively within the native hardware perimeter (Android StrongBox/TEE KeyStore or iOS Secure Enclave). Only opaque key aliases, cryptographic operation identifiers, DER-encoded public keys, and attestation certificate chains may cross into the WebView.

## Strict Guidelines
- Engineers MUST ALWAYS mark native key generation specifications with `setUserAuthenticationRequired`, `setIsStrongBoxBacked(true)` (Android), or `kSecAccessControlPrivateKeyUsage` with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` (iOS) to strictly prevent key extraction.
- Engineers MUST NEVER return private key material, PKCS#8 blobs, or raw seed bytes in `JSObject` or `PluginCall.resolve()` payloads.
- The JavaScript Capacitor interface MUST ONLY accept cryptographic challenges and opaque key aliases (`keyAlias: string`), returning detached signatures or server-verifiable X.509 attestation certificate chains.
- Native plugins MUST enforce challenge-response nonces generated by the relying-party backend to mitigate replay attacks against hardware key attestation records.
- The WebView execution layer MUST treat all returned signatures and attestations as untrusted until verified by the remote backend server.

## Bad vs Good Implementations
### Hardware Key Signing via Capacitor Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting private key material into the WebView JavaScript execution context subjects cryptographic secrets to DOM-based XSS, unauthorized inspection via remote debugging, memory scraping, and malicious script injection.
```typescript
import { registerPlugin } from '@capacitor/core';

interface InsecureCryptoPlugin {
  exportPrivateKey(options: { alias: string }): Promise<{ privateKeyPem: string }>;
  signLocally(options: { privateKeyPem: string; data: string }): Promise<{ signature: string }>;
}

const InsecureCrypto = registerPlugin<InsecureCryptoPlugin>('InsecureCrypto');

export async function signPayloadInsecurely(alias: string, payload: string): Promise<string> {
  // CRITICAL SECURITY VIOLATION: Private key is extracted across the bridge into WebView memory
  const { privateKeyPem } = await InsecureCrypto.exportPrivateKey({ alias });
  const { signature } = await InsecureCrypto.signLocally({ privateKeyPem, data: payload });
  return signature;
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to the Hardware-Backed Bridge Invariant by ensuring the key is non-extractable. Native StrongBox/Secure Enclave hardware executes the cryptographic signature, returning only the detached signature across the Capacitor bridge.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface AttestationResult {
  alias: string;
  certificateChain: string[]; // Base64 DER X.509 attestation certificates
  publicKey: string;          // Base64 DER SubjectPublicKeyInfo
}

export interface SecureSignRequest {
  alias: string;
  challenge: string;          // Cryptographic server nonce
  dataToSign: string;         // SHA-256 digest in hex/base64
}

export interface SecureSignResult {
  signature: string;          // Base64 DER-encoded ECDSA signature
}

export interface SecureKeyBridgePlugin {
  generateAttestedHardwareKey(options: { alias: string; attestationChallenge: string }): Promise<AttestationResult>;
  signWithHardwareKey(options: SecureSignRequest): Promise<SecureSignResult>;
}

export const SecureKeyBridge = registerPlugin<SecureKeyBridgePlugin>('SecureKeyBridge');

export async function performAttestedSign(
  alias: string,
  challenge: string,
  digest: string
): Promise<string> {
  // Private key never leaves Android StrongBox KeyStore or Apple Secure Enclave.
  // WebView only supplies the payload digest and receives the detached hardware-signed assertion.
  const result = await SecureKeyBridge.signWithHardwareKey({
    alias,
    challenge,
    dataToSign: digest,
  });
  return result.signature;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Hardware Keystore and Key Attestation Bridge Invariant

Capacitor 7 Secure Hardware Keystore and Key Attestation Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces non-exportable hardware-backed key isolation across the Capacitor 7 JavaScript-to-Native bridge. Mandates that private cryptographic keys residing in Android Keystore (StrongBox/TEE) and Apple Secure Enclave are strictly non-extractable, exposing only opaque key aliases, cryptographic challenges, and public attestation certificate chains to the WebView JavaScript runtime. 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 Private Keys or Symmetric Secrets Across the Capacitor Bridge to the WebView Context 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 Private Keys or Symmetric Secrets Across the Capacitor Bridge to the WebView ContextCritical
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 mark native key generation specifications with `setUserAuthenticationRequired`, `setIsStrongBoxBacked(true)` (Android), or `kSecAccessControlPrivateKeyUsage` with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` (iOS) to strictly prevent key extraction.

Engineers MUST ALWAYS mark native key generation specifications with `setUserAuthenticationRequired`, `setIsStrongBoxBacked(true)` (Android), or `kSecAccessControlPrivateKeyUsage` with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` (iOS) to strictly prevent key extraction.

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 private key material, PKCS#8 blobs, or raw seed bytes in `JSObject` or `PluginCall.resolve()` payloads.

Engineers MUST NEVER return private key material, PKCS#8 blobs, or raw seed bytes in `JSObject` or `PluginCall.resolve()` payloads.

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

The JavaScript Capacitor interface MUST ONLY accept cryptographic challenges and opaque key aliases (`keyAlias

The JavaScript Capacitor interface MUST ONLY accept cryptographic challenges and opaque key aliases (`keyAlias: string`), returning detached signatures or server-verifiable X.509 attestation certificate chains.

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

Native plugins MUST enforce challenge-response nonces generated by the relying-party backend to mitigate replay attacks against hardware key attestation records.

Native plugins MUST enforce challenge-response nonces generated by the relying-party backend to mitigate replay attacks against hardware key attestation records.

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

The WebView execution layer MUST treat all returned signatures and attestations as untrusted until verified by the remote backend server.

The WebView execution layer MUST treat all returned signatures and attestations as untrusted until verified by the remote backend server.

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 Hardware Keystore and Key Attestation Bridge Invariant critical for AI coding assistants?

Enforces non-exportable hardware-backed key isolation across the Capacitor 7 JavaScript-to-Native bridge. Mandates that private cryptographic keys residing in Android Keystore (StrongBox/TEE) and Apple Secure Enclave are strictly non-extractable, exposing only opaque key aliases, cryptographic challenges, and public attestation certificate chains to the WebView JavaScript runtime. 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 Private Keys or Symmetric Secrets Across the Capacitor Bridge to the WebView Context) 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