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

Capacitor 7 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard

Capacitor 7 enforces strict bridge lifecycle contracts, asynchronous native plugin interop, and mandatory Android 15 edge-to-edge window inset handling. Storing sensitive authentication tokens in unencrypted web storage or failing to bind biometric authentication directly to hardware-backed Keystore or Secure Enclave mechanisms compromises app integrity and causes fatal crash or viewport occlusion issues on modern mobile operating systems.

Prohibited Anti-Pattern: Persisting biometrically gated tokens in plaintext Web Storage or CapacitorPreferences while ignoring Android 15 edge-to-edge safe area occlusion.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard - Capacitor 7 enforces strict bridge lifecycle contracts, asynchronous native plugin interop, and mandatory Android 15 edge-to-edge window inset handling. Storing sensitive authentication tokens in unencrypted web storage or failing to bind biometric authentication directly to hardware-backed Keystore or Secure Enclave mechanisms compromises app integrity and causes fatal crash or viewport occlusion issues on modern mobile operating systems.
globs: src/**/*.{ts,tsx,vue,svelte}, android/app/src/main/res/values/styles.xml, android/app/src/main/AndroidManifest.xml, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-biometric-auth-production-standard"
---

# Capacitor 7 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting biometrically gated tokens in plaintext Web Storage or CapacitorPreferences while ignoring Android 15 edge-to-edge safe area occlusion.

## System Constraints
You are a Principal Mobile Architect specializing in Capacitor 7 native bridges, hardware-backed biometric security, and Android 15 / iOS 18 system constraints. You MUST enforce secure enclave storage for sensitive tokens, ensure full edge-to-edge viewport conformance, and guarantee all native bridge listeners are properly deregistered to prevent memory leaks and thread exhaustion.

## Strict Guidelines
- Tokens gated by biometrics MUST ALWAYS be stored in hardware-backed Secure Enclave or Android KeyStore using native secure storage plugins, and MUST NEVER be written to localStorage, IndexedDB, or standard CapacitorPreferences.
- Applications running on Capacitor 7 with Android 15 target SDK MUST accommodate forced edge-to-edge rendering by consuming CSS env(safe-area-inset-*) or the native safe-area plugin to prevent UI occlusion behind navigation bars.
- Biometric challenge invocations MUST explicitly handle cancellation error codes (UserCancel, SystemCancel, BiometricsLockedOut) and MUST NOT block the WebView main thread or throw uncaught promise rejections.
- Native plugin listeners (such as App.addListener for lifecycle events) MUST be tracked and explicitly removed via PluginListenerHandle.remove() upon component or service unmount.
- Capacitor bridge calls executed across native boundaries SHOULD validate input and output payloads using runtime schemas to avoid native deserialization crashes.

## Bad vs Good Implementations
### Hardware-Backed Biometric Authentication & Secure Storage with Lifecycle Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing sensitive session credentials in CapacitorPreferences or localStorage places them in unencrypted XML/plist/WebStorage files easily read on rooted/jailbroken devices. It bypasses hardware-backed biometrics entirely and ignores Android 15 lifecycle requirements.
```typescript
import { Preferences } from '@capacitor/preferences';

// ANTI-PATTERN: Insecure token handling and unhandled promise cancellation
export async function authenticateUser(jwtToken: string) {
  // Insecure: Pretends to prompt or ignores native biometric verification
  // Insecure: Persists plain-text tokens into SharedPreferences/UserDefaults
  await Preferences.set({
    key: 'auth_token',
    value: jwtToken,
  });
  localStorage.setItem('session_active', 'true');
}
```

#### Production Standard (Correct)
> **Standard**: Verifies hardware biometric availability, triggers native system prompts while intercepting cancellation signals without crashing, persists tokens into hardware-backed Secure Enclave / Android KeyStore, and manages Capacitor 7 lifecycle listeners with deterministic cleanup.
```typescript
import { NativeBiometric } from 'capacitor-native-biometric';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';
import { App, PluginListenerHandle } from '@capacitor/app';

const SECURE_TOKEN_KEY = 'auth_token_enclave';

export class BiometricSessionManager {
  private appStateHandle: PluginListenerHandle | null = null;

  public async initialize(): Promise<void> {
    this.appStateHandle = await App.addListener('appStateChange', (state) => {
      if (!state.isActive) {
        // Minimize risk by sanitizing in-memory sensitive variables on backgrounding
        this.onAppBackgrounded();
      }
    });
  }

  public async authenticateAndStore(token: string): Promise<boolean> {
    const availability = await NativeBiometric.isAvailable();
    if (!availability.isAvailable) {
      throw new Error('Biometric hardware is unavailable or not enrolled.');
    }

    try {
      await NativeBiometric.verifyIdentity({
        reason: 'Authenticate to access secure enclave session',
        title: 'Biometric Authentication',
        subtitle: 'Verify identity to store access token',
        description: 'Touch sensor or face scan required',
        maxAttempts: 3,
      });

      await SecureStoragePlugin.set({
        key: SECURE_TOKEN_KEY,
        value: token,
      });
      return true;
    } catch (error: unknown) {
      const err = error as { code?: string; message?: string };
      if (err.code === 'USER_CANCEL' || err.code === 'SYSTEM_CANCEL') {
        return false;
      }
      throw new Error(`Biometric verification failed: ${err.message ?? 'Unknown'}`);
    }
  }

  private onAppBackgrounded(): void {
    // Application background handler logic
  }

  public async destroy(): Promise<void> {
    if (this.appStateHandle) {
      await this.appStateHandle.remove();
      this.appStateHandle = null;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard

Capacitor 7 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard defines an industrial-grade behavioral standard for mobile engineering. Capacitor 7 enforces strict bridge lifecycle contracts, asynchronous native plugin interop, and mandatory Android 15 edge-to-edge window inset handling. Storing sensitive authentication tokens in unencrypted web storage or failing to bind biometric authentication directly to hardware-backed Keystore or Secure Enclave mechanisms compromises app integrity and causes fatal crash or viewport occlusion issues on modern mobile operating systems. 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 biometrically gated tokens in plaintext Web Storage or CapacitorPreferences while ignoring Android 15 edge-to-edge safe area occlusion. 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 biometrically gated tokens in plaintext Web Storage or CapacitorPreferences while ignoring Android 15 edge-to-edge safe area occlusion.Critical
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

Tokens gated by biometrics MUST ALWAYS be stored in hardware-backed Secure Enclave or Android KeyStore using native secure storage plugins, and MUST NEVER be written to localStorage, IndexedDB, or standard CapacitorPreferences.

Tokens gated by biometrics MUST ALWAYS be stored in hardware-backed Secure Enclave or Android KeyStore using native secure storage plugins, and MUST NEVER be written to localStorage, IndexedDB, or standard CapacitorPreferences.

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

Applications running on Capacitor 7 with Android 15 target SDK MUST accommodate forced edge-to-edge rendering by consuming CSS env(safe-area-inset-*) or the native safe-area plugin to prevent UI occlusion behind navigation bars.

Applications running on Capacitor 7 with Android 15 target SDK MUST accommodate forced edge-to-edge rendering by consuming CSS env(safe-area-inset-*) or the native safe-area plugin to prevent UI occlusion behind navigation bars.

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

Biometric challenge invocations MUST explicitly handle cancellation error codes (UserCancel, SystemCancel, BiometricsLockedOut) and MUST NOT block the WebView main thread or throw uncaught promise rejections.

Biometric challenge invocations MUST explicitly handle cancellation error codes (UserCancel, SystemCancel, BiometricsLockedOut) and MUST NOT block the WebView main thread or throw uncaught promise rejections.

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 plugin listeners (such as App.addListener for lifecycle events) MUST be tracked and explicitly removed via PluginListenerHandle.remove() upon component or service unmount.

Native plugin listeners (such as App.addListener for lifecycle events) MUST be tracked and explicitly removed via PluginListenerHandle.remove() upon component or service unmount.

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

Capacitor bridge calls executed across native boundaries SHOULD validate input and output payloads using runtime schemas to avoid native deserialization crashes.

Capacitor bridge calls executed across native boundaries SHOULD validate input and output payloads using runtime schemas to avoid native deserialization crashes.

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 Native Bridge, Biometric Auth & Android 15 Lifecycle Production Standard critical for AI coding assistants?

Capacitor 7 enforces strict bridge lifecycle contracts, asynchronous native plugin interop, and mandatory Android 15 edge-to-edge window inset handling. Storing sensitive authentication tokens in unencrypted web storage or failing to bind biometric authentication directly to hardware-backed Keystore or Secure Enclave mechanisms compromises app integrity and causes fatal crash or viewport occlusion issues on modern mobile operating systems. 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 biometrically gated tokens in plaintext Web Storage or CapacitorPreferences while ignoring Android 15 edge-to-edge safe area occlusion.) 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