@abraca/dabra 2.101.0 → 2.103.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 (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CoverReconcile.js","names":[],"sources":["../../src/CoverReconcile.ts"],"sourcesContent":["/**\n * CoverReconcile — keep a document's cover-image metadata in sync with the\n * image/video file blocks that actually live in its content.\n *\n * The cover (`meta.coverUploadId` / `coverDocId` / `coverMimeType` on the\n * doc's own tree entry) is *persisted* metadata, not derived live — the\n * kanban/gallery/table views read it without loading each card's content.\n * Historically the only thing that reconciled it was cou-sh's TipTap editor\n * (`reconcileCover` in DocRenderer.vue), so any write that did NOT go through\n * that editor — MCP `write_document`, `@abraca/convert`, the CLI, another SDK\n * — could leave an orphaned cover pointing at an image the body no longer\n * contains. This is the shared, write-path-level reconciliation so every\n * content write through the SDK keeps the cover honest.\n *\n * Semantics mirror cou-sh's editor reconciler exactly:\n * - cover set + still references a present image/video → leave it (a\n * user-chosen cover is preserved as long as its image is in the doc);\n * - cover set + its image is gone, others remain → swap to the first;\n * - cover set + no image/video remains → clear the three cover keys;\n * - no cover + at least one image/video → adopt the first as the cover.\n */\nimport * as Y from \"yjs\";\nimport { toPlain, patchEntry } from \"./DocUtils.ts\";\n\nexport interface MediaFileBlock {\n\tuploadId: string;\n\tdocId: string;\n\tmimeType: string;\n}\n\nconst EXT_MIME: Record<string, string> = {\n\tpng: \"image/png\",\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tgif: \"image/gif\",\n\twebp: \"image/webp\",\n\tavif: \"image/avif\",\n\tsvg: \"image/svg+xml\",\n\tbmp: \"image/bmp\",\n\theic: \"image/heic\",\n\theif: \"image/heif\",\n\tmp4: \"video/mp4\",\n\twebm: \"video/webm\",\n\tmov: \"video/quicktime\",\n\tm4v: \"video/x-m4v\",\n\togv: \"video/ogg\",\n\tmkv: \"video/x-matroska\",\n};\n\nfunction attr(node: Y.XmlElement, name: string): string | undefined {\n\tconst v = node.getAttribute(name);\n\treturn typeof v === \"string\" && v ? v : undefined;\n}\n\n/**\n * Resolve a file node's mime type. A `fileBlock` may carry the mime under\n * `mimeType` (cou-sh's TipTap/y-prosemirror node attr) or `mime` (the\n * `@abraca/convert` markdown path), and may carry neither — in which case we\n * infer it from the filename/src extension (the convert sidecar `src` is\n * `.abracadabra/files/<id>-<filename>`). Returns \"\" when it can't be\n * classified as image/video.\n */\nfunction resolveMime(node: Y.XmlElement): string {\n\tconst explicit = attr(node, \"mimeType\") ?? attr(node, \"mime\");\n\tif (explicit) return explicit;\n\tconst name = attr(node, \"filename\") ?? attr(node, \"src\") ?? \"\";\n\tconst ext = name.split(\".\").pop()?.toLowerCase() ?? \"\";\n\treturn EXT_MIME[ext] ?? \"\";\n}\n\n/**\n * Recursively collect image/video `fileBlock` nodes from a Y.XmlFragment (or\n * element subtree), in document order. Mirrors the TipTap\n * `doc.descendants()` walk used by cou-sh — fileBlocks may be nested inside\n * other block nodes, so this recurses rather than scanning only top level.\n */\nexport function collectMediaFileBlocks(\n\troot: Y.XmlFragment | Y.XmlElement,\n): MediaFileBlock[] {\n\tconst out: MediaFileBlock[] = [];\n\tconst visit = (node: Y.AbstractType<unknown>): void => {\n\t\tif (node instanceof Y.XmlElement && node.nodeName === \"fileBlock\") {\n\t\t\tconst uploadId = attr(node, \"uploadId\") ?? attr(node, \"upload-id\");\n\t\t\tif (uploadId) {\n\t\t\t\tconst mimeType = resolveMime(node);\n\t\t\t\tif (\n\t\t\t\t\tmimeType.startsWith(\"image/\") ||\n\t\t\t\t\tmimeType.startsWith(\"video/\")\n\t\t\t\t) {\n\t\t\t\t\tout.push({\n\t\t\t\t\t\tuploadId,\n\t\t\t\t\t\tdocId: attr(node, \"docId\") ?? \"\",\n\t\t\t\t\t\tmimeType,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (node instanceof Y.XmlElement || node instanceof Y.XmlFragment) {\n\t\t\tfor (let i = 0; i < node.length; i++) {\n\t\t\t\tvisit(node.get(i) as Y.AbstractType<unknown>);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(root as unknown as Y.AbstractType<unknown>);\n\treturn out;\n}\n\n/**\n * Reconcile the cover metadata of `docId`'s tree entry against the media file\n * blocks currently present in `fragment`. No-op when the entry is missing or\n * the cover is already valid, so it is safe (and cheap) to call after every\n * content write. The `treeMap` is the root doc-tree Y.Map; the cover lives on\n * the doc's OWN self-entry (`treeMap.get(docId).meta`).\n */\nexport function reconcileDocCover(\n\ttreeMap: Y.Map<unknown>,\n\tdocId: string,\n\tfragment: Y.XmlFragment | Y.XmlElement,\n): void {\n\tconst raw = treeMap.get(docId);\n\tif (!raw) return;\n\n\tconst entry = toPlain(raw) as Record<string, unknown>;\n\tconst meta = ((entry.meta as Record<string, unknown>) ?? {}) as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\tconst currentCoverId = meta.coverUploadId as string | undefined;\n\n\tconst media = collectMediaFileBlocks(fragment);\n\n\t// Cover already references a present image/video → nothing to do.\n\tif (currentCoverId && media.some((b) => b.uploadId === currentCoverId)) {\n\t\treturn;\n\t}\n\n\tif (media.length > 0) {\n\t\t// Adopt (no cover) or swap (stale cover) to the first media block.\n\t\tconst best = media[0]!;\n\t\tif (\n\t\t\tcurrentCoverId === best.uploadId &&\n\t\t\tmeta.coverDocId === (best.docId || docId) &&\n\t\t\tmeta.coverMimeType === best.mimeType\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tpatchEntry(treeMap, docId, {\n\t\t\tmeta: {\n\t\t\t\t...meta,\n\t\t\t\tcoverUploadId: best.uploadId,\n\t\t\t\tcoverDocId: best.docId || docId,\n\t\t\t\tcoverMimeType: best.mimeType,\n\t\t\t},\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t\treturn;\n\t}\n\n\t// No media remains. Clear the cover keys only if one was set.\n\tif (!currentCoverId && !meta.coverDocId && !meta.coverMimeType) return;\n\tconst {\n\t\tcoverUploadId: _cu,\n\t\tcoverDocId: _cd,\n\t\tcoverMimeType: _cm,\n\t\t...rest\n\t} = meta;\n\tpatchEntry(treeMap, docId, { meta: rest, updatedAt: Date.now() });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,WAAmC;CACxC,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,KAAK;CACL,KAAK;CACL,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL;AAED,SAAS,KAAK,MAAoB,MAAkC;CACnE,MAAM,IAAI,KAAK,aAAa,KAAK;AACjC,QAAO,OAAO,MAAM,YAAY,IAAI,IAAI;;;;;;;;;;AAWzC,SAAS,YAAY,MAA4B;CAChD,MAAM,WAAW,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,OAAO;AAC7D,KAAI,SAAU,QAAO;AAGrB,QAAO,UAFM,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,MAAM,IAAI,IAC3C,MAAM,IAAI,CAAC,KAAK,EAAE,aAAa,IAAI,OAC5B;;;;;;;;AASzB,SAAgB,uBACf,MACmB;CACnB,MAAM,MAAwB,EAAE;CAChC,MAAM,SAAS,SAAwC;AACtD,MAAI,gBAAgB,EAAE,cAAc,KAAK,aAAa,aAAa;GAClE,MAAM,WAAW,KAAK,MAAM,WAAW,IAAI,KAAK,MAAM,YAAY;AAClE,OAAI,UAAU;IACb,MAAM,WAAW,YAAY,KAAK;AAClC,QACC,SAAS,WAAW,SAAS,IAC7B,SAAS,WAAW,SAAS,CAE7B,KAAI,KAAK;KACR;KACA,OAAO,KAAK,MAAM,QAAQ,IAAI;KAC9B;KACA,CAAC;;;AAIL,MAAI,gBAAgB,EAAE,cAAc,gBAAgB,EAAE,YACrD,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,IAChC,OAAM,KAAK,IAAI,EAAE,CAA4B;;AAIhD,OAAM,KAA2C;AACjD,QAAO;;;;;;;;;AAUR,SAAgB,kBACf,SACA,OACA,UACO;CACP,MAAM,MAAM,QAAQ,IAAI,MAAM;AAC9B,KAAI,CAAC,IAAK;CAGV,MAAM,OADQ,QAAQ,IAAI,CACL,QAAoC,EAAE;CAI3D,MAAM,iBAAiB,KAAK;CAE5B,MAAM,QAAQ,uBAAuB,SAAS;AAG9C,KAAI,kBAAkB,MAAM,MAAM,MAAM,EAAE,aAAa,eAAe,CACrE;AAGD,KAAI,MAAM,SAAS,GAAG;EAErB,MAAM,OAAO,MAAM;AACnB,MACC,mBAAmB,KAAK,YACxB,KAAK,gBAAgB,KAAK,SAAS,UACnC,KAAK,kBAAkB,KAAK,SAE5B;AAED,aAAW,SAAS,OAAO;GAC1B,MAAM;IACL,GAAG;IACH,eAAe,KAAK;IACpB,YAAY,KAAK,SAAS;IAC1B,eAAe,KAAK;IACpB;GACD,WAAW,KAAK,KAAK;GACrB,CAAC;AACF;;AAID,KAAI,CAAC,kBAAkB,CAAC,KAAK,cAAc,CAAC,KAAK,cAAe;CAChE,MAAM,EACL,eAAe,KACf,YAAY,KACZ,eAAe,KACf,GAAG,SACA;AACJ,YAAW,SAAS,OAAO;EAAE,MAAM;EAAM,WAAW,KAAK,KAAK;EAAE,CAAC"}
@@ -0,0 +1,580 @@
1
+ import { ed25519PublicToX25519, ed25519SecretToX25519 } from "./x25519Convert.js";
2
+ import { deriveSeedWrappingKey, mnemonicToEd25519Seed, mnemonicToKeyPair, unwrapSeed, wrapSeed } from "./MnemonicKeyDerivation.js";
3
+ import { sha256, sha512 } from "@noble/hashes/sha2.js";
4
+ import * as ed from "@noble/ed25519";
5
+ import { hkdf } from "@noble/hashes/hkdf.js";
6
+
7
+ //#region packages/provider/src/CryptoIdentityKeystore.ts
8
+ /**
9
+ * CryptoIdentityKeystore
10
+ *
11
+ * Ed25519 identity management with two derivation modes:
12
+ *
13
+ * 1. **Passkey-only (legacy)**: PRF output → HKDF → Ed25519 seed.
14
+ * The passkey IS the identity source.
15
+ *
16
+ * 2. **Mnemonic-rooted**: BIP-39 mnemonic → Ed25519 seed, encrypted by
17
+ * passkey PRF for day-to-day convenience. The mnemonic IS the identity
18
+ * source; the passkey is a convenience wrapper. Recovery via mnemonic
19
+ * re-derives the exact same key.
20
+ *
21
+ * Both modes coexist. IndexedDB records with `encryptedSeed` use mode 2;
22
+ * records without it use mode 1 (backward compatible).
23
+ *
24
+ * Dependencies: @noble/ed25519, @noble/hashes, @noble/curves, @scure/bip39
25
+ */
26
+ ed.hashes.sha512 = sha512;
27
+ ed.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
28
+ /**
29
+ * Fixed PRF eval salt. Must be constant across all devices so the same synced
30
+ * passkey produces the same PRF output everywhere.
31
+ *
32
+ * Value: SHA-256("abracadabra-prf-salt-v1"), precomputed.
33
+ */
34
+ const PRF_SALT = new Uint8Array([
35
+ 183,
36
+ 121,
37
+ 65,
38
+ 162,
39
+ 231,
40
+ 133,
41
+ 29,
42
+ 250,
43
+ 94,
44
+ 193,
45
+ 171,
46
+ 182,
47
+ 80,
48
+ 26,
49
+ 92,
50
+ 133,
51
+ 117,
52
+ 253,
53
+ 62,
54
+ 63,
55
+ 146,
56
+ 201,
57
+ 225,
58
+ 167,
59
+ 78,
60
+ 186,
61
+ 113,
62
+ 252,
63
+ 242,
64
+ 177,
65
+ 18,
66
+ 207
67
+ ]);
68
+ const HKDF_INFO = new TextEncoder().encode("abracadabra-identity-v1");
69
+ function toBase64url(bytes) {
70
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
71
+ }
72
+ function fromBase64url(b64) {
73
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
74
+ const padLen = (4 - padded.length % 4) % 4;
75
+ const padded2 = padded + "=".repeat(padLen);
76
+ return Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));
77
+ }
78
+ const DB_NAME = "abracadabra:identity";
79
+ const STORE_NAME = "identity";
80
+ function openDb() {
81
+ return new Promise((resolve, reject) => {
82
+ const req = indexedDB.open(DB_NAME, 3);
83
+ req.onupgradeneeded = () => {
84
+ const db = req.result;
85
+ if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
86
+ };
87
+ req.onsuccess = () => resolve(req.result);
88
+ req.onerror = () => reject(req.error);
89
+ });
90
+ }
91
+ async function dbGetAll(db) {
92
+ return new Promise((resolve, reject) => {
93
+ const store = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME);
94
+ const results = [];
95
+ const req = store.openCursor();
96
+ req.onsuccess = () => {
97
+ const cursor = req.result;
98
+ if (cursor) {
99
+ results.push({
100
+ key: cursor.key,
101
+ value: cursor.value
102
+ });
103
+ cursor.continue();
104
+ } else resolve(results);
105
+ };
106
+ req.onerror = () => reject(req.error);
107
+ });
108
+ }
109
+ async function dbGet(db, key) {
110
+ return new Promise((resolve, reject) => {
111
+ const req = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(key);
112
+ req.onsuccess = () => resolve(req.result);
113
+ req.onerror = () => reject(req.error);
114
+ });
115
+ }
116
+ async function dbPut(db, key, value) {
117
+ return new Promise((resolve, reject) => {
118
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).put(value, key);
119
+ req.onsuccess = () => resolve();
120
+ req.onerror = () => reject(req.error);
121
+ });
122
+ }
123
+ async function dbClear(db) {
124
+ return new Promise((resolve, reject) => {
125
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).clear();
126
+ req.onsuccess = () => resolve();
127
+ req.onerror = () => reject(req.error);
128
+ });
129
+ }
130
+ /** Derive a 32-byte Ed25519 seed from raw PRF output. */
131
+ function deriveEd25519Seed(prfOutput) {
132
+ return hkdf(sha256, new Uint8Array(prfOutput), PRF_SALT, HKDF_INFO, 32);
133
+ }
134
+ function extractPrfOutput(credential) {
135
+ const prfOutput = credential.getClientExtensionResults()?.prf?.results?.first;
136
+ if (!prfOutput) throw new Error("WebAuthn PRF extension not available on this authenticator. A PRF-capable platform authenticator (e.g. iCloud Keychain) is required.");
137
+ return prfOutput;
138
+ }
139
+ var CryptoIdentityKeystore = class {
140
+ /**
141
+ * Check whether the platform supports WebAuthn with PRF extension.
142
+ * Call this before offering the "Secure with Passkey" option.
143
+ */
144
+ static async isPrfAvailable() {
145
+ if (typeof window === "undefined" || !window.PublicKeyCredential) return false;
146
+ try {
147
+ if (!await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()) return false;
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ /**
154
+ * Create a synced discoverable passkey and derive the Ed25519 identity from
155
+ * its PRF output. The passkey is stored in the platform credential manager
156
+ * (e.g. iCloud Keychain) and syncs across devices automatically.
157
+ *
158
+ * Returns the base64url-encoded public key, X25519 public key, and credential ID.
159
+ * The caller must register the public key with the server.
160
+ */
161
+ async register(username, rpId, rpName) {
162
+ const credential = await navigator.credentials.create({ publicKey: {
163
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
164
+ rp: {
165
+ id: rpId,
166
+ name: rpName
167
+ },
168
+ user: {
169
+ id: new TextEncoder().encode(username),
170
+ name: username,
171
+ displayName: username
172
+ },
173
+ pubKeyCredParams: [{
174
+ alg: -7,
175
+ type: "public-key"
176
+ }, {
177
+ alg: -257,
178
+ type: "public-key"
179
+ }],
180
+ authenticatorSelection: {
181
+ residentKey: "required",
182
+ requireResidentKey: true,
183
+ userVerification: "required"
184
+ },
185
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
186
+ } });
187
+ if (!credential) throw new Error("WebAuthn credential creation cancelled");
188
+ const seed = deriveEd25519Seed(extractPrfOutput(credential));
189
+ const publicKey = await ed.getPublicKeyAsync(seed);
190
+ const publicKeyB64 = toBase64url(publicKey);
191
+ const x25519PubB64 = toBase64url(ed25519PublicToX25519(publicKey));
192
+ const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
193
+ const db = await openDb();
194
+ await dbPut(db, credentialIdB64, {
195
+ username,
196
+ publicKey: publicKeyB64,
197
+ credentialId: credential.rawId
198
+ });
199
+ db.close();
200
+ seed.fill(0);
201
+ return {
202
+ publicKey: publicKeyB64,
203
+ x25519PublicKey: x25519PubB64,
204
+ credentialId: credentialIdB64
205
+ };
206
+ }
207
+ /**
208
+ * Sign a base64url-encoded challenge using the Ed25519 key derived from
209
+ * a passkey assertion. Triggers a WebAuthn prompt (biometric / PIN).
210
+ *
211
+ * @param challengeB64 - base64url-encoded challenge bytes from the server.
212
+ * @param credentialIdHint - optional credential ID to select a specific passkey.
213
+ * @returns base64url-encoded Ed25519 signature (64 bytes).
214
+ */
215
+ async sign(challengeB64, credentialIdHint) {
216
+ const { seed } = await this._assertAndDerive(credentialIdHint);
217
+ try {
218
+ const challengeBytes = fromBase64url(challengeB64);
219
+ return toBase64url(await ed.signAsync(challengeBytes, seed));
220
+ } finally {
221
+ seed.fill(0);
222
+ }
223
+ }
224
+ /**
225
+ * Returns the cached base64url public key, or null if no identity is cached.
226
+ *
227
+ * Does NOT trigger a WebAuthn prompt. If the cache is empty (e.g. IndexedDB
228
+ * cleared), returns null — the identity can be recovered via sign() or
229
+ * a fresh register() with the same synced passkey.
230
+ */
231
+ async getPublicKey(credentialIdHint) {
232
+ const db = await openDb();
233
+ try {
234
+ if (credentialIdHint) return (await dbGet(db, credentialIdHint))?.publicKey ?? null;
235
+ const all = await dbGetAll(db);
236
+ return all.length > 0 ? all[0].value.publicKey : null;
237
+ } finally {
238
+ db.close();
239
+ }
240
+ }
241
+ /**
242
+ * Returns the locally-cached username label, or null if no identity is cached.
243
+ */
244
+ async getUsername(credentialIdHint) {
245
+ const db = await openDb();
246
+ try {
247
+ if (credentialIdHint) return (await dbGet(db, credentialIdHint))?.username ?? null;
248
+ const all = await dbGetAll(db);
249
+ return all.length > 0 ? all[0].value.username : null;
250
+ } finally {
251
+ db.close();
252
+ }
253
+ }
254
+ /**
255
+ * Updates the cached username for a given credential (or the first cached identity).
256
+ * Call this after the user sets/changes their display name so it persists across devices.
257
+ */
258
+ async setUsername(username, credentialIdHint) {
259
+ const db = await openDb();
260
+ try {
261
+ if (credentialIdHint) {
262
+ const stored = await dbGet(db, credentialIdHint);
263
+ if (stored) await dbPut(db, credentialIdHint, {
264
+ ...stored,
265
+ username
266
+ });
267
+ } else {
268
+ const all = await dbGetAll(db);
269
+ if (all.length > 0) await dbPut(db, String(all[0].key), {
270
+ ...all[0].value,
271
+ username
272
+ });
273
+ }
274
+ } finally {
275
+ db.close();
276
+ }
277
+ }
278
+ /** Returns true if an identity is cached in IndexedDB. */
279
+ async hasIdentity() {
280
+ const db = await openDb();
281
+ try {
282
+ return (await dbGetAll(db)).length > 0;
283
+ } finally {
284
+ db.close();
285
+ }
286
+ }
287
+ /** Remove cached identity record(s) from IndexedDB. The passkey itself
288
+ * remains in the platform credential store. */
289
+ async clear() {
290
+ const db = await openDb();
291
+ await dbClear(db);
292
+ db.close();
293
+ }
294
+ /**
295
+ * Returns the X25519 public key derived from the cached Ed25519 public key.
296
+ * Does NOT require WebAuthn — computed from the cached public key only.
297
+ * Returns null if no identity is cached.
298
+ */
299
+ async getX25519PublicKey() {
300
+ const db = await openDb();
301
+ try {
302
+ const all = await dbGetAll(db);
303
+ if (all.length === 0) return null;
304
+ return ed25519PublicToX25519(fromBase64url(all[0].value.publicKey));
305
+ } finally {
306
+ db.close();
307
+ }
308
+ }
309
+ /**
310
+ * Returns the X25519 private key derived from the Ed25519 seed.
311
+ * Requires a WebAuthn assertion to get the PRF output.
312
+ * The caller MUST wipe the returned Uint8Array after use.
313
+ */
314
+ async getX25519PrivateKey(credentialIdHint) {
315
+ const { seed } = await this._assertAndDerive(credentialIdHint);
316
+ try {
317
+ return ed25519SecretToX25519(seed);
318
+ } finally {
319
+ seed.fill(0);
320
+ }
321
+ }
322
+ /**
323
+ * Trigger a WebAuthn assertion to derive (or re-derive) the identity and
324
+ * update the IndexedDB cache. Returns the public key and credential ID.
325
+ *
326
+ * Use this when the cache is empty but you need the public key before
327
+ * signing (e.g. to send it to the server for the challenge request).
328
+ */
329
+ async deriveIdentity(credentialIdHint) {
330
+ const { seed, publicKeyB64, credentialIdB64 } = await this._assertAndDerive(credentialIdHint);
331
+ seed.fill(0);
332
+ return {
333
+ publicKey: publicKeyB64,
334
+ credentialId: credentialIdB64
335
+ };
336
+ }
337
+ /**
338
+ * List all cached credential IDs. Useful for account switching UI.
339
+ */
340
+ async listCachedIdentities() {
341
+ const db = await openDb();
342
+ try {
343
+ return (await dbGetAll(db)).map(({ key, value }) => ({
344
+ credentialId: key,
345
+ publicKey: value.publicKey,
346
+ username: value.username
347
+ }));
348
+ } finally {
349
+ db.close();
350
+ }
351
+ }
352
+ /**
353
+ * Register a new identity rooted in a BIP-39 mnemonic. Optionally wraps the
354
+ * derived seed with a passkey for biometric day-to-day access.
355
+ *
356
+ * @param username - Display name for the identity.
357
+ * @param mnemonic - Valid BIP-39 mnemonic (12 or 24 words).
358
+ * @param passphrase - Optional BIP-39 passphrase ("25th word").
359
+ * @param rpId - WebAuthn relying party ID (omit to skip passkey wrapping).
360
+ * @param rpName - WebAuthn relying party display name.
361
+ * @returns Public keys and optional credential ID.
362
+ */
363
+ async registerWithMnemonic(username, mnemonic, passphrase, rpId, rpName) {
364
+ const kp = await mnemonicToKeyPair(mnemonic, passphrase);
365
+ try {
366
+ if (rpId && rpName) {
367
+ const credential = await navigator.credentials.create({ publicKey: {
368
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
369
+ rp: {
370
+ id: rpId,
371
+ name: rpName
372
+ },
373
+ user: {
374
+ id: new TextEncoder().encode(username),
375
+ name: username,
376
+ displayName: username
377
+ },
378
+ pubKeyCredParams: [{
379
+ alg: -7,
380
+ type: "public-key"
381
+ }, {
382
+ alg: -257,
383
+ type: "public-key"
384
+ }],
385
+ authenticatorSelection: {
386
+ residentKey: "required",
387
+ requireResidentKey: true,
388
+ userVerification: "required"
389
+ },
390
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
391
+ } });
392
+ if (!credential) throw new Error("WebAuthn credential creation cancelled");
393
+ const prfOutput = extractPrfOutput(credential);
394
+ const wrapSalt = crypto.getRandomValues(new Uint8Array(32));
395
+ const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
396
+ const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
397
+ wrapKey.fill(0);
398
+ const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
399
+ const db = await openDb();
400
+ await dbPut(db, credentialIdB64, {
401
+ username,
402
+ publicKey: kp.publicKeyB64,
403
+ credentialId: credential.rawId,
404
+ encryptedSeed: ciphertext,
405
+ seedIv: iv,
406
+ wrapSalt,
407
+ authMethod: "mnemonic"
408
+ });
409
+ db.close();
410
+ return {
411
+ publicKey: kp.publicKeyB64,
412
+ x25519PublicKey: kp.x25519PublicKeyB64,
413
+ credentialId: credentialIdB64
414
+ };
415
+ }
416
+ return {
417
+ publicKey: kp.publicKeyB64,
418
+ x25519PublicKey: kp.x25519PublicKeyB64
419
+ };
420
+ } finally {
421
+ kp.seed.fill(0);
422
+ }
423
+ }
424
+ /**
425
+ * Wrap an existing mnemonic-derived seed with a new passkey. Use this when
426
+ * a user logged in via mnemonic and wants to add biometric convenience.
427
+ *
428
+ * @param mnemonic - The user's BIP-39 mnemonic.
429
+ * @param passphrase - Optional BIP-39 passphrase.
430
+ * @param rpId - WebAuthn relying party ID.
431
+ * @param rpName - WebAuthn relying party display name.
432
+ * @returns The new credential ID.
433
+ */
434
+ async wrapSeedWithPasskey(mnemonic, passphrase, rpId, rpName) {
435
+ const kp = await mnemonicToKeyPair(mnemonic, passphrase);
436
+ try {
437
+ const credential = await navigator.credentials.create({ publicKey: {
438
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
439
+ rp: {
440
+ id: rpId,
441
+ name: rpName
442
+ },
443
+ user: {
444
+ id: fromBase64url(kp.publicKeyB64),
445
+ name: kp.publicKeyB64.slice(0, 16),
446
+ displayName: kp.publicKeyB64.slice(0, 16)
447
+ },
448
+ pubKeyCredParams: [{
449
+ alg: -7,
450
+ type: "public-key"
451
+ }, {
452
+ alg: -257,
453
+ type: "public-key"
454
+ }],
455
+ authenticatorSelection: {
456
+ residentKey: "required",
457
+ requireResidentKey: true,
458
+ userVerification: "required"
459
+ },
460
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
461
+ } });
462
+ if (!credential) throw new Error("WebAuthn credential creation cancelled");
463
+ const prfOutput = extractPrfOutput(credential);
464
+ const wrapSalt = crypto.getRandomValues(new Uint8Array(32));
465
+ const wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);
466
+ const { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);
467
+ wrapKey.fill(0);
468
+ const credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));
469
+ let username = "";
470
+ try {
471
+ const db = await openDb();
472
+ const existing = (await dbGetAll(db)).find((e) => e.value.publicKey === kp.publicKeyB64);
473
+ if (existing) username = existing.value.username;
474
+ db.close();
475
+ } catch {}
476
+ const db = await openDb();
477
+ await dbPut(db, credentialIdB64, {
478
+ username,
479
+ publicKey: kp.publicKeyB64,
480
+ credentialId: credential.rawId,
481
+ encryptedSeed: ciphertext,
482
+ seedIv: iv,
483
+ wrapSalt,
484
+ authMethod: "mnemonic"
485
+ });
486
+ db.close();
487
+ return { credentialId: credentialIdB64 };
488
+ } finally {
489
+ kp.seed.fill(0);
490
+ }
491
+ }
492
+ /**
493
+ * Sign a challenge directly with a provided seed. No WebAuthn prompt.
494
+ * For ephemeral mnemonic sessions where the seed is held in memory.
495
+ *
496
+ * The caller manages the seed lifecycle (wiping on session end).
497
+ */
498
+ static async signWithSeed(challengeB64, seed) {
499
+ const challengeBytes = fromBase64url(challengeB64);
500
+ return toBase64url(await ed.signAsync(challengeBytes, seed));
501
+ }
502
+ /**
503
+ * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.
504
+ * Useful for CLI or one-shot operations.
505
+ */
506
+ static async signWithMnemonic(mnemonic, challengeB64, passphrase) {
507
+ const seed = mnemonicToEd25519Seed(mnemonic, passphrase);
508
+ try {
509
+ const challengeBytes = fromBase64url(challengeB64);
510
+ return toBase64url(await ed.signAsync(challengeBytes, seed));
511
+ } finally {
512
+ seed.fill(0);
513
+ }
514
+ }
515
+ /**
516
+ * Perform a WebAuthn assertion with PRF, derive the Ed25519 seed, and
517
+ * update the IndexedDB cache. Returns the seed (caller MUST wipe it).
518
+ */
519
+ async _assertAndDerive(credentialIdHint) {
520
+ const allowCredentials = [];
521
+ if (credentialIdHint) allowCredentials.push({
522
+ id: fromBase64url(credentialIdHint),
523
+ type: "public-key"
524
+ });
525
+ else try {
526
+ const db = await openDb();
527
+ const all = await dbGetAll(db);
528
+ db.close();
529
+ for (const { value } of all) allowCredentials.push({
530
+ id: value.credentialId,
531
+ type: "public-key"
532
+ });
533
+ } catch {}
534
+ const assertion = await navigator.credentials.get({ publicKey: {
535
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
536
+ ...allowCredentials.length > 0 ? { allowCredentials } : {},
537
+ userVerification: "required",
538
+ extensions: { prf: { eval: { first: PRF_SALT.buffer } } }
539
+ } });
540
+ if (!assertion) throw new Error("WebAuthn assertion cancelled");
541
+ const prfOutput = extractPrfOutput(assertion);
542
+ const credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));
543
+ let stored;
544
+ try {
545
+ const db = await openDb();
546
+ stored = await dbGet(db, credentialIdB64);
547
+ db.close();
548
+ } catch {}
549
+ let seed;
550
+ if (stored?.encryptedSeed && stored.seedIv && stored.wrapSalt) {
551
+ const wrapKey = deriveSeedWrappingKey(prfOutput, stored.wrapSalt);
552
+ seed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);
553
+ wrapKey.fill(0);
554
+ } else seed = deriveEd25519Seed(prfOutput);
555
+ const publicKeyB64 = toBase64url(await ed.getPublicKeyAsync(seed));
556
+ try {
557
+ const db = await openDb();
558
+ const existing = await dbGet(db, credentialIdB64);
559
+ await dbPut(db, credentialIdB64, {
560
+ username: existing?.username ?? "",
561
+ publicKey: publicKeyB64,
562
+ credentialId: assertion.rawId,
563
+ encryptedSeed: existing?.encryptedSeed,
564
+ seedIv: existing?.seedIv,
565
+ wrapSalt: existing?.wrapSalt,
566
+ authMethod: existing?.authMethod
567
+ });
568
+ db.close();
569
+ } catch {}
570
+ return {
571
+ seed,
572
+ publicKeyB64,
573
+ credentialIdB64
574
+ };
575
+ }
576
+ };
577
+
578
+ //#endregion
579
+ export { CryptoIdentityKeystore };
580
+ //# sourceMappingURL=CryptoIdentityKeystore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CryptoIdentityKeystore.js","names":[],"sources":["../../src/CryptoIdentityKeystore.ts"],"sourcesContent":["/**\n * CryptoIdentityKeystore\n *\n * Ed25519 identity management with two derivation modes:\n *\n * 1. **Passkey-only (legacy)**: PRF output → HKDF → Ed25519 seed.\n * The passkey IS the identity source.\n *\n * 2. **Mnemonic-rooted**: BIP-39 mnemonic → Ed25519 seed, encrypted by\n * passkey PRF for day-to-day convenience. The mnemonic IS the identity\n * source; the passkey is a convenience wrapper. Recovery via mnemonic\n * re-derives the exact same key.\n *\n * Both modes coexist. IndexedDB records with `encryptedSeed` use mode 2;\n * records without it use mode 1 (backward compatible).\n *\n * Dependencies: @noble/ed25519, @noble/hashes, @noble/curves, @scure/bip39\n */\n\nimport * as ed from \"@noble/ed25519\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256, sha512 } from \"@noble/hashes/sha2.js\";\n// Ed25519→X25519 conversion only; `@noble/curves` stays off the boot path.\nimport { ed25519PublicToX25519, ed25519SecretToX25519 } from \"./x25519Convert.ts\";\n\n// @noble/ed25519 v3: wire sha512 for sync paths and define an async hook so\n// signAsync/verifyAsync don't require a Web Crypto fallback in Node.\ned.hashes.sha512 = sha512;\ned.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));\nimport {\n\tmnemonicToKeyPair,\n\tmnemonicToEd25519Seed,\n\tderiveSeedWrappingKey,\n\twrapSeed,\n\tunwrapSeed,\n} from \"./MnemonicKeyDerivation.ts\";\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/**\n * Fixed PRF eval salt. Must be constant across all devices so the same synced\n * passkey produces the same PRF output everywhere.\n *\n * Value: SHA-256(\"abracadabra-prf-salt-v1\"), precomputed.\n */\nconst PRF_SALT = new Uint8Array([\n\t0xb7, 0x79, 0x41, 0xa2, 0xe7, 0x85, 0x1d, 0xfa,\n\t0x5e, 0xc1, 0xab, 0xb6, 0x50, 0x1a, 0x5c, 0x85,\n\t0x75, 0xfd, 0x3e, 0x3f, 0x92, 0xc9, 0xe1, 0xa7,\n\t0x4e, 0xba, 0x71, 0xfc, 0xf2, 0xb1, 0x12, 0xcf,\n]);\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-identity-v1\");\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** Lightweight cache record — no private key material stored in plaintext. */\ninterface StoredIdentity {\n\tusername: string;\n\t/** base64url-encoded Ed25519 public key (32 bytes). */\n\tpublicKey: string;\n\t/** WebAuthn credential ID for allowCredentials hint. */\n\tcredentialId: ArrayBuffer;\n\t// ── Mnemonic-rooted fields (absent = legacy passkey-only mode) ──\n\t/** AES-256-GCM ciphertext of the 32-byte Ed25519 seed (48 bytes with tag). */\n\tencryptedSeed?: ArrayBuffer;\n\t/** 12-byte AES-GCM nonce used for seed encryption. */\n\tseedIv?: Uint8Array;\n\t/** 32-byte random salt for HKDF(PRF → wrapping key). Per-credential. */\n\twrapSalt?: Uint8Array;\n\t/** How the identity was created. Absent = legacy passkey-only. */\n\tauthMethod?: \"passkey\" | \"mnemonic\";\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction toBase64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nfunction fromBase64url(b64: string): Uint8Array {\n\tconst padded = b64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padLen = (4 - (padded.length % 4)) % 4;\n\tconst padded2 = padded + \"=\".repeat(padLen);\n\treturn Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));\n}\n\nconst DB_NAME = \"abracadabra:identity\";\nconst STORE_NAME = \"identity\";\n\n// ── IndexedDB helpers ─────────────────────────────────────────────────────────\n\nfunction openDb(): Promise<IDBDatabase> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst req = indexedDB.open(DB_NAME, 3);\n\t\treq.onupgradeneeded = () => {\n\t\t\tconst db = req.result;\n\t\t\t// v1: plain object store; v2: credentialId-keyed records\n\t\t\t// v3: optional encryptedSeed/seedIv/wrapSalt/authMethod fields on values\n\t\t\t// (no structural changes — same store, new optional value fields)\n\t\t\tif (!db.objectStoreNames.contains(STORE_NAME)) {\n\t\t\t\tdb.createObjectStore(STORE_NAME);\n\t\t\t}\n\t\t};\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGetAll(db: IDBDatabase): Promise<{ key: IDBValidKey; value: StoredIdentity }[]> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst store = tx.objectStore(STORE_NAME);\n\t\tconst results: { key: IDBValidKey; value: StoredIdentity }[] = [];\n\t\tconst req = store.openCursor();\n\t\treq.onsuccess = () => {\n\t\t\tconst cursor = req.result;\n\t\t\tif (cursor) {\n\t\t\t\tresults.push({ key: cursor.key, value: cursor.value as StoredIdentity });\n\t\t\t\tcursor.continue();\n\t\t\t} else {\n\t\t\t\tresolve(results);\n\t\t\t}\n\t\t};\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbGet(db: IDBDatabase, key: string): Promise<StoredIdentity | undefined> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readonly\");\n\t\tconst req = tx.objectStore(STORE_NAME).get(key);\n\t\treq.onsuccess = () => resolve(req.result as StoredIdentity | undefined);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbPut(db: IDBDatabase, key: string, value: StoredIdentity): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).put(value, key);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbDelete(db: IDBDatabase, key: string): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).delete(key);\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nasync function dbClear(db: IDBDatabase): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst tx = db.transaction(STORE_NAME, \"readwrite\");\n\t\tconst req = tx.objectStore(STORE_NAME).clear();\n\t\treq.onsuccess = () => resolve();\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\n// ── Key derivation ────────────────────────────────────────────────────────────\n\n/** Derive a 32-byte Ed25519 seed from raw PRF output. */\nfunction deriveEd25519Seed(prfOutput: ArrayBuffer): Uint8Array {\n\treturn hkdf(sha256, new Uint8Array(prfOutput), PRF_SALT, HKDF_INFO, 32);\n}\n\n// ── PRF extraction helper ────────────────────────────────────────────────────\n\nfunction extractPrfOutput(\n\tcredential: PublicKeyCredential,\n): ArrayBuffer {\n\tconst extResults = credential.getClientExtensionResults() as {\n\t\tprf?: { results?: { first?: ArrayBuffer } };\n\t};\n\tconst prfOutput = extResults?.prf?.results?.first;\n\tif (!prfOutput) {\n\t\tthrow new Error(\n\t\t\t\"WebAuthn PRF extension not available on this authenticator. \" +\n\t\t\t\"A PRF-capable platform authenticator (e.g. iCloud Keychain) is required.\",\n\t\t);\n\t}\n\treturn prfOutput;\n}\n\n// ── Main class ───────────────────────────────────────────────────────────────\n\nexport class CryptoIdentityKeystore {\n\n\t/**\n\t * Check whether the platform supports WebAuthn with PRF extension.\n\t * Call this before offering the \"Secure with Passkey\" option.\n\t */\n\tstatic async isPrfAvailable(): Promise<boolean> {\n\t\tif (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n\t\ttry {\n\t\t\t// Check for platform authenticator\n\t\t\tconst available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t\t\tif (!available) return false;\n\n\t\t\t// PRF is indicated by the presence of the extension in the client;\n\t\t\t// there's no direct feature-detection API. We check for the\n\t\t\t// AuthenticationExtensionsClientInputs type support as a proxy.\n\t\t\t// The definitive test happens at registration time.\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Create a synced discoverable passkey and derive the Ed25519 identity from\n\t * its PRF output. The passkey is stored in the platform credential manager\n\t * (e.g. iCloud Keychain) and syncs across devices automatically.\n\t *\n\t * Returns the base64url-encoded public key, X25519 public key, and credential ID.\n\t * The caller must register the public key with the server.\n\t */\n\tasync register(\n\t\tusername: string,\n\t\trpId: string,\n\t\trpName: string,\n\t): Promise<{ publicKey: string; x25519PublicKey: string; credentialId: string }> {\n\t\t// 1. Create a discoverable WebAuthn credential with PRF\n\t\tconst credential = await navigator.credentials.create({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\tuser: {\n\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\tname: username,\n\t\t\t\t\tdisplayName: username,\n\t\t\t\t},\n\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t{ alg: -7, type: \"public-key\" }, // ES256\n\t\t\t\t\t{ alg: -257, type: \"public-key\" }, // RS256\n\t\t\t\t],\n\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t},\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!credential) {\n\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t}\n\n\t\t// 2. Extract PRF output and derive Ed25519 keypair\n\t\tconst prfOutput = extractPrfOutput(credential);\n\t\tconst seed = deriveEd25519Seed(prfOutput);\n\t\tconst publicKey = await ed.getPublicKeyAsync(seed);\n\t\tconst publicKeyB64 = toBase64url(publicKey);\n\n\t\t// 3. Derive X25519 public key\n\t\tconst x25519Pub = ed25519PublicToX25519(publicKey);\n\t\tconst x25519PubB64 = toBase64url(x25519Pub);\n\n\t\t// 4. Credential ID for future allowCredentials hints\n\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\n\t\t// 5. Cache in IndexedDB (lightweight — no private key material)\n\t\tconst db = await openDb();\n\t\tawait dbPut(db, credentialIdB64, {\n\t\t\tusername,\n\t\t\tpublicKey: publicKeyB64,\n\t\t\tcredentialId: credential.rawId,\n\t\t});\n\t\tdb.close();\n\n\t\t// 6. Wipe seed from memory\n\t\tseed.fill(0);\n\n\t\treturn {\n\t\t\tpublicKey: publicKeyB64,\n\t\t\tx25519PublicKey: x25519PubB64,\n\t\t\tcredentialId: credentialIdB64,\n\t\t};\n\t}\n\n\t/**\n\t * Sign a base64url-encoded challenge using the Ed25519 key derived from\n\t * a passkey assertion. Triggers a WebAuthn prompt (biometric / PIN).\n\t *\n\t * @param challengeB64 - base64url-encoded challenge bytes from the server.\n\t * @param credentialIdHint - optional credential ID to select a specific passkey.\n\t * @returns base64url-encoded Ed25519 signature (64 bytes).\n\t */\n\tasync sign(challengeB64: string, credentialIdHint?: string): Promise<string> {\n\t\tconst { seed } = await this._assertAndDerive(credentialIdHint);\n\n\t\ttry {\n\t\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\t\treturn toBase64url(signature);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Returns the cached base64url public key, or null if no identity is cached.\n\t *\n\t * Does NOT trigger a WebAuthn prompt. If the cache is empty (e.g. IndexedDB\n\t * cleared), returns null — the identity can be recovered via sign() or\n\t * a fresh register() with the same synced passkey.\n\t */\n\tasync getPublicKey(credentialIdHint?: string): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\treturn stored?.publicKey ?? null;\n\t\t\t}\n\t\t\t// Return the first cached identity\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0 ? all[0].value.publicKey : null;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Returns the locally-cached username label, or null if no identity is cached.\n\t */\n\tasync getUsername(credentialIdHint?: string): Promise<string | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\treturn stored?.username ?? null;\n\t\t\t}\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0 ? all[0].value.username : null;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Updates the cached username for a given credential (or the first cached identity).\n\t * Call this after the user sets/changes their display name so it persists across devices.\n\t */\n\tasync setUsername(username: string, credentialIdHint?: string): Promise<void> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tif (credentialIdHint) {\n\t\t\t\tconst stored = await dbGet(db, credentialIdHint);\n\t\t\t\tif (stored) {\n\t\t\t\t\tawait dbPut(db, credentialIdHint, { ...stored, username });\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tif (all.length > 0) {\n\t\t\t\t\tawait dbPut(db, String(all[0].key), { ...all[0].value, username });\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/** Returns true if an identity is cached in IndexedDB. */\n\tasync hasIdentity(): Promise<boolean> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.length > 0;\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/** Remove cached identity record(s) from IndexedDB. The passkey itself\n\t * remains in the platform credential store. */\n\tasync clear(): Promise<void> {\n\t\tconst db = await openDb();\n\t\tawait dbClear(db);\n\t\tdb.close();\n\t}\n\n\t/**\n\t * Returns the X25519 public key derived from the cached Ed25519 public key.\n\t * Does NOT require WebAuthn — computed from the cached public key only.\n\t * Returns null if no identity is cached.\n\t */\n\tasync getX25519PublicKey(): Promise<Uint8Array | null> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\tif (all.length === 0) return null;\n\t\t\tconst edPub = fromBase64url(all[0].value.publicKey);\n\t\t\treturn ed25519PublicToX25519(edPub);\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t/**\n\t * Returns the X25519 private key derived from the Ed25519 seed.\n\t * Requires a WebAuthn assertion to get the PRF output.\n\t * The caller MUST wipe the returned Uint8Array after use.\n\t */\n\tasync getX25519PrivateKey(credentialIdHint?: string): Promise<Uint8Array> {\n\t\tconst { seed } = await this._assertAndDerive(credentialIdHint);\n\t\ttry {\n\t\t\treturn ed25519SecretToX25519(seed);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Trigger a WebAuthn assertion to derive (or re-derive) the identity and\n\t * update the IndexedDB cache. Returns the public key and credential ID.\n\t *\n\t * Use this when the cache is empty but you need the public key before\n\t * signing (e.g. to send it to the server for the challenge request).\n\t */\n\tasync deriveIdentity(credentialIdHint?: string): Promise<{ publicKey: string; credentialId: string }> {\n\t\tconst { seed, publicKeyB64, credentialIdB64 } = await this._assertAndDerive(credentialIdHint);\n\t\tseed.fill(0);\n\t\treturn { publicKey: publicKeyB64, credentialId: credentialIdB64 };\n\t}\n\n\t/**\n\t * List all cached credential IDs. Useful for account switching UI.\n\t */\n\tasync listCachedIdentities(): Promise<{ credentialId: string; publicKey: string; username: string }[]> {\n\t\tconst db = await openDb();\n\t\ttry {\n\t\t\tconst all = await dbGetAll(db);\n\t\t\treturn all.map(({ key, value }) => ({\n\t\t\t\tcredentialId: key as string,\n\t\t\t\tpublicKey: value.publicKey,\n\t\t\t\tusername: value.username,\n\t\t\t}));\n\t\t} finally {\n\t\t\tdb.close();\n\t\t}\n\t}\n\n\t// ── Mnemonic-based methods ───────────────────────────────────────────────\n\n\t/**\n\t * Register a new identity rooted in a BIP-39 mnemonic. Optionally wraps the\n\t * derived seed with a passkey for biometric day-to-day access.\n\t *\n\t * @param username - Display name for the identity.\n\t * @param mnemonic - Valid BIP-39 mnemonic (12 or 24 words).\n\t * @param passphrase - Optional BIP-39 passphrase (\"25th word\").\n\t * @param rpId - WebAuthn relying party ID (omit to skip passkey wrapping).\n\t * @param rpName - WebAuthn relying party display name.\n\t * @returns Public keys and optional credential ID.\n\t */\n\tasync registerWithMnemonic(\n\t\tusername: string,\n\t\tmnemonic: string,\n\t\tpassphrase?: string,\n\t\trpId?: string,\n\t\trpName?: string,\n\t): Promise<{ publicKey: string; x25519PublicKey: string; credentialId?: string }> {\n\t\tconst kp = await mnemonicToKeyPair(mnemonic, passphrase);\n\n\t\ttry {\n\t\t\tif (rpId && rpName) {\n\t\t\t\t// Create a passkey to wrap the mnemonic-derived seed\n\t\t\t\tconst credential = await navigator.credentials.create({\n\t\t\t\t\tpublicKey: {\n\t\t\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\t\t\tuser: {\n\t\t\t\t\t\t\tid: new TextEncoder().encode(username),\n\t\t\t\t\t\t\tname: username,\n\t\t\t\t\t\t\tdisplayName: username,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t\t\t{ alg: -7, type: \"public-key\" },\n\t\t\t\t\t\t\t{ alg: -257, type: \"public-key\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\textensions: {\n\t\t\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t\t\t},\n\t\t\t\t}) as PublicKeyCredential | null;\n\n\t\t\t\tif (!credential) {\n\t\t\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t\t\t}\n\n\t\t\t\tconst prfOutput = extractPrfOutput(credential);\n\t\t\t\tconst wrapSalt = crypto.getRandomValues(new Uint8Array(32));\n\t\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);\n\t\t\t\tconst { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);\n\t\t\t\twrapKey.fill(0);\n\n\t\t\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\t\t\t\tconst db = await openDb();\n\t\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\t\tusername,\n\t\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\t\tcredentialId: credential.rawId,\n\t\t\t\t\tencryptedSeed: ciphertext,\n\t\t\t\t\tseedIv: iv,\n\t\t\t\t\twrapSalt,\n\t\t\t\t\tauthMethod: \"mnemonic\",\n\t\t\t\t});\n\t\t\t\tdb.close();\n\n\t\t\t\treturn {\n\t\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\t\tx25519PublicKey: kp.x25519PublicKeyB64,\n\t\t\t\t\tcredentialId: credentialIdB64,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// No passkey wrapping — ephemeral or mnemonic-only mode\n\t\t\treturn {\n\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\tx25519PublicKey: kp.x25519PublicKeyB64,\n\t\t\t};\n\t\t} finally {\n\t\t\tkp.seed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Wrap an existing mnemonic-derived seed with a new passkey. Use this when\n\t * a user logged in via mnemonic and wants to add biometric convenience.\n\t *\n\t * @param mnemonic - The user's BIP-39 mnemonic.\n\t * @param passphrase - Optional BIP-39 passphrase.\n\t * @param rpId - WebAuthn relying party ID.\n\t * @param rpName - WebAuthn relying party display name.\n\t * @returns The new credential ID.\n\t */\n\tasync wrapSeedWithPasskey(\n\t\tmnemonic: string,\n\t\tpassphrase: string | undefined,\n\t\trpId: string,\n\t\trpName: string,\n\t): Promise<{ credentialId: string }> {\n\t\tconst kp = await mnemonicToKeyPair(mnemonic, passphrase);\n\t\ttry {\n\t\t\tconst credential = await navigator.credentials.create({\n\t\t\t\tpublicKey: {\n\t\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t\trp: { id: rpId, name: rpName },\n\t\t\t\t\tuser: {\n\t\t\t\t\t\tid: fromBase64url(kp.publicKeyB64) as BufferSource,\n\t\t\t\t\t\tname: kp.publicKeyB64.slice(0, 16),\n\t\t\t\t\t\tdisplayName: kp.publicKeyB64.slice(0, 16),\n\t\t\t\t\t},\n\t\t\t\t\tpubKeyCredParams: [\n\t\t\t\t\t\t{ alg: -7, type: \"public-key\" },\n\t\t\t\t\t\t{ alg: -257, type: \"public-key\" },\n\t\t\t\t\t],\n\t\t\t\t\tauthenticatorSelection: {\n\t\t\t\t\t\tresidentKey: \"required\",\n\t\t\t\t\t\trequireResidentKey: true,\n\t\t\t\t\t\tuserVerification: \"required\",\n\t\t\t\t\t},\n\t\t\t\t\textensions: {\n\t\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t\t},\n\t\t\t}) as PublicKeyCredential | null;\n\n\t\t\tif (!credential) {\n\t\t\t\tthrow new Error(\"WebAuthn credential creation cancelled\");\n\t\t\t}\n\n\t\t\tconst prfOutput = extractPrfOutput(credential);\n\t\t\tconst wrapSalt = crypto.getRandomValues(new Uint8Array(32));\n\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, wrapSalt);\n\t\t\tconst { ciphertext, iv } = await wrapSeed(kp.seed, wrapKey);\n\t\t\twrapKey.fill(0);\n\n\t\t\tconst credentialIdB64 = toBase64url(new Uint8Array(credential.rawId));\n\n\t\t\t// Try to preserve username from an existing record with the same pubkey\n\t\t\tlet username = \"\";\n\t\t\ttry {\n\t\t\t\tconst db = await openDb();\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tconst existing = all.find(e => e.value.publicKey === kp.publicKeyB64);\n\t\t\t\tif (existing) username = existing.value.username;\n\t\t\t\tdb.close();\n\t\t\t} catch { /* non-fatal */ }\n\n\t\t\tconst db = await openDb();\n\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\tusername,\n\t\t\t\tpublicKey: kp.publicKeyB64,\n\t\t\t\tcredentialId: credential.rawId,\n\t\t\t\tencryptedSeed: ciphertext,\n\t\t\t\tseedIv: iv,\n\t\t\t\twrapSalt,\n\t\t\t\tauthMethod: \"mnemonic\",\n\t\t\t});\n\t\t\tdb.close();\n\n\t\t\treturn { credentialId: credentialIdB64 };\n\t\t} finally {\n\t\t\tkp.seed.fill(0);\n\t\t}\n\t}\n\n\t/**\n\t * Sign a challenge directly with a provided seed. No WebAuthn prompt.\n\t * For ephemeral mnemonic sessions where the seed is held in memory.\n\t *\n\t * The caller manages the seed lifecycle (wiping on session end).\n\t */\n\tstatic async signWithSeed(challengeB64: string, seed: Uint8Array): Promise<string> {\n\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\treturn toBase64url(signature);\n\t}\n\n\t/**\n\t * Stateless mnemonic sign: derive seed, sign, wipe. No IndexedDB, no WebAuthn.\n\t * Useful for CLI or one-shot operations.\n\t */\n\tstatic async signWithMnemonic(\n\t\tmnemonic: string,\n\t\tchallengeB64: string,\n\t\tpassphrase?: string,\n\t): Promise<string> {\n\t\tconst seed = mnemonicToEd25519Seed(mnemonic, passphrase);\n\t\ttry {\n\t\t\tconst challengeBytes = fromBase64url(challengeB64);\n\t\t\tconst signature = await ed.signAsync(challengeBytes, seed);\n\t\t\treturn toBase64url(signature);\n\t\t} finally {\n\t\t\tseed.fill(0);\n\t\t}\n\t}\n\n\t// ── Internal ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Perform a WebAuthn assertion with PRF, derive the Ed25519 seed, and\n\t * update the IndexedDB cache. Returns the seed (caller MUST wipe it).\n\t */\n\tprivate async _assertAndDerive(credentialIdHint?: string): Promise<{\n\t\tseed: Uint8Array;\n\t\tpublicKeyB64: string;\n\t\tcredentialIdB64: string;\n\t}> {\n\t\t// Build allowCredentials from hint or cached records\n\t\tconst allowCredentials: PublicKeyCredentialDescriptor[] = [];\n\n\t\tif (credentialIdHint) {\n\t\t\tallowCredentials.push({\n\t\t\t\tid: fromBase64url(credentialIdHint) as BufferSource,\n\t\t\t\ttype: \"public-key\",\n\t\t\t});\n\t\t} else {\n\t\t\t// Try cached credential IDs for a targeted prompt\n\t\t\ttry {\n\t\t\t\tconst db = await openDb();\n\t\t\t\tconst all = await dbGetAll(db);\n\t\t\t\tdb.close();\n\t\t\t\tfor (const { value } of all) {\n\t\t\t\t\tallowCredentials.push({\n\t\t\t\t\t\tid: value.credentialId,\n\t\t\t\t\t\ttype: \"public-key\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// IndexedDB unavailable — proceed with discoverable credentials\n\t\t\t}\n\t\t}\n\n\t\tconst assertion = await navigator.credentials.get({\n\t\t\tpublicKey: {\n\t\t\t\tchallenge: crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t...(allowCredentials.length > 0 ? { allowCredentials } : {}),\n\t\t\t\tuserVerification: \"required\",\n\t\t\t\textensions: {\n\t\t\t\t\tprf: { eval: { first: PRF_SALT.buffer } },\n\t\t\t\t} as AuthenticationExtensionsClientInputs,\n\t\t\t},\n\t\t}) as PublicKeyCredential | null;\n\n\t\tif (!assertion) {\n\t\t\tthrow new Error(\"WebAuthn assertion cancelled\");\n\t\t}\n\n\t\tconst prfOutput = extractPrfOutput(assertion);\n\t\tconst credentialIdB64 = toBase64url(new Uint8Array(assertion.rawId));\n\n\t\t// Check if this credential has a wrapped mnemonic seed\n\t\tlet stored: StoredIdentity | undefined;\n\t\ttry {\n\t\t\tconst db = await openDb();\n\t\t\tstored = await dbGet(db, credentialIdB64);\n\t\t\tdb.close();\n\t\t} catch {\n\t\t\t// IndexedDB unavailable — fall through to legacy derivation\n\t\t}\n\n\t\tlet seed: Uint8Array;\n\t\tif (stored?.encryptedSeed && stored.seedIv && stored.wrapSalt) {\n\t\t\t// Mnemonic-rooted: decrypt the stored seed using PRF-derived wrap key\n\t\t\tconst wrapKey = deriveSeedWrappingKey(prfOutput, stored.wrapSalt);\n\t\t\tseed = await unwrapSeed(stored.encryptedSeed, stored.seedIv, wrapKey);\n\t\t\twrapKey.fill(0);\n\t\t} else {\n\t\t\t// Legacy passkey-only: derive seed directly from PRF via HKDF\n\t\t\tseed = deriveEd25519Seed(prfOutput);\n\t\t}\n\n\t\tconst publicKey = await ed.getPublicKeyAsync(seed);\n\t\tconst publicKeyB64 = toBase64url(publicKey);\n\n\t\t// Update cache (preserve mnemonic-rooted fields if present)\n\t\ttry {\n\t\t\tconst db = await openDb();\n\t\t\tconst existing = await dbGet(db, credentialIdB64);\n\t\t\tawait dbPut(db, credentialIdB64, {\n\t\t\t\tusername: existing?.username ?? \"\",\n\t\t\t\tpublicKey: publicKeyB64,\n\t\t\t\tcredentialId: assertion.rawId,\n\t\t\t\t// Preserve wrapped seed fields from existing record\n\t\t\t\tencryptedSeed: existing?.encryptedSeed,\n\t\t\t\tseedIv: existing?.seedIv,\n\t\t\t\twrapSalt: existing?.wrapSalt,\n\t\t\t\tauthMethod: existing?.authMethod,\n\t\t\t});\n\t\t\tdb.close();\n\t\t} catch {\n\t\t\t// Cache update failure is non-fatal\n\t\t}\n\n\t\treturn { seed, publicKeyB64, credentialIdB64 };\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,GAAG,OAAO,SAAS;AACnB,GAAG,OAAO,eAAe,MAAkB,QAAQ,QAAQ,OAAO,EAAE,CAAC;;;;;;;AAiBrE,MAAM,WAAW,IAAI,WAAW;CAC/B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAC1C;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAC1C;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAC1C;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAC1C,CAAC;AAEF,MAAM,YAAY,IAAI,aAAa,CAAC,OAAO,0BAA0B;AAwBrE,SAAS,YAAY,OAA2B;AAC/C,QAAO,KAAK,OAAO,aAAa,GAAG,MAAM,CAAC,CACxC,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,IAAI,CACnB,Q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