@abraca/dabra 2.90.0 → 2.92.0

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.
Files changed (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,754 +0,0 @@
1
- /**
2
- * CryptoIdentityKeystore
3
- *
4
- * Ed25519 identity management with two derivation modes:
5
- *
6
- * 1. **Passkey-only (legacy)**: PRF output → HKDF → Ed25519 seed.
7
- * The passkey IS the identity source.
8
- *
9
- * 2. **Mnemonic-rooted**: BIP-39 mnemonic → Ed25519 seed, encrypted by
10
- * passkey PRF for day-to-day convenience. The mnemonic IS the identity
11
- * source; the passkey is a convenience wrapper. Recovery via mnemonic
12
- * re-derives the exact same key.
13
- *
14
- * Both modes coexist. IndexedDB records with `encryptedSeed` use mode 2;
15
- * records without it use mode 1 (backward compatible).
16
- *
17
- * Dependencies: @noble/ed25519, @noble/hashes, @noble/curves, @scure/bip39
18
- */
19
-
20
- import * as ed from "@noble/ed25519";
21
- import { hkdf } from "@noble/hashes/hkdf.js";
22
- import { sha256, sha512 } from "@noble/hashes/sha2.js";
23
- import { ed25519 as nobleEd25519Curves } from "@noble/curves/ed25519.js";
24
-
25
- // @noble/ed25519 v3: wire sha512 for sync paths and define an async hook so
26
- // signAsync/verifyAsync don't require a Web Crypto fallback in Node.
27
- ed.hashes.sha512 = sha512;
28
- ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
29
- import {
30
- mnemonicToKeyPair,
31
- mnemonicToEd25519Seed,
32
- deriveSeedWrappingKey,
33
- wrapSeed,
34
- unwrapSeed,
35
- } from "./MnemonicKeyDerivation.ts";
36
-
37
- // ── Constants ───────────────────────────────────────────────────────────────
38
-
39
- /**
40
- * Fixed PRF eval salt. Must be constant across all devices so the same synced
41
- * passkey produces the same PRF output everywhere.
42
- *
43
- * Value: SHA-256("abracadabra-prf-salt-v1"), precomputed.
44
- */
45
- const PRF_SALT = new Uint8Array([
46
- 0xb7, 0x79, 0x41, 0xa2, 0xe7, 0x85, 0x1d, 0xfa,
47
- 0x5e, 0xc1, 0xab, 0xb6, 0x50, 0x1a, 0x5c, 0x85,
48
- 0x75, 0xfd, 0x3e, 0x3f, 0x92, 0xc9, 0xe1, 0xa7,
49
- 0x4e, 0xba, 0x71, 0xfc, 0xf2, 0xb1, 0x12, 0xcf,
50
- ]);
51
-
52
- const HKDF_INFO = new TextEncoder().encode("abracadabra-identity-v1");
53
-
54
- // ── Types ────────────────────────────────────────────────────────────────────
55
-
56
- /** Lightweight cache record — no private key material stored in plaintext. */
57
- interface StoredIdentity {
58
- username: string;
59
- /** base64url-encoded Ed25519 public key (32 bytes). */
60
- publicKey: string;
61
- /** WebAuthn credential ID for allowCredentials hint. */
62
- credentialId: ArrayBuffer;
63
- // ── Mnemonic-rooted fields (absent = legacy passkey-only mode) ──
64
- /** AES-256-GCM ciphertext of the 32-byte Ed25519 seed (48 bytes with tag). */
65
- encryptedSeed?: ArrayBuffer;
66
- /** 12-byte AES-GCM nonce used for seed encryption. */
67
- seedIv?: Uint8Array;
68
- /** 32-byte random salt for HKDF(PRF → wrapping key). Per-credential. */
69
- wrapSalt?: Uint8Array;
70
- /** How the identity was created. Absent = legacy passkey-only. */
71
- authMethod?: "passkey" | "mnemonic";
72
- }
73
-
74
- // ── Helpers ──────────────────────────────────────────────────────────────────
75
-
76
- function toBase64url(bytes: Uint8Array): string {
77
- return btoa(String.fromCharCode(...bytes))
78
- .replace(/\+/g, "-")
79
- .replace(/\//g, "_")
80
- .replace(/=/g, "");
81
- }
82
-
83
- function fromBase64url(b64: string): Uint8Array {
84
- const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
85
- const padLen = (4 - (padded.length % 4)) % 4;
86
- const padded2 = padded + "=".repeat(padLen);
87
- return Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));
88
- }
89
-
90
- const DB_NAME = "abracadabra:identity";
91
- const STORE_NAME = "identity";
92
-
93
- // ── IndexedDB helpers ─────────────────────────────────────────────────────────
94
-
95
- function openDb(): Promise<IDBDatabase> {
96
- return new Promise((resolve, reject) => {
97
- const req = indexedDB.open(DB_NAME, 3);
98
- req.onupgradeneeded = () => {
99
- const db = req.result;
100
- // v1: plain object store; v2: credentialId-keyed records
101
- // v3: optional encryptedSeed/seedIv/wrapSalt/authMethod fields on values
102
- // (no structural changes — same store, new optional value fields)
103
- if (!db.objectStoreNames.contains(STORE_NAME)) {
104
- db.createObjectStore(STORE_NAME);
105
- }
106
- };
107
- req.onsuccess = () => resolve(req.result);
108
- req.onerror = () => reject(req.error);
109
- });
110
- }
111
-
112
- async function dbGetAll(db: IDBDatabase): Promise<{ key: IDBValidKey; value: StoredIdentity }[]> {
113
- return new Promise((resolve, reject) => {
114
- const tx = db.transaction(STORE_NAME, "readonly");
115
- const store = tx.objectStore(STORE_NAME);
116
- const results: { key: IDBValidKey; value: StoredIdentity }[] = [];
117
- const req = store.openCursor();
118
- req.onsuccess = () => {
119
- const cursor = req.result;
120
- if (cursor) {
121
- results.push({ key: cursor.key, value: cursor.value as StoredIdentity });
122
- cursor.continue();
123
- } else {
124
- resolve(results);
125
- }
126
- };
127
- req.onerror = () => reject(req.error);
128
- });
129
- }
130
-
131
- async function dbGet(db: IDBDatabase, key: string): Promise<StoredIdentity | undefined> {
132
- return new Promise((resolve, reject) => {
133
- const tx = db.transaction(STORE_NAME, "readonly");
134
- const req = tx.objectStore(STORE_NAME).get(key);
135
- req.onsuccess = () => resolve(req.result as StoredIdentity | undefined);
136
- req.onerror = () => reject(req.error);
137
- });
138
- }
139
-
140
- async function dbPut(db: IDBDatabase, key: string, value: StoredIdentity): Promise<void> {
141
- return new Promise((resolve, reject) => {
142
- const tx = db.transaction(STORE_NAME, "readwrite");
143
- const req = tx.objectStore(STORE_NAME).put(value, key);
144
- req.onsuccess = () => resolve();
145
- req.onerror = () => reject(req.error);
146
- });
147
- }
148
-
149
- async function dbDelete(db: IDBDatabase, key: string): Promise<void> {
150
- return new Promise((resolve, reject) => {
151
- const tx = db.transaction(STORE_NAME, "readwrite");
152
- const req = tx.objectStore(STORE_NAME).delete(key);
153
- req.onsuccess = () => resolve();
154
- req.onerror = () => reject(req.error);
155
- });
156
- }
157
-
158
- async function dbClear(db: IDBDatabase): Promise<void> {
159
- return new Promise((resolve, reject) => {
160
- const tx = db.transaction(STORE_NAME, "readwrite");
161
- const req = tx.objectStore(STORE_NAME).clear();
162
- req.onsuccess = () => resolve();
163
- req.onerror = () => reject(req.error);
164
- });
165
- }
166
-
167
- // ── Key derivation ────────────────────────────────────────────────────────────
168
-
169
- /** Derive a 32-byte Ed25519 seed from raw PRF output. */
170
- function deriveEd25519Seed(prfOutput: ArrayBuffer): Uint8Array {
171
- return hkdf(sha256, new Uint8Array(prfOutput), PRF_SALT, HKDF_INFO, 32);
172
- }
173
-
174
- // ── PRF extraction helper ────────────────────────────────────────────────────
175
-
176
- function extractPrfOutput(
177
- credential: PublicKeyCredential,
178
- ): ArrayBuffer {
179
- const extResults = credential.getClientExtensionResults() as {
180
- prf?: { results?: { first?: ArrayBuffer } };
181
- };
182
- const prfOutput = extResults?.prf?.results?.first;
183
- if (!prfOutput) {
184
- throw new Error(
185
- "WebAuthn PRF extension not available on this authenticator. " +
186
- "A PRF-capable platform authenticator (e.g. iCloud Keychain) is required.",
187
- );
188
- }
189
- return prfOutput;
190
- }
191
-
192
- // ── Main class ───────────────────────────────────────────────────────────────
193
-
194
- export class CryptoIdentityKeystore {
195
-
196
- /**
197
- * Check whether the platform supports WebAuthn with PRF extension.
198
- * Call this before offering the "Secure with Passkey" option.
199
- */
200
- static async isPrfAvailable(): Promise<boolean> {
201
- if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
202
- try {
203
- // Check for platform authenticator
204
- const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
205
- if (!available) return false;
206
-
207
- // PRF is indicated by the presence of the extension in the client;
208
- // there's no direct feature-detection API. We check for the
209
- // AuthenticationExtensionsClientInputs type support as a proxy.
210
- // The definitive test happens at registration time.
211
- return true;
212
- } catch {
213
- return false;
214
- }
215
- }
216
-
217
- /**
218
- * Create a synced discoverable passkey and derive the Ed25519 identity from
219
- * its PRF output. The passkey is stored in the platform credential manager
220
- * (e.g. iCloud Keychain) and syncs across devices automatically.
221
- *
222
- * Returns the base64url-encoded public key, X25519 public key, and credential ID.
223
- * The caller must register the public key with the server.
224
- */
225
- async register(
226
- username: string,
227
- rpId: string,
228
- rpName: string,
229
- ): Promise<{ publicKey: string; x25519PublicKey: string; credentialId: string }> {
230
- // 1. Create a discoverable WebAuthn credential with PRF
231
- const credential = await navigator.credentials.create({
232
- publicKey: {
233
- challenge: crypto.getRandomValues(new Uint8Array(32)),
234
- rp: { id: rpId, name: rpName },
235
- user: {
236
- id: new TextEncoder().encode(username),
237
- name: username,
238
- displayName: username,
239
- },
240
- pubKeyCredParams: [
241
- { alg: -7, type: "public-key" }, // ES256
242
- { alg: -257, type: "public-key" }, // RS256
243
- ],
244
- authenticatorSelection: {
245
- residentKey: "required",
246
- requireResidentKey: true,
247
- userVerification: "required",
248
- },
249
- extensions: {
250
- prf: { eval: { first: PRF_SALT.buffer } },
251
- } as AuthenticationExtensionsClientInputs,
252
- },
253
- }) as PublicKeyCredential | null;
254
-
255
- if (!credential) {
256
- throw new Error("WebAuthn credential creation cancelled");
257
- }
258
-
259
- // 2. Extract PRF output and derive Ed25519 keypair
260
- const prfOutput = extractPrfOutput(credential);
261
- const seed = deriveEd25519Seed(prfOutput);
262
- const publicKey = await ed.getPublicKeyAsync(seed);
263
- const publicKeyB64 = toBase64url(publicKey);
264
-
265
- // 3. Derive X25519 public key
266
- const x25519Pub = nobleEd25519Curves.utils.toMontgomery(publicKey);
267
- const x25519PubB64 = toBase64url(x25519Pub);
268
-
269
- // 4. Credential ID for future allowCredentials hints
270
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
271
-
272
- // 5. Cache in IndexedDB (lightweight — no private key material)
273
- const db = await openDb();
274
- await dbPut(db, credentialIdB64, {
275
- username,
276
- publicKey: publicKeyB64,
277
- credentialId: credential.rawId,
278
- });
279
- db.close();
280
-
281
- // 6. Wipe seed from memory
282
- seed.fill(0);
283
-
284
- return {
285
- publicKey: publicKeyB64,
286
- x25519PublicKey: x25519PubB64,
287
- credentialId: credentialIdB64,
288
- };
289
- }
290
-
291
- /**
292
- * Sign a base64url-encoded challenge using the Ed25519 key derived from
293
- * a passkey assertion. Triggers a WebAuthn prompt (biometric / PIN).
294
- *
295
- * @param challengeB64 - base64url-encoded challenge bytes from the server.
296
- * @param credentialIdHint - optional credential ID to select a specific passkey.
297
- * @returns base64url-encoded Ed25519 signature (64 bytes).
298
- */
299
- async sign(challengeB64: string, credentialIdHint?: string): Promise<string> {
300
- const { seed } = await this._assertAndDerive(credentialIdHint);
301
-
302
- try {
303
- const challengeBytes = fromBase64url(challengeB64);
304
- const signature = await ed.signAsync(challengeBytes, seed);
305
- return toBase64url(signature);
306
- } finally {
307
- seed.fill(0);
308
- }
309
- }
310
-
311
- /**
312
- * Returns the cached base64url public key, or null if no identity is cached.
313
- *
314
- * Does NOT trigger a WebAuthn prompt. If the cache is empty (e.g. IndexedDB
315
- * cleared), returns null — the identity can be recovered via sign() or
316
- * a fresh register() with the same synced passkey.
317
- */
318
- async getPublicKey(credentialIdHint?: string): Promise<string | null> {
319
- const db = await openDb();
320
- try {
321
- if (credentialIdHint) {
322
- const stored = await dbGet(db, credentialIdHint);
323
- return stored?.publicKey ?? null;
324
- }
325
- // Return the first cached identity
326
- const all = await dbGetAll(db);
327
- return all.length > 0 ? all[0].value.publicKey : null;
328
- } finally {
329
- db.close();
330
- }
331
- }
332
-
333
- /**
334
- * Returns the locally-cached username label, or null if no identity is cached.
335
- */
336
- async getUsername(credentialIdHint?: string): Promise<string | null> {
337
- const db = await openDb();
338
- try {
339
- if (credentialIdHint) {
340
- const stored = await dbGet(db, credentialIdHint);
341
- return stored?.username ?? null;
342
- }
343
- const all = await dbGetAll(db);
344
- return all.length > 0 ? all[0].value.username : null;
345
- } finally {
346
- db.close();
347
- }
348
- }
349
-
350
- /**
351
- * Updates the cached username for a given credential (or the first cached identity).
352
- * Call this after the user sets/changes their display name so it persists across devices.
353
- */
354
- async setUsername(username: string, credentialIdHint?: string): Promise<void> {
355
- const db = await openDb();
356
- try {
357
- if (credentialIdHint) {
358
- const stored = await dbGet(db, credentialIdHint);
359
- if (stored) {
360
- await dbPut(db, credentialIdHint, { ...stored, username });
361
- }
362
- } else {
363
- const all = await dbGetAll(db);
364
- if (all.length > 0) {
365
- await dbPut(db, String(all[0].key), { ...all[0].value, username });
366
- }
367
- }
368
- } finally {
369
- db.close();
370
- }
371
- }
372
-
373
- /** Returns true if an identity is cached in IndexedDB. */
374
- async hasIdentity(): Promise<boolean> {
375
- const db = await openDb();
376
- try {
377
- const all = await dbGetAll(db);
378
- return all.length > 0;
379
- } finally {
380
- db.close();
381
- }
382
- }
383
-
384
- /** Remove cached identity record(s) from IndexedDB. The passkey itself
385
- * remains in the platform credential store. */
386
- async clear(): Promise<void> {
387
- const db = await openDb();
388
- await dbClear(db);
389
- db.close();
390
- }
391
-
392
- /**
393
- * Returns the X25519 public key derived from the cached Ed25519 public key.
394
- * Does NOT require WebAuthn — computed from the cached public key only.
395
- * Returns null if no identity is cached.
396
- */
397
- async getX25519PublicKey(): Promise<Uint8Array | null> {
398
- const db = await openDb();
399
- try {
400
- const all = await dbGetAll(db);
401
- if (all.length === 0) return null;
402
- const edPub = fromBase64url(all[0].value.publicKey);
403
- return nobleEd25519Curves.utils.toMontgomery(edPub);
404
- } finally {
405
- db.close();
406
- }
407
- }
408
-
409
- /**
410
- * Returns the X25519 private key derived from the Ed25519 seed.
411
- * Requires a WebAuthn assertion to get the PRF output.
412
- * The caller MUST wipe the returned Uint8Array after use.
413
- */
414
- async getX25519PrivateKey(credentialIdHint?: string): Promise<Uint8Array> {
415
- const { seed } = await this._assertAndDerive(credentialIdHint);
416
- try {
417
- return nobleEd25519Curves.utils.toMontgomerySecret(seed);
418
- } finally {
419
- seed.fill(0);
420
- }
421
- }
422
-
423
- /**
424
- * Trigger a WebAuthn assertion to derive (or re-derive) the identity and
425
- * update the IndexedDB cache. Returns the public key and credential ID.
426
- *
427
- * Use this when the cache is empty but you need the public key before
428
- * signing (e.g. to send it to the server for the challenge request).
429
- */
430
- async deriveIdentity(credentialIdHint?: string): Promise<{ publicKey: string; credentialId: string }> {
431
- const { seed, publicKeyB64, credentialIdB64 } = await this._assertAndDerive(credentialIdHint);
432
- seed.fill(0);
433
- return { publicKey: publicKeyB64, credentialId: credentialIdB64 };
434
- }
435
-
436
- /**
437
- * List all cached credential IDs. Useful for account switching UI.
438
- */
439
- async listCachedIdentities(): Promise<{ credentialId: string; publicKey: string; username: string }[]> {
440
- const db = await openDb();
441
- try {
442
- const all = await dbGetAll(db);
443
- return all.map(({ key, value }) => ({
444
- credentialId: key as string,
445
- publicKey: value.publicKey,
446
- username: value.username,
447
- }));
448
- } finally {
449
- db.close();
450
- }
451
- }
452
-
453
- // ── Mnemonic-based methods ───────────────────────────────────────────────
454
-
455
- /**
456
- * Register a new identity rooted in a BIP-39 mnemonic. Optionally wraps the
457
- * derived seed with a passkey for biometric day-to-day access.
458
- *
459
- * @param username - Display name for the identity.
460
- * @param mnemonic - Valid BIP-39 mnemonic (12 or 24 words).
461
- * @param passphrase - Optional BIP-39 passphrase ("25th word").
462
- * @param rpId - WebAuthn relying party ID (omit to skip passkey wrapping).
463
- * @param rpName - WebAuthn relying party display name.
464
- * @returns Public keys and optional credential ID.
465
- */
466
- async registerWithMnemonic(
467
- username: string,
468
- mnemonic: string,
469
- passphrase?: string,
470
- rpId?: string,
471
- rpName?: string,
472
- ): Promise<{ publicKey: string; x25519PublicKey: string; credentialId?: string }> {
473
- const kp = await mnemonicToKeyPair(mnemonic, passphrase);
474
-
475
- try {
476
- if (rpId && rpName) {
477
- // Create a passkey to wrap the mnemonic-derived seed
478
- const credential = await navigator.credentials.create({
479
- publicKey: {
480
- challenge: crypto.getRandomValues(new Uint8Array(32)),
481
- rp: { id: rpId, name: rpName },
482
- user: {
483
- id: new TextEncoder().encode(username),
484
- name: username,
485
- displayName: username,
486
- },
487
- pubKeyCredParams: [
488
- { alg: -7, type: "public-key" },
489
- { alg: -257, type: "public-key" },
490
- ],
491
- authenticatorSelection: {
492
- residentKey: "required",
493
- requireResidentKey: true,
494
- userVerification: "required",
495
- },
496
- extensions: {
497
- prf: { eval: { first: PRF_SALT.buffer } },
498
- } as AuthenticationExtensionsClientInputs,
499
- },
500
- }) as PublicKeyCredential | null;
501
-
502
- if (!credential) {
503
- throw new Error("WebAuthn credential creation cancelled");
504
- }
505
-
506
- const prfOutput = extractPrfOutput(credential);
507
- const wrapSalt = crypto.getRandomValues(new Uint8Array(32));
508
- const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
509
- const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
510
- wrapKey.fill(0);
511
-
512
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
513
- const db = await openDb();
514
- await dbPut(db, credentialIdB64, {
515
- username,
516
- publicKey: kp.publicKeyB64,
517
- credentialId: credential.rawId,
518
- encryptedSeed: ciphertext,
519
- seedIv: iv,
520
- wrapSalt,
521
- authMethod: "mnemonic",
522
- });
523
- db.close();
524
-
525
- return {
526
- publicKey: kp.publicKeyB64,
527
- x25519PublicKey: kp.x25519PublicKeyB64,
528
- credentialId: credentialIdB64,
529
- };
530
- }
531
-
532
- // No passkey wrapping — ephemeral or mnemonic-only mode
533
- return {
534
- publicKey: kp.publicKeyB64,
535
- x25519PublicKey: kp.x25519PublicKeyB64,
536
- };
537
- } finally {
538
- kp.seed.fill(0);
539
- }
540
- }
541
-
542
- /**
543
- * Wrap an existing mnemonic-derived seed with a new passkey. Use this when
544
- * a user logged in via mnemonic and wants to add biometric convenience.
545
- *
546
- * @param mnemonic - The user's BIP-39 mnemonic.
547
- * @param passphrase - Optional BIP-39 passphrase.
548
- * @param rpId - WebAuthn relying party ID.
549
- * @param rpName - WebAuthn relying party display name.
550
- * @returns The new credential ID.
551
- */
552
- async wrapSeedWithPasskey(
553
- mnemonic: string,
554
- passphrase: string | undefined,
555
- rpId: string,
556
- rpName: string,
557
- ): Promise<{ credentialId: string }> {
558
- const kp = await mnemonicToKeyPair(mnemonic, passphrase);
559
- try {
560
- const credential = await navigator.credentials.create({
561
- publicKey: {
562
- challenge: crypto.getRandomValues(new Uint8Array(32)),
563
- rp: { id: rpId, name: rpName },
564
- user: {
565
- id: fromBase64url(kp.publicKeyB64) as BufferSource,
566
- name: kp.publicKeyB64.slice(0, 16),
567
- displayName: kp.publicKeyB64.slice(0, 16),
568
- },
569
- pubKeyCredParams: [
570
- { alg: -7, type: "public-key" },
571
- { alg: -257, type: "public-key" },
572
- ],
573
- authenticatorSelection: {
574
- residentKey: "required",
575
- requireResidentKey: true,
576
- userVerification: "required",
577
- },
578
- extensions: {
579
- prf: { eval: { first: PRF_SALT.buffer } },
580
- } as AuthenticationExtensionsClientInputs,
581
- },
582
- }) as PublicKeyCredential | null;
583
-
584
- if (!credential) {
585
- throw new Error("WebAuthn credential creation cancelled");
586
- }
587
-
588
- const prfOutput = extractPrfOutput(credential);
589
- const wrapSalt = crypto.getRandomValues(new Uint8Array(32));
590
- const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
591
- const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
592
- wrapKey.fill(0);
593
-
594
- const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
595
-
596
- // Try to preserve username from an existing record with the same pubkey
597
- let username = "";
598
- try {
599
- const db = await openDb();
600
- const all = await dbGetAll(db);
601
- const existing = all.find(e => e.value.publicKey === kp.publicKeyB64);
602
- if (existing) username = existing.value.username;
603
- db.close();
604
- } catch { /* non-fatal */ }
605
-
606
- const db = await openDb();
607
- await dbPut(db, credentialIdB64, {
608
- username,
609
- publicKey: kp.publicKeyB64,
610
- credentialId: credential.rawId,
611
- encryptedSeed: ciphertext,
612
- seedIv: iv,
613
- wrapSalt,
614
- authMethod: "mnemonic",
615
- });
616
- db.close();
617
-
618
- return { credentialId: credentialIdB64 };
619
- } finally {
620
- kp.seed.fill(0);
621
- }
622
- }
623
-
624
- /**
625
- * Sign a challenge directly with a provided seed. No WebAuthn prompt.
626
- * For ephemeral mnemonic sessions where the seed is held in memory.
627
- *
628
- * The caller manages the seed lifecycle (wiping on session end).
629
- */
630
- static async signWithSeed(challengeB64: string, seed: Uint8Array): Promise<string> {
631
- const challengeBytes = fromBase64url(challengeB64);
632
- const signature = await ed.signAsync(challengeBytes, seed);
633
- return toBase64url(signature);
634
- }
635
-
636
- /**
637
- * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
638
- * Useful for CLI or one-shot operations.
639
- */
640
- static async signWithMnemonic(
641
- mnemonic: string,
642
- challengeB64: string,
643
- passphrase?: string,
644
- ): Promise<string> {
645
- const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
646
- try {
647
- const challengeBytes = fromBase64url(challengeB64);
648
- const signature = await ed.signAsync(challengeBytes, seed);
649
- return toBase64url(signature);
650
- } finally {
651
- seed.fill(0);
652
- }
653
- }
654
-
655
- // ── Internal ─────────────────────────────────────────────────────────────
656
-
657
- /**
658
- * Perform a WebAuthn assertion with PRF, derive the Ed25519 seed, and
659
- * update the IndexedDB cache. Returns the seed (caller MUST wipe it).
660
- */
661
- private async _assertAndDerive(credentialIdHint?: string): Promise<{
662
- seed: Uint8Array;
663
- publicKeyB64: string;
664
- credentialIdB64: string;
665
- }> {
666
- // Build allowCredentials from hint or cached records
667
- const allowCredentials: PublicKeyCredentialDescriptor[] = [];
668
-
669
- if (credentialIdHint) {
670
- allowCredentials.push({
671
- id: fromBase64url(credentialIdHint) as BufferSource,
672
- type: "public-key",
673
- });
674
- } else {
675
- // Try cached credential IDs for a targeted prompt
676
- try {
677
- const db = await openDb();
678
- const all = await dbGetAll(db);
679
- db.close();
680
- for (const { value } of all) {
681
- allowCredentials.push({
682
- id: value.credentialId,
683
- type: "public-key",
684
- });
685
- }
686
- } catch {
687
- // IndexedDB unavailable — proceed with discoverable credentials
688
- }
689
- }
690
-
691
- const assertion = await navigator.credentials.get({
692
- publicKey: {
693
- challenge: crypto.getRandomValues(new Uint8Array(32)),
694
- ...(allowCredentials.length > 0 ? { allowCredentials } : {}),
695
- userVerification: "required",
696
- extensions: {
697
- prf: { eval: { first: PRF_SALT.buffer } },
698
- } as AuthenticationExtensionsClientInputs,
699
- },
700
- }) as PublicKeyCredential | null;
701
-
702
- if (!assertion) {
703
- throw new Error("WebAuthn assertion cancelled");
704
- }
705
-
706
- const prfOutput = extractPrfOutput(assertion);
707
- const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
708
-
709
- // Check if this credential has a wrapped mnemonic seed
710
- let stored: StoredIdentity | undefined;
711
- try {
712
- const db = await openDb();
713
- stored = await dbGet(db, credentialIdB64);
714
- db.close();
715
- } catch {
716
- // IndexedDB unavailable — fall through to legacy derivation
717
- }
718
-
719
- let seed: Uint8Array;
720
- if (stored?.encryptedSeed && stored.seedIv && stored.wrapSalt) {
721
- // Mnemonic-rooted: decrypt the stored seed using PRF-derived wrap key
722
- const wrapKey = deriveSeedWrappingKey(prfOutput, stored.wrapSalt);
723
- seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
724
- wrapKey.fill(0);
725
- } else {
726
- // Legacy passkey-only: derive seed directly from PRF via HKDF
727
- seed = deriveEd25519Seed(prfOutput);
728
- }
729
-
730
- const publicKey = await ed.getPublicKeyAsync(seed);
731
- const publicKeyB64 = toBase64url(publicKey);
732
-
733
- // Update cache (preserve mnemonic-rooted fields if present)
734
- try {
735
- const db = await openDb();
736
- const existing = await dbGet(db, credentialIdB64);
737
- await dbPut(db, credentialIdB64, {
738
- username: existing?.username ?? "",
739
- publicKey: publicKeyB64,
740
- credentialId: assertion.rawId,
741
- // Preserve wrapped seed fields from existing record
742
- encryptedSeed: existing?.encryptedSeed,
743
- seedIv: existing?.seedIv,
744
- wrapSalt: existing?.wrapSalt,
745
- authMethod: existing?.authMethod,
746
- });
747
- db.close();
748
- } catch {
749
- // Cache update failure is non-fatal
750
- }
751
-
752
- return { seed, publicKeyB64, credentialIdB64 };
753
- }
754
- }