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

Hardware-Enclave Biometric Token Binding Invariant for Capacitor 7

Cryptographically tethers local authentication and refresh tokens to hardware-backed Secure Enclave or Android StrongBox key pairs requiring biometric verification. Prevents session hijacking and token exfiltration across hybrid WebViews, rooted environments, or device backup compromises.

Prohibited Anti-Pattern: Storing Bare Bearer Tokens in Hybrid Storage Without Biometric Proof-of-Possession

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Enclave Biometric Token Binding Invariant for Capacitor 7 - Cryptographically tethers local authentication and refresh tokens to hardware-backed Secure Enclave or Android StrongBox key pairs requiring biometric verification. Prevents session hijacking and token exfiltration across hybrid WebViews, rooted environments, or device backup compromises.
globs: src/auth/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-biometric-enclave-token-binding"
---

# Hardware-Enclave Biometric Token Binding Invariant for Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Storing Bare Bearer Tokens in Hybrid Storage Without Biometric Proof-of-Possession

## System Constraints
You are a Principal Mobile Security Architect enforcing cryptographic hardware token binding in Capacitor 7 hybrid applications. You must prevent session theft by ensuring all refresh operations require Proof-of-Possession (DPoP/signed nonces) derived from hardware-backed private keys stored exclusively inside Apple's Secure Enclave or Android's KeyStore/StrongBox, strictly gated by user biometrics.

## Strict Guidelines
- Engineers MUST NEVER persist raw, unbounded refresh tokens in Capacitor Preferences, LocalStorage, IndexedDB, or standard unprotected Keychain/Keystore slots.
- Engineers MUST generate an asymmetric key pair (P-256 / ES256) inside the hardware-backed Enclave/KeyStore flagged with user-presence biometric authorization requirements.
- Services MUST exchange refresh tokens only in combination with a cryptographic Proof-of-Possession signature (e.g., RFC 9449 DPoP or signed challenge nonce) computed by the hardware enclave during a verified biometric prompt.
- Clients MUST invalidate local hardware-derived credentials and flush session state immediately if KeyStore/Keychain biometric invalidation events occur (e.g., new biometric enrollment detected).
- Components NEVER execute raw OAuth token refreshes in background headless tasks if the operation bypasses biometric prompt requirements enforced by hardware access control.

## Bad vs Good Implementations
### Hardware-Enclave Biometric PoP Binding vs. Bare Capacitor Preferences

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw refresh tokens stored in Preferences can be extracted by any WebView script injection (XSS) or file-system inspection, enabling persistent session hijacking without user presence.
```typescript
import { Preferences } from '@capacitor/preferences';
import axios from 'axios';

export class AuthService {
  // VULNERABLE: Token is stored in plain SQLite/XML preferences and can be exfiltrated
  // via hybrid WebView XSS, device backup, or file-system traversal on rooted/jailbroken devices.
  async refreshSession(): Promise<string> {
    const { value: refreshToken } = await Preferences.get({ key: 'auth_refresh_token' });
    if (!refreshToken) throw new Error('No refresh token available');

    const response = await axios.post('https://api.example.com/oauth/token', {
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
    });

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

#### Production Standard (Correct)
> **Standard**: The private key never leaves the hardware Enclave. Each token refresh triggers an Enclave-gated biometric prompt to sign an ephemeral server challenge, rendering exfiltrated app storage useless to an attacker.
```typescript
import { NativeBiometricAuthEnclave } from '@/plugins/biometric-enclave';
import axios from 'axios';

export class SecureAuthService {
  private readonly tokenEndpoint = 'https://api.example.com/oauth/token';

  // HARDENED: Hardware-backed Enclave signs a cryptographic challenge requiring Biometric Auth.
  // Refresh token is useless to an attacker without the hardware-bound private key signature.
  async refreshSession(): Promise<string> {
    // 1. Fetch challenge nonce from authorization server
    const { data: challenge } = await axios.post(`${this.tokenEndpoint}/challenge`);
    
    // 2. Hardware Enclave prompts for biometrics and signs challenge (iOS Secure Enclave / Android StrongBox)
    const signature = await NativeBiometricAuthEnclave.signPayload({
      keyAlias: 'auth_device_binding_key',
      promptTitle: 'Authenticate to refresh your session',
      payload: challenge.nonce,
    });

    // 3. Exchange bound refresh token with hardware-verified signature
    const response = await axios.post(this.tokenEndpoint, {
      grant_type: 'hardware_bound_refresh',
      client_id: 'capacitor-mobile-app',
      device_key_id: signature.keyId,
      nonce: challenge.nonce,
      signature: signature.signatureBase64,
    });

    return response.data.access_token;
  }
}
```

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: Hardware-Enclave Biometric Token Binding Invariant for Capacitor 7

Hardware-Enclave Biometric Token Binding Invariant for Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Cryptographically tethers local authentication and refresh tokens to hardware-backed Secure Enclave or Android StrongBox key pairs requiring biometric verification. Prevents session hijacking and token exfiltration across hybrid WebViews, rooted environments, or device backup compromises. 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: Storing Bare Bearer Tokens in Hybrid Storage Without Biometric Proof-of-Possession 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 DriftStoring Bare Bearer Tokens in Hybrid Storage Without Biometric Proof-of-PossessionCritical
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 persist raw, unbounded refresh tokens in Capacitor Preferences, LocalStorage, IndexedDB, or standard unprotected Keychain/Keystore slots.

Engineers MUST NEVER persist raw, unbounded refresh tokens in Capacitor Preferences, LocalStorage, IndexedDB, or standard unprotected Keychain/Keystore slots.

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 generate an asymmetric key pair (P-256 / ES256) inside the hardware-backed Enclave/KeyStore flagged with user-presence biometric authorization requirements.

Engineers MUST generate an asymmetric key pair (P-256 / ES256) inside the hardware-backed Enclave/KeyStore flagged with user-presence biometric authorization requirements.

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 exchange refresh tokens only in combination with a cryptographic Proof-of-Possession signature (e.g., RFC 9449 DPoP or signed challenge nonce) computed by the hardware enclave during a verified biometric prompt.

Services MUST exchange refresh tokens only in combination with a cryptographic Proof-of-Possession signature (e.g., RFC 9449 DPoP or signed challenge nonce) computed by the hardware enclave during a verified biometric prompt.

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

Clients MUST invalidate local hardware-derived credentials and flush session state immediately if KeyStore/Keychain biometric invalidation events occur (e.g., new biometric enrollment detected).

Clients MUST invalidate local hardware-derived credentials and flush session state immediately if KeyStore/Keychain biometric invalidation events occur (e.g., new biometric enrollment detected).

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

Components NEVER execute raw OAuth token refreshes in background headless tasks if the operation bypasses biometric prompt requirements enforced by hardware access control.

Components NEVER execute raw OAuth token refreshes in background headless tasks if the operation bypasses biometric prompt requirements enforced by hardware access control.

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 Biometric Token Binding Invariant for Capacitor 7 critical for AI coding assistants?

Cryptographically tethers local authentication and refresh tokens to hardware-backed Secure Enclave or Android StrongBox key pairs requiring biometric verification. Prevents session hijacking and token exfiltration across hybrid WebViews, rooted environments, or device backup compromises. 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 (Storing Bare Bearer Tokens in Hybrid Storage Without Biometric Proof-of-Possession) 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-Enclave