This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-secure-enclave-webauthn-bridge-guardrail

Capacitor 7 Hardware-Backed WebAuthn Level-3 Enclave Bridge Guardrail

Enforces strict isolation between Capacitor 7 hybrid WebViews and underlying hardware-backed authentication modules (Apple Secure Enclave and Android KeyStore StrongBox). All credential generation, assertion signatures, and biometric user verifications must be handled via native bridge calls returning opaque attestation payloads and WebAuthn-compliant signatures without ever exposing raw asymmetric keys, private seeds, or plaintext biometric claims to the WebView DOM or JavaScript runtime.

Prohibited Anti-Pattern: Exposing Raw Cryptographic Key Material or Simulated Biometric Tokens in Hybrid WebView DOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Hardware-Backed WebAuthn Level-3 Enclave Bridge Guardrail - Enforces strict isolation between Capacitor 7 hybrid WebViews and underlying hardware-backed authentication modules (Apple Secure Enclave and Android KeyStore StrongBox). All credential generation, assertion signatures, and biometric user verifications must be handled via native bridge calls returning opaque attestation payloads and WebAuthn-compliant signatures without ever exposing raw asymmetric keys, private seeds, or plaintext biometric claims to the WebView DOM or JavaScript runtime.
globs: src/**/*.{ts,tsx}, ios/App/App/**/*.{swift,m}, android/app/src/main/**/*.{java,kt}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-webauthn-bridge-guardrail"
---

# Capacitor 7 Hardware-Backed WebAuthn Level-3 Enclave Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Raw Cryptographic Key Material or Simulated Biometric Tokens in Hybrid WebView DOM

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-trust hardware-backed credential storage in Capacitor 7 hybrid mobile applications. Never allow private key generation, handling, or parsing in the JavaScript/TypeScript layer. Ensure all WebAuthn/Passkey registration and assertion workflows delegate strictly to native Swift/Kotlin plugins that bind credentials to the Apple Secure Enclave (kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly / SecAccessControlCreateWithFlags) or Android Keystore StrongBox (setKeySize, setIsStrongBoxBacked). Ensure DOM interaction is restricted to handling opaque ArrayBuffer credentials, standard WebAuthn CBOR/DER structures, or passing server-issued nonces/challenges.

## Strict Guidelines
- Engineers MUST ALWAYS isolate cryptographic private keys within the platform's hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android) using native Capacitor 7 plugin bridges.
- Engineers MUST NOT generate, import, or decrypt private asymmetric keys within JavaScript/TypeScript runtime code or the WebView DOM.
- Engineers MUST validate server-provided cryptographic challenges strictly against hardware-signed attestation statements or signature outputs before transmitting to backend relying parties.
- Native plugins MUST enforce biometric user verification flags (UserVerificationRequirement.REQUIRED) at the hardware level, rejecting software-fallback bypasses in production builds.
- Web code SHOULD only handle Base64URL-encoded authenticator data, DER-encoded signature payloads, and public credential IDs, treating all cryptographic operations as opaque RPCs.

## Bad vs Good Implementations
### Hardware-Backed WebAuthn Assertion Bridge vs. JavaScript In-Memory Signing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Private key material is retrieved from unencrypted or standard software storage into the WebView DOM. This exposes the private key to DOM-based XSS, memory dump exploits, and supply-chain script tampering. It bypasses hardware-backed Secure Enclave / StrongBox biometric access controls.
```typescript
import { Preferences } from '@capacitor/preferences';
import * as jose from 'jose';

// ANTI-PATTERN: Loading a stored raw private key into WebView memory
// and executing signatures inside the DOM JavaScript sandbox.
export async function signAuthenticationChallenge(challenge: string): Promise<string> {
  const { value: privateKeyJwk } = await Preferences.get({ key: 'user_signing_key' });
  if (!privateKeyJwk) throw new Error('Key not found');
  
  const rawKey = JSON.parse(privateKeyJwk);
  const privateKey = await jose.importJWK(rawKey, 'ES256');
  
  const jws = await new jose.SignJWT({ sub: 'user_123', nonce: challenge })
    .setProtectedHeader({ alg: 'ES256' })
    .setIssuedAt()
    .sign(privateKey);
    
  return jws;
}
```

#### Production Standard (Correct)
> **Standard**: Delegates cryptographic operations to the native Capacitor plugin (`EnclavePasskey`). The hardware security module executes biometric verification and signs the payload internally. The WebView never accesses or controls the private key, ensuring compliance with Level-3 Hardware-Backed WebAuthn standards.
```typescript
import { registerPlugin } from '@capacitor/core';

interface NativePasskeyPlugin {
  authenticateWithEnclave(options: {
    challenge: string;
    rpId: string;
    credentialId: string;
  }): Promise<{
    clientDataJSON: string;
    authenticatorData: string;
    signature: string;
    userHandle?: string;
  }>;
}

const EnclavePasskey = registerPlugin<NativePasskeyPlugin>('EnclavePasskey');

// PRODUCTION FIX: The WebView only orchestrates native Hardware-Backed assertion.
// Private key never leaves the Apple Secure Enclave / Android StrongBox.
export async function signAuthenticationChallenge(challenge: string, credentialId: string): Promise<{
  clientDataJSON: string;
  authenticatorData: string;
  signature: string;
}> {
  // Hardware enclave directly prompts for FaceID/Biometrics and computes signature
  const result = await EnclavePasskey.authenticateWithEnclave({
    challenge,
    rpId: 'auth.enterprise.com',
    credentialId
  });

  // WebView receives only opaque assertions formatted per WebAuthn L3 spec
  return {
    clientDataJSON: result.clientDataJSON,
    authenticatorData: result.authenticatorData,
    signature: result.signature
  };
}
```

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 WebAuthn Level-3 Enclave Bridge Guardrail

Capacitor 7 Hardware-Backed WebAuthn Level-3 Enclave Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation between Capacitor 7 hybrid WebViews and underlying hardware-backed authentication modules (Apple Secure Enclave and Android KeyStore StrongBox). All credential generation, assertion signatures, and biometric user verifications must be handled via native bridge calls returning opaque attestation payloads and WebAuthn-compliant signatures without ever exposing raw asymmetric keys, private seeds, or plaintext biometric claims to the WebView DOM or 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: Exposing Raw Cryptographic Key Material or Simulated Biometric Tokens in Hybrid WebView DOM 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 DriftExposing Raw Cryptographic Key Material or Simulated Biometric Tokens in Hybrid WebView DOMCritical
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 isolate cryptographic private keys within the platform's hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android) using native Capacitor 7 plugin bridges.

Engineers MUST ALWAYS isolate cryptographic private keys within the platform's hardware security module (Secure Enclave on iOS, StrongBox Keymaster on Android) using native Capacitor 7 plugin bridges.

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 generate, import, or decrypt private asymmetric keys within JavaScript/TypeScript runtime code or the WebView DOM.

Engineers MUST NOT generate, import, or decrypt private asymmetric keys within JavaScript/TypeScript runtime code or the WebView DOM.

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 validate server-provided cryptographic challenges strictly against hardware-signed attestation statements or signature outputs before transmitting to backend relying parties.

Engineers MUST validate server-provided cryptographic challenges strictly against hardware-signed attestation statements or signature outputs before transmitting to backend relying parties.

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 plugins MUST enforce biometric user verification flags (UserVerificationRequirement.REQUIRED) at the hardware level, rejecting software-fallback bypasses in production builds.

Native plugins MUST enforce biometric user verification flags (UserVerificationRequirement.REQUIRED) at the hardware level, rejecting software-fallback bypasses in production builds.

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

Web code SHOULD only handle Base64URL-encoded authenticator data, DER-encoded signature payloads, and public credential IDs, treating all cryptographic operations as opaque RPCs.

Web code SHOULD only handle Base64URL-encoded authenticator data, DER-encoded signature payloads, and public credential IDs, treating all cryptographic operations as opaque RPCs.

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 WebAuthn Level-3 Enclave Bridge Guardrail critical for AI coding assistants?

Enforces strict isolation between Capacitor 7 hybrid WebViews and underlying hardware-backed authentication modules (Apple Secure Enclave and Android KeyStore StrongBox). All credential generation, assertion signatures, and biometric user verifications must be handled via native bridge calls returning opaque attestation payloads and WebAuthn-compliant signatures without ever exposing raw asymmetric keys, private seeds, or plaintext biometric claims to the WebView DOM or 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 (Exposing Raw Cryptographic Key Material or Simulated Biometric Tokens in Hybrid WebView DOM) 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