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

Capacitor 7 Native Bridge Invariants, Hardware Keystore, and Android 15 Edge-to-Edge

Enforces strict lifecycle management for Capacitor 7 native bridges, hardware-backed Keystore/Secure Enclave token persistence, and Android 15 edge-to-edge layout constraints. Prevents memory leaks from uncleaned plugin listeners, token exposure in unencrypted WebStorage, and UI occlusions caused by mandatory window insets.

Prohibited Anti-Pattern: Persisting Session Tokens in Web Storage and Leaking Capacitor Plugin Listeners Under Android 15 Insets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native Bridge Invariants, Hardware Keystore, and Android 15 Edge-to-Edge - Enforces strict lifecycle management for Capacitor 7 native bridges, hardware-backed Keystore/Secure Enclave token persistence, and Android 15 edge-to-edge layout constraints. Prevents memory leaks from uncleaned plugin listeners, token exposure in unencrypted WebStorage, and UI occlusions caused by mandatory window insets.
globs: src/**/*.{ts,tsx}, android/app/src/main/**/*.{java,kt}, ios/App/App/**/*.{swift,m}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-bridge-biometric-auth"
---

# Capacitor 7 Native Bridge Invariants, Hardware Keystore, and Android 15 Edge-to-Edge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Persisting Session Tokens in Web Storage and Leaking Capacitor Plugin Listeners Under Android 15 Insets

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 native bridge safety, hardware-backed cryptographic enclave storage, and Android 15 edge-to-edge handling. Mandate zero use of non-hardware storage for JWTs or credentials, strictly enforce PluginListenerHandle disposal on unmount, and require edge-to-edge window inset handling via standard CSS safe-area variables or native window insets.

## Strict Guidelines
- Engineers MUST ALWAYS store authentication tokens, refresh tokens, and private secrets exclusively in hardware-backed storage (iOS Keychain via kSecAccessControlBiometryAny/CurrentSet and Android Keystore via KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) rather than localStorage, IndexedDB, or standard unencrypted SharedPreferences.
- Engineers MUST ALWAYS retain references to `PluginListenerHandle` returned by native Capacitor 7 plugin calls and invoke `.remove()` during component cleanup or teardown lifecycle hooks to prevent memory leaks and zombie bridge invocations.
- Engineers MUST NOT rely on deprecated Android window flags (e.g., `FLAG_FULLSCREEN`, `setStatusBarColor`) for layout sizing, as Android 15 (API 35) strictly enforces edge-to-edge windowing; layout viewports MUST consume `window-inset-top`, `window-inset-bottom`, or CSS `env(safe-area-inset-*)`.
- Services MUST verify hardware biometric availability (`BiometricAuth.checkBiometry()`) and confirm device credential fallback policies before invoking native prompt methods to prevent unhandled bridge rejections.
- Components NEVER render user interactions or critical navigation controls within raw native boundary regions without explicit CSS `safe-area-inset` padding or native `WindowInsetsCompat` margin offsets.

## Bad vs Good Implementations
### Biometric Token Acquisition and Capacitor 7 Listener Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Discards the PluginListenerHandle causing permanent bridge retain cycles on every mount, exposes the authentication secret in standard browser localStorage rather than hardware-backed Keystore/KeyChain, and uses hardcoded padding that will overlap system gesture bars on Android 15.
```typescript
import { useEffect } from 'react';
import { App } from '@capacitor/app';

export function AuthSession() {
  useEffect(() => {
    // ANTI-PATTERN: Listener handle is discarded; results in native bridge memory leak
    App.addListener('appStateChange', (state) => {
      if (!state.isActive) {
        // ANTI-PATTERN: Insecure Web Storage vulnerable to XSS and process extraction
        localStorage.removeItem('auth_token');
      }
    });
  }, []);

  const handleLogin = async () => {
    // Simulating token persistence
    const fakeToken = 'raw-bearer-token';
    localStorage.setItem('auth_token', fakeToken);
  };

  // ANTI-PATTERN: Hardcoded paddings ignore Android 15 mandatory edge-to-edge insets
  return (
    <div style={{ paddingTop: '20px', paddingBottom: '20px' }}>
      <button onClick={handleLogin}>Authenticate</button>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Correctly disposes of the Capacitor `PluginListenerHandle` on unmount, enforces hardware-backed biometric authentication before saving credentials into the Secure Enclave/KeyStore, and adheres to Android 15 edge-to-edge constraints using CSS safe-area environment variables.
```typescript
import React, { useEffect, useCallback } from 'react';
import { App } from '@capacitor/app';
import type { PluginListenerHandle } from '@capacitor/core';
import { NativeBiometric, BiometryType } from 'capacitor-native-biometric';

const KEYSTORE_SERVER_KEY = 'com.enterprise.app.authtoken';

export const AuthSession: React.FC = () => {
  useEffect(() => {
    let listenerHandle: PluginListenerHandle | null = null;

    const setupLifecycle = async (): Promise<void> => {
      listenerHandle = await App.addListener('appStateChange', async (state) => {
        if (!state.isActive) {
          // Clear memory-resident references on background
        }
      });
    };

    void setupLifecycle();

    return () => {
      // Mandatory cleanup of Capacitor 7 bridge listener
      void listenerHandle?.remove();
    };
  }, []);

  const authenticateAndStoreToken = useCallback(async (token: string): Promise<void> => {
    const check = await NativeBiometric.isAvailable();
    if (!check.isAvailable || check.biometryType === BiometryType.NONE) {
      throw new Error('Biometric hardware unavailable or unconfigured');
    }

    await NativeBiometric.verifyIdentity({
      reason: 'Access secure enclave credentials',
      title: 'Biometric Authentication',
      fallbackTitle: 'Use Device Passcode',
    });

    // Persist securely to hardware Secure Enclave / Android KeyStore
    await NativeBiometric.setCredentials({
      server: KEYSTORE_SERVER_KEY,
      username: 'session_token',
      password: token,
    });
  }, []);

  // Safe area variables strictly enforced for Android 15 API 35 edge-to-edge layout
  return (
    <div
      style={{
        paddingTop: 'env(safe-area-inset-top, 0px)',
        paddingBottom: 'env(safe-area-inset-bottom, 0px)',
        paddingLeft: 'env(safe-area-inset-left, 0px)',
        paddingRight: 'env(safe-area-inset-right, 0px)',
        minHeight: '100vh',
        boxSizing: 'border-box'
      }}
    >
      <button onClick={() => void authenticateAndStoreToken('secure_session_payload')}>
        Secure Biometric Authenticate
      </button>
    </div>
  );
};
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Native Bridge Invariants, Hardware Keystore, and Android 15 Edge-to-Edge

Capacitor 7 Native Bridge Invariants, Hardware Keystore, and Android 15 Edge-to-Edge defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lifecycle management for Capacitor 7 native bridges, hardware-backed Keystore/Secure Enclave token persistence, and Android 15 edge-to-edge layout constraints. Prevents memory leaks from uncleaned plugin listeners, token exposure in unencrypted WebStorage, and UI occlusions caused by mandatory window insets. 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 Session Tokens in Web Storage and Leaking Capacitor Plugin Listeners Under Android 15 Insets 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 Session Tokens in Web Storage and Leaking Capacitor Plugin Listeners Under Android 15 InsetsCritical
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 authentication tokens, refresh tokens, and private secrets exclusively in hardware-backed storage (iOS Keychain via kSecAccessControlBiometryAny/CurrentSet and Android Keystore via KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) rather than localStorage, IndexedDB, or standard unencrypted SharedPreferences.

Engineers MUST ALWAYS store authentication tokens, refresh tokens, and private secrets exclusively in hardware-backed storage (iOS Keychain via kSecAccessControlBiometryAny/CurrentSet and Android Keystore via KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) rather than localStorage, IndexedDB, or standard unencrypted SharedPreferences.

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 ALWAYS retain references to `PluginListenerHandle` returned by native Capacitor 7 plugin calls and invoke `.remove()` during component cleanup or teardown lifecycle hooks to prevent memory leaks and zombie bridge invocations.

Engineers MUST ALWAYS retain references to `PluginListenerHandle` returned by native Capacitor 7 plugin calls and invoke `.remove()` during component cleanup or teardown lifecycle hooks to prevent memory leaks and zombie bridge invocations.

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

Engineers MUST NOT rely on deprecated Android window flags (e.g., `FLAG_FULLSCREEN`, `setStatusBarColor`) for layout sizing, as Android 15 (API 35) strictly enforces edge-to-edge windowing

Engineers MUST NOT rely on deprecated Android window flags (e.g., `FLAG_FULLSCREEN`, `setStatusBarColor`) for layout sizing, as Android 15 (API 35) strictly enforces edge-to-edge windowing; layout viewports MUST consume `window-inset-top`, `window-inset-bottom`, or CSS `env(safe-area-inset-*)`.

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 verify hardware biometric availability (`BiometricAuth.checkBiometry()`) and confirm device credential fallback policies before invoking native prompt methods to prevent unhandled bridge rejections.

Services MUST verify hardware biometric availability (`BiometricAuth.checkBiometry()`) and confirm device credential fallback policies before invoking native prompt methods to prevent unhandled bridge 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.
5

Components NEVER render user interactions or critical navigation controls within raw native boundary regions without explicit CSS `safe-area-inset` padding or native `WindowInsetsCompat` margin offsets.

Components NEVER render user interactions or critical navigation controls within raw native boundary regions without explicit CSS `safe-area-inset` padding or native `WindowInsetsCompat` margin offsets.

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 Invariants, Hardware Keystore, and Android 15 Edge-to-Edge critical for AI coding assistants?

Enforces strict lifecycle management for Capacitor 7 native bridges, hardware-backed Keystore/Secure Enclave token persistence, and Android 15 edge-to-edge layout constraints. Prevents memory leaks from uncleaned plugin listeners, token exposure in unencrypted WebStorage, and UI occlusions caused by mandatory window insets. 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 Session Tokens in Web Storage and Leaking Capacitor Plugin Listeners Under Android 15 Insets) 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