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

Capacitor 7 WebAuthn PRF Hardware Key Derivation Invariant

Enforces hardware-backed zero-knowledge key derivation using the WebAuthn Pseudo-Random Function (PRF) extension within Capacitor 7 native bridges. Ensures derived symmetric encryption keys are computed in native secure enclaves/Keystore without exposing long-lived master secrets, credential IDs, or raw entropy directly to the untrusted WebView JavaScript context.

Prohibited Anti-Pattern: Deriving master encryption keys in WebView JavaScript or caching PRF raw outputs in unencrypted storage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 WebAuthn PRF Hardware Key Derivation Invariant - Enforces hardware-backed zero-knowledge key derivation using the WebAuthn Pseudo-Random Function (PRF) extension within Capacitor 7 native bridges. Ensures derived symmetric encryption keys are computed in native secure enclaves/Keystore without exposing long-lived master secrets, credential IDs, or raw entropy directly to the untrusted WebView JavaScript context.
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-webauthn-prf-hardware-derivation"
---

# Capacitor 7 WebAuthn PRF Hardware Key Derivation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Deriving master encryption keys in WebView JavaScript or caching PRF raw outputs in unencrypted storage

## System Constraints
You are a Principal Mobile Security Architect enforcing zero-knowledge biometric key derivation via WebAuthn PRF (Pseudo-Random Function) extension in Capacitor 7. The WebView is an untrusted execution context susceptible to XSS, debugging hooks, and memory inspection. You must ensure that PRF-derived outputs are handled either entirely within native Secure Enclave/KeyStore wrappers or immediately processed via ephemeral HKDF pipelines without exposing base salt material or persisting PRF secrets to web storage.

## Strict Guidelines
- Engineers MUST ALWAYS verify that the WebAuthn authenticator supports the 'prf' extension during registration (navigator.credentials.create) and authentication (navigator.credentials.get).
- Engineers MUST NEVER persist the raw PRF output (results.prf) to localStorage, IndexedDB, or any client-side JavaScript storage.
- Engineers MUST derive ephemeral operational keys using HKDF (HMAC-based Extract-and-Expand Key Derivation Function) with high-entropy native salts and explicit context strings.
- Services MUST clear sensitive TypedArrays from memory (ArrayBuffer/Uint8Array zeroing) immediately after completing the cryptographic operation in the WebView.
- Native plugins MUST route PRF evaluation requests through platform-native biometrics (Credential Manager on Android 14+ / ASAuthorizationPlatformPublicKeyCredentialProvider on iOS 17+) when using hybrid plugins.

## Bad vs Good Implementations
### WebAuthn PRF Authentication and Key Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to configure the 'prf' extension in the authentication options, blindly reads extension outputs without null-checks, and leaks raw cryptographic master secrets into insecure web storage.
```typescript
import { Preferences } from '@capacitor/preferences';

async function authenticateAndDeriveKey(credentialId: Uint8Array, salt: Uint8Array) {
  // Anti-pattern: No PRF extension check and caching derived raw entropy in plaintext storage
  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      userVerification: 'required'
    }
  }) as PublicKeyCredential;

  // Storing credentials and raw material in WebView preferences directly
  const rawKey = (assertion.getClientExtensionResults() as any).prf?.results?.first;
  await Preferences.set({
    key: 'master_encryption_key',
    value: btoa(String.fromCharCode(...new Uint8Array(rawKey)))
  });
  return rawKey;
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly requests the PRF extension using salt parameters, validates authenticator responses, derives a single-purpose non-extractable CryptoKey via HKDF, and zeroes raw bytes in memory immediately.
```typescript
async function deriveVaultKeyWithPRF(
  credentialId: Uint8Array,
  salt: Uint8Array,
  infoString: string
): Promise<CryptoKey> {
  if (!window.PublicKeyCredential || !PublicKeyCredential.isConditionalMediationAvailable) {
    throw new Error('WebAuthn PRF unsupported on this platform');
  }

  const assertion = await navigator.credentials.get({
    publicKey: {
      challenge: crypto.getRandomValues(new Uint8Array(32)),
      allowCredentials: [{ id: credentialId, type: 'public-key' }],
      userVerification: 'required',
      extensions: {
        prf: {
          eval: {
            first: salt
          }
        }
      }
    }
  }) as PublicKeyCredential | null;

  if (!assertion) {
    throw new Error('Authentication canceled or failed');
  }

  const extResults = assertion.getClientExtensionResults() as {
    prf?: { results?: { first?: ArrayBuffer } };
  };

  const prfRaw = extResults.prf?.results?.first;
  if (!prfRaw) {
    throw new Error('Hardware Authenticator did not return PRF entropy');
  }

  const rawBytes = new Uint8Array(prfRaw);
  try {
    // HKDF to derive scoped operational key without persisting raw PRF output
    const baseKey = await crypto.subtle.importKey(
      'raw',
      rawBytes,
      'HKDF',
      false,
      ['deriveKey']
    );

    return await crypto.subtle.deriveKey(
      {
        name: 'HKDF',
        hash: 'SHA-256',
        salt: new Uint8Array(16), // Domain-specific fixed salt
        info: new TextEncoder().encode(infoString)
      },
      baseKey,
      { name: 'AES-GCM', length: 256 },
      false,
      ['encrypt', 'decrypt']
    );
  } finally {
    // Zero out memory of raw entropy buffer
    rawBytes.fill(0);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 WebAuthn PRF Hardware Key Derivation Invariant

Capacitor 7 WebAuthn PRF Hardware Key Derivation Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-backed zero-knowledge key derivation using the WebAuthn Pseudo-Random Function (PRF) extension within Capacitor 7 native bridges. Ensures derived symmetric encryption keys are computed in native secure enclaves/Keystore without exposing long-lived master secrets, credential IDs, or raw entropy directly to the untrusted WebView JavaScript context. 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: Deriving master encryption keys in WebView JavaScript or caching PRF raw outputs in unencrypted storage 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 DriftDeriving master encryption keys in WebView JavaScript or caching PRF raw outputs in unencrypted storageCritical
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 verify that the WebAuthn authenticator supports the 'prf' extension during registration (navigator.credentials.create) and authentication (navigator.credentials.get).

Engineers MUST ALWAYS verify that the WebAuthn authenticator supports the 'prf' extension during registration (navigator.credentials.create) and authentication (navigator.credentials.get).

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 NEVER persist the raw PRF output (results.prf) to localStorage, IndexedDB, or any client-side JavaScript storage.

Engineers MUST NEVER persist the raw PRF output (results.prf) to localStorage, IndexedDB, or any client-side JavaScript storage.

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 derive ephemeral operational keys using HKDF (HMAC-based Extract-and-Expand Key Derivation Function) with high-entropy native salts and explicit context strings.

Engineers MUST derive ephemeral operational keys using HKDF (HMAC-based Extract-and-Expand Key Derivation Function) with high-entropy native salts and explicit context strings.

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 clear sensitive TypedArrays from memory (ArrayBuffer/Uint8Array zeroing) immediately after completing the cryptographic operation in the WebView.

Services MUST clear sensitive TypedArrays from memory (ArrayBuffer/Uint8Array zeroing) immediately after completing the cryptographic operation in the 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.
5

Native plugins MUST route PRF evaluation requests through platform-native biometrics (Credential Manager on Android 14+ / ASAuthorizationPlatformPublicKeyCredentialProvider on iOS 17+) when using hybrid plugins.

Native plugins MUST route PRF evaluation requests through platform-native biometrics (Credential Manager on Android 14+ / ASAuthorizationPlatformPublicKeyCredentialProvider on iOS 17+) when using hybrid plugins.

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 WebAuthn PRF Hardware Key Derivation Invariant critical for AI coding assistants?

Enforces hardware-backed zero-knowledge key derivation using the WebAuthn Pseudo-Random Function (PRF) extension within Capacitor 7 native bridges. Ensures derived symmetric encryption keys are computed in native secure enclaves/Keystore without exposing long-lived master secrets, credential IDs, or raw entropy directly to the untrusted WebView JavaScript context. 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 (Deriving master encryption keys in WebView JavaScript or caching PRF raw outputs in unencrypted storage) 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