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

Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7

Mandates that all passkey registration and assertion flows within Capacitor 7 hybrid applications interface directly with native platform authenticators (iOS ASAuthorizationController backed by Secure Enclave, Android Credential Manager backed by StrongBox/TEE). Strictly prohibits software-based key emulation, client-side challenge synthesis, and insecure storage fallbacks like Capacitor Preferences or localStorage.

Prohibited Anti-Pattern: Falling Back to Insecure Web Storage or Software Key Emulation on Passkey Bridge Failure

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7 - Mandates that all passkey registration and assertion flows within Capacitor 7 hybrid applications interface directly with native platform authenticators (iOS ASAuthorizationController backed by Secure Enclave, Android Credential Manager backed by StrongBox/TEE). Strictly prohibits software-based key emulation, client-side challenge synthesis, and insecure storage fallbacks like Capacitor Preferences or localStorage.
globs: src/**/*.{ts,tsx,js}, ios/App/**/*.{swift,m}, android/app/**/*.{kt,java}, capacitor.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-secure-enclave-passkey-bridge"
---

# Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Falling Back to Insecure Web Storage or Software Key Emulation on Passkey Bridge Failure

## System Constraints
You are a Principal Mobile Security Architect enforcing hardware-backed WebAuthn attestation standards in Capacitor 7 applications. You must ensure that every cryptographic credential operation delegates to the native operating system passkey subsystem (ASAuthorizationPlatformPublicKeyCredentialProvider on iOS and CredentialManager on Android). Reject any code that attempts to mock, polyfill, or fallback to software-derived private keys, localStorage, IndexedDB, or standard unencrypted Capacitor Preferences.

## Strict Guidelines
- Engineers MUST ALWAYS delegate WebAuthn operations to native bridge plugins backed by Apple ASAuthorization and Android Credential Manager.
- Engineers MUST NOT provide software-based crypto fallbacks or store private keys in Capacitor Preferences, localStorage, or IndexedDB if native biometric hardware is unavailable.
- Code MUST transmit raw attestation and assertion buffers as Base64URL-encoded strings between the WebView and the native bridge layer.
- Services MUST validate that the relying party identifier (rpId) strictly matches the configured platform domain associations (Apple App Site Association and Android Digital Asset Links).
- Services MUST consume single-use cryptographic challenges generated exclusively by the relying party server and verify signatures server-side.
- Components NEVER intercept or suppress native user biometric prompts with synthetic PIN or password prompts within the hybrid WebView.

## Bad vs Good Implementations
### Insecure WebAuthn Fallback vs Native Hardware-Backed Passkey Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly invokes navigator.credentials in WKWebView/Android WebView where passkey attestation is unreliable or unsupported, and critically falls back to storing an unencrypted software token in Capacitor Preferences when native attestation fails.
```typescript
import { Preferences } from '@capacitor/preferences';

interface RegistrationOptions {
  challenge: string;
  userId: string;
}

export async function registerPasskey(options: RegistrationOptions): Promise<void> {
  try {
    // Anti-pattern: Intercepting failure and falling back to software key emulation in unencrypted storage
    if (!window.PublicKeyCredential) {
      throw new Error('WebAuthn not supported in WebView');
    }
    // Calling browser API directly in hybrid webview without native bridge guarantees
    await navigator.credentials.create({
      publicKey: {
        challenge: Uint8Array.from(atob(options.challenge), c => c.charCodeAt(0)),
        rp: { name: 'Acme Hybrid', id: 'acme.com' },
        user: { id: Uint8Array.from(atob(options.userId), c => c.charCodeAt(0)), name: 'user', displayName: 'User' },
        pubKeyCredParams: [{ alg: -7, type: 'public-key' }]
      }
    });
  } catch (error) {
    console.warn('Native biometric failed, falling back to local fallback token', error);
    // CRITICAL FLAW: Storing mock private keys/session tokens in Capacitor Preferences
    await Preferences.set({
      key: `fallback_passkey_${options.userId}`,
      value: JSON.stringify({ userId: options.userId, softwareFallbackToken: crypto.randomUUID() })
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces strict delegation to the native Capacitor 7 plugin binding hardware-backed authenticators (Secure Enclave / StrongBox). Never provides fallback paths to insecure client storage, failing closed on platform errors.
```typescript
import { registerPlugin } from '@capacitor/core';

export interface NativePasskeyPlugin {
  registerPasskey(options: {
    rpId: string;
    challenge: string;
    userId: string;
    userName: string;
  }): Promise<{
    rawId: string;
    attestationObject: string;
    clientDataJSON: string;
  }>;
}

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

interface ServerPasskeyOptions {
  rpId: string;
  challengeBase64Url: string;
  userIdBase64Url: string;
  userName: string;
}

export async function registerPasskey(options: ServerPasskeyOptions) {
  // Invariant: Always delegate directly to hardware-backed native OS authenticator
  // iOS: ASAuthorizationPlatformPublicKeyCredentialProvider (Secure Enclave)
  // Android: CredentialManager with StrongBox / Play Services FIDO2
  try {
    const response = await PasskeyBridge.registerPasskey({
      rpId: options.rpId,
      challenge: options.challengeBase64Url,
      userId: options.userIdBase64Url,
      userName: options.userName
    });

    return {
      credentialId: response.rawId,
      attestationObject: response.attestationObject,
      clientDataJSON: response.clientDataJSON
    };
  } catch (nativeError) {
    // Fail closed: Never downgrade to software storage or synthetic passkeys
    throw new Error(`Hardware-backed passkey registration failed: ${(nativeError as Error).message}`);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7

Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Mandates that all passkey registration and assertion flows within Capacitor 7 hybrid applications interface directly with native platform authenticators (iOS ASAuthorizationController backed by Secure Enclave, Android Credential Manager backed by StrongBox/TEE). Strictly prohibits software-based key emulation, client-side challenge synthesis, and insecure storage fallbacks like Capacitor Preferences or localStorage. 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: Falling Back to Insecure Web Storage or Software Key Emulation on Passkey Bridge Failure 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 DriftFalling Back to Insecure Web Storage or Software Key Emulation on Passkey Bridge FailureCritical
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 delegate WebAuthn operations to native bridge plugins backed by Apple ASAuthorization and Android Credential Manager.

Engineers MUST ALWAYS delegate WebAuthn operations to native bridge plugins backed by Apple ASAuthorization and Android Credential Manager.

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 provide software-based crypto fallbacks or store private keys in Capacitor Preferences, localStorage, or IndexedDB if native biometric hardware is unavailable.

Engineers MUST NOT provide software-based crypto fallbacks or store private keys in Capacitor Preferences, localStorage, or IndexedDB if native biometric hardware is unavailable.

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 transmit raw attestation and assertion buffers as Base64URL-encoded strings between the WebView and the native bridge layer.

Code MUST transmit raw attestation and assertion buffers as Base64URL-encoded strings between the WebView and the native bridge layer.

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 validate that the relying party identifier (rpId) strictly matches the configured platform domain associations (Apple App Site Association and Android Digital Asset Links).

Services MUST validate that the relying party identifier (rpId) strictly matches the configured platform domain associations (Apple App Site Association and Android Digital Asset Links).

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

Services MUST consume single-use cryptographic challenges generated exclusively by the relying party server and verify signatures server-side.

Services MUST consume single-use cryptographic challenges generated exclusively by the relying party server and verify signatures server-side.

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

Components NEVER intercept or suppress native user biometric prompts with synthetic PIN or password prompts within the hybrid WebView.

Components NEVER intercept or suppress native user biometric prompts with synthetic PIN or password prompts within the hybrid WebView.

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 Hardware-Backed WebAuthn Attestation & Passkey Bridge Guardrail in Capacitor 7 critical for AI coding assistants?

Mandates that all passkey registration and assertion flows within Capacitor 7 hybrid applications interface directly with native platform authenticators (iOS ASAuthorizationController backed by Secure Enclave, Android Credential Manager backed by StrongBox/TEE). Strictly prohibits software-based key emulation, client-side challenge synthesis, and insecure storage fallbacks like Capacitor Preferences or localStorage. 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 (Falling Back to Insecure Web Storage or Software Key Emulation on Passkey Bridge Failure) 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

Hardware-Backed