@open-e2ee/signal-protocol-sdk 2.0.2 → 4.0.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 (576) hide show
  1. package/ADAPTERS.md +14 -21
  2. package/ARCHITECTURE.md +1 -2
  3. package/CHANGELOG.md +90 -0
  4. package/LICENSE +11 -655
  5. package/LICENSE-APACHE +201 -0
  6. package/LICENSE-MIT +21 -0
  7. package/NOTICE +5 -7
  8. package/README.md +11 -11
  9. package/SECURITY.md +2 -2
  10. package/TROUBLESHOOTING.md +6 -10
  11. package/client/README.md +36 -18
  12. package/device/README.md +1 -1
  13. package/dist/blocking/manager.d.ts +2 -2
  14. package/dist/blocking/manager.d.ts.map +1 -1
  15. package/dist/blocking/manager.js.map +1 -1
  16. package/dist/client/client.d.ts +45 -34
  17. package/dist/client/client.d.ts.map +1 -1
  18. package/dist/client/client.js +178 -115
  19. package/dist/client/client.js.map +1 -1
  20. package/dist/client/compose.d.ts +7 -7
  21. package/dist/client/compose.d.ts.map +1 -1
  22. package/dist/client/compose.js +2 -2
  23. package/dist/client/compose.js.map +1 -1
  24. package/dist/client/config.d.ts +24 -28
  25. package/dist/client/config.d.ts.map +1 -1
  26. package/dist/client/config.js.map +1 -1
  27. package/dist/client/content-adapter.d.ts +2 -0
  28. package/dist/client/content-adapter.d.ts.map +1 -1
  29. package/dist/client/content-adapter.js +4 -0
  30. package/dist/client/content-adapter.js.map +1 -1
  31. package/dist/client/dual-store.d.ts +5 -5
  32. package/dist/client/dual-store.d.ts.map +1 -1
  33. package/dist/client/dual-store.js.map +1 -1
  34. package/dist/client/endorsement-manager.d.ts +6 -3
  35. package/dist/client/endorsement-manager.d.ts.map +1 -1
  36. package/dist/client/endorsement-manager.js +14 -6
  37. package/dist/client/endorsement-manager.js.map +1 -1
  38. package/dist/client/files.d.ts +1 -1
  39. package/dist/client/files.js +1 -1
  40. package/dist/client/group-authority.d.ts +8 -0
  41. package/dist/client/group-authority.d.ts.map +1 -0
  42. package/dist/client/group-authority.js +2 -0
  43. package/dist/client/group-authority.js.map +1 -0
  44. package/dist/client/group-outbox.d.ts +4 -4
  45. package/dist/client/group-outbox.d.ts.map +1 -1
  46. package/dist/client/group-sealed-sender.d.ts +2 -2
  47. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  48. package/dist/client/groups.d.ts +1 -1
  49. package/dist/client/groups.js +1 -1
  50. package/dist/client/headless.d.ts +11 -16
  51. package/dist/client/headless.d.ts.map +1 -1
  52. package/dist/client/headless.js +4 -9
  53. package/dist/client/headless.js.map +1 -1
  54. package/dist/client/hosted-anonymous-delivery.d.ts +32 -0
  55. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -0
  56. package/dist/client/hosted-anonymous-delivery.js +239 -0
  57. package/dist/client/hosted-anonymous-delivery.js.map +1 -0
  58. package/dist/client/hosted-connection.d.ts +1 -1
  59. package/dist/client/hosted-connection.d.ts.map +1 -1
  60. package/dist/client/hosted-connection.js +18 -51
  61. package/dist/client/hosted-connection.js.map +1 -1
  62. package/dist/client/hosted-group-authority.d.ts +11 -0
  63. package/dist/client/hosted-group-authority.d.ts.map +1 -0
  64. package/dist/client/hosted-group-authority.js +96 -0
  65. package/dist/client/hosted-group-authority.js.map +1 -0
  66. package/dist/client/hosted-groups.d.ts +31 -0
  67. package/dist/client/hosted-groups.d.ts.map +1 -0
  68. package/dist/client/hosted-groups.js +217 -0
  69. package/dist/client/hosted-groups.js.map +1 -0
  70. package/dist/client/hosted-mailbox-subscription.d.ts +34 -0
  71. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -0
  72. package/dist/client/hosted-mailbox-subscription.js +257 -0
  73. package/dist/client/hosted-mailbox-subscription.js.map +1 -0
  74. package/dist/client/hosted-prekey-publication.d.ts +51 -0
  75. package/dist/client/hosted-prekey-publication.d.ts.map +1 -0
  76. package/dist/client/hosted-prekey-publication.js +249 -0
  77. package/dist/client/hosted-prekey-publication.js.map +1 -0
  78. package/dist/client/hosted-push.d.ts +5 -6
  79. package/dist/client/hosted-push.d.ts.map +1 -1
  80. package/dist/client/hosted-push.js +22 -22
  81. package/dist/client/hosted-push.js.map +1 -1
  82. package/dist/client/hosted-transport.d.ts +62 -40
  83. package/dist/client/hosted-transport.d.ts.map +1 -1
  84. package/dist/client/hosted-transport.js +666 -341
  85. package/dist/client/hosted-transport.js.map +1 -1
  86. package/dist/client/hosted-trust.d.ts +29 -0
  87. package/dist/client/hosted-trust.d.ts.map +1 -0
  88. package/dist/client/hosted-trust.js +28 -0
  89. package/dist/client/hosted-trust.js.map +1 -0
  90. package/dist/client/hosted.d.ts +26 -21
  91. package/dist/client/hosted.d.ts.map +1 -1
  92. package/dist/client/hosted.js +80 -36
  93. package/dist/client/hosted.js.map +1 -1
  94. package/dist/client/index.d.ts +15 -15
  95. package/dist/client/index.d.ts.map +1 -1
  96. package/dist/client/index.js +7 -7
  97. package/dist/client/index.js.map +1 -1
  98. package/dist/client/key-rotation-core.d.ts +16 -8
  99. package/dist/client/key-rotation-core.d.ts.map +1 -1
  100. package/dist/client/key-rotation-core.js +14 -3
  101. package/dist/client/key-rotation-core.js.map +1 -1
  102. package/dist/client/key-rotation.d.ts +3 -2
  103. package/dist/client/key-rotation.d.ts.map +1 -1
  104. package/dist/client/key-rotation.js +5 -5
  105. package/dist/client/key-rotation.js.map +1 -1
  106. package/dist/client/media-queue-persistence.d.ts +14 -0
  107. package/dist/client/media-queue-persistence.d.ts.map +1 -0
  108. package/dist/client/media-queue-persistence.js +123 -0
  109. package/dist/client/media-queue-persistence.js.map +1 -0
  110. package/dist/client/media-upload-budget.d.ts +3 -0
  111. package/dist/client/media-upload-budget.d.ts.map +1 -0
  112. package/dist/client/media-upload-budget.js +27 -0
  113. package/dist/client/media-upload-budget.js.map +1 -0
  114. package/dist/client/media.d.ts +51 -15
  115. package/dist/client/media.d.ts.map +1 -1
  116. package/dist/client/media.js +541 -73
  117. package/dist/client/media.js.map +1 -1
  118. package/dist/client/messages.d.ts +1 -1
  119. package/dist/client/messages.d.ts.map +1 -1
  120. package/dist/client/messages.js +14 -15
  121. package/dist/client/messages.js.map +1 -1
  122. package/dist/client/multi-device.d.ts +1 -1
  123. package/dist/client/multi-device.js +1 -1
  124. package/dist/client/prekeys.d.ts +1 -1
  125. package/dist/client/prekeys.d.ts.map +1 -1
  126. package/dist/client/prekeys.js +132 -44
  127. package/dist/client/prekeys.js.map +1 -1
  128. package/dist/client/relay-subscription.d.ts +5 -1
  129. package/dist/client/relay-subscription.d.ts.map +1 -1
  130. package/dist/client/relay-subscription.js +59 -26
  131. package/dist/client/relay-subscription.js.map +1 -1
  132. package/dist/client/retry.d.ts +3 -3
  133. package/dist/client/retry.d.ts.map +1 -1
  134. package/dist/client/retry.js +1 -1
  135. package/dist/client/retry.js.map +1 -1
  136. package/dist/client/sealed-sender.d.ts +5 -5
  137. package/dist/client/sealed-sender.d.ts.map +1 -1
  138. package/dist/client/sealed-sender.js.map +1 -1
  139. package/dist/client/sender-key-distribution.d.ts +8 -0
  140. package/dist/client/sender-key-distribution.d.ts.map +1 -0
  141. package/dist/client/sender-key-distribution.js +59 -0
  142. package/dist/client/sender-key-distribution.js.map +1 -0
  143. package/dist/client/sessions.d.ts +3 -3
  144. package/dist/client/sessions.d.ts.map +1 -1
  145. package/dist/client/sessions.js +1 -1
  146. package/dist/client/sessions.js.map +1 -1
  147. package/dist/client/signal-service-cipher.d.ts +12 -8
  148. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  149. package/dist/client/signal-service-cipher.js +41 -16
  150. package/dist/client/signal-service-cipher.js.map +1 -1
  151. package/dist/client/state.d.ts +1 -1
  152. package/dist/client/state.js +1 -1
  153. package/dist/client/types.d.ts +10 -10
  154. package/dist/client/types.d.ts.map +1 -1
  155. package/dist/client/types.js +1 -1
  156. package/dist/device/connection.d.ts.map +1 -1
  157. package/dist/device/connection.js.map +1 -1
  158. package/dist/device/device-id.d.ts +2 -2
  159. package/dist/device/device-id.d.ts.map +1 -1
  160. package/dist/device/device-id.js.map +1 -1
  161. package/dist/device/{expo-metadata.d.ts → expo/index.d.ts} +3 -3
  162. package/dist/device/expo/index.d.ts.map +1 -0
  163. package/dist/device/{expo-metadata.js → expo/index.js} +2 -2
  164. package/dist/device/expo/index.js.map +1 -0
  165. package/dist/device/index.d.ts +1 -1
  166. package/dist/device/index.d.ts.map +1 -1
  167. package/dist/device/index.js +1 -1
  168. package/dist/device/index.js.map +1 -1
  169. package/dist/device/lifecycle/index.d.ts +1 -1
  170. package/dist/device/lifecycle/index.d.ts.map +1 -1
  171. package/dist/device/lifecycle/types.d.ts +8 -8
  172. package/dist/device/lifecycle/types.d.ts.map +1 -1
  173. package/dist/device/provisioning.d.ts +13 -13
  174. package/dist/device/provisioning.d.ts.map +1 -1
  175. package/dist/device/provisioning.js +1 -1
  176. package/dist/device/provisioning.js.map +1 -1
  177. package/dist/device/transfer.d.ts +13 -13
  178. package/dist/device/transfer.d.ts.map +1 -1
  179. package/dist/device/transfer.js.map +1 -1
  180. package/dist/device/types.d.ts +3 -3
  181. package/dist/device/types.d.ts.map +1 -1
  182. package/dist/groups/index.d.ts +1 -1
  183. package/dist/groups/index.d.ts.map +1 -1
  184. package/dist/groups/server.d.ts +10 -0
  185. package/dist/groups/server.d.ts.map +1 -0
  186. package/dist/groups/server.js +6 -0
  187. package/dist/groups/server.js.map +1 -0
  188. package/dist/hooks/use-connection-presence.d.ts +6 -8
  189. package/dist/hooks/use-connection-presence.d.ts.map +1 -1
  190. package/dist/hooks/use-connection-presence.js +2 -4
  191. package/dist/hooks/use-connection-presence.js.map +1 -1
  192. package/dist/hooks/use-group-membership.d.ts +2 -2
  193. package/dist/hooks/use-group-membership.d.ts.map +1 -1
  194. package/dist/hooks/use-group-membership.js.map +1 -1
  195. package/dist/hooks/use-key-rotation.d.ts +2 -2
  196. package/dist/hooks/use-key-rotation.d.ts.map +1 -1
  197. package/dist/hooks/use-session-health.d.ts +2 -2
  198. package/dist/hooks/use-session-health.d.ts.map +1 -1
  199. package/dist/index.d.ts +57 -55
  200. package/dist/index.d.ts.map +1 -1
  201. package/dist/index.js +27 -26
  202. package/dist/index.js.map +1 -1
  203. package/dist/internal/crypto/ec/x25519-validation.d.ts +4 -4
  204. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  205. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  206. package/dist/internal/groups/authority-certificate.d.ts +22 -0
  207. package/dist/internal/groups/authority-certificate.d.ts.map +1 -0
  208. package/dist/internal/groups/authority-certificate.js +99 -0
  209. package/dist/internal/groups/authority-certificate.js.map +1 -0
  210. package/dist/internal/groups/error-details.d.ts +9 -0
  211. package/dist/internal/groups/error-details.d.ts.map +1 -0
  212. package/dist/internal/groups/error-details.js +30 -0
  213. package/dist/internal/groups/error-details.js.map +1 -0
  214. package/dist/internal/groups/index.d.ts +1 -1
  215. package/dist/internal/groups/index.d.ts.map +1 -1
  216. package/dist/internal/groups/manager.d.ts +9 -4
  217. package/dist/internal/groups/manager.d.ts.map +1 -1
  218. package/dist/internal/groups/manager.js +3 -0
  219. package/dist/internal/groups/manager.js.map +1 -1
  220. package/dist/internal/groups/sdk-store.d.ts +4 -4
  221. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  222. package/dist/internal/groups/sdk-store.js.map +1 -1
  223. package/dist/internal/groups/server-engine.d.ts +9 -2
  224. package/dist/internal/groups/server-engine.d.ts.map +1 -1
  225. package/dist/internal/groups/server-engine.js +51 -19
  226. package/dist/internal/groups/server-engine.js.map +1 -1
  227. package/dist/internal/groups/wire.d.ts.map +1 -1
  228. package/dist/internal/groups/wire.js +10 -9
  229. package/dist/internal/groups/wire.js.map +1 -1
  230. package/dist/internal/manager/index.d.ts +2 -2
  231. package/dist/internal/manager/index.d.ts.map +1 -1
  232. package/dist/internal/manager/index.js +1 -1
  233. package/dist/internal/manager/index.js.map +1 -1
  234. package/dist/internal/manager/manager.d.ts +23 -23
  235. package/dist/internal/manager/manager.d.ts.map +1 -1
  236. package/dist/internal/manager/manager.js +40 -43
  237. package/dist/internal/manager/manager.js.map +1 -1
  238. package/dist/internal/protocol/double-ratchet/chains.d.ts +9 -9
  239. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  240. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  241. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +2 -2
  242. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  243. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  244. package/dist/internal/protocol/pqxdh/pqxdh.d.ts +3 -3
  245. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  246. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  247. package/dist/internal/protocol/sender-keys/manager.d.ts +4 -4
  248. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  249. package/dist/internal/protocol/sender-keys/manager.js +27 -14
  250. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  251. package/dist/internal/protocol/spqr/ml-kem-braid/authenticator.d.ts +3 -3
  252. package/dist/internal/protocol/spqr/ml-kem-braid/authenticator.d.ts.map +1 -1
  253. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts +3 -3
  254. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts.map +1 -1
  255. package/dist/internal/protocol/spqr/ml-kem-braid/index.d.ts +2 -2
  256. package/dist/internal/protocol/spqr/ml-kem-braid/index.d.ts.map +1 -1
  257. package/dist/internal/protocol/spqr/ml-kem-braid/index.js +1 -1
  258. package/dist/internal/protocol/spqr/ml-kem-braid/index.js.map +1 -1
  259. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.d.ts +3 -3
  260. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.d.ts.map +1 -1
  261. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js +2 -2
  262. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js.map +1 -1
  263. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts +3 -3
  264. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts.map +1 -1
  265. package/dist/internal/protocol/spqr/spqr.d.ts +5 -5
  266. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  267. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  268. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts +4 -4
  269. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts.map +1 -1
  270. package/dist/internal/protocol/triple-ratchet/ratchet.js.map +1 -1
  271. package/dist/internal/protocol/x3dh/x3dh.d.ts +3 -3
  272. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +1 -1
  273. package/dist/internal/protocol/x3dh/x3dh.js.map +1 -1
  274. package/dist/internal/sesame/device-registry.d.ts +16 -16
  275. package/dist/internal/sesame/device-registry.d.ts.map +1 -1
  276. package/dist/internal/sesame/device-registry.js +6 -6
  277. package/dist/internal/sesame/device-registry.js.map +1 -1
  278. package/dist/internal/sesame/index.d.ts +4 -4
  279. package/dist/internal/sesame/index.d.ts.map +1 -1
  280. package/dist/internal/sesame/index.js +2 -2
  281. package/dist/internal/sesame/index.js.map +1 -1
  282. package/dist/internal/sesame/manager.d.ts +10 -10
  283. package/dist/internal/sesame/manager.d.ts.map +1 -1
  284. package/dist/internal/sesame/manager.js +13 -13
  285. package/dist/internal/sesame/manager.js.map +1 -1
  286. package/dist/internal/sesame/types.d.ts +5 -5
  287. package/dist/internal/sesame/types.d.ts.map +1 -1
  288. package/dist/internal/session/cipher.d.ts +4 -4
  289. package/dist/internal/session/cipher.d.ts.map +1 -1
  290. package/dist/internal/session/cipher.js +31 -28
  291. package/dist/internal/session/cipher.js.map +1 -1
  292. package/dist/internal/session/decryption.js.map +1 -1
  293. package/dist/internal/session/factory.d.ts +3 -3
  294. package/dist/internal/session/factory.d.ts.map +1 -1
  295. package/dist/internal/session/factory.js.map +1 -1
  296. package/dist/internal/session/handshake.d.ts +2 -2
  297. package/dist/internal/session/handshake.d.ts.map +1 -1
  298. package/dist/internal/session/handshake.js.map +1 -1
  299. package/dist/internal/session/ratchet.d.ts +4 -4
  300. package/dist/internal/session/ratchet.d.ts.map +1 -1
  301. package/dist/internal/session/ratchet.js.map +1 -1
  302. package/dist/internal/session/types.d.ts +5 -5
  303. package/dist/internal/session/types.d.ts.map +1 -1
  304. package/dist/internal/session/validation.d.ts +3 -3
  305. package/dist/internal/session/validation.d.ts.map +1 -1
  306. package/dist/internal/session/validation.js.map +1 -1
  307. package/dist/layers.d.ts +4 -4
  308. package/dist/layers.d.ts.map +1 -1
  309. package/dist/layers.js +12 -12
  310. package/dist/layers.js.map +1 -1
  311. package/dist/local/store/expo/adapter.d.ts +15 -9
  312. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  313. package/dist/local/store/expo/adapter.js +29 -10
  314. package/dist/local/store/expo/adapter.js.map +1 -1
  315. package/dist/local/store/expo/database-key.d.ts +5 -5
  316. package/dist/local/store/expo/database-key.d.ts.map +1 -1
  317. package/dist/local/store/expo/database-key.js.map +1 -1
  318. package/dist/local/store/expo/index.d.ts +3 -3
  319. package/dist/local/store/expo/index.d.ts.map +1 -1
  320. package/dist/local/store/expo/key-storage.d.ts +11 -5
  321. package/dist/local/store/expo/key-storage.d.ts.map +1 -1
  322. package/dist/local/store/expo/key-storage.js +82 -17
  323. package/dist/local/store/expo/key-storage.js.map +1 -1
  324. package/dist/local/store/expo/models/kyber-prekey-used.d.ts +1 -4
  325. package/dist/local/store/expo/models/kyber-prekey-used.d.ts.map +1 -1
  326. package/dist/local/store/expo/models/kyber-prekey-used.js +23 -9
  327. package/dist/local/store/expo/models/kyber-prekey-used.js.map +1 -1
  328. package/dist/local/store/expo/models/kyber-prekey.d.ts +4 -4
  329. package/dist/local/store/expo/models/kyber-prekey.d.ts.map +1 -1
  330. package/dist/local/store/expo/models/kyber-prekey.js +67 -26
  331. package/dist/local/store/expo/models/kyber-prekey.js.map +1 -1
  332. package/dist/local/store/expo/schema.d.ts +21 -2
  333. package/dist/local/store/expo/schema.d.ts.map +1 -1
  334. package/dist/local/store/expo/schema.js +10 -2
  335. package/dist/local/store/expo/schema.js.map +1 -1
  336. package/dist/local/store/index.d.ts +3 -3
  337. package/dist/local/store/index.d.ts.map +1 -1
  338. package/dist/local/store/index.js +1 -1
  339. package/dist/local/store/kyber-prekey-lifecycle.d.ts +46 -0
  340. package/dist/local/store/kyber-prekey-lifecycle.d.ts.map +1 -0
  341. package/dist/local/store/kyber-prekey-lifecycle.js +88 -0
  342. package/dist/local/store/kyber-prekey-lifecycle.js.map +1 -0
  343. package/dist/local/store/memory/adapter.d.ts +14 -6
  344. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  345. package/dist/local/store/memory/adapter.js +114 -29
  346. package/dist/local/store/memory/adapter.js.map +1 -1
  347. package/dist/local/store/node/adapter.d.ts +9 -3
  348. package/dist/local/store/node/adapter.d.ts.map +1 -1
  349. package/dist/local/store/node/adapter.js +31 -13
  350. package/dist/local/store/node/adapter.js.map +1 -1
  351. package/dist/local/store/node/database-file-commit.d.ts +8 -0
  352. package/dist/local/store/node/database-file-commit.d.ts.map +1 -0
  353. package/dist/local/store/node/database-file-commit.js +62 -0
  354. package/dist/local/store/node/database-file-commit.js.map +1 -0
  355. package/dist/local/store/node/database-key.d.ts +6 -1
  356. package/dist/local/store/node/database-key.d.ts.map +1 -1
  357. package/dist/local/store/node/database-key.js +79 -44
  358. package/dist/local/store/node/database-key.js.map +1 -1
  359. package/dist/local/store/node/database-lock.d.ts +8 -0
  360. package/dist/local/store/node/database-lock.d.ts.map +1 -0
  361. package/dist/local/store/node/database-lock.js +44 -0
  362. package/dist/local/store/node/database-lock.js.map +1 -0
  363. package/dist/local/store/node/database.d.ts +17 -16
  364. package/dist/local/store/node/database.d.ts.map +1 -1
  365. package/dist/local/store/node/database.js +197 -202
  366. package/dist/local/store/node/database.js.map +1 -1
  367. package/dist/local/store/react-native/adapter.d.ts +10 -4
  368. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  369. package/dist/local/store/react-native/adapter.js +151 -66
  370. package/dist/local/store/react-native/adapter.js.map +1 -1
  371. package/dist/local/store/received-content.d.ts +9 -0
  372. package/dist/local/store/received-content.d.ts.map +1 -0
  373. package/dist/local/store/received-content.js +46 -0
  374. package/dist/local/store/received-content.js.map +1 -0
  375. package/dist/local/store/reliability.d.ts +4 -4
  376. package/dist/local/store/reliability.d.ts.map +1 -1
  377. package/dist/local/store/reliability.js +7 -4
  378. package/dist/local/store/reliability.js.map +1 -1
  379. package/dist/local/store/web/adapter.d.ts +11 -5
  380. package/dist/local/store/web/adapter.d.ts.map +1 -1
  381. package/dist/local/store/web/adapter.js +207 -74
  382. package/dist/local/store/web/adapter.js.map +1 -1
  383. package/dist/local/vault/expo-secure-store.d.ts +2 -2
  384. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  385. package/dist/local/vault/index.d.ts +1 -1
  386. package/dist/local/vault/index.d.ts.map +1 -1
  387. package/dist/logger.d.ts +4 -4
  388. package/dist/logger.d.ts.map +1 -1
  389. package/dist/logger.js.map +1 -1
  390. package/dist/media/index.d.ts +71 -61
  391. package/dist/media/index.d.ts.map +1 -1
  392. package/dist/media/index.js +550 -386
  393. package/dist/media/index.js.map +1 -1
  394. package/dist/media/prepared-upload.d.ts +37 -0
  395. package/dist/media/prepared-upload.d.ts.map +1 -0
  396. package/dist/media/prepared-upload.js +46 -0
  397. package/dist/media/prepared-upload.js.map +1 -0
  398. package/dist/profile/contact-state.d.ts +2 -2
  399. package/dist/profile/contact-state.d.ts.map +1 -1
  400. package/dist/profile/contact-state.js.map +1 -1
  401. package/dist/profile/profile-key.d.ts +2 -2
  402. package/dist/profile/profile-key.d.ts.map +1 -1
  403. package/dist/profile/profile-key.js.map +1 -1
  404. package/dist/profile/update-service.d.ts +2 -2
  405. package/dist/profile/update-service.d.ts.map +1 -1
  406. package/dist/profile/update-service.js.map +1 -1
  407. package/dist/remote/object-store/convex-r2/server.d.ts +2 -1
  408. package/dist/remote/object-store/convex-r2/server.d.ts.map +1 -1
  409. package/dist/remote/object-store/convex-r2/server.js +4 -0
  410. package/dist/remote/object-store/convex-r2/server.js.map +1 -1
  411. package/dist/remote/object-store/convex-r2/storage.d.ts.map +1 -1
  412. package/dist/remote/object-store/convex-r2/storage.js +1 -0
  413. package/dist/remote/object-store/convex-r2/storage.js.map +1 -1
  414. package/dist/remote/object-store/index.d.ts +3 -1
  415. package/dist/remote/object-store/index.d.ts.map +1 -1
  416. package/dist/remote/object-store/index.js +1 -1
  417. package/dist/remote/object-store/index.js.map +1 -1
  418. package/dist/remote/object-store/s3/storage.d.ts +3 -1
  419. package/dist/remote/object-store/s3/storage.d.ts.map +1 -1
  420. package/dist/remote/object-store/s3/storage.js +9 -2
  421. package/dist/remote/object-store/s3/storage.js.map +1 -1
  422. package/dist/remote/object-store/types.d.ts +33 -4
  423. package/dist/remote/object-store/types.d.ts.map +1 -1
  424. package/dist/remote/object-store/upload-error.d.ts +23 -0
  425. package/dist/remote/object-store/upload-error.d.ts.map +1 -0
  426. package/dist/remote/object-store/upload-error.js +33 -0
  427. package/dist/remote/object-store/upload-error.js.map +1 -0
  428. package/dist/remote/object-store/validation.d.ts +7 -1
  429. package/dist/remote/object-store/validation.d.ts.map +1 -1
  430. package/dist/remote/object-store/validation.js +39 -25
  431. package/dist/remote/object-store/validation.js.map +1 -1
  432. package/dist/remote/relay/index.d.ts +7 -14
  433. package/dist/remote/relay/index.d.ts.map +1 -1
  434. package/dist/remote/relay/index.js +6 -13
  435. package/dist/remote/relay/index.js.map +1 -1
  436. package/dist/remote/relay/memory/adapter.d.ts +5 -4
  437. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  438. package/dist/remote/relay/memory/adapter.js +14 -4
  439. package/dist/remote/relay/memory/adapter.js.map +1 -1
  440. package/dist/remote/relay/types.d.ts +36 -25
  441. package/dist/remote/relay/types.d.ts.map +1 -1
  442. package/dist/remote/relay/types.js +1 -1
  443. package/dist/types/api.d.ts +59 -24
  444. package/dist/types/api.d.ts.map +1 -1
  445. package/dist/types/index.js +1 -1
  446. package/dist/types/index.js.map +1 -1
  447. package/dist/types/session.d.ts +6 -0
  448. package/dist/types/session.d.ts.map +1 -1
  449. package/dist/types/session.js.map +1 -1
  450. package/docs/ASSURANCE.md +7 -7
  451. package/docs/CLIENT_COMPOSITION.md +16 -23
  452. package/docs/DEVIATIONS.md +1 -1
  453. package/docs/DOCUMENTATION_STANDARDS.md +4 -0
  454. package/docs/ERROR_HANDLING.md +2 -2
  455. package/docs/GETTING_STARTED.md +23 -38
  456. package/docs/INTERFACES.md +36 -27
  457. package/docs/PACKAGE_SURFACE.md +9 -16
  458. package/docs/RECIPES.md +10 -23
  459. package/examples/browser/index.html +2 -2
  460. package/groups/README.md +4 -4
  461. package/local/store/README.md +22 -7
  462. package/local/store/expo/README.md +24 -20
  463. package/local/store/memory/README.md +1 -1
  464. package/local/store/node/README.md +31 -2
  465. package/local/store/react-native/README.md +1 -1
  466. package/local/store/web/README.md +1 -1
  467. package/local/vault/README.md +1 -1
  468. package/media/README.md +94 -0
  469. package/package.json +17 -27
  470. package/remote/README.md +24 -24
  471. package/remote/object-store/README.md +8 -0
  472. package/remote/object-store/s3/README.md +10 -1
  473. package/remote/relay/README.md +4 -3
  474. package/remote/relay/memory/README.md +1 -1
  475. package/types/README.md +2 -2
  476. package/COMMERCIAL.md +0 -56
  477. package/dist/device/expo-metadata.d.ts.map +0 -1
  478. package/dist/device/expo-metadata.js.map +0 -1
  479. package/dist/remote/relay/convex/backend.d.ts +0 -394
  480. package/dist/remote/relay/convex/backend.d.ts.map +0 -1
  481. package/dist/remote/relay/convex/backend.js +0 -678
  482. package/dist/remote/relay/convex/backend.js.map +0 -1
  483. package/dist/remote/relay/convex/component/_generated/api.d.ts +0 -58
  484. package/dist/remote/relay/convex/component/_generated/api.d.ts.map +0 -1
  485. package/dist/remote/relay/convex/component/_generated/api.js +0 -31
  486. package/dist/remote/relay/convex/component/_generated/api.js.map +0 -1
  487. package/dist/remote/relay/convex/component/_generated/component.d.ts +0 -475
  488. package/dist/remote/relay/convex/component/_generated/component.d.ts.map +0 -1
  489. package/dist/remote/relay/convex/component/_generated/component.js +0 -11
  490. package/dist/remote/relay/convex/component/_generated/component.js.map +0 -1
  491. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts +0 -46
  492. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts.map +0 -1
  493. package/dist/remote/relay/convex/component/_generated/dataModel.js +0 -11
  494. package/dist/remote/relay/convex/component/_generated/dataModel.js.map +0 -1
  495. package/dist/remote/relay/convex/component/_generated/server.d.ts +0 -129
  496. package/dist/remote/relay/convex/component/_generated/server.d.ts.map +0 -1
  497. package/dist/remote/relay/convex/component/_generated/server.js +0 -79
  498. package/dist/remote/relay/convex/component/_generated/server.js.map +0 -1
  499. package/dist/remote/relay/convex/component/accounts.d.ts +0 -45
  500. package/dist/remote/relay/convex/component/accounts.d.ts.map +0 -1
  501. package/dist/remote/relay/convex/component/accounts.js +0 -184
  502. package/dist/remote/relay/convex/component/accounts.js.map +0 -1
  503. package/dist/remote/relay/convex/component/certificates.d.ts +0 -10
  504. package/dist/remote/relay/convex/component/certificates.d.ts.map +0 -1
  505. package/dist/remote/relay/convex/component/certificates.js +0 -126
  506. package/dist/remote/relay/convex/component/certificates.js.map +0 -1
  507. package/dist/remote/relay/convex/component/cleanup.d.ts +0 -32
  508. package/dist/remote/relay/convex/component/cleanup.d.ts.map +0 -1
  509. package/dist/remote/relay/convex/component/cleanup.js +0 -146
  510. package/dist/remote/relay/convex/component/cleanup.js.map +0 -1
  511. package/dist/remote/relay/convex/component/convex.config.d.ts +0 -5
  512. package/dist/remote/relay/convex/component/convex.config.d.ts.map +0 -1
  513. package/dist/remote/relay/convex/component/convex.config.js +0 -35
  514. package/dist/remote/relay/convex/component/convex.config.js.map +0 -1
  515. package/dist/remote/relay/convex/component/crons.d.ts +0 -3
  516. package/dist/remote/relay/convex/component/crons.d.ts.map +0 -1
  517. package/dist/remote/relay/convex/component/crons.js +0 -10
  518. package/dist/remote/relay/convex/component/crons.js.map +0 -1
  519. package/dist/remote/relay/convex/component/devices.d.ts +0 -102
  520. package/dist/remote/relay/convex/component/devices.d.ts.map +0 -1
  521. package/dist/remote/relay/convex/component/devices.js +0 -300
  522. package/dist/remote/relay/convex/component/devices.js.map +0 -1
  523. package/dist/remote/relay/convex/component/errors.d.ts +0 -22
  524. package/dist/remote/relay/convex/component/errors.d.ts.map +0 -1
  525. package/dist/remote/relay/convex/component/errors.js +0 -17
  526. package/dist/remote/relay/convex/component/errors.js.map +0 -1
  527. package/dist/remote/relay/convex/component/groups.d.ts +0 -63
  528. package/dist/remote/relay/convex/component/groups.d.ts.map +0 -1
  529. package/dist/remote/relay/convex/component/groups.js +0 -341
  530. package/dist/remote/relay/convex/component/groups.js.map +0 -1
  531. package/dist/remote/relay/convex/component/keys.d.ts +0 -130
  532. package/dist/remote/relay/convex/component/keys.d.ts.map +0 -1
  533. package/dist/remote/relay/convex/component/keys.js +0 -578
  534. package/dist/remote/relay/convex/component/keys.js.map +0 -1
  535. package/dist/remote/relay/convex/component/messages.d.ts +0 -105
  536. package/dist/remote/relay/convex/component/messages.d.ts.map +0 -1
  537. package/dist/remote/relay/convex/component/messages.js +0 -702
  538. package/dist/remote/relay/convex/component/messages.js.map +0 -1
  539. package/dist/remote/relay/convex/component/provisioning.d.ts +0 -92
  540. package/dist/remote/relay/convex/component/provisioning.d.ts.map +0 -1
  541. package/dist/remote/relay/convex/component/provisioning.js +0 -360
  542. package/dist/remote/relay/convex/component/provisioning.js.map +0 -1
  543. package/dist/remote/relay/convex/component/runtime.d.ts +0 -18
  544. package/dist/remote/relay/convex/component/runtime.d.ts.map +0 -1
  545. package/dist/remote/relay/convex/component/runtime.js +0 -144
  546. package/dist/remote/relay/convex/component/runtime.js.map +0 -1
  547. package/dist/remote/relay/convex/component/schema.d.ts +0 -358
  548. package/dist/remote/relay/convex/component/schema.d.ts.map +0 -1
  549. package/dist/remote/relay/convex/component/schema.js +0 -288
  550. package/dist/remote/relay/convex/component/schema.js.map +0 -1
  551. package/dist/remote/relay/convex/component/zkAuth.d.ts +0 -18
  552. package/dist/remote/relay/convex/component/zkAuth.d.ts.map +0 -1
  553. package/dist/remote/relay/convex/component/zkAuth.js +0 -86
  554. package/dist/remote/relay/convex/component/zkAuth.js.map +0 -1
  555. package/dist/remote/relay/convex/constants.d.ts +0 -3
  556. package/dist/remote/relay/convex/constants.d.ts.map +0 -1
  557. package/dist/remote/relay/convex/constants.js +0 -3
  558. package/dist/remote/relay/convex/constants.js.map +0 -1
  559. package/dist/remote/relay/convex/group-server.d.ts +0 -123
  560. package/dist/remote/relay/convex/group-server.d.ts.map +0 -1
  561. package/dist/remote/relay/convex/group-server.js +0 -184
  562. package/dist/remote/relay/convex/group-server.js.map +0 -1
  563. package/dist/remote/relay/convex/index.d.ts +0 -42
  564. package/dist/remote/relay/convex/index.d.ts.map +0 -1
  565. package/dist/remote/relay/convex/index.js +0 -38
  566. package/dist/remote/relay/convex/index.js.map +0 -1
  567. package/dist/remote/relay/convex/relay.d.ts +0 -323
  568. package/dist/remote/relay/convex/relay.d.ts.map +0 -1
  569. package/dist/remote/relay/convex/relay.js +0 -1144
  570. package/dist/remote/relay/convex/relay.js.map +0 -1
  571. package/dist/remote/relay/convex/types.d.ts +0 -24
  572. package/dist/remote/relay/convex/types.d.ts.map +0 -1
  573. package/dist/remote/relay/convex/types.js +0 -14
  574. package/dist/remote/relay/convex/types.js.map +0 -1
  575. package/remote/relay/convex/README.md +0 -61
  576. package/remote/relay/convex/component/README.md +0 -462
@@ -1,1144 +0,0 @@
1
- /**
2
- * ConvexSignalProtocolRelayServer
3
- *
4
- * Implementation of ISignalProtocolRelayServer using the Signal Protocol Convex component.
5
- * Zero-knowledge server - all content is opaque ciphertext.
6
- *
7
- * Uses the signal component's 16-table schema.
8
- *
9
- * ## Component API Access Pattern
10
- *
11
- * This file consumes typed, app-injected API references for the Signal Protocol
12
- * component's functions. The app-level wrappers are defined in:
13
- * - convex/signal/keys.ts
14
- * - convex/signal/devices.ts
15
- * - convex/signal/messages.ts
16
- * - convex/signal/provisioning.ts
17
- *
18
- */
19
- import { ConvexClient as BrowserConvexClient } from 'convex/browser';
20
- import { decodeCompositeIdentityV1, encodeCompositeIdentityV1 } from '../../../keys/identity.js';
21
- import { SealedSenderAuthError } from '../../../types/errors.js';
22
- import { resolveSignalProtocolLogger } from '../../../logger.js';
23
- import { ConvexGroupServer } from './group-server.js';
24
- const RETRY_POLL_INTERVAL_MS = 2000;
25
- /**
26
- * Polling interval for message subscription (in milliseconds).
27
- * Used as fallback when push-based subscription is not available.
28
- */
29
- const MESSAGE_POLL_INTERVAL_MS = 2000;
30
- /**
31
- * Idle threshold for message batch detection (milliseconds).
32
- * When no new messages arrive for this duration, the batch is considered complete.
33
- */
34
- const MESSAGE_IDLE_THRESHOLD_MS = 500;
35
- /**
36
- * Maximum batch window before forced flush (milliseconds).
37
- * Prevents indefinite batching if messages keep arriving.
38
- */
39
- const MAX_BATCH_WINDOW_MS = 5000;
40
- /**
41
- * Whether a rejection is the component's structured `UNAUTHORIZED`.
42
- *
43
- * Reads the `ConvexError` payload rather than matching on the message text.
44
- *
45
- * A substring test for `'Unauthorized'` was wrong in both directions. Any
46
- * unrelated failure whose message happened to contain the word downgraded a
47
- * sealed send to identified delivery. That disclosed the sender to the relay,
48
- * to work around an error that was never an authorization failure. A genuine
49
- * `code: 'UNAUTHORIZED'` rejection whose message did not spell the word went
50
- * undetected, and surfaced as a hard send failure.
51
- */
52
- function isUnauthorizedRejection(error) {
53
- const data = error !== null && typeof error === 'object' && 'data' in error
54
- ? error.data
55
- : undefined;
56
- return data?.code === 'UNAUTHORIZED';
57
- }
58
- /**
59
- * ConvexSignalProtocolRelayServer - Implementation of ISignalProtocolRelayServer
60
- *
61
- * Uses the Convex Signal Protocol component for the 16-table relay schema.
62
- *
63
- * @example
64
- * ```typescript
65
- * import { ConvexReactClient } from 'convex/react';
66
- * import { ConvexSignalProtocolRelayServer } from './relay.js';
67
- *
68
- * const convex = new ConvexReactClient(process.env.CONVEX_URL!);
69
- * const relay = new ConvexSignalProtocolRelayServer(convex, convexSignalProtocolRelayApi, {
70
- * currentUserId: 'current-user-id',
71
- * });
72
- *
73
- * // Subscribe to incoming envelopes
74
- * const unsubscribe = relay.subscribe(userId, deviceId, (envelope) => {
75
- * // Decrypt and process
76
- * });
77
- *
78
- * // Send encrypted envelope
79
- * await relay.send({
80
- * targetUserId: 'bob',
81
- * targetDeviceId: 1,
82
- * senderUserId: 'alice',
83
- * senderDeviceId: 1,
84
- * ciphertext: encryptedBytes,
85
- * messageType: 'ciphertext',
86
- * });
87
- * ```
88
- */
89
- export class ConvexSignalProtocolRelayServer {
90
- convex;
91
- api;
92
- subscriptions = new Map();
93
- subscriptionClient = null;
94
- currentUserId;
95
- getAuthToken;
96
- logger;
97
- groupServer;
98
- /**
99
- * Create a new ConvexSignalProtocolRelayServer.
100
- *
101
- * @param convex - Convex client (React or HTTP)
102
- * @param api - Generated Convex Signal Protocol API map for queries and mutations
103
- * @param options.currentUserId - Current user's ID for ownership-scoped relay operations
104
- * @param options.getAuthToken - Optional auth token getter for push-based subscriptions.
105
- * When provided, creates an internal ConvexClient with WebSocket push.
106
- * @param options.logger - Optional logger for relay operations
107
- */
108
- constructor(convex, api, options = {}) {
109
- this.convex = convex;
110
- this.api = api;
111
- this.currentUserId = options.currentUserId;
112
- this.getAuthToken = options.getAuthToken;
113
- this.logger = resolveSignalProtocolLogger(options.logger);
114
- if (api.groups && api.zkAuth) {
115
- this.groupServer = {
116
- server: new ConvexGroupServer(convex, api.groups),
117
- issueAuthCredential: (userId) => this.issueAuthCredential(userId),
118
- setUnidentifiedAccessKey: (_userId, accessKey) => this.setUnidentifiedAccessKey(accessKey),
119
- issueProfileKeyCredential: (_userId, request) => this.issueProfileKeyCredential(request),
120
- };
121
- }
122
- }
123
- /**
124
- * Get or create the internal subscription client for push-based updates.
125
- * Created lazily on first use to avoid unnecessary connections.
126
- */
127
- async getSubscriptionClient() {
128
- if (this.subscriptionClient)
129
- return this.subscriptionClient;
130
- const url = process.env.EXPO_PUBLIC_CONVEX_URL;
131
- if (!url || !this.getAuthToken)
132
- return null;
133
- try {
134
- this.subscriptionClient = new BrowserConvexClient(url);
135
- // Re-fetch token on each auth request (handles token expiry)
136
- this.subscriptionClient.setAuth(async () => {
137
- return (await this.getAuthToken?.()) ?? null;
138
- });
139
- this.logger.debug('Created internal subscription client for push-based updates', {
140
- category: 'E2EE',
141
- });
142
- return this.subscriptionClient;
143
- }
144
- catch (error) {
145
- this.logger.warn('Failed to create subscription client, will use polling fallback', {
146
- category: 'E2EE',
147
- error: error,
148
- });
149
- return null;
150
- }
151
- }
152
- // ════════════════════════════════════════════════════════════════════════════
153
- // ENVELOPE DELIVERY
154
- // ════════════════════════════════════════════════════════════════════════════
155
- async send(envelope) {
156
- const ciphertext = typeof envelope.ciphertext === 'string'
157
- ? envelope.ciphertext
158
- : this.uint8ArrayToBase64(envelope.ciphertext);
159
- const result = await this.convex.mutation(this.api.messages.send, {
160
- targetUserId: envelope.targetUserId,
161
- targetDeviceId: envelope.targetDeviceId,
162
- // senderUserId derived server-side from JWT auth
163
- senderDeviceId: envelope.senderDeviceId,
164
- ciphertext,
165
- messageType: envelope.messageType,
166
- deliveryClass: envelope.deliveryClass,
167
- timestamp: envelope.timestamp,
168
- clientMessageId: envelope.clientMessageId,
169
- // Relay-side stale-device detection validates the registration ID only.
170
- // Signed-prekey staleness is detected client-side during authenticated
171
- // decryption and recovery.
172
- recipientRegistrationId: envelope.recipientRegistrationId,
173
- });
174
- return result;
175
- }
176
- /**
177
- * Subscribe to incoming envelopes for this device.
178
- *
179
- * When getAuthToken is provided (via constructor), uses WebSocket push
180
- * for instant delivery (~50ms). Otherwise, falls back to polling every 2 seconds.
181
- *
182
- * Supports optional batching callbacks for notification coalescing.
183
- * When messages arrive rapidly, onBatchStart is called once at the start,
184
- * and onBatchEnd is called after an idle period (no new messages for 500ms).
185
- *
186
- * @param userId - Current user ID
187
- * @param deviceId - This device's ID (1-5)
188
- * @param onEnvelope - Callback for each incoming envelope
189
- * @param options - Optional batching callbacks
190
- * @returns Unsubscribe function
191
- *
192
- */
193
- subscribe(userId, deviceId, onEnvelope, options) {
194
- // Use push-based subscription if auth token getter is available
195
- if (this.getAuthToken) {
196
- return this.subscribeMessagesPush(userId, deviceId, onEnvelope, options);
197
- }
198
- // Fallback to polling for ConvexHttpClient or when no auth token getter provided
199
- return this.subscribeMessagesPolling(userId, deviceId, onEnvelope, options);
200
- }
201
- /**
202
- * Push-based message subscription using internal ConvexClient.
203
- * Provides instant delivery via WebSocket with idle-detection batching.
204
- *
205
- * Batching behavior:
206
- * - Messages are queued until idle (no new messages for MESSAGE_IDLE_THRESHOLD_MS)
207
- * - onBatchStart called when first message arrives
208
- * - onBatchEnd called when batch is flushed
209
- * - Forced flush after MAX_BATCH_WINDOW_MS to prevent indefinite batching
210
- */
211
- subscribeMessagesPush(userId, deviceId, onEnvelope, options) {
212
- const key = `messages:${userId}:${deviceId}`;
213
- const processedIds = new Set();
214
- let clientUnsubscribe = null;
215
- let isActive = true;
216
- // Idle-detection batching state
217
- let pendingEnvelopes = [];
218
- let idleTimer = null;
219
- let batchStartTime = null;
220
- const flushBatch = () => {
221
- if (idleTimer)
222
- clearTimeout(idleTimer);
223
- idleTimer = null;
224
- const batch = pendingEnvelopes;
225
- pendingEnvelopes = [];
226
- batchStartTime = null;
227
- // Deliver all pending envelopes
228
- for (const envelope of batch) {
229
- onEnvelope(envelope);
230
- }
231
- if (batch.length > 0) {
232
- options?.onBatchEnd?.();
233
- }
234
- };
235
- const queueEnvelope = (envelope) => {
236
- if (pendingEnvelopes.length === 0) {
237
- options?.onBatchStart?.();
238
- batchStartTime = Date.now();
239
- }
240
- pendingEnvelopes.push(envelope);
241
- if (idleTimer)
242
- clearTimeout(idleTimer);
243
- // Force flush if max batch window exceeded
244
- if (batchStartTime && Date.now() - batchStartTime >= MAX_BATCH_WINDOW_MS) {
245
- flushBatch();
246
- return;
247
- }
248
- // Set idle timer
249
- idleTimer = setTimeout(flushBatch, MESSAGE_IDLE_THRESHOLD_MS);
250
- };
251
- this.logger.debug('[Relay] Subscription started', {
252
- category: 'E2EE',
253
- data: { userId, deviceId },
254
- });
255
- // Async initialization - get or create the subscription client
256
- this.getSubscriptionClient().then((client) => {
257
- // Check if already unsubscribed before setting up listener
258
- if (!isActive) {
259
- return; // Do not set up anything if already cancelled
260
- }
261
- if (!client) {
262
- // Fall back to polling if client creation failed
263
- this.logger.warn('Subscription client unavailable, falling back to polling', {
264
- category: 'E2EE',
265
- });
266
- const pollingUnsub = this.subscribeMessagesPolling(userId, deviceId, onEnvelope, options);
267
- this.subscriptions.set(key, pollingUnsub);
268
- return;
269
- }
270
- clientUnsubscribe = client.onUpdate(this.api.messages.getPendingMessages, { deviceId }, (messages) => {
271
- // Guard against callbacks after unsubscribe
272
- if (!isActive)
273
- return;
274
- for (const msg of messages) {
275
- if (processedIds.has(msg.id))
276
- continue;
277
- processedIds.add(msg.id);
278
- queueEnvelope({
279
- id: msg.id,
280
- targetUserId: userId,
281
- targetDeviceId: deviceId,
282
- senderUserId: msg.senderUserId,
283
- senderDeviceId: msg.senderDeviceId,
284
- ciphertext: msg.ciphertext,
285
- messageType: msg.messageType,
286
- deliveryClass: msg.deliveryClass,
287
- timestamp: msg.timestamp,
288
- serverTimestamp: msg.serverTimestamp,
289
- });
290
- }
291
- // Cleanup processed IDs no longer in pending
292
- const currentIds = new Set(messages.map((m) => m.id));
293
- for (const id of processedIds) {
294
- if (!currentIds.has(id))
295
- processedIds.delete(id);
296
- }
297
- });
298
- // If unsubscribe was called during init, clean up now
299
- if (!isActive && clientUnsubscribe) {
300
- clientUnsubscribe();
301
- clientUnsubscribe = null;
302
- }
303
- });
304
- // Return unsubscribe function that cleans up
305
- const wrappedUnsubscribe = () => {
306
- isActive = false;
307
- flushBatch(); // Flush any pending on unsubscribe
308
- clientUnsubscribe?.();
309
- this.subscriptions.delete(key);
310
- };
311
- this.subscriptions.set(key, wrappedUnsubscribe);
312
- return wrappedUnsubscribe;
313
- }
314
- /**
315
- * Polling-based message subscription fallback.
316
- * Used when no getAuthToken is available or subscription client creation fails.
317
- *
318
- * NOTE: This has ~2 second latency. Use push-based subscription for production.
319
- */
320
- subscribeMessagesPolling(userId, deviceId, onEnvelope, options) {
321
- const key = `messages:${userId}:${deviceId}`;
322
- let isActive = true;
323
- let lastMessageIds = new Set();
324
- this.logger.debug('Starting polling-based message subscription (fallback)', {
325
- category: 'E2EE',
326
- data: { userId, deviceId, pollIntervalMs: MESSAGE_POLL_INTERVAL_MS },
327
- });
328
- // Polling fallback for non-React contexts
329
- const poll = async () => {
330
- if (!isActive)
331
- return;
332
- try {
333
- const messages = await this.convex.query(this.api.messages.getPendingMessages, {
334
- deviceId,
335
- });
336
- // Track if we have new messages for batching
337
- const newMessages = [];
338
- for (const msg of messages) {
339
- // Only process new messages
340
- if (!lastMessageIds.has(msg.id)) {
341
- lastMessageIds.add(msg.id);
342
- newMessages.push({
343
- id: msg.id,
344
- targetUserId: userId,
345
- targetDeviceId: deviceId,
346
- senderUserId: msg.senderUserId,
347
- senderDeviceId: msg.senderDeviceId,
348
- ciphertext: msg.ciphertext,
349
- messageType: msg.messageType,
350
- deliveryClass: msg.deliveryClass,
351
- timestamp: msg.timestamp,
352
- serverTimestamp: msg.serverTimestamp,
353
- });
354
- }
355
- }
356
- // Deliver with batch callbacks (polling knows batch boundaries upfront)
357
- if (newMessages.length > 0) {
358
- options?.onBatchStart?.();
359
- for (const envelope of newMessages) {
360
- onEnvelope(envelope);
361
- }
362
- options?.onBatchEnd?.();
363
- }
364
- // Update tracked IDs (remove ones no longer in pending)
365
- const currentIds = new Set(messages.map((m) => m.id));
366
- lastMessageIds = currentIds;
367
- }
368
- catch (error) {
369
- this.logger.error('Error polling messages', {
370
- category: 'E2EE',
371
- error: error,
372
- });
373
- }
374
- // Poll every 2 seconds
375
- if (isActive) {
376
- setTimeout(poll, MESSAGE_POLL_INTERVAL_MS);
377
- }
378
- };
379
- // Start polling
380
- poll();
381
- const unsubscribe = () => {
382
- isActive = false;
383
- this.subscriptions.delete(key);
384
- };
385
- this.subscriptions.set(key, unsubscribe);
386
- return unsubscribe;
387
- }
388
- async markDelivered(messageId) {
389
- await this.convex.mutation(this.api.messages.markDelivered, {
390
- messageId,
391
- });
392
- }
393
- // ════════════════════════════════════════════════════════════════════════════
394
- // DEVICE REGISTRY
395
- // ════════════════════════════════════════════════════════════════════════════
396
- async getDevices(userId) {
397
- const devices = await this.convex.query(this.api.devices.getDevices, {
398
- userId,
399
- });
400
- return devices;
401
- }
402
- async registerDevice(_userId, device) {
403
- const result = await this.convex.mutation(this.api.devices.registerDevice, {
404
- // userId derived server-side from JWT auth
405
- deviceId: device.deviceId,
406
- encryptedDeviceName: device.encryptedDeviceName,
407
- deviceType: device.deviceType,
408
- // Note: Push tokens are managed separately via convex/signal/push.ts
409
- });
410
- return result.deviceId;
411
- }
412
- async removeDevice(_userId, deviceId) {
413
- await this.convex.mutation(this.api.devices.removeDevice, {
414
- // userId derived server-side from JWT auth
415
- deviceId,
416
- });
417
- }
418
- // Note: updatePushToken removed - push tokens are managed by convex/signal/push.ts
419
- // using @convex-dev/expo-push-notifications with device-aware composite keys.
420
- async markDeviceConnected(deviceId) {
421
- await this.convex.mutation(this.api.devices.markDeviceConnected, {
422
- deviceId,
423
- });
424
- }
425
- async markDeviceDisconnected(deviceId) {
426
- await this.convex.mutation(this.api.devices.markDeviceDisconnected, {
427
- deviceId,
428
- });
429
- }
430
- async heartbeat(deviceId) {
431
- await this.convex.mutation(this.api.devices.presenceHeartbeat, {
432
- deviceId,
433
- });
434
- }
435
- // ════════════════════════════════════════════════════════════════════════════
436
- // IDENTITY KEYS
437
- // ════════════════════════════════════════════════════════════════════════════
438
- async provisionIdentityKey(request) {
439
- const { userId, deviceId, identity, registrationId, identityType = 'aci' } = request;
440
- await this.convex.mutation(this.api.keys.uploadIdentityKey, {
441
- mode: 'provision',
442
- userId,
443
- deviceId,
444
- compositeIdentity: this.uint8ArrayToBase64(encodeCompositeIdentityV1(identity)),
445
- registrationId,
446
- identityType,
447
- });
448
- }
449
- async rotateIdentityKey(request) {
450
- const { userId, deviceId, identity, registrationId, identityType = 'aci', expectedCurrentCommitment, } = request;
451
- await this.convex.mutation(this.api.keys.uploadIdentityKey, {
452
- mode: 'rotate',
453
- userId,
454
- deviceId,
455
- compositeIdentity: this.uint8ArrayToBase64(encodeCompositeIdentityV1(identity)),
456
- registrationId,
457
- identityType,
458
- expectedCurrentCommitment: this.uint8ArrayToBase64(expectedCurrentCommitment),
459
- });
460
- }
461
- async getIdentityKey(userId, identityType) {
462
- const encodedIdentity = await this.convex.query(this.api.keys.getIdentityKey, {
463
- userId,
464
- identityType: identityType ?? 'aci',
465
- });
466
- if (!encodedIdentity) {
467
- return null;
468
- }
469
- return decodeCompositeIdentityV1(this.base64ToUint8Array(encodedIdentity));
470
- }
471
- // ════════════════════════════════════════════════════════════════════════════
472
- // PREKEY MANAGEMENT
473
- // ════════════════════════════════════════════════════════════════════════════
474
- async uploadPreKeys(userId, deviceId, keys, identityType) {
475
- await this.convex.mutation(this.api.keys.uploadPreKeys, {
476
- userId,
477
- deviceId,
478
- identityType: identityType ?? 'aci',
479
- keys: keys.map((key) => ({
480
- type: key.type,
481
- keyId: key.keyId,
482
- publicKey: key.publicKey,
483
- signature: key.signature,
484
- })),
485
- });
486
- }
487
- /**
488
- * Fetch prekey bundle for session establishment.
489
- *
490
- * Rate limited to 10 fetches per minute per fetcher-target pair.
491
- * Fetcher identity is always derived from auth on the server side
492
- * (matches the relay application format).
493
- *
494
- * @param userId - Target user ID
495
- * @param deviceId - Target device ID
496
- * @param _fetcherUserId - Deprecated, ignored. Fetcher derived from auth server-side.
497
- */
498
- async fetchPreKeyBundle(userId, deviceId, _fetcherUserId, identityType) {
499
- const bundle = await this.convex.mutation(this.api.keys.fetchPreKeyBundle, {
500
- userId,
501
- deviceId,
502
- identityType: identityType ?? 'aci',
503
- });
504
- if (!bundle) {
505
- return null;
506
- }
507
- // Cast to branded types - data crosses wire boundary as plain strings
508
- // Adapters handle the casting internally so callers do not need to
509
- return {
510
- registrationId: bundle.registrationId,
511
- deviceId: bundle.deviceId,
512
- identity: decodeCompositeIdentityV1(this.base64ToUint8Array(bundle.compositeIdentity)),
513
- ecSignedPreKey: {
514
- keyId: bundle.ecSignedPreKey.keyId,
515
- publicKey: bundle.ecSignedPreKey.publicKey,
516
- signature: bundle.ecSignedPreKey.signature,
517
- },
518
- ecOneTimePreKey: bundle.ecOneTimePreKey
519
- ? {
520
- keyId: bundle.ecOneTimePreKey.keyId,
521
- publicKey: bundle.ecOneTimePreKey.publicKey,
522
- }
523
- : null,
524
- kemLastResortPreKey: bundle.kemLastResortPreKey
525
- ? {
526
- keyId: bundle.kemLastResortPreKey.keyId,
527
- publicKey: bundle.kemLastResortPreKey.publicKey,
528
- signature: bundle.kemLastResortPreKey.signature,
529
- }
530
- : null,
531
- kemOneTimePreKey: bundle.kemOneTimePreKey
532
- ? {
533
- keyId: bundle.kemOneTimePreKey.keyId,
534
- publicKey: bundle.kemOneTimePreKey.publicKey,
535
- signature: bundle.kemOneTimePreKey.signature,
536
- }
537
- : null,
538
- };
539
- }
540
- async getPreKeyCount(userId, deviceId, type, identityType) {
541
- return await this.convex.query(this.api.keys.getPreKeyCount, {
542
- userId,
543
- deviceId,
544
- type,
545
- identityType: identityType ?? 'aci',
546
- });
547
- }
548
- async clearStaleKemPreKeys(userId, deviceId, identityType) {
549
- return await this.convex.mutation(this.api.keys.clearStaleKemPreKeys, {
550
- userId,
551
- deviceId,
552
- identityType: identityType ?? 'aci',
553
- });
554
- }
555
- // ════════════════════════════════════════════════════════════════════════════
556
- // CONVENIENCE METHODS (Key Rotation)
557
- // ════════════════════════════════════════════════════════════════════════════
558
- async uploadEcSignedPreKey(userId, ecSignedPreKey, identityType) {
559
- await this.convex.mutation(this.api.keys.uploadEcSignedPreKey, {
560
- userId,
561
- identityType: identityType ?? 'aci',
562
- ecSignedPreKey: {
563
- id: ecSignedPreKey.keyId,
564
- deviceId: ecSignedPreKey.deviceId,
565
- publicKey: ecSignedPreKey.publicKey,
566
- signature: ecSignedPreKey.signature,
567
- timestamp: ecSignedPreKey.timestamp,
568
- },
569
- });
570
- }
571
- async uploadKemLastResortPreKey(userId, kemLastResortPreKey, identityType) {
572
- await this.convex.mutation(this.api.keys.uploadKemLastResortPreKey, {
573
- userId,
574
- identityType: identityType ?? 'aci',
575
- kemLastResortPreKey: {
576
- id: kemLastResortPreKey.keyId,
577
- deviceId: kemLastResortPreKey.deviceId,
578
- publicKey: kemLastResortPreKey.publicKey,
579
- signature: kemLastResortPreKey.signature,
580
- timestamp: kemLastResortPreKey.timestamp,
581
- },
582
- });
583
- }
584
- // ════════════════════════════════════════════════════════════════════════════
585
- // GROUP MEMBER RESOLUTION (Sender Keys): local-first. No membership map
586
- // ════════════════════════════════════════════════════════════════════════════
587
- async getActiveDevices(userId) {
588
- const devices = await this.convex.query(this.api.messages.getActiveDevices, {
589
- userId,
590
- });
591
- return devices;
592
- }
593
- // ════════════════════════════════════════════════════════════════════════════
594
- // SEALED SENDER (Anonymous Delivery)
595
- // ════════════════════════════════════════════════════════════════════════════
596
- async fetchSenderCertificate(deviceId) {
597
- return await this.convex.mutation(this.api.certificates.issueSenderCertificate, {
598
- deviceId,
599
- });
600
- }
601
- /**
602
- * Send a V2 multi-recipient sealed sender message.
603
- *
604
- * Parses the V2 binary blob client-side, then sends structured
605
- * per-recipient data to the Convex mutation for server-side fan-out.
606
- *
607
- * @param sentMessageBase64 - Base64-encoded V2 multi-recipient binary blob
608
- * @param auth - Sealed sender authentication (access key or group send token)
609
- * @param timestamp - Client timestamp for message identification
610
- * @param recipientUserIds - Original user IDs in same order as binary recipients
611
- */
612
- async sendMultiRecipientUnidentified(sentMessageBase64, auth, timestamp, deliveryClass, recipientUserIds, clientMessageId) {
613
- const { base64ToBytes, bytesToBase64 } = await import('../../../internal/crypto/index.js');
614
- const { asBase64 } = await import('../../../types/utils.js');
615
- const { deserializeSentMessage } = await import('../../../internal/protocol/sealed-sender/multi-recipient-message.js');
616
- const binaryBlob = base64ToBytes(asBase64(sentMessageBase64));
617
- const parsed = deserializeSentMessage(binaryBlob);
618
- // Flatten: each recipient can have MULTIPLE devices
619
- const flatRecipients = parsed.recipients.flatMap((r, i) => r.devices.map((d) => ({
620
- userId: recipientUserIds?.[i] ?? r.serviceId,
621
- deviceId: d.deviceId,
622
- registrationId: d.registrationId,
623
- encryptedMessageKeyBase64: bytesToBase64(r.encryptedMessageKey),
624
- authenticationTagBase64: bytesToBase64(r.authenticationTag),
625
- })));
626
- try {
627
- if (auth.type === 'groupSendToken') {
628
- // Attach the claimed ACI to each recipient: the server verifies the
629
- // token against the claims before it reads any account.
630
- const claimedRecipients = flatRecipients.map((recipient) => {
631
- const claimed = auth.recipientAciBytes.get(recipient.userId);
632
- if (!claimed) {
633
- throw new SealedSenderAuthError();
634
- }
635
- return {
636
- ...recipient,
637
- aciBytes: claimed.buffer.slice(claimed.byteOffset, claimed.byteOffset + claimed.byteLength),
638
- };
639
- });
640
- return await this.convex.mutation(this.api.messages.sendMultiRecipientUnidentified, {
641
- recipients: claimedRecipients,
642
- ephemeralPublicBase64: bytesToBase64(parsed.ephemeralPublic),
643
- messageCiphertextBase64: bytesToBase64(parsed.messageCiphertext),
644
- deliveryClass,
645
- timestamp,
646
- clientMessageId,
647
- groupSendToken: auth.groupSendToken.buffer.slice(auth.groupSendToken.byteOffset, auth.groupSendToken.byteOffset + auth.groupSendToken.byteLength),
648
- });
649
- }
650
- return await this.convex.mutation(this.api.messages.sendMultiRecipientUnidentified, {
651
- recipients: flatRecipients,
652
- ephemeralPublicBase64: bytesToBase64(parsed.ephemeralPublic),
653
- messageCiphertextBase64: bytesToBase64(parsed.messageCiphertext),
654
- deliveryClass,
655
- timestamp,
656
- clientMessageId,
657
- unidentifiedAccessKey: auth.unidentifiedAccessKey,
658
- });
659
- }
660
- catch (error) {
661
- if (isUnauthorizedRejection(error)) {
662
- throw new SealedSenderAuthError(error instanceof Error ? error : undefined);
663
- }
664
- throw error;
665
- }
666
- }
667
- // ════════════════════════════════════════════════════════════════════════════
668
- // RETRY REQUESTS (SESAME Spec §6.2)
669
- // ════════════════════════════════════════════════════════════════════════════
670
- /**
671
- * Send retry request to the original sender.
672
- *
673
- * Called by recipient when decryption fails. The request is stored
674
- * in the sender's retry request queue for them to process.
675
- */
676
- async sendRetryRequest(request) {
677
- await this.convex.mutation(this.api.messages.sendRetryRequest, {
678
- // requesterUserId derived server-side from JWT auth
679
- requesterDeviceId: request.requesterDeviceId,
680
- originalSenderUserId: request.originalSenderUserId,
681
- originalSenderDeviceId: request.originalSenderDeviceId,
682
- failedTimestamp: request.failedTimestamp,
683
- timestamp: request.timestamp,
684
- reason: request.reason,
685
- });
686
- }
687
- /**
688
- * Subscribe to incoming retry requests for this device.
689
- *
690
- * When getAuthToken is provided (via constructor), uses WebSocket push
691
- * for instant delivery (<100ms). Otherwise, falls back to polling every 2 seconds.
692
- *
693
- * @param userId - User ID (original sender)
694
- * @param deviceId - Device ID
695
- * @param handler - Callback for each retry request
696
- * @returns Unsubscribe function
697
- */
698
- subscribeRetryRequests(userId, deviceId, handler) {
699
- // Use push-based subscription if auth token getter is available
700
- if (this.getAuthToken) {
701
- return this.subscribeRetryRequestsPush(userId, deviceId, handler);
702
- }
703
- // Fallback to polling for ConvexHttpClient or when no auth token getter provided
704
- return this.subscribeRetryRequestsPolling(userId, deviceId, handler);
705
- }
706
- /**
707
- * Push-based subscription using internal ConvexClient.
708
- * Provides instant delivery via WebSocket.
709
- */
710
- subscribeRetryRequestsPush(userId, deviceId, handler) {
711
- const key = `retry:${userId}:${deviceId}`;
712
- const processedIds = new Set();
713
- let clientUnsubscribe = null;
714
- let isActive = true;
715
- this.logger.debug('Starting push-based retry request subscription', {
716
- category: 'E2EE',
717
- data: { userId, deviceId },
718
- });
719
- // Async initialization - get or create the subscription client
720
- this.getSubscriptionClient().then((client) => {
721
- if (!client || !isActive) {
722
- // Fall back to polling if client creation failed
723
- if (isActive) {
724
- this.logger.warn('Subscription client unavailable, falling back to polling', {
725
- category: 'E2EE',
726
- });
727
- const pollingUnsub = this.subscribeRetryRequestsPolling(userId, deviceId, handler);
728
- this.subscriptions.set(key, pollingUnsub);
729
- }
730
- return;
731
- }
732
- clientUnsubscribe = client.onUpdate(this.api.messages.getPendingRetryRequests, { deviceId }, async (requests) => {
733
- for (const req of requests) {
734
- // Skip already processed requests
735
- if (processedIds.has(req.id)) {
736
- continue;
737
- }
738
- // Mark as processing to prevent duplicate handling
739
- processedIds.add(req.id);
740
- try {
741
- await handler({
742
- requesterUserId: req.requesterUserId,
743
- requesterDeviceId: req.requesterDeviceId,
744
- originalSenderUserId: req.originalSenderUserId,
745
- originalSenderDeviceId: req.originalSenderDeviceId,
746
- failedTimestamp: req.failedTimestamp,
747
- timestamp: req.timestamp,
748
- reason: req.reason,
749
- });
750
- }
751
- catch (handlerError) {
752
- // Handler failed. Safe to retry on next update
753
- processedIds.delete(req.id);
754
- this.logger.error('Error in retry request handler', {
755
- category: 'E2EE',
756
- error: handlerError,
757
- data: { requestId: req.id },
758
- });
759
- continue;
760
- }
761
- // Handler succeeded. Mark as handled on server (best-effort)
762
- try {
763
- await this.convex.mutation(this.api.messages.markRetryRequestHandled, {
764
- requestId: req.id,
765
- });
766
- this.logger.debug('Retry request handled successfully', {
767
- category: 'E2EE',
768
- data: {
769
- requestId: req.id,
770
- failedTimestamp: req.failedTimestamp,
771
- },
772
- });
773
- }
774
- catch (markError) {
775
- // Mark failed but handler already ran. Keep in processedIds to prevent duplicate
776
- this.logger.warn('Failed to mark retry request as handled (handler already ran)', {
777
- category: 'E2EE',
778
- data: { requestId: req.id },
779
- error: markError,
780
- });
781
- }
782
- }
783
- // Cleanup: remove IDs no longer in pending results (already deleted from server)
784
- const currentIds = new Set(requests.map((r) => r.id));
785
- for (const id of processedIds) {
786
- if (!currentIds.has(id)) {
787
- processedIds.delete(id);
788
- }
789
- }
790
- });
791
- });
792
- // Return unsubscribe function that cleans up
793
- const wrappedUnsubscribe = () => {
794
- isActive = false;
795
- clientUnsubscribe?.();
796
- this.subscriptions.delete(key);
797
- };
798
- this.subscriptions.set(key, wrappedUnsubscribe);
799
- return wrappedUnsubscribe;
800
- }
801
- /**
802
- * Polling-based subscription fallback.
803
- * Used when no getAuthToken is available or subscription client creation fails.
804
- *
805
- * NOTE: This has ~2 second latency. Use push-based subscription for production.
806
- */
807
- subscribeRetryRequestsPolling(userId, deviceId, handler) {
808
- const key = `retry:${userId}:${deviceId}`;
809
- let isActive = true;
810
- // Use stable set that accumulates processed IDs (do not replace on each poll)
811
- // This prevents both duplicate processing and lost requests
812
- const processedIds = new Set();
813
- this.logger.debug('Starting polling-based retry request subscription (fallback)', {
814
- category: 'E2EE',
815
- data: { userId, deviceId, pollIntervalMs: RETRY_POLL_INTERVAL_MS },
816
- });
817
- const poll = async () => {
818
- if (!isActive)
819
- return;
820
- try {
821
- const requests = await this.convex.query(this.api.messages.getPendingRetryRequests, {
822
- deviceId,
823
- });
824
- for (const req of requests) {
825
- // Skip already processed requests
826
- if (processedIds.has(req.id)) {
827
- continue;
828
- }
829
- // Mark as processing to prevent duplicate handling
830
- processedIds.add(req.id);
831
- try {
832
- await handler({
833
- requesterUserId: req.requesterUserId,
834
- requesterDeviceId: req.requesterDeviceId,
835
- originalSenderUserId: req.originalSenderUserId,
836
- originalSenderDeviceId: req.originalSenderDeviceId,
837
- failedTimestamp: req.failedTimestamp,
838
- timestamp: req.timestamp,
839
- reason: req.reason,
840
- });
841
- }
842
- catch (handlerError) {
843
- // Handler failed. Safe to retry on next poll
844
- processedIds.delete(req.id);
845
- this.logger.error('Error in retry request handler', {
846
- category: 'E2EE',
847
- error: handlerError,
848
- });
849
- continue;
850
- }
851
- // Handler succeeded. Mark as handled on server (best-effort)
852
- try {
853
- await this.convex.mutation(this.api.messages.markRetryRequestHandled, {
854
- requestId: req.id,
855
- });
856
- }
857
- catch (markError) {
858
- // Mark failed but handler already ran. Keep in processedIds to prevent duplicate
859
- this.logger.warn('Failed to mark retry request as handled (handler already ran)', {
860
- category: 'E2EE',
861
- error: markError,
862
- });
863
- }
864
- }
865
- // Cleanup: remove IDs no longer in pending results (already deleted from server)
866
- // This prevents memory leak from accumulating old IDs
867
- const currentIds = new Set(requests.map((r) => r.id));
868
- for (const id of processedIds) {
869
- if (!currentIds.has(id)) {
870
- processedIds.delete(id);
871
- }
872
- }
873
- }
874
- catch (error) {
875
- this.logger.error('Error polling retry requests', {
876
- category: 'E2EE',
877
- error: error,
878
- });
879
- }
880
- // Continue polling
881
- if (isActive) {
882
- setTimeout(poll, RETRY_POLL_INTERVAL_MS);
883
- }
884
- };
885
- // Start polling
886
- poll();
887
- const unsubscribe = () => {
888
- isActive = false;
889
- this.subscriptions.delete(key);
890
- };
891
- this.subscriptions.set(key, unsubscribe);
892
- return unsubscribe;
893
- }
894
- // ════════════════════════════════════════════════════════════════════════════
895
- // PROVISIONING SERVICE (IProvisioningService)
896
- // ════════════════════════════════════════════════════════════════════════════
897
- async createProvisioningSession(userId, ephemeralPublicKey) {
898
- return await this.convex.mutation(this.api.provisioning.createProvisioningSession, {
899
- userId,
900
- ephemeralPublicKey,
901
- });
902
- }
903
- async connectNewDevice(sessionId, ephemeralPublicKey, deviceMetadata) {
904
- await this.convex.mutation(this.api.provisioning.connectNewDevice, {
905
- sessionId,
906
- ephemeralPublicKey,
907
- deviceMetadata,
908
- });
909
- }
910
- async sendProvisioningMessage(sessionId, encryptedMessage, userId) {
911
- if (!userId && !this.currentUserId) {
912
- throw new Error('userId required for sendProvisioningMessage');
913
- }
914
- await this.convex.mutation(this.api.provisioning.sendProvisioningMessage, {
915
- userId: userId ?? this.currentUserId,
916
- sessionId,
917
- encryptedMessage,
918
- });
919
- }
920
- async getProvisioningMessage(sessionId) {
921
- // No cast: the reference carries the component's own return validator, so
922
- // a component change that stops satisfying this signature fails here.
923
- return await this.convex.query(this.api.provisioning.getProvisioningMessage, {
924
- sessionId,
925
- });
926
- }
927
- async completeProvisioning(sessionId, deviceMetadata) {
928
- return await this.convex.mutation(this.api.provisioning.completeProvisioning, {
929
- sessionId,
930
- deviceMetadata,
931
- });
932
- }
933
- async acknowledgeProvisioning(sessionId) {
934
- await this.convex.mutation(this.api.provisioning.acknowledgeProvisioning, {
935
- sessionId,
936
- });
937
- }
938
- async rollbackProvisioning(sessionId) {
939
- await this.convex.mutation(this.api.provisioning.rollbackProvisioning, {
940
- sessionId,
941
- });
942
- }
943
- async deleteProvisioningSession(sessionId, userId) {
944
- if (!userId && !this.currentUserId) {
945
- throw new Error('userId required for deleteProvisioningSession');
946
- }
947
- await this.convex.mutation(this.api.provisioning.deleteProvisioningSession, {
948
- userId: userId ?? this.currentUserId,
949
- sessionId,
950
- });
951
- }
952
- // ════════════════════════════════════════════════════════════════════════════
953
- // KEY ROTATION SERVICE (IKeyRotationService)
954
- // ════════════════════════════════════════════════════════════════════════════
955
- async getEcSignedPreKeyMetadata(userId, deviceId, identityType) {
956
- const metadata = await this.convex.query(this.api.keys.getEcSignedPreKeyMetadata, {
957
- userId,
958
- deviceId,
959
- identityType: identityType ?? 'aci',
960
- });
961
- return metadata;
962
- }
963
- async getKemLastResortPreKeyMetadata(userId, deviceId, identityType) {
964
- const metadata = await this.convex.query(this.api.keys.getKemLastResortPreKeyMetadata, {
965
- userId,
966
- deviceId,
967
- identityType: identityType ?? 'aci',
968
- });
969
- return metadata;
970
- }
971
- // ════════════════════════════════════════════════════════════════════════════
972
- // GROUP STATE (encrypted, server-opaque)
973
- // ════════════════════════════════════════════════════════════════════════════
974
- async createGroupState(groupId, encryptedState, authorization) {
975
- const { groups } = this.requireGroupServerApi();
976
- await this.convex.mutation(groups.createGroup, {
977
- groupId: this.toBytes(groupId),
978
- encryptedState: this.toBytes(encryptedState),
979
- presentation: this.toBytes(authorization.presentation),
980
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
981
- });
982
- }
983
- async getGroupState(groupId, authorization, version) {
984
- const { groups } = this.requireGroupServerApi();
985
- const result = await this.convex.query(groups.getGroup, {
986
- groupId: this.toBytes(groupId),
987
- presentation: this.toBytes(authorization.presentation),
988
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
989
- version,
990
- });
991
- if (!result)
992
- return null;
993
- return {
994
- encryptedState: new Uint8Array(result.encryptedState),
995
- version: result.version,
996
- baselineSignature: new Uint8Array(result.baselineSignature),
997
- };
998
- }
999
- async getGroupJoinInfo(groupId, inviteLinkPassword, authorization) {
1000
- const { groups } = this.requireGroupServerApi();
1001
- const result = await this.convex.query(groups.getGroupJoinInfo, {
1002
- groupId: this.toBytes(groupId),
1003
- inviteLinkPassword: this.toBytes(inviteLinkPassword),
1004
- presentation: this.toBytes(authorization.presentation),
1005
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
1006
- });
1007
- if (!result)
1008
- return null;
1009
- return {
1010
- encryptedJoinInfo: new Uint8Array(result.encryptedJoinInfo),
1011
- version: result.version,
1012
- };
1013
- }
1014
- async getGroupChanges(groupId, fromVersion, authorization) {
1015
- const { groups } = this.requireGroupServerApi();
1016
- const result = await this.convex.query(groups.getGroupChanges, {
1017
- groupId: this.toBytes(groupId),
1018
- fromVersion,
1019
- presentation: this.toBytes(authorization.presentation),
1020
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
1021
- });
1022
- return {
1023
- entries: result.entries.map((entry) => ({
1024
- version: entry.version,
1025
- actions: new Uint8Array(entry.actions),
1026
- serverSignature: new Uint8Array(entry.serverSignature),
1027
- changeEpoch: entry.changeEpoch,
1028
- timestamp: entry.timestamp,
1029
- })),
1030
- hasMore: result.hasMore,
1031
- };
1032
- }
1033
- async submitGroupChange(groupId, expectedVersion, actions, inviteLinkPassword, authorization) {
1034
- // S13: the server derives the change epoch from the accepted actions. A
1035
- // legacy caller-supplied epoch must be rejected, matching
1036
- // ConvexGroupServer.submitGroupChange.
1037
- if (arguments.length !== 5) {
1038
- throw new Error('INVALID_REQUEST: Group change submission must not carry an epoch');
1039
- }
1040
- const { groups } = this.requireGroupServerApi();
1041
- const result = await this.convex.mutation(groups.submitGroupChange, {
1042
- groupId: this.toBytes(groupId),
1043
- expectedVersion,
1044
- actions: this.toBytes(actions),
1045
- inviteLinkPassword: this.toBytes(inviteLinkPassword),
1046
- presentation: this.toBytes(authorization.presentation),
1047
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
1048
- });
1049
- return {
1050
- version: result.version,
1051
- actions: new Uint8Array(result.actions),
1052
- serverSignature: new Uint8Array(result.serverSignature),
1053
- changeEpoch: result.changeEpoch,
1054
- timestamp: result.timestamp,
1055
- };
1056
- }
1057
- async issueAuthCredential(_userId) {
1058
- // userId kept for ISignalProtocolRelayServer interface compat. The server uses the auth session
1059
- const api = this.requireGroupServerApi();
1060
- const result = await this.convex.mutation(api.zkAuth.issueAuthCredentialMutation, {});
1061
- return new Uint8Array(result);
1062
- }
1063
- async setUnidentifiedAccessKey(accessKey) {
1064
- const api = this.requireGroupServerApi();
1065
- await this.convex.mutation(api.zkAuth.setUnidentifiedAccessKeyMutation, {
1066
- accessKey: this.toBytes(accessKey),
1067
- });
1068
- }
1069
- async issueProfileKeyCredential(request) {
1070
- const api = this.requireGroupServerApi();
1071
- const result = await this.convex.mutation(api.zkAuth.issueProfileKeyCredentialMutation, {
1072
- request: this.toBytes(request),
1073
- });
1074
- return new Uint8Array(result);
1075
- }
1076
- async refreshGroupSendEndorsements(groupId, authorization) {
1077
- const api = this.requireGroupServerApi();
1078
- const result = await this.convex.mutation(api.groups.refreshGroupSendEndorsements, {
1079
- groupId: this.toBytes(groupId),
1080
- presentation: this.toBytes(authorization.presentation),
1081
- groupPublicParams: this.toBytes(authorization.groupPublicParams),
1082
- });
1083
- return {
1084
- endorsements: new Uint8Array(result.endorsements),
1085
- expiration: result.expiration,
1086
- };
1087
- }
1088
- // ════════════════════════════════════════════════════════════════════════════
1089
- // UTILITY METHODS
1090
- // ════════════════════════════════════════════════════════════════════════════
1091
- requireGroupServerApi() {
1092
- if (!this.api.groups || !this.api.zkAuth) {
1093
- throw new Error('This Convex relay does not expose the groupServer capability; configure both groups and zkAuth API modules');
1094
- }
1095
- return {
1096
- groups: this.api.groups,
1097
- zkAuth: this.api.zkAuth,
1098
- };
1099
- }
1100
- /** Convert Uint8Array to ArrayBuffer for Convex v.bytes() args. */
1101
- toBytes(data) {
1102
- return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
1103
- }
1104
- uint8ArrayToBase64(data) {
1105
- // Use Buffer in Node.js or btoa in browser
1106
- if (typeof Buffer !== 'undefined') {
1107
- return Buffer.from(data).toString('base64');
1108
- }
1109
- let binary = '';
1110
- const len = data.byteLength;
1111
- for (let i = 0; i < len; i++) {
1112
- binary += String.fromCharCode(data[i]);
1113
- }
1114
- return btoa(binary);
1115
- }
1116
- base64ToUint8Array(base64) {
1117
- if (typeof Buffer !== 'undefined') {
1118
- return new Uint8Array(Buffer.from(base64, 'base64'));
1119
- }
1120
- const binary = atob(base64);
1121
- const len = binary.length;
1122
- const bytes = new Uint8Array(len);
1123
- for (let i = 0; i < len; i++) {
1124
- bytes[i] = binary.charCodeAt(i);
1125
- }
1126
- return bytes;
1127
- }
1128
- /**
1129
- * Clean up all subscriptions and close the internal subscription client.
1130
- */
1131
- async destroy() {
1132
- // Unsubscribe all active subscriptions
1133
- for (const unsubscribe of this.subscriptions.values()) {
1134
- unsubscribe();
1135
- }
1136
- this.subscriptions.clear();
1137
- // Close the internal subscription client if it exists
1138
- if (this.subscriptionClient) {
1139
- await this.subscriptionClient.close();
1140
- this.subscriptionClient = null;
1141
- }
1142
- }
1143
- }
1144
- //# sourceMappingURL=relay.js.map