This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-keystore-nonce-enclave-barrier

Capacitor 7 Hardware-Backed KeyStore Cryptographic Nonce Enclave Barrier

Enforces strict isolation between Capacitor 7 WebViews and hardware-backed keystores (Android StrongBox/TEE and iOS Secure Enclave) via single-use, server-attested challenge nonces. Prevents bridge memory-scraping and replay attacks by guaranteeing that the native enclave signs only cryptographically fresh, atomically consumed payloads and never exposes raw key material to the JavaScript runtime.

Prohibited Anti-Pattern: Unbounded or Nonce-Less WebView Native Cryptographic Invocations Vulnerable to Bridge Scraping and Replay

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed KeyStore Cryptographic Nonce Enclave Barrier - Enforces strict isolation between Capacitor 7 WebViews and hardware-backed keystores (Android StrongBox/TEE and iOS Secure Enclave) via single-use, server-attested challenge nonces. Prevents bridge memory-scraping and replay attacks by guaranteeing that the native enclave signs only cryptographically fresh, atomically consumed payloads and never exposes raw key material to the JavaScript runtime.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/**/*.{kt,java}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-keystore-nonce-enclave-barrier"
---

# Capacitor 7 Hardware-Backed KeyStore Cryptographic Nonce Enclave Barrier

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded or Nonce-Less WebView Native Cryptographic Invocations Vulnerable to Bridge Scraping and Replay

## System Constraints
You are a Principal Mobile Security Architect enforcing strict cryptographic enclave boundaries in Capacitor 7 applications. Your directive is to isolate the mobile WebView runtime from native biometric cryptographic operations by mandating single-use, hardware-attested Secure Enclave and Android KeyStore nonces, completely eliminating bridge memory-scraping and cross-site scripting signature replay attacks.

## Strict Guidelines
- Engineers MUST ALWAYS require a server-originated, cryptographically random, ephemeral challenge nonce (minimum 256 bits) for every native signing or biometric decryption operation.
- Engineers MUST NOT persist, cache, or allow reuse of challenge nonces across Capacitor JavaScript-to-Native bridge boundaries.
- Native plugins MUST enforce atomic nonce invalidation in native memory (Secure Enclave / Android KeyStore StrongBox) immediately upon consumption, regardless of operation success or failure.
- The JavaScript bridge interface MUST NEVER receive, handle, or serialize raw private key material, symmetric encryption keys, or long-lived authentication tokens.
- Native bridge methods MUST validate user biometric authentication within the hardware enclave using flags like `UserAuthenticationRequirement` (Android) or `kSecAccessControlBiometryCurrentSet` (iOS) bound to the active nonce payload.
- All cryptographic results returned across the Capacitor bridge SHOULD contain only the cryptographic signature, an ephemeral assertion token, and the burned nonce confirmation.

## Bad vs Good Implementations
### Secure Enclave Hardware Signing Bridge Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native plugin accepts a caller-provided payload without requiring an attested, single-use challenge nonce from the secure backend. A malicious script or memory inspector injecting into the Capacitor WebView can replay calls to `signPayload` or forge transactions without proof of freshness.
```typescript
import { registerPlugin } from '@capacitor/core';

interface InsecureBiometricPlugin {
  // Anti-pattern: No server challenge nonce required; signature can be replayed
  // if WebView memory or the Capacitor JavaScript bridge is intercepted.
  signPayload(options: { payload: string }): Promise<{ signature: string }>;
}

const BiometricAuth = registerPlugin<InsecureBiometricPlugin>('BiometricAuth');

export async function authenticateTransaction(transactionId: string): Promise<string> {
  // VULNERABLE: Direct signing of static payload without nonce verification
  const result = await BiometricAuth.signPayload({
    payload: JSON.stringify({ txId: transactionId, timestamp: Date.now() })
  });
  return result.signature;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces a strict cryptographic barrier: every signing operation requires an ephemeral server challenge nonce. The native layer consumes and burns the nonce inside the hardware enclave alongside biometric confirmation, returning proof of nonce invalidation to prevent bridge replay or memory-scraping attacks.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SecureEnclavePlugin {
  signChallengeWithBiometrics(options: {
    challengeNonce: string;
    payloadHash: string;
    timeoutMs: number;
  }): Promise<{
    signature: string;
    burnedNonce: string;
    hardwareAttestation?: string;
  }>;
}

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

export async function signSecureTransaction(
  transactionPayload: Record<string, unknown>,
  serverNonceProvider: () => Promise<string>
): Promise<{ signature: string; burnedNonce: string }> {
  // 1. Fetch fresh, ephemeral, single-use 256-bit challenge nonce from backend
  const challengeNonce = await serverNonceProvider();
  if (!challengeNonce || challengeNonce.length < 32) {
    throw new Error('Invalid or insufficient challenge nonce from enclave authority.');
  }

  // 2. Hash payload locally before crossing the bridge to minimize data exposure
  const encoder = new TextEncoder();
  const payloadBytes = encoder.encode(JSON.stringify(transactionPayload));
  const digestBuffer = await crypto.subtle.digest('SHA-256', payloadBytes);
  const payloadHash = Array.from(new Uint8Array(digestBuffer))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');

  // 3. Delegate to native Hardware KeyStore / Secure Enclave with strict barrier
  const result = await SecureEnclave.signChallengeWithBiometrics({
    challengeNonce,
    payloadHash,
    timeoutMs: 15000
  });

  // 4. Verify native bridge burned the exact requested nonce
  if (result.burnedNonce !== challengeNonce) {
    throw new Error('Cryptographic nonce desynchronization: Bridge replay detected.');
  }

  return {
    signature: result.signature,
    burnedNonce: result.burnedNonce
  };
}
```

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 KeyStore Cryptographic Nonce Enclave Barrier

Capacitor 7 Hardware-Backed KeyStore Cryptographic Nonce Enclave Barrier defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation between Capacitor 7 WebViews and hardware-backed keystores (Android StrongBox/TEE and iOS Secure Enclave) via single-use, server-attested challenge nonces. Prevents bridge memory-scraping and replay attacks by guaranteeing that the native enclave signs only cryptographically fresh, atomically consumed payloads and never exposes raw key material to the JavaScript runtime. 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: Unbounded or Nonce-Less WebView Native Cryptographic Invocations Vulnerable to Bridge Scraping and Replay 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 DriftUnbounded or Nonce-Less WebView Native Cryptographic Invocations Vulnerable to Bridge Scraping and ReplayCritical
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 require a server-originated, cryptographically random, ephemeral challenge nonce (minimum 256 bits) for every native signing or biometric decryption operation.

Engineers MUST ALWAYS require a server-originated, cryptographically random, ephemeral challenge nonce (minimum 256 bits) for every native signing or biometric decryption operation.

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 persist, cache, or allow reuse of challenge nonces across Capacitor JavaScript-to-Native bridge boundaries.

Engineers MUST NOT persist, cache, or allow reuse of challenge nonces across Capacitor JavaScript-to-Native bridge boundaries.

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

Native plugins MUST enforce atomic nonce invalidation in native memory (Secure Enclave / Android KeyStore StrongBox) immediately upon consumption, regardless of operation success or failure.

Native plugins MUST enforce atomic nonce invalidation in native memory (Secure Enclave / Android KeyStore StrongBox) immediately upon consumption, regardless of operation success or failure.

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

The JavaScript bridge interface MUST NEVER receive, handle, or serialize raw private key material, symmetric encryption keys, or long-lived authentication tokens.

The JavaScript bridge interface MUST NEVER receive, handle, or serialize raw private key material, symmetric encryption keys, or long-lived authentication tokens.

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

Native bridge methods MUST validate user biometric authentication within the hardware enclave using flags like `UserAuthenticationRequirement` (Android) or `kSecAccessControlBiometryCurrentSet` (iOS) bound to the active nonce payload.

Native bridge methods MUST validate user biometric authentication within the hardware enclave using flags like `UserAuthenticationRequirement` (Android) or `kSecAccessControlBiometryCurrentSet` (iOS) bound to the active nonce payload.

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.
6

All cryptographic results returned across the Capacitor bridge SHOULD contain only the cryptographic signature, an ephemeral assertion token, and the burned nonce confirmation.

All cryptographic results returned across the Capacitor bridge SHOULD contain only the cryptographic signature, an ephemeral assertion token, and the burned nonce confirmation.

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 KeyStore Cryptographic Nonce Enclave Barrier critical for AI coding assistants?

Enforces strict isolation between Capacitor 7 WebViews and hardware-backed keystores (Android StrongBox/TEE and iOS Secure Enclave) via single-use, server-attested challenge nonces. Prevents bridge memory-scraping and replay attacks by guaranteeing that the native enclave signs only cryptographically fresh, atomically consumed payloads and never exposes raw key material to the JavaScript runtime. 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 (Unbounded or Nonce-Less WebView Native Cryptographic Invocations Vulnerable to Bridge Scraping and Replay) 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