w3pk 0.10.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -105,7 +105,7 @@ interface WebAuthnCredential {
105
105
  - Standards: BIP32, BIP39, BIP44, EIP-155
106
106
  - Curve: secp256k1 (Bitcoin/Ethereum standard)
107
107
  - Algorithm: ECDSA + Keccak-256
108
- - Storage: IndexedDB (AES-256-GCM encrypted)
108
+ - Storage: localStorage (AES-256-GCM encrypted)
109
109
  - Managed by: Application (w3pk)
110
110
 
111
111
  **Capabilities**:
@@ -148,42 +148,33 @@ m/44'/60'/0'/0/2 ← Third address
148
148
 
149
149
  **Purpose**: Link WebAuthn authentication to wallet encryption
150
150
 
151
- **Implementation**: [src/wallet/crypto.ts](src/wallet/crypto.ts)
152
-
153
- ✅ **SECURITY**: Uses PRF-based encryption with authenticator-held secrets and random salts
151
+ **Implementation**: [src/wallet/crypto.ts:21-66](src/wallet/crypto.ts#L21-L66)
154
152
 
155
- **SECURE Implementation (PRF-based)**:
153
+ **Process**:
156
154
  ```typescript
157
155
  function deriveEncryptionKeyFromWebAuthn(
158
- prfOutput: ArrayBuffer, // From WebAuthn PRF extension
159
- salt: Uint8Array // Random 32-byte salt
156
+ credentialId: string,
157
+ publicKey: string
160
158
  ): CryptoKey {
161
- // Step 1: Validate inputs
162
- assert(prfOutput.byteLength === 32);
163
- assert(salt.byteLength === 32);
159
+ // Step 1: Combine inputs
160
+ const keyMaterial = `w3pk-v4:${credentialId}:${publicKey}`;
164
161
 
165
- // Step 2: Import PRF output (authenticator-held secret)
166
- const keyMaterial = importKey(prfOutput);
162
+ // Step 2: Hash with SHA-256
163
+ const hash = SHA256(keyMaterial);
167
164
 
168
- // Step 3: PBKDF2 key derivation with random salt
169
- const encryptionKey = PBKDF2(keyMaterial, salt, 210000);
165
+ // Step 3: PBKDF2 key derivation (210,000 iterations)
166
+ const encryptionKey = PBKDF2(hash, salt, 210000);
170
167
 
171
168
  // Result: AES-256-GCM key (NEVER STORED)
172
169
  return encryptionKey;
173
170
  }
174
171
  ```
175
172
 
176
- **Security Properties**:
177
- - **Authenticator Secret**: Uses PRF output from hardware (never exposed to application)
178
- - **Random Salts**: Each encryption uses unique 32-byte salt (prevents precomputation)
179
- - **PBKDF2**: 210,000 iterations (OWASP 2023 recommendation)
180
- - **AES-256-GCM**: Strong authenticated encryption
181
- - **Authentication-gated**: Requires biometric/PIN to trigger PRF
182
-
183
- **Implementation Note**:
184
- The SDK uses `deriveEncryptionKeyAuto()` as a helper that:
185
- 1. Uses PRF-based encryption when available (secure)
186
- 2. Falls back to v2 implementation for existing wallets without PRF support
173
+ **Properties**:
174
+ - **Deterministic**: Same inputs → Same output
175
+ - **Secure**: 210,000 PBKDF2 iterations (OWASP 2023)
176
+ - **Stateless**: No key storage required
177
+ - **Authentication-gated**: Requires biometric/PIN to access inputs
187
178
 
188
179
  ---
189
180
 
@@ -226,12 +217,11 @@ STEP 2: Create WebAuthn Credential (INDEPENDENT)
226
217
 
227
218
  STEP 3: Derive Encryption Key
228
219
  ┌──────────────────────────────────────┐
229
- │ deriveEncryptionKeyFromWebAuthn() │
220
+ │ deriveEncryptionKeyFromWebAuthn() │
230
221
  │ │
231
- │ Input: PRF output (32 bytes secret) │
232
- │ + random salt (32 bytes) │
222
+ │ Input: credentialId + publicKey │
233
223
  │ ↓ │
234
- │ Import PRF as key material │
224
+ │ SHA-256 hash │
235
225
  │ ↓ │
236
226
  │ PBKDF2 (210,000 iterations) │
237
227
  │ ↓ │
@@ -241,10 +231,10 @@ STEP 3: Derive Encryption Key
241
231
 
242
232
  STEP 4: Encrypt & Store
243
233
  ┌────────────────────────────┬────────────────────────────┐
244
- │ localStorage │ IndexedDB │
234
+ │ localStorage │ localStorage │
245
235
  │ ───────────── │ ───────────── │
246
236
  │ │ │
247
- │ w3pk_credential_*: │ Web3PasskeyWallet: │
237
+ │ w3pk_credential_*: │ w3pk_wallet_<address>: │
248
238
  │ { │ { │
249
239
  │ id: "hash(abc123)", │ ethereumAddress, │
250
240
  │ publicKey (plaintext), │ encryptedMnemonic, │
@@ -278,9 +268,9 @@ STEP 1: WebAuthn Authentication
278
268
 
279
269
  STEP 2: Fetch Stored Data
280
270
  ┌────────────────────────────┬────────────────────────────┐
281
- │ localStorage │ IndexedDB │
271
+ │ localStorage │ localStorage │
282
272
  │ │ │
283
- │ Get by credentialId: │ Get by credentialId: │
273
+ │ Get by credentialId: │ Get by address: │
284
274
  │ → publicKey │ → encryptedMnemonic │
285
275
  └─────────────┬──────────────┴──────────────┬─────────────┘
286
276
  │ │
@@ -403,15 +393,16 @@ User wants to send 1 ETH
403
393
 
404
394
  **Why publicKey is plaintext**: It's needed to derive the encryption key. It's the **public** part of the WebAuthn key pair—not sensitive.
405
395
 
406
- ### IndexedDB Structure
396
+ ### Wallet Storage
407
397
 
408
- **Database**: `Web3PasskeyWallet`
409
- **Store**: `wallets`
410
- **Key Path**: `ethereumAddress`
398
+ **Storage**: localStorage, next to the credential metadata, so browser eviction removes both or neither
399
+ **Key**: `w3pk_wallet_<ethereumAddress>`
411
400
  **Purpose**: Encrypted wallet storage
412
401
 
402
+ Persistent sessions use `w3pk_session_<ethereumAddress>` and backup metadata `w3pk_backups`, in the same localStorage.
403
+
413
404
  ```typescript
414
- // Example record in IndexedDB
405
+ // Example record in localStorage
415
406
  {
416
407
  ethereumAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
417
408
  encryptedMnemonic: "U2FsdGVkX1+vupppZksvRf...", // AES-256-GCM blob
@@ -496,29 +487,43 @@ const signedTx = await wallet.signTransaction(tx);
496
487
  **Implementation**: [src/wallet/crypto.ts:21-66](src/wallet/crypto.ts#L21-L66)
497
488
 
498
489
  ```javascript
499
- // SECURE: PRF-based key derivation
500
490
  async function deriveEncryptionKeyFromWebAuthn(
501
- prfOutput: ArrayBuffer, // From WebAuthn PRF extension
502
- salt: Uint8Array // Random 32-byte salt
491
+ credentialId: string,
492
+ publicKey: string
503
493
  ): Promise<CryptoKey> {
504
- // 1. Import PRF output as key material (authenticator secret)
505
- const keyMaterial = await crypto.subtle.importKey(
494
+ // 1. Combine inputs into key material
495
+ const keyMaterial = `w3pk-v4:${credentialId}:${publicKey}`;
496
+
497
+ // 2. SHA-256 hash
498
+ const keyMaterialHash = await crypto.subtle.digest(
499
+ "SHA-256",
500
+ new TextEncoder().encode(keyMaterial)
501
+ );
502
+
503
+ // 3. Import as PBKDF2 base key
504
+ const importedKey = await crypto.subtle.importKey(
506
505
  "raw",
507
- prfOutput, // SECRET from authenticator
506
+ keyMaterialHash,
508
507
  { name: "PBKDF2" },
509
508
  false,
510
509
  ["deriveKey"]
511
510
  );
512
511
 
513
- // 2. Derive AES-256-GCM key with PBKDF2
512
+ // 4. Generate deterministic salt
513
+ const salt = await crypto.subtle.digest(
514
+ "SHA-256",
515
+ new TextEncoder().encode("w3pk-salt-v4")
516
+ );
517
+
518
+ // 5. Derive AES-256-GCM key
514
519
  return crypto.subtle.deriveKey(
515
520
  {
516
521
  name: "PBKDF2",
517
- salt: salt, // Random 32-byte salt (stored with ciphertext)
522
+ salt: new Uint8Array(salt),
518
523
  iterations: 210000, // OWASP 2023 recommendation
519
524
  hash: "SHA-256",
520
525
  },
521
- keyMaterial, // PRF output from authenticator
526
+ importedKey,
522
527
  { name: "AES-GCM", length: 256 },
523
528
  false,
524
529
  ["encrypt", "decrypt"]
@@ -526,12 +531,11 @@ async function deriveEncryptionKeyFromWebAuthn(
526
531
  }
527
532
  ```
528
533
 
529
- **Security Properties**:
530
- - **Authenticator-Bound**: PRF output is hardware-held secret (never exposed)
531
- - **Unique Salts**: Each encryption uses random salt (no precomputation)
532
- - **Strong KDF**: 210,000 PBKDF2 iterations make brute-force impractical (OWASP 2023)
534
+ **Properties**:
535
+ - **Deterministic**: Same inputs always produce same output
536
+ - **Secure**: 210,000 iterations make brute-force impractical
533
537
  - **Stateless**: No need to store the encryption key
534
- - **Fast**: ~100-200ms on modern devices
538
+ - **Fast enough**: ~100-200ms on modern devices
535
539
 
536
540
  ---
537
541
 
@@ -560,7 +564,7 @@ Layer 2: Encryption Key Derivation
560
564
  Layer 3: Encrypted Mnemonic Storage
561
565
  ┌─────────────────────────────────────┐
562
566
  │ ✅ AES-256-GCM encryption │
563
- │ ✅ IndexedDB storage │
567
+ │ ✅ localStorage storage │
564
568
  │ ✅ Cannot decrypt without Layers 1&2│
565
569
  └─────────────────────────────────────┘
566
570
  ↓ REVEALS
@@ -746,7 +750,7 @@ Passkey (Face ID) → Decrypt mnemonic → Use wallet
746
750
  |---------|----------|---------------|------------|
747
751
  | **Curve** | P-256 | secp256k1 | N/A (uses AES) |
748
752
  | **Purpose** | Authentication | Transactions | Encryption |
749
- | **Storage** | Secure Enclave | IndexedDB | None (derived) |
753
+ | **Storage** | Secure Enclave | localStorage | None (derived) |
750
754
  | **Backup** | iCloud/Google | 12-word phrase | N/A |
751
755
  | **Standards** | FIDO2, W3C | BIP32/39/44 | PBKDF2, AES-GCM |
752
756
  | **Managed By** | OS | App | App |
@@ -805,7 +809,7 @@ Scenarios:
805
809
  }
806
810
  ```
807
811
 
808
- ### What's in IndexedDB?
812
+ ### What's in `w3pk_wallet_<address>`?
809
813
 
810
814
  ```json
811
815
  {
@@ -97,6 +97,19 @@ This document details WebAuthn support across browsers, operating systems, and d
97
97
  | **VirtualBox/VMs** | No biometric passthrough | Use password fallback |
98
98
  | **Remote Desktop** | Biometrics not forwarded | Use local device |
99
99
 
100
+ #### 🗑️ **Storage That Can Be Wiped**
101
+
102
+ The encrypted wallet, persistent sessions and backup metadata live in localStorage, next to the credential metadata, so they are either all there or all gone. The passkey itself lives in the authenticator and survives all of the cases below, but the wallet does not: the mnemonic is random and can't be rebuilt from the passkey. Users need a backup file or the recovery phrase.
103
+
104
+ | Environment | What happens | Mitigation |
105
+ |-------------|--------------|------------|
106
+ | **Safari (macOS, iOS)** | localStorage deleted after 7 days of browser use without the user interacting with the site | Add the web app to the Home Screen (exempt), keep a backup |
107
+ | **Any browser: clearing site data** | localStorage deleted with cookies and site data | Keep a backup |
108
+ | **Private/Incognito windows** | localStorage discarded when the window closes | Don't use for a long-lived wallet |
109
+ | **Chrome/Firefox under storage pressure** | Origins without persistent storage can be evicted | w3pk calls `navigator.storage.persist()`; check `w3pk.storagePersisted` |
110
+
111
+ Chrome grants persistent storage from engagement heuristics (bookmarked, installed, frequently visited) without a prompt; Firefox asks the user; Safari doesn't exempt sites from its 7-day cap. See [SECURITY.md → Storage durability](./SECURITY.md#storage-durability-what-can-still-wipe-the-wallet).
112
+
100
113
  ### Hardware Security Keys
101
114
 
102
115
  | Key Type | CTAP Version | w3pk Support | Release Date |
@@ -36,13 +36,13 @@ await w3pk.getAddress()
36
36
 
37
37
  ### Don't Import Internal Classes
38
38
 
39
- Internal implementation classes like `WalletSigner`, `SessionManager`, `IndexedDBWalletStorage`, etc. are **not part of the public API** and may change without notice:
39
+ Internal implementation classes like `WalletSigner`, `SessionManager`, `LocalStorageWalletStorage`, etc. are **not part of the public API** and may change without notice:
40
40
 
41
41
  ```typescript
42
42
  // ❌ Don't do this - internal APIs
43
43
  import { WalletSigner } from 'w3pk/wallet/signing'
44
44
  import { SessionManager } from 'w3pk/core/session'
45
- import { IndexedDBWalletStorage } from 'w3pk/wallet/storage'
45
+ import { LocalStorageWalletStorage } from 'w3pk/wallet/storage'
46
46
 
47
47
  // ✅ Do this instead - public SDK API
48
48
  import { createWeb3Passkey } from 'w3pk'
@@ -90,9 +90,9 @@ const auth2 = await w3pk.signAuthorization({
90
90
  ```typescript
91
91
  // ❌ Don't use internal WalletSigner class directly
92
92
  import { WalletSigner } from 'w3pk/wallet/signing'
93
- import { IndexedDBWalletStorage } from 'w3pk/wallet/storage'
93
+ import { LocalStorageWalletStorage } from 'w3pk/wallet/storage'
94
94
 
95
- const storage = new IndexedDBWalletStorage()
95
+ const storage = new LocalStorageWalletStorage()
96
96
  const signer = new WalletSigner(storage)
97
97
 
98
98
  // This bypasses session management and requires manual credential handling
@@ -120,6 +120,7 @@ await signer.signAuthorization(
120
120
 
121
121
  **Backup & Recovery:**
122
122
  - `createBackupFile()` - Create encrypted backup
123
+ - `confirmRecoveryPhraseBackup()` - Record that the user wrote down the recovery phrase
123
124
  - `restoreFromBackupFile()` - Restore from backup
124
125
  - `setupSocialRecovery()` - Split backup among guardians
125
126
  - `recoverFromGuardians()` - Recover from guardian shares
@@ -696,6 +697,8 @@ const result = await w3pk.signMessage(message, {
696
697
  })
697
698
  ```
698
699
 
700
+ SIWE works in STANDARD, STRICT and YOLO modes; PRIMARY mode throws. Get the address with the same mode and tag you sign with. In production, have the server issue the nonce and tie it to the address, as EIP-4361 recommends; see [examples/siwe-login.ts](../examples/siwe-login.ts).
701
+
699
702
  **Use for:**
700
703
  - Web3 authentication flows
701
704
  - App login
@@ -1220,23 +1223,37 @@ async function promptBackupOptions() {
1220
1223
 
1221
1224
  ### Allow Users Multiple Backup Options
1222
1225
 
1223
- **Critical:** Users should set up at least one backup method immediately after registration.
1226
+ **Critical:** Users should set up at least one backup method immediately after registration. Browser storage can be wiped (eviction, Safari's 7-day cap, clearing site data), and a wallet without a backup is then lost for good.
1224
1227
 
1225
1228
  ```typescript
1226
- // ✅ Provide multiple backup options
1227
- async function setupBackups() {
1228
- const status = await w3pk.getBackupStatus()
1229
+ // ✅ Ask for a backup right after registration
1230
+ const { hasBackup } = await w3pk.register({ username })
1229
1231
 
1230
- console.log('Security Score:', status.securityScore.score)
1231
- console.log('Has passkey sync:', status.securityScore.hasPasskeyBackup)
1232
- console.log('Has encrypted backup:', status.securityScore.hasEncryptedBackup)
1233
- console.log('Has social recovery:', status.securityScore.hasSocialRecovery)
1232
+ if (!hasBackup) {
1233
+ // "Back up now": a backup file, or the recovery phrase written down
1234
+ const choice = await showBackupNowPrompt()
1234
1235
 
1235
- // Warn if security score is low
1236
- if (status.securityScore.score < 60) {
1237
- showBackupWarning()
1236
+ if (choice === 'file') {
1237
+ const { blob, filename } = await w3pk.createBackupFile('password', password)
1238
+ downloadFile(blob, filename)
1239
+ } else if (choice === 'phrase') {
1240
+ await showRecoveryPhrase()
1241
+ await w3pk.confirmRecoveryPhraseBackup()
1238
1242
  }
1239
1243
  }
1244
+
1245
+ // ✅ Keep warning while no backup exists
1246
+ async function checkBackup() {
1247
+ const status = await w3pk.getBackupStatus()
1248
+
1249
+ if (!status.hasBackup) {
1250
+ showBackupWarning() // the score is capped at 20 ('vulnerable')
1251
+ }
1252
+
1253
+ console.log('Security Score:', status.securityScore.total)
1254
+ console.log('Backup methods:', status.methods) // 'file' | 'qr' | 'phrase'
1255
+ console.log('Last backup:', status.lastBackupAt)
1256
+ }
1240
1257
  ```
1241
1258
 
1242
1259
  ### Three-Layer Backup Strategy
@@ -1252,7 +1269,7 @@ Encourage users to enable multiple backup methods:
1252
1269
  // - Microsoft Account (Windows/Edge)
1253
1270
 
1254
1271
  const status = await w3pk.getBackupStatus()
1255
- if (status.securityScore.hasPasskeyBackup) {
1272
+ if (status.passkeySync.enabled) {
1256
1273
  console.log('✅ Passkey synced to cloud')
1257
1274
  }
1258
1275
  ```
@@ -1316,11 +1333,10 @@ async function setupSocialRecovery() {
1316
1333
  // Check backup status regularly
1317
1334
  async function checkBackupReminder() {
1318
1335
  const status = await w3pk.getBackupStatus()
1319
- const daysSinceRegistration = calculateDaysSince(status.createdAt)
1336
+ const daysSinceRegistration = calculateDaysSince(registeredAt) // tracked by your app
1320
1337
 
1321
1338
  // Remind users who haven't set up backup
1322
- if (!status.securityScore.hasEncryptedBackup &&
1323
- !status.securityScore.hasSocialRecovery) {
1339
+ if (!status.hasBackup) {
1324
1340
 
1325
1341
  if (daysSinceRegistration === 1) {
1326
1342
  showBackupReminder('urgent')
@@ -1412,13 +1428,10 @@ const strictWallet = await w3pk.deriveWallet('STRICT')
1412
1428
  ```
1413
1429
 
1414
1430
  **Persistent Session Security:**
1415
- - STANDARD mode: Persistent sessions ✅ allowed
1416
- - YOLO mode: Persistent sessions ✅ allowed
1417
- - STRICT mode: Persistent sessions ❌ NEVER allowed
1418
- - Sessions encrypted with WebAuthn-derived keys
1419
- - Requires valid credential to decrypt
1420
- - Time-limited expiration
1421
- - Origin-isolated via IndexedDB
1431
+ - STANDARD / YOLO: persistent sessions allowed. STRICT: ❌ NEVER allowed.
1432
+ - Time-limited expiration; origin-isolated via localStorage.
1433
+ - ⚠️ The at-rest key is derived from **public** credential metadata in the same browser profile, not an authenticator secret — a persistent session is **decryptable by anyone who can read this origin's storage**, for the whole duration it's enabled. "Remember Me" is a UX-for-security trade-off that widens the exposure window; it does not add a new trust dependency beyond the origin-code integrity you already rely on. Keep the duration short for higher-value wallets and don't enable on shared devices.
1434
+ - Decide this deliberately against your threat model: **[SECURITY.md → At-Rest Encryption](./SECURITY.md#at-rest-encryption-what-it-protects-and-what-it-doesnt)**.
1422
1435
 
1423
1436
  ### Build Verification
1424
1437