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

Capacitor 7 Hardware-Backed Key Attestation and Session Binding Standard

Binds mobile JWT refresh sessions to hardware-backed cryptographic keys generated inside the Apple Secure Enclave or Android StrongBox/TEE Keystore. Mandates client-side Demonstrating Proof of Possession (DPoP) or challenge-response assertion signing inside isolated hardware, rendering exfiltrated refresh tokens mathematically unusable by adversaries.

Prohibited Anti-Pattern: Persisting Raw Bearer Refresh Tokens in WebView Storage or Software-Only Keychains Without Enclave Proof-of-Possession

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed Key Attestation and Session Binding Standard - Binds mobile JWT refresh sessions to hardware-backed cryptographic keys generated inside the Apple Secure Enclave or Android StrongBox/TEE Keystore. Mandates client-side Demonstrating Proof of Possession (DPoP) or challenge-response assertion signing inside isolated hardware, rendering exfiltrated refresh tokens mathematically unusable by adversaries.
globs: src/auth/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/interceptors/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-attestation-session-invariant"
---

# Capacitor 7 Hardware-Backed Key Attestation and Session Binding Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Persisting Raw Bearer Refresh Tokens in WebView Storage or Software-Only Keychains Without Enclave Proof-of-Possession

## System Constraints
You are a Principal Security Architect enforcing Capacitor 7 hardware-backed cryptographic security invariants. You must prevent token exfiltration attacks by ensuring mobile clients never rely on raw, software-accessible bearer refresh tokens. Enforce that all session refreshing operations require non-exportable asymmetric cryptographic signatures directly generated inside the device Secure Enclave or Android StrongBox/TEE.

## Strict Guidelines
- Engineers MUST ALWAYS generate asymmetric key pairs (P-256 / secp256r1) with private keys designated as non-exportable and bound strictly to Apple Secure Enclave or Android KeyStore StrongBox.
- Engineers MUST NOT store raw refresh tokens or private signing keys in localStorage, IndexedDB, Capacitor Preferences, or software-encrypted SQLite databases.
- Code SHOULD verify hardware attestation certificates (Apple App Attest / Android Key Attestation) on the authentication server during initial enrollment before accepting device-bound public keys.
- Services MUST generate an RFC 9449 DPoP (Demonstrating Proof-of-Possession) proof or signed nonce challenge using the hardware-isolated private key for every token refresh request.
- Components NEVER expose private keys to the JavaScript WebView context; all cryptographic signing operations MUST be proxied through native Capacitor 7 plugin calls directly to native security APIs.

## Bad vs Good Implementations
### Hardware Enclave Session Refresh vs Insecure Software Bearer Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Stores unprotected bearer refresh tokens inside Capacitor Preferences. If the device is jailbroken, rooted, or compromised by malware, the token can be exfiltrated and replayed from any unauthorized machine without requiring proof of device possession.
```typescript
import { Preferences } from '@capacitor/preferences';

interface SessionResponse {
  accessToken: string;
  refreshToken: string;
}

export async function refreshSessionInsecure(): Promise<string> {
  // Flaw: Storing raw bearer tokens in standard preferences enables
  // complete session hijacking via filesystem access, backup extraction, or rooted memory dumps.
  const { value: refreshToken } = await Preferences.get({ key: 'auth_refresh_token' });
  if (!refreshToken) {
    throw new Error('No refresh token available');
  }

  const response = await fetch('https://api.example.com/auth/refresh', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refreshToken })
  });

  if (!response.ok) throw new Error('Session refresh failed');
  const data: SessionResponse = await response.json();
  
  await Preferences.set({ key: 'auth_refresh_token', value: data.refreshToken });
  return data.accessToken;
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations to hardware-backed secure modules. The private key cannot be extracted even on compromised devices. Refreshing requires an enclave-signed assertion over an ephemeral challenge nonce, neutralizing token exfiltration.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  signChallenge(options: { alias: string; payload: string }): Promise<{ signature: string; publicKey: string }>;
}

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

interface HardwareBoundRefreshRequest {
  sessionHandle: string;
  clientAssertion: string;
  nonce: string;
}

interface AuthTokens {
  accessToken: string;
}

export async function refreshHardwareBoundSession(
  sessionHandle: string,
  authServerUrl: string
): Promise<string> {
  // 1. Fetch ephemeral server nonce to prevent replay attacks
  const nonceResponse = await fetch(`${authServerUrl}/auth/challenge`, { method: 'POST' });
  if (!nonceResponse.ok) throw new Error('Challenge generation failed');
  const { nonce } = (await nonceResponse.json()) as { nonce: string };

  // 2. Delegate assertion signing to native hardware (Secure Enclave / StrongBox)
  // JavaScript never sees the private key; signature is computed in silicon.
  const payloadToSign = `${sessionHandle}:${nonce}:${Date.now()}`;
  const { signature } = await SecureEnclave.signChallenge({
    alias: 'primary_auth_key',
    payload: payloadToSign
  });

  // 3. Exchange hardware-signed assertion for short-lived access token
  const refreshResponse = await fetch(`${authServerUrl}/auth/hardware-refresh`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Device-Nonce': nonce
    },
    body: JSON.stringify({
      sessionHandle,
      clientAssertion: signature,
      nonce
    } satisfies HardwareBoundRefreshRequest)
  });

  if (!refreshResponse.ok) throw new Error('Hardware-bound session refresh rejected');
  const { accessToken } = (await refreshResponse.json()) as AuthTokens;
  return accessToken;
}
```

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 and Session Binding Standard

Capacitor 7 Hardware-Backed Key Attestation and Session Binding Standard defines an industrial-grade behavioral standard for security engineering. Binds mobile JWT refresh sessions to hardware-backed cryptographic keys generated inside the Apple Secure Enclave or Android StrongBox/TEE Keystore. Mandates client-side Demonstrating Proof of Possession (DPoP) or challenge-response assertion signing inside isolated hardware, rendering exfiltrated refresh tokens mathematically unusable by adversaries. 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 Refresh Tokens in WebView Storage or Software-Only Keychains Without Enclave 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 DriftPersisting Raw Bearer Refresh Tokens in WebView Storage or Software-Only Keychains Without Enclave 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 ALWAYS generate asymmetric key pairs (P-256 / secp256r1) with private keys designated as non-exportable and bound strictly to Apple Secure Enclave or Android KeyStore StrongBox.

Engineers MUST ALWAYS generate asymmetric key pairs (P-256 / secp256r1) with private keys designated as non-exportable and bound strictly to Apple Secure Enclave or Android KeyStore StrongBox.

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 refresh tokens or private signing keys in localStorage, IndexedDB, Capacitor Preferences, or software-encrypted SQLite databases.

Engineers MUST NOT store raw refresh tokens or private signing keys in localStorage, IndexedDB, Capacitor Preferences, or software-encrypted SQLite databases.

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

Code SHOULD verify hardware attestation certificates (Apple App Attest / Android Key Attestation) on the authentication server during initial enrollment before accepting device-bound public keys.

Code SHOULD verify hardware attestation certificates (Apple App Attest / Android Key Attestation) on the authentication server during initial enrollment before accepting device-bound public keys.

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

Services MUST generate an RFC 9449 DPoP (Demonstrating Proof-of-Possession) proof or signed nonce challenge using the hardware-isolated private key for every token refresh request.

Services MUST generate an RFC 9449 DPoP (Demonstrating Proof-of-Possession) proof or signed nonce challenge using the hardware-isolated private key for every token refresh request.

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 expose private keys to the JavaScript WebView context

Components NEVER expose private keys to the JavaScript WebView context; all cryptographic signing operations MUST be proxied through native Capacitor 7 plugin calls directly to native security APIs.

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 and Session Binding Standard critical for AI coding assistants?

Binds mobile JWT refresh sessions to hardware-backed cryptographic keys generated inside the Apple Secure Enclave or Android StrongBox/TEE Keystore. Mandates client-side Demonstrating Proof of Possession (DPoP) or challenge-response assertion signing inside isolated hardware, rendering exfiltrated refresh tokens mathematically unusable by adversaries. 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 Refresh Tokens in WebView Storage or Software-Only Keychains Without Enclave 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.

1 Rule in Stack

Capacitor