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

Capacitor 7 Hardware Keystore Invalidation Recovery and Session Eviction Standard

Enforces deterministic handling of hardware-backed cryptographic key invalidations resulting from biometric enrollment changes (Android KeyPermanentlyInvalidatedException and iOS errSecAuthFailed/errSecItemNotFound) in Capacitor 7 applications. Guarantees that poisoned, invalidated keystore entries trigger atomic purge of downstream auth state, prevent infinite authentication loops, and route users through clean re-enrollment.

Prohibited Anti-Pattern: Swallowing Keystore Invalidation Errors as Transient Network or Decryption Failures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware Keystore Invalidation Recovery and Session Eviction Standard - Enforces deterministic handling of hardware-backed cryptographic key invalidations resulting from biometric enrollment changes (Android KeyPermanentlyInvalidatedException and iOS errSecAuthFailed/errSecItemNotFound) in Capacitor 7 applications. Guarantees that poisoned, invalidated keystore entries trigger atomic purge of downstream auth state, prevent infinite authentication loops, and route users through clean re-enrollment.
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}, src/auth/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-hardware-keystore-invalidation-recovery-pattern"
---

# Capacitor 7 Hardware Keystore Invalidation Recovery and Session Eviction Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Swallowing Keystore Invalidation Errors as Transient Network or Decryption Failures

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Hardware Keystore Invalidation Recovery Patterns. Hardware-backed secure storage keys (Android KeyStore with setUserAuthenticationRequired(true) and iOS Keychain with kSecAccessControlBiometryCurrentSet) are irrevocably invalidated whenever the OS detects biometric enrollment mutation (new finger/face added or removed). You must mandate deterministic detection of these platform-specific terminal invalidation codes, enforce atomic state eradication (tokens, biometric tokens, cached credentials), and prevent silent retry loops.

## Strict Guidelines
- Services MUST inspect low-level error codes from Capacitor native plugins to discriminate permanent hardware keystore invalidations (e.g., 'KeyPermanentlyInvalidatedException', 'errSecAuthFailed', 'errSecItemNotFound', OS status -25293) from recoverable user cancellations.
- Services MUST execute an atomic local session purge—purging secure storage entries, SQLite session tables, and in-memory auth caches—immediately upon detecting an invalidated hardware key.
- Code MUST NEVER retry cryptographic operations in an automatic loop when encountering a KeyPermanentlyInvalidatedException or equivalent Keychain hardware eviction.
- Engineers MUST configure Android KeyGenParameterSpec with setInvalidatedByBiometricEnrollment(true) and iOS Keychain items with kSecAccessControlBiometryCurrentSet to ensure cryptographic integrity against unauthorized biometric additions.
- Components NEVER assume secure storage failure is an offline/network error; fatal hardware security exceptions must explicitly transition the state machine to an unauthenticated, re-enrollment-required state.

## Bad vs Good Implementations
### Biometric Token Decryption and Invalidation Recovery Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Treats hardware cryptographic failures as generic recoverable errors. If biometric state mutated, Android KeyStore and iOS Keychain permanently invalidate keys. Falling back to an insecure cache or repeatedly calling the broken keystore results in unhandled native exceptions or unauthorized state retention.
```typescript
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

export async function getAuthSession(): Promise<string | null> {
  try {
    const result = await SecureStoragePlugin.get({ key: 'auth_biometric_token' });
    return result.value;
  } catch (error: any) {
    // ANTI-PATTERN: Swallowing permanent keystore invalidation as a generic fallback
    // Retrying or assuming user simply cancelled biometrics leads to app lockup
    console.warn('Failed to retrieve token, falling back to cache', error.message);
    return localStorage.getItem('cached_fallback_token');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Uses deterministic pattern matching against platform-specific hardware keystore invalidation signals. Upon detection, it forcefully unlinks the poisoned key, purges local session persistence, and halts infinite loops, requiring safe credential re-enrollment.
```typescript
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';

export interface AuthEvictionHandler {
  purgeLocalState(): Promise<void>;
  notifySessionInvalidated(reason: 'BIOMETRIC_MUTATION' | 'KEY_CORRUPTED'): Promise<void>;
}

const HARDWARE_INVALIDATION_PATTERNS = [
  'KeyPermanentlyInvalidatedException',
  'errSecAuthFailed',
  'errSecItemNotFound',
  'UNAUTHORIZED_BIOMETRIC_CHANGE',
  '-25293' // errSecAuthFailed Apple OSStatus
] as const;

export function isHardwareKeyInvalidated(error: unknown): boolean {
  if (!(error instanceof Error)) return false;
  const message = error.message ?? '';
  return HARDWARE_INVALIDATION_PATTERNS.some((pattern) => message.includes(pattern));
}

export async function getDecryptedAuthSession(evictionHandler: AuthEvictionHandler): Promise<string | null> {
  try {
    const result = await SecureStoragePlugin.get({ key: 'auth_biometric_token' });
    return result.value;
  } catch (error: unknown) {
    if (isHardwareKeyInvalidated(error)) {
      // Deterministic recovery: Purge poisoned key and downstream credentials atomically
      await SecureStoragePlugin.remove({ key: 'auth_biometric_token' }).catch(() => {});
      await evictionHandler.purgeLocalState();
      await evictionHandler.notifySessionInvalidated('BIOMETRIC_MUTATION');
      return null;
    }
    throw error; // Propagate actionable non-invalidation errors (e.g., user cancellation)
  }
}
```

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 Keystore Invalidation Recovery and Session Eviction Standard

Capacitor 7 Hardware Keystore Invalidation Recovery and Session Eviction Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic handling of hardware-backed cryptographic key invalidations resulting from biometric enrollment changes (Android KeyPermanentlyInvalidatedException and iOS errSecAuthFailed/errSecItemNotFound) in Capacitor 7 applications. Guarantees that poisoned, invalidated keystore entries trigger atomic purge of downstream auth state, prevent infinite authentication loops, and route users through clean re-enrollment. 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: Swallowing Keystore Invalidation Errors as Transient Network or Decryption Failures 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 DriftSwallowing Keystore Invalidation Errors as Transient Network or Decryption FailuresCritical
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

Services MUST inspect low-level error codes from Capacitor native plugins to discriminate permanent hardware keystore invalidations (e.g., 'KeyPermanentlyInvalidatedException', 'errSecAuthFailed', 'errSecItemNotFound', OS status -25293) from recoverable user cancellations.

Services MUST inspect low-level error codes from Capacitor native plugins to discriminate permanent hardware keystore invalidations (e.g., 'KeyPermanentlyInvalidatedException', 'errSecAuthFailed', 'errSecItemNotFound', OS status -25293) from recoverable user cancellations.

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

Services MUST execute an atomic local session purge—purging secure storage entries, SQLite session tables, and in-memory auth caches—immediately upon detecting an invalidated hardware key.

Services MUST execute an atomic local session purge—purging secure storage entries, SQLite session tables, and in-memory auth caches—immediately upon detecting an invalidated hardware 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.
3

Code MUST NEVER retry cryptographic operations in an automatic loop when encountering a KeyPermanentlyInvalidatedException or equivalent Keychain hardware eviction.

Code MUST NEVER retry cryptographic operations in an automatic loop when encountering a KeyPermanentlyInvalidatedException or equivalent Keychain hardware eviction.

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 configure Android KeyGenParameterSpec with setInvalidatedByBiometricEnrollment(true) and iOS Keychain items with kSecAccessControlBiometryCurrentSet to ensure cryptographic integrity against unauthorized biometric additions.

Engineers MUST configure Android KeyGenParameterSpec with setInvalidatedByBiometricEnrollment(true) and iOS Keychain items with kSecAccessControlBiometryCurrentSet to ensure cryptographic integrity against unauthorized biometric additions.

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 assume secure storage failure is an offline/network error

Components NEVER assume secure storage failure is an offline/network error; fatal hardware security exceptions must explicitly transition the state machine to an unauthenticated, re-enrollment-required state.

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 Keystore Invalidation Recovery and Session Eviction Standard critical for AI coding assistants?

Enforces deterministic handling of hardware-backed cryptographic key invalidations resulting from biometric enrollment changes (Android KeyPermanentlyInvalidatedException and iOS errSecAuthFailed/errSecItemNotFound) in Capacitor 7 applications. Guarantees that poisoned, invalidated keystore entries trigger atomic purge of downstream auth state, prevent infinite authentication loops, and route users through clean re-enrollment. 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 (Swallowing Keystore Invalidation Errors as Transient Network or Decryption Failures) 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