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

Capacitor 7 Secure Enclave Hardware-Attested Token Binding Guardrail

Enforces hardware-backed cryptographic token binding across the Capacitor 7 JavaScript-to-Native bridge. Mandates that authentication sessions derive from non-extractable Secure Enclave/Android Keystore asymmetric keys gated by biometric prompts, preventing session hijacking via malicious WebView inspection, cross-site scripting (XSS), or compromised local storage.

Prohibited Anti-Pattern: Persisting Raw Bearer Tokens in WebView Storage Without Hardware-Backed Cryptographic Attestation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Secure Enclave Hardware-Attested Token Binding Guardrail - Enforces hardware-backed cryptographic token binding across the Capacitor 7 JavaScript-to-Native bridge. Mandates that authentication sessions derive from non-extractable Secure Enclave/Android Keystore asymmetric keys gated by biometric prompts, preventing session hijacking via malicious WebView inspection, cross-site scripting (XSS), or compromised local storage.
globs: src/**/*.{ts,tsx}, 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-biometric-enclave-attestation-standard"
---

# Capacitor 7 Secure Enclave Hardware-Attested Token Binding Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Raw Bearer Tokens in WebView Storage Without Hardware-Backed Cryptographic Attestation

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware token binding in Capacitor 7 applications. You must ensure that no authentication bearer tokens or cryptographic private keys reside in the Capacitor WebView context (localStorage, IndexedDB, or standard Preferences). All API requests requiring authentication must be signed using non-extractable Secure Enclave or Android StrongBox-backed private keys via a native plugin bridge enforcing UserAuthenticationValidity.

## Strict Guidelines
- Engineers MUST ALWAYS store private cryptographic keys exclusively inside iOS Secure Enclave or Android StrongBox/Keystore with non-exportable flags.
- Engineers MUST NOT store raw bearer tokens or refresh tokens in WebView-accessible storage (such as window.localStorage, window.sessionStorage, or standard IndexedDB).
- Services MUST implement Demonstrating Proof-of-Possession (DPoP) or asymmetric request signing via native bridge calls before dispatching sensitive API requests.
- Native plugins MUST enforce biometric evaluation (`kSecAccessControlBiometryAny` or `KeyProperties.AUTH_BIOMETRIC_STRONG`) with explicit user verification timeouts for sensitive signing operations.
- The WebView client MUST transmit hardware-attestation certificates (Apple App Attest or Android Key Attestation) during key enrollment to prove key enclave residency to the backend auth server.

## Bad vs Good Implementations
### Hardware-Attested Request Signing vs Insecure Local Storage Bearer Token

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing static bearer tokens in unencrypted or software-accessible WebView storage allows cross-context session hijacking if any third-party script, dependency injection, or XSS vulnerability is exploited within the Capacitor WebView.
```typescript
import { Preferences } from '@capacitor/preferences';

export async function authenticatedFetch(url: string, options: RequestInit = {}): Promise<Response> {
  // ANTI-PATTERN: Raw bearer token stored in WebView-accessible preferences
  const { value: token } = await Preferences.get({ key: 'auth_bearer_token' });
  
  if (!token) {
    throw new Error('Unauthenticated user session');
  }

  // Token can be intercepted by XSS, bridge reflection, or backup extraction
  return fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      'Authorization': `Bearer ${token}`
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: The cryptographic private key is provisioned exclusively in the hardware Secure Enclave. The WebView communicates only payload hashes across the native bridge, and the hardware signs the payload with biometric authorization. Session tokens stolen from network or storage cannot be replayed without physical hardware access.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  signPayload(options: { alias: string; payload: string; prompt: string }): Promise<{ signature: string; keyId: string }>;
}

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

export async function authenticatedFetch(url: string, options: RequestInit = {}): Promise<Response> {
  const method = options.method?.toUpperCase() || 'GET';
  const timestamp = Date.now().toString();
  const nonce = crypto.randomUUID();
  
  // Hardware-bound invariant: Private key never touches WebView runtime memory
  const payloadToSign = `${method}:${url}:${timestamp}:${nonce}`;
  
  const { signature, keyId } = await EnclaveSigner.signPayload({
    alias: 'identity_key_sec_p256',
    payload: payloadToSign,
    prompt: 'Authenticate to authorize this transaction'
  });

  return fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      'X-Attested-Key-ID': keyId,
      'X-Attested-Timestamp': timestamp,
      'X-Attested-Nonce': nonce,
      'X-Attested-Signature': signature
    }
  });
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Secure Enclave Hardware-Attested Token Binding Guardrail

Capacitor 7 Secure Enclave Hardware-Attested Token Binding Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed cryptographic token binding across the Capacitor 7 JavaScript-to-Native bridge. Mandates that authentication sessions derive from non-extractable Secure Enclave/Android Keystore asymmetric keys gated by biometric prompts, preventing session hijacking via malicious WebView inspection, cross-site scripting (XSS), or compromised local storage. 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 Raw Bearer Tokens in WebView Storage Without Hardware-Backed Cryptographic Attestation 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 Raw Bearer Tokens in WebView Storage Without Hardware-Backed Cryptographic AttestationCritical
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 store private cryptographic keys exclusively inside iOS Secure Enclave or Android StrongBox/Keystore with non-exportable flags.

Engineers MUST ALWAYS store private cryptographic keys exclusively inside iOS Secure Enclave or Android StrongBox/Keystore with non-exportable flags.

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 raw bearer tokens or refresh tokens in WebView-accessible storage (such as window.localStorage, window.sessionStorage, or standard IndexedDB).

Engineers MUST NOT store raw bearer tokens or refresh tokens in WebView-accessible storage (such as window.localStorage, window.sessionStorage, or standard IndexedDB).

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) or asymmetric request signing via native bridge calls before dispatching sensitive API requests.

Services MUST implement Demonstrating Proof-of-Possession (DPoP) or asymmetric request signing via native bridge calls before dispatching sensitive API requests.

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 biometric evaluation (`kSecAccessControlBiometryAny` or `KeyProperties.AUTH_BIOMETRIC_STRONG`) with explicit user verification timeouts for sensitive signing operations.

Native plugins MUST enforce biometric evaluation (`kSecAccessControlBiometryAny` or `KeyProperties.AUTH_BIOMETRIC_STRONG`) with explicit user verification timeouts for sensitive signing operations.

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 client MUST transmit hardware-attestation certificates (Apple App Attest or Android Key Attestation) during key enrollment to prove key enclave residency to the backend auth server.

The WebView client MUST transmit hardware-attestation certificates (Apple App Attest or Android Key Attestation) during key enrollment to prove key enclave residency to the backend auth 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 Enclave Hardware-Attested Token Binding Guardrail critical for AI coding assistants?

Enforces hardware-backed cryptographic token binding across the Capacitor 7 JavaScript-to-Native bridge. Mandates that authentication sessions derive from non-extractable Secure Enclave/Android Keystore asymmetric keys gated by biometric prompts, preventing session hijacking via malicious WebView inspection, cross-site scripting (XSS), or compromised local storage. 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 Raw Bearer Tokens in WebView Storage Without Hardware-Backed Cryptographic Attestation) 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