@open-e2ee/signal-protocol-sdk 2.0.2 → 3.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 (410) hide show
  1. package/ADAPTERS.md +10 -17
  2. package/ARCHITECTURE.md +1 -2
  3. package/CHANGELOG.md +74 -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 +2 -6
  11. package/client/README.md +34 -16
  12. package/device/README.md +1 -1
  13. package/dist/client/client.d.ts +13 -2
  14. package/dist/client/client.d.ts.map +1 -1
  15. package/dist/client/client.js +136 -73
  16. package/dist/client/client.js.map +1 -1
  17. package/dist/client/config.d.ts +14 -18
  18. package/dist/client/config.d.ts.map +1 -1
  19. package/dist/client/config.js.map +1 -1
  20. package/dist/client/content-adapter.d.ts +2 -0
  21. package/dist/client/content-adapter.d.ts.map +1 -1
  22. package/dist/client/content-adapter.js +4 -0
  23. package/dist/client/content-adapter.js.map +1 -1
  24. package/dist/client/endorsement-manager.d.ts +4 -1
  25. package/dist/client/endorsement-manager.d.ts.map +1 -1
  26. package/dist/client/endorsement-manager.js +14 -6
  27. package/dist/client/endorsement-manager.js.map +1 -1
  28. package/dist/client/group-authority.d.ts +8 -0
  29. package/dist/client/group-authority.d.ts.map +1 -0
  30. package/dist/client/group-authority.js +2 -0
  31. package/dist/client/group-authority.js.map +1 -0
  32. package/dist/client/headless.d.ts +3 -8
  33. package/dist/client/headless.d.ts.map +1 -1
  34. package/dist/client/headless.js +3 -8
  35. package/dist/client/headless.js.map +1 -1
  36. package/dist/client/hosted-anonymous-delivery.d.ts +32 -0
  37. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -0
  38. package/dist/client/hosted-anonymous-delivery.js +239 -0
  39. package/dist/client/hosted-anonymous-delivery.js.map +1 -0
  40. package/dist/client/hosted-connection.d.ts +1 -1
  41. package/dist/client/hosted-connection.d.ts.map +1 -1
  42. package/dist/client/hosted-connection.js +18 -51
  43. package/dist/client/hosted-connection.js.map +1 -1
  44. package/dist/client/hosted-group-authority.d.ts +11 -0
  45. package/dist/client/hosted-group-authority.d.ts.map +1 -0
  46. package/dist/client/hosted-group-authority.js +96 -0
  47. package/dist/client/hosted-group-authority.js.map +1 -0
  48. package/dist/client/hosted-groups.d.ts +31 -0
  49. package/dist/client/hosted-groups.d.ts.map +1 -0
  50. package/dist/client/hosted-groups.js +217 -0
  51. package/dist/client/hosted-groups.js.map +1 -0
  52. package/dist/client/hosted-mailbox-subscription.d.ts +34 -0
  53. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -0
  54. package/dist/client/hosted-mailbox-subscription.js +257 -0
  55. package/dist/client/hosted-mailbox-subscription.js.map +1 -0
  56. package/dist/client/hosted-prekey-publication.d.ts +51 -0
  57. package/dist/client/hosted-prekey-publication.d.ts.map +1 -0
  58. package/dist/client/hosted-prekey-publication.js +249 -0
  59. package/dist/client/hosted-prekey-publication.js.map +1 -0
  60. package/dist/client/hosted-push.d.ts +4 -5
  61. package/dist/client/hosted-push.d.ts.map +1 -1
  62. package/dist/client/hosted-push.js +22 -22
  63. package/dist/client/hosted-push.js.map +1 -1
  64. package/dist/client/hosted-transport.d.ts +57 -35
  65. package/dist/client/hosted-transport.d.ts.map +1 -1
  66. package/dist/client/hosted-transport.js +666 -341
  67. package/dist/client/hosted-transport.js.map +1 -1
  68. package/dist/client/hosted-trust.d.ts +29 -0
  69. package/dist/client/hosted-trust.d.ts.map +1 -0
  70. package/dist/client/hosted-trust.js +28 -0
  71. package/dist/client/hosted-trust.js.map +1 -0
  72. package/dist/client/hosted.d.ts +18 -13
  73. package/dist/client/hosted.d.ts.map +1 -1
  74. package/dist/client/hosted.js +78 -34
  75. package/dist/client/hosted.js.map +1 -1
  76. package/dist/client/index.d.ts +14 -14
  77. package/dist/client/index.d.ts.map +1 -1
  78. package/dist/client/index.js +7 -7
  79. package/dist/client/index.js.map +1 -1
  80. package/dist/client/key-rotation-core.d.ts +8 -0
  81. package/dist/client/key-rotation-core.d.ts.map +1 -1
  82. package/dist/client/key-rotation-core.js +12 -1
  83. package/dist/client/key-rotation-core.js.map +1 -1
  84. package/dist/client/key-rotation.d.ts +2 -1
  85. package/dist/client/key-rotation.d.ts.map +1 -1
  86. package/dist/client/key-rotation.js +4 -4
  87. package/dist/client/key-rotation.js.map +1 -1
  88. package/dist/client/media-queue-persistence.d.ts +14 -0
  89. package/dist/client/media-queue-persistence.d.ts.map +1 -0
  90. package/dist/client/media-queue-persistence.js +123 -0
  91. package/dist/client/media-queue-persistence.js.map +1 -0
  92. package/dist/client/media-upload-budget.d.ts +3 -0
  93. package/dist/client/media-upload-budget.d.ts.map +1 -0
  94. package/dist/client/media-upload-budget.js +27 -0
  95. package/dist/client/media-upload-budget.js.map +1 -0
  96. package/dist/client/media.d.ts +51 -15
  97. package/dist/client/media.d.ts.map +1 -1
  98. package/dist/client/media.js +541 -73
  99. package/dist/client/media.js.map +1 -1
  100. package/dist/client/messages.d.ts.map +1 -1
  101. package/dist/client/messages.js +13 -14
  102. package/dist/client/messages.js.map +1 -1
  103. package/dist/client/prekeys.d.ts.map +1 -1
  104. package/dist/client/prekeys.js +131 -43
  105. package/dist/client/prekeys.js.map +1 -1
  106. package/dist/client/relay-subscription.d.ts +4 -0
  107. package/dist/client/relay-subscription.d.ts.map +1 -1
  108. package/dist/client/relay-subscription.js +58 -25
  109. package/dist/client/relay-subscription.js.map +1 -1
  110. package/dist/client/sender-key-distribution.d.ts +8 -0
  111. package/dist/client/sender-key-distribution.d.ts.map +1 -0
  112. package/dist/client/sender-key-distribution.js +59 -0
  113. package/dist/client/sender-key-distribution.js.map +1 -0
  114. package/dist/client/signal-service-cipher.d.ts +7 -3
  115. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  116. package/dist/client/signal-service-cipher.js +41 -16
  117. package/dist/client/signal-service-cipher.js.map +1 -1
  118. package/dist/device/{expo-metadata.d.ts → expo/index.d.ts} +3 -3
  119. package/dist/device/expo/index.d.ts.map +1 -0
  120. package/dist/device/{expo-metadata.js → expo/index.js} +2 -2
  121. package/dist/device/expo/index.js.map +1 -0
  122. package/dist/device/index.js +1 -1
  123. package/dist/device/index.js.map +1 -1
  124. package/dist/device/provisioning.d.ts +1 -1
  125. package/dist/device/provisioning.js +1 -1
  126. package/dist/device/types.d.ts +1 -1
  127. package/dist/groups/server.d.ts +10 -0
  128. package/dist/groups/server.d.ts.map +1 -0
  129. package/dist/groups/server.js +6 -0
  130. package/dist/groups/server.js.map +1 -0
  131. package/dist/hooks/use-connection-presence.d.ts +2 -4
  132. package/dist/hooks/use-connection-presence.d.ts.map +1 -1
  133. package/dist/hooks/use-connection-presence.js +2 -4
  134. package/dist/hooks/use-connection-presence.js.map +1 -1
  135. package/dist/index.d.ts +51 -49
  136. package/dist/index.d.ts.map +1 -1
  137. package/dist/index.js +25 -24
  138. package/dist/index.js.map +1 -1
  139. package/dist/internal/groups/authority-certificate.d.ts +22 -0
  140. package/dist/internal/groups/authority-certificate.d.ts.map +1 -0
  141. package/dist/internal/groups/authority-certificate.js +99 -0
  142. package/dist/internal/groups/authority-certificate.js.map +1 -0
  143. package/dist/internal/groups/error-details.d.ts +9 -0
  144. package/dist/internal/groups/error-details.d.ts.map +1 -0
  145. package/dist/internal/groups/error-details.js +30 -0
  146. package/dist/internal/groups/error-details.js.map +1 -0
  147. package/dist/internal/groups/manager.d.ts +5 -0
  148. package/dist/internal/groups/manager.d.ts.map +1 -1
  149. package/dist/internal/groups/manager.js +3 -0
  150. package/dist/internal/groups/manager.js.map +1 -1
  151. package/dist/internal/groups/server-engine.d.ts +7 -0
  152. package/dist/internal/groups/server-engine.d.ts.map +1 -1
  153. package/dist/internal/groups/server-engine.js +51 -19
  154. package/dist/internal/groups/server-engine.js.map +1 -1
  155. package/dist/internal/groups/wire.d.ts.map +1 -1
  156. package/dist/internal/groups/wire.js +10 -9
  157. package/dist/internal/groups/wire.js.map +1 -1
  158. package/dist/internal/manager/manager.d.ts +1 -1
  159. package/dist/internal/manager/manager.d.ts.map +1 -1
  160. package/dist/internal/manager/manager.js +22 -25
  161. package/dist/internal/manager/manager.js.map +1 -1
  162. package/dist/internal/protocol/sender-keys/manager.d.ts +1 -1
  163. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  164. package/dist/internal/protocol/sender-keys/manager.js +27 -14
  165. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  166. package/dist/internal/sesame/manager.d.ts +2 -2
  167. package/dist/internal/sesame/manager.d.ts.map +1 -1
  168. package/dist/internal/sesame/manager.js +6 -6
  169. package/dist/internal/sesame/manager.js.map +1 -1
  170. package/dist/internal/sesame/types.d.ts +1 -1
  171. package/dist/internal/sesame/types.d.ts.map +1 -1
  172. package/dist/internal/session/cipher.d.ts +1 -1
  173. package/dist/internal/session/cipher.d.ts.map +1 -1
  174. package/dist/internal/session/cipher.js +31 -28
  175. package/dist/internal/session/cipher.js.map +1 -1
  176. package/dist/layers.d.ts +1 -1
  177. package/dist/layers.d.ts.map +1 -1
  178. package/dist/layers.js +1 -1
  179. package/dist/layers.js.map +1 -1
  180. package/dist/local/store/expo/adapter.d.ts +8 -2
  181. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  182. package/dist/local/store/expo/adapter.js +28 -9
  183. package/dist/local/store/expo/adapter.js.map +1 -1
  184. package/dist/local/store/expo/key-storage.d.ts +7 -1
  185. package/dist/local/store/expo/key-storage.d.ts.map +1 -1
  186. package/dist/local/store/expo/key-storage.js +82 -17
  187. package/dist/local/store/expo/key-storage.js.map +1 -1
  188. package/dist/local/store/expo/models/kyber-prekey-used.d.ts +1 -4
  189. package/dist/local/store/expo/models/kyber-prekey-used.d.ts.map +1 -1
  190. package/dist/local/store/expo/models/kyber-prekey-used.js +23 -9
  191. package/dist/local/store/expo/models/kyber-prekey-used.js.map +1 -1
  192. package/dist/local/store/expo/models/kyber-prekey.d.ts +4 -4
  193. package/dist/local/store/expo/models/kyber-prekey.d.ts.map +1 -1
  194. package/dist/local/store/expo/models/kyber-prekey.js +67 -26
  195. package/dist/local/store/expo/models/kyber-prekey.js.map +1 -1
  196. package/dist/local/store/expo/schema.d.ts +21 -2
  197. package/dist/local/store/expo/schema.d.ts.map +1 -1
  198. package/dist/local/store/expo/schema.js +10 -2
  199. package/dist/local/store/expo/schema.js.map +1 -1
  200. package/dist/local/store/kyber-prekey-lifecycle.d.ts +46 -0
  201. package/dist/local/store/kyber-prekey-lifecycle.d.ts.map +1 -0
  202. package/dist/local/store/kyber-prekey-lifecycle.js +88 -0
  203. package/dist/local/store/kyber-prekey-lifecycle.js.map +1 -0
  204. package/dist/local/store/memory/adapter.d.ts +11 -3
  205. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  206. package/dist/local/store/memory/adapter.js +113 -28
  207. package/dist/local/store/memory/adapter.js.map +1 -1
  208. package/dist/local/store/node/adapter.d.ts +8 -2
  209. package/dist/local/store/node/adapter.d.ts.map +1 -1
  210. package/dist/local/store/node/adapter.js +31 -13
  211. package/dist/local/store/node/adapter.js.map +1 -1
  212. package/dist/local/store/node/database-file-commit.d.ts +8 -0
  213. package/dist/local/store/node/database-file-commit.d.ts.map +1 -0
  214. package/dist/local/store/node/database-file-commit.js +62 -0
  215. package/dist/local/store/node/database-file-commit.js.map +1 -0
  216. package/dist/local/store/node/database-key.d.ts +6 -1
  217. package/dist/local/store/node/database-key.d.ts.map +1 -1
  218. package/dist/local/store/node/database-key.js +79 -44
  219. package/dist/local/store/node/database-key.js.map +1 -1
  220. package/dist/local/store/node/database-lock.d.ts +8 -0
  221. package/dist/local/store/node/database-lock.d.ts.map +1 -0
  222. package/dist/local/store/node/database-lock.js +44 -0
  223. package/dist/local/store/node/database-lock.js.map +1 -0
  224. package/dist/local/store/node/database.d.ts +15 -14
  225. package/dist/local/store/node/database.d.ts.map +1 -1
  226. package/dist/local/store/node/database.js +197 -202
  227. package/dist/local/store/node/database.js.map +1 -1
  228. package/dist/local/store/react-native/adapter.d.ts +8 -2
  229. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  230. package/dist/local/store/react-native/adapter.js +151 -66
  231. package/dist/local/store/react-native/adapter.js.map +1 -1
  232. package/dist/local/store/received-content.d.ts +9 -0
  233. package/dist/local/store/received-content.d.ts.map +1 -0
  234. package/dist/local/store/received-content.js +46 -0
  235. package/dist/local/store/received-content.js.map +1 -0
  236. package/dist/local/store/reliability.d.ts +2 -2
  237. package/dist/local/store/reliability.d.ts.map +1 -1
  238. package/dist/local/store/reliability.js +7 -4
  239. package/dist/local/store/reliability.js.map +1 -1
  240. package/dist/local/store/web/adapter.d.ts +8 -2
  241. package/dist/local/store/web/adapter.d.ts.map +1 -1
  242. package/dist/local/store/web/adapter.js +206 -73
  243. package/dist/local/store/web/adapter.js.map +1 -1
  244. package/dist/media/index.d.ts +71 -61
  245. package/dist/media/index.d.ts.map +1 -1
  246. package/dist/media/index.js +550 -386
  247. package/dist/media/index.js.map +1 -1
  248. package/dist/media/prepared-upload.d.ts +37 -0
  249. package/dist/media/prepared-upload.d.ts.map +1 -0
  250. package/dist/media/prepared-upload.js +46 -0
  251. package/dist/media/prepared-upload.js.map +1 -0
  252. package/dist/remote/object-store/convex-r2/server.d.ts +2 -1
  253. package/dist/remote/object-store/convex-r2/server.d.ts.map +1 -1
  254. package/dist/remote/object-store/convex-r2/server.js +4 -0
  255. package/dist/remote/object-store/convex-r2/server.js.map +1 -1
  256. package/dist/remote/object-store/convex-r2/storage.d.ts.map +1 -1
  257. package/dist/remote/object-store/convex-r2/storage.js +1 -0
  258. package/dist/remote/object-store/convex-r2/storage.js.map +1 -1
  259. package/dist/remote/object-store/index.d.ts +3 -1
  260. package/dist/remote/object-store/index.d.ts.map +1 -1
  261. package/dist/remote/object-store/index.js +1 -1
  262. package/dist/remote/object-store/index.js.map +1 -1
  263. package/dist/remote/object-store/s3/storage.d.ts +3 -1
  264. package/dist/remote/object-store/s3/storage.d.ts.map +1 -1
  265. package/dist/remote/object-store/s3/storage.js +9 -2
  266. package/dist/remote/object-store/s3/storage.js.map +1 -1
  267. package/dist/remote/object-store/types.d.ts +33 -4
  268. package/dist/remote/object-store/types.d.ts.map +1 -1
  269. package/dist/remote/object-store/upload-error.d.ts +23 -0
  270. package/dist/remote/object-store/upload-error.d.ts.map +1 -0
  271. package/dist/remote/object-store/upload-error.js +33 -0
  272. package/dist/remote/object-store/upload-error.js.map +1 -0
  273. package/dist/remote/object-store/validation.d.ts +7 -1
  274. package/dist/remote/object-store/validation.d.ts.map +1 -1
  275. package/dist/remote/object-store/validation.js +39 -25
  276. package/dist/remote/object-store/validation.js.map +1 -1
  277. package/dist/remote/relay/index.d.ts +5 -12
  278. package/dist/remote/relay/index.d.ts.map +1 -1
  279. package/dist/remote/relay/index.js +4 -11
  280. package/dist/remote/relay/index.js.map +1 -1
  281. package/dist/remote/relay/memory/adapter.d.ts +2 -1
  282. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  283. package/dist/remote/relay/memory/adapter.js +10 -0
  284. package/dist/remote/relay/memory/adapter.js.map +1 -1
  285. package/dist/remote/relay/types.d.ts +28 -17
  286. package/dist/remote/relay/types.d.ts.map +1 -1
  287. package/dist/types/api.d.ts +36 -1
  288. package/dist/types/api.d.ts.map +1 -1
  289. package/dist/types/session.d.ts +6 -0
  290. package/dist/types/session.d.ts.map +1 -1
  291. package/dist/types/session.js.map +1 -1
  292. package/docs/ASSURANCE.md +7 -7
  293. package/docs/CLIENT_COMPOSITION.md +12 -19
  294. package/docs/DEVIATIONS.md +1 -1
  295. package/docs/DOCUMENTATION_STANDARDS.md +4 -0
  296. package/docs/GETTING_STARTED.md +23 -38
  297. package/docs/INTERFACES.md +22 -13
  298. package/docs/PACKAGE_SURFACE.md +5 -12
  299. package/docs/RECIPES.md +10 -23
  300. package/examples/browser/index.html +2 -2
  301. package/local/store/README.md +16 -1
  302. package/local/store/expo/README.md +23 -19
  303. package/local/store/node/README.md +29 -0
  304. package/media/README.md +94 -0
  305. package/package.json +17 -27
  306. package/remote/README.md +16 -16
  307. package/remote/object-store/README.md +8 -0
  308. package/remote/object-store/s3/README.md +10 -1
  309. package/remote/relay/README.md +3 -2
  310. package/COMMERCIAL.md +0 -56
  311. package/dist/device/expo-metadata.d.ts.map +0 -1
  312. package/dist/device/expo-metadata.js.map +0 -1
  313. package/dist/remote/relay/convex/backend.d.ts +0 -394
  314. package/dist/remote/relay/convex/backend.d.ts.map +0 -1
  315. package/dist/remote/relay/convex/backend.js +0 -678
  316. package/dist/remote/relay/convex/backend.js.map +0 -1
  317. package/dist/remote/relay/convex/component/_generated/api.d.ts +0 -58
  318. package/dist/remote/relay/convex/component/_generated/api.d.ts.map +0 -1
  319. package/dist/remote/relay/convex/component/_generated/api.js +0 -31
  320. package/dist/remote/relay/convex/component/_generated/api.js.map +0 -1
  321. package/dist/remote/relay/convex/component/_generated/component.d.ts +0 -475
  322. package/dist/remote/relay/convex/component/_generated/component.d.ts.map +0 -1
  323. package/dist/remote/relay/convex/component/_generated/component.js +0 -11
  324. package/dist/remote/relay/convex/component/_generated/component.js.map +0 -1
  325. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts +0 -46
  326. package/dist/remote/relay/convex/component/_generated/dataModel.d.ts.map +0 -1
  327. package/dist/remote/relay/convex/component/_generated/dataModel.js +0 -11
  328. package/dist/remote/relay/convex/component/_generated/dataModel.js.map +0 -1
  329. package/dist/remote/relay/convex/component/_generated/server.d.ts +0 -129
  330. package/dist/remote/relay/convex/component/_generated/server.d.ts.map +0 -1
  331. package/dist/remote/relay/convex/component/_generated/server.js +0 -79
  332. package/dist/remote/relay/convex/component/_generated/server.js.map +0 -1
  333. package/dist/remote/relay/convex/component/accounts.d.ts +0 -45
  334. package/dist/remote/relay/convex/component/accounts.d.ts.map +0 -1
  335. package/dist/remote/relay/convex/component/accounts.js +0 -184
  336. package/dist/remote/relay/convex/component/accounts.js.map +0 -1
  337. package/dist/remote/relay/convex/component/certificates.d.ts +0 -10
  338. package/dist/remote/relay/convex/component/certificates.d.ts.map +0 -1
  339. package/dist/remote/relay/convex/component/certificates.js +0 -126
  340. package/dist/remote/relay/convex/component/certificates.js.map +0 -1
  341. package/dist/remote/relay/convex/component/cleanup.d.ts +0 -32
  342. package/dist/remote/relay/convex/component/cleanup.d.ts.map +0 -1
  343. package/dist/remote/relay/convex/component/cleanup.js +0 -146
  344. package/dist/remote/relay/convex/component/cleanup.js.map +0 -1
  345. package/dist/remote/relay/convex/component/convex.config.d.ts +0 -5
  346. package/dist/remote/relay/convex/component/convex.config.d.ts.map +0 -1
  347. package/dist/remote/relay/convex/component/convex.config.js +0 -35
  348. package/dist/remote/relay/convex/component/convex.config.js.map +0 -1
  349. package/dist/remote/relay/convex/component/crons.d.ts +0 -3
  350. package/dist/remote/relay/convex/component/crons.d.ts.map +0 -1
  351. package/dist/remote/relay/convex/component/crons.js +0 -10
  352. package/dist/remote/relay/convex/component/crons.js.map +0 -1
  353. package/dist/remote/relay/convex/component/devices.d.ts +0 -102
  354. package/dist/remote/relay/convex/component/devices.d.ts.map +0 -1
  355. package/dist/remote/relay/convex/component/devices.js +0 -300
  356. package/dist/remote/relay/convex/component/devices.js.map +0 -1
  357. package/dist/remote/relay/convex/component/errors.d.ts +0 -22
  358. package/dist/remote/relay/convex/component/errors.d.ts.map +0 -1
  359. package/dist/remote/relay/convex/component/errors.js +0 -17
  360. package/dist/remote/relay/convex/component/errors.js.map +0 -1
  361. package/dist/remote/relay/convex/component/groups.d.ts +0 -63
  362. package/dist/remote/relay/convex/component/groups.d.ts.map +0 -1
  363. package/dist/remote/relay/convex/component/groups.js +0 -341
  364. package/dist/remote/relay/convex/component/groups.js.map +0 -1
  365. package/dist/remote/relay/convex/component/keys.d.ts +0 -130
  366. package/dist/remote/relay/convex/component/keys.d.ts.map +0 -1
  367. package/dist/remote/relay/convex/component/keys.js +0 -578
  368. package/dist/remote/relay/convex/component/keys.js.map +0 -1
  369. package/dist/remote/relay/convex/component/messages.d.ts +0 -105
  370. package/dist/remote/relay/convex/component/messages.d.ts.map +0 -1
  371. package/dist/remote/relay/convex/component/messages.js +0 -702
  372. package/dist/remote/relay/convex/component/messages.js.map +0 -1
  373. package/dist/remote/relay/convex/component/provisioning.d.ts +0 -92
  374. package/dist/remote/relay/convex/component/provisioning.d.ts.map +0 -1
  375. package/dist/remote/relay/convex/component/provisioning.js +0 -360
  376. package/dist/remote/relay/convex/component/provisioning.js.map +0 -1
  377. package/dist/remote/relay/convex/component/runtime.d.ts +0 -18
  378. package/dist/remote/relay/convex/component/runtime.d.ts.map +0 -1
  379. package/dist/remote/relay/convex/component/runtime.js +0 -144
  380. package/dist/remote/relay/convex/component/runtime.js.map +0 -1
  381. package/dist/remote/relay/convex/component/schema.d.ts +0 -358
  382. package/dist/remote/relay/convex/component/schema.d.ts.map +0 -1
  383. package/dist/remote/relay/convex/component/schema.js +0 -288
  384. package/dist/remote/relay/convex/component/schema.js.map +0 -1
  385. package/dist/remote/relay/convex/component/zkAuth.d.ts +0 -18
  386. package/dist/remote/relay/convex/component/zkAuth.d.ts.map +0 -1
  387. package/dist/remote/relay/convex/component/zkAuth.js +0 -86
  388. package/dist/remote/relay/convex/component/zkAuth.js.map +0 -1
  389. package/dist/remote/relay/convex/constants.d.ts +0 -3
  390. package/dist/remote/relay/convex/constants.d.ts.map +0 -1
  391. package/dist/remote/relay/convex/constants.js +0 -3
  392. package/dist/remote/relay/convex/constants.js.map +0 -1
  393. package/dist/remote/relay/convex/group-server.d.ts +0 -123
  394. package/dist/remote/relay/convex/group-server.d.ts.map +0 -1
  395. package/dist/remote/relay/convex/group-server.js +0 -184
  396. package/dist/remote/relay/convex/group-server.js.map +0 -1
  397. package/dist/remote/relay/convex/index.d.ts +0 -42
  398. package/dist/remote/relay/convex/index.d.ts.map +0 -1
  399. package/dist/remote/relay/convex/index.js +0 -38
  400. package/dist/remote/relay/convex/index.js.map +0 -1
  401. package/dist/remote/relay/convex/relay.d.ts +0 -323
  402. package/dist/remote/relay/convex/relay.d.ts.map +0 -1
  403. package/dist/remote/relay/convex/relay.js +0 -1144
  404. package/dist/remote/relay/convex/relay.js.map +0 -1
  405. package/dist/remote/relay/convex/types.d.ts +0 -24
  406. package/dist/remote/relay/convex/types.d.ts.map +0 -1
  407. package/dist/remote/relay/convex/types.js +0 -14
  408. package/dist/remote/relay/convex/types.js.map +0 -1
  409. package/remote/relay/convex/README.md +0 -61
  410. package/remote/relay/convex/component/README.md +0 -462
@@ -1,35 +1,40 @@
1
- import { createCompositeIdentityV1, decodeCompositeIdentityV1, encodeCompositeIdentityV1, } from '../keys/identity.js';
2
- import { base64ToBytes, bytesToBase64, bytesToUrlSafeBase64, concatBytes, generateUuidV4, sha256, stringToBytes, urlSafeToBase64, } from '../internal/crypto/index.js';
3
- const SESSION_METADATA_PREFIX = 'hostedRelay.session.v1:';
1
+ import AsyncLock from "async-lock";
2
+ import { createCompositeIdentityV1, decodeCompositeIdentityV1, encodeCompositeIdentityV1, } from "../keys/identity.js";
3
+ import { base64ToBytes, bytesToBase64, bytesToUrlSafeBase64, concatBytes, generateUuidV4, sha256, stringToBytes, urlSafeToBase64, } from "../internal/crypto/index.js";
4
+ import { RemoteObjectUploadError } from "../remote/object-store/index.js";
5
+ import { subscribeHostedMailbox, } from "./hosted-mailbox-subscription.js";
6
+ import { HostedGroupServer } from "./hosted-groups.js";
7
+ import { HostedAnonymousDelivery, decodeHostedAnonymousEnvelope, } from "./hosted-anonymous-delivery.js";
8
+ import { applyPreKeyUploads, parseHostedPreKeyStatus, parseStoredPendingPublication, parseStoredPublication, publicationMatchesStatus, registrationPreKey, statusPreKeys, storedPreKey, storedPublication, } from "./hosted-prekey-publication.js";
9
+ const SESSION_METADATA_PREFIX = "hostedRelay.session.v1:";
4
10
  const DEVICE_TOKEN_REFRESH_SECONDS = 60;
5
11
  const MAXIMUM_RESPONSE_BYTES = 1024 * 1024;
6
- const HOSTED_ONE_TIME_PREKEY_LIMIT = 100;
7
12
  const PREKEY_EXPIRY_MILLISECONDS = 30 * 24 * 60 * 60 * 1000;
8
- const POLL_MILLISECONDS = 2_000;
9
13
  const DELIVERY_WIRE_VERSION = 1;
10
- const DEVICE_AUTHENTICATION_SIGNATURE_LABEL = stringToBytes('OpenE2EE Relay device authentication v1\0');
11
- const REGISTRATION_MATERIAL_LABEL = stringToBytes('OpenE2EE Relay registration material v1\0');
12
- const REGISTRATION_CHALLENGE_LABEL = stringToBytes('OpenE2EE Relay registration challenge v1\0');
13
- const RECOVERY_CHALLENGE_LABEL = stringToBytes('OpenE2EE Relay recovery challenge v1\0');
14
- const TOKEN_REFRESH_CHALLENGE_LABEL = stringToBytes('OpenE2EE Relay device token refresh challenge v1\0');
14
+ const DEVICE_AUTHENTICATION_SIGNATURE_LABEL = stringToBytes("OpenE2EE Relay device authentication v1\0");
15
+ const REGISTRATION_MATERIAL_LABEL = stringToBytes("OpenE2EE Relay registration material v1\0");
16
+ const REGISTRATION_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay registration challenge v1\0");
17
+ const RECOVERY_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay recovery challenge v1\0");
18
+ const TOKEN_REFRESH_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay device token refresh challenge v1\0");
19
+ const hostedPreKeyPublicationLock = new AsyncLock({ maxPending: 100 });
15
20
  export class HostedRelayHttpError extends Error {
16
21
  code;
17
22
  data;
18
23
  status;
19
24
  constructor(status, code, message, data) {
20
25
  super(message);
21
- this.name = 'HostedRelayHttpError';
26
+ this.name = "HostedRelayHttpError";
22
27
  this.status = status;
23
28
  this.code = code;
24
29
  this.data = data;
25
30
  }
26
31
  }
27
32
  function record(value) {
28
- return typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29
34
  }
30
35
  function uint32be(value) {
31
36
  if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff_ffff) {
32
- throw new Error('Hosted Relay unsigned integer is invalid');
37
+ throw new Error("Signal Protocol Relay unsigned integer is invalid");
33
38
  }
34
39
  return new Uint8Array([value >>> 24, value >>> 16, value >>> 8, value]);
35
40
  }
@@ -52,7 +57,7 @@ function canonicalBase64(value) {
52
57
  return bytesToBase64(value);
53
58
  }
54
59
  function decodeCanonicalBase64(value, label) {
55
- if (typeof value !== 'string')
60
+ if (typeof value !== "string")
56
61
  throw new Error(`${label} is invalid`);
57
62
  const decoded = base64ToBytes(value);
58
63
  if (bytesToBase64(decoded) !== value)
@@ -74,16 +79,16 @@ function relayScopeId(connection) {
74
79
  return bytesToUrlSafeBase64(connection.relayScopeId);
75
80
  }
76
81
  function identifiedEndpoint(connection) {
77
- return connection.protocolEndpoint.replace(/\/$/u, '');
82
+ return connection.protocolEndpoint.replace(/\/$/u, "");
78
83
  }
79
84
  async function parseResponse(response) {
80
85
  const body = await response.text();
81
86
  if (body.length > MAXIMUM_RESPONSE_BYTES) {
82
- throw new Error('Managed Relay response is too large');
87
+ throw new Error("Signal Protocol Relay response is too large");
83
88
  }
84
89
  if (response.ok && response.status === 204) {
85
90
  if (body.length !== 0) {
86
- throw new Error('Managed Relay returned an invalid response');
91
+ throw new Error("Signal Protocol Relay returned an invalid response");
87
92
  }
88
93
  return undefined;
89
94
  }
@@ -92,52 +97,54 @@ async function parseResponse(response) {
92
97
  parsed = JSON.parse(body);
93
98
  }
94
99
  catch {
95
- throw new Error('Managed Relay returned invalid JSON');
100
+ throw new Error("Signal Protocol Relay returned invalid JSON");
96
101
  }
97
102
  if (!response.ok) {
98
103
  const error = record(parsed) && record(parsed.error) ? parsed.error : {};
99
- const code = typeof error.code === 'string' ? error.code : 'UNKNOWN';
100
- const message = typeof error.message === 'string'
104
+ const code = typeof error.code === "string" ? error.code : "UNKNOWN";
105
+ const message = typeof error.message === "string"
101
106
  ? error.message
102
- : 'Managed Relay request failed';
107
+ : "Signal Protocol Relay request failed";
103
108
  throw new HostedRelayHttpError(response.status, code, message);
104
109
  }
105
110
  return parsed;
106
111
  }
107
112
  async function postJson(connection, path, body, token) {
108
113
  const headers = new Headers({
109
- accept: 'application/json',
110
- 'content-type': 'application/json',
114
+ accept: "application/json",
115
+ "content-type": "application/json",
111
116
  });
112
117
  if (token !== undefined)
113
- headers.set('authorization', `Bearer ${token}`);
118
+ headers.set("authorization", `Bearer ${token}`);
114
119
  let response;
115
120
  try {
116
121
  response = await fetch(`${identifiedEndpoint(connection)}${path}`, {
117
122
  body: JSON.stringify(body),
118
123
  headers,
119
- method: 'POST',
124
+ method: "POST",
125
+ credentials: "omit",
126
+ redirect: "error",
120
127
  });
121
128
  }
122
129
  catch (cause) {
123
- throw new Error('Managed Relay request could not be completed', { cause });
130
+ throw new Error("Signal Protocol Relay request could not be completed", { cause });
124
131
  }
125
132
  return parseResponse(response);
126
133
  }
127
134
  function assertionIdentifier(assertion) {
128
- const parts = assertion.split('.');
135
+ const parts = assertion.split(".");
129
136
  if (parts.length !== 3) {
130
- throw new Error('Identity provider returned an invalid assertion');
137
+ throw new Error("Identity provider returned an invalid assertion");
131
138
  }
132
139
  let claims;
133
140
  try {
134
- claims = JSON.parse(new TextDecoder().decode(decodeBase64Url(parts[1], 'Assertion claims')));
141
+ claims = JSON.parse(new TextDecoder().decode(decodeBase64Url(parts[1], "Assertion claims")));
135
142
  }
136
143
  catch {
137
- throw new Error('Identity provider returned an invalid assertion');
144
+ throw new Error("Identity provider returned an invalid assertion");
138
145
  }
139
- if (!record(claims) || typeof claims.jti !== 'string' || !claims.jti) {
140
- throw new Error('Identity provider returned an invalid assertion');
146
+ if (!record(claims) || typeof claims.jti !== "string" || !claims.jti) {
147
+ throw new Error("Identity provider returned an invalid assertion");
141
148
  }
142
149
  return claims.jti;
143
150
  }
@@ -163,14 +170,14 @@ async function registrationMaterialFingerprint(identity, registrationId, prekeys
163
170
  const entries = [
164
171
  ...prekeys.signedPreKeys.map((prekey) => ({
165
172
  ...prekey,
166
- kind: 'signed',
173
+ kind: "signed",
167
174
  })),
168
175
  ...prekeys.oneTimePreKeys.map((prekey) => ({
169
176
  ...prekey,
170
- kind: 'one-time',
177
+ kind: "one-time",
171
178
  })),
172
179
  ].sort((left, right) => `${left.kind}:${left.algorithm}:${String(left.keyId)}`.localeCompare(`${right.kind}:${right.algorithm}:${String(right.keyId)}`));
173
- return bytesToUrlSafeBase64(await sha256(concatBytes(REGISTRATION_MATERIAL_LABEL, text('aci'), text('signal-composite-v1'), uint32be(registrationId), lengthPrefixed(encodeCompositeIdentityV1(identity)), ...entries.flatMap((prekey) => [
180
+ return bytesToUrlSafeBase64(await sha256(concatBytes(REGISTRATION_MATERIAL_LABEL, text("aci"), text("signal-composite-v1"), uint32be(registrationId), lengthPrefixed(encodeCompositeIdentityV1(identity)), ...entries.flatMap((prekey) => [
174
181
  text(prekey.kind),
175
182
  text(prekey.algorithm),
176
183
  uint32be(prekey.keyId),
@@ -179,7 +186,7 @@ async function registrationMaterialFingerprint(identity, registrationId, prekeys
179
186
  ]))));
180
187
  }
181
188
  async function registrationChallenge(request) {
182
- return sha256(concatBytes(request.assertionPurpose === 'recover'
189
+ return sha256(concatBytes(request.assertionPurpose === "recover"
183
190
  ? RECOVERY_CHALLENGE_LABEL
184
191
  : REGISTRATION_CHALLENGE_LABEL, text(relayScopeId(request.connection)), text(assertionIdentifier(request.assertion)), text(request.operationId), text(await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys))));
185
192
  }
@@ -192,32 +199,41 @@ function parseSession(value, connection) {
192
199
  parsed = JSON.parse(value);
193
200
  }
194
201
  catch {
195
- throw new Error('Stored hosted Relay session is invalid');
202
+ throw new Error("Stored Signal Protocol Relay session is invalid");
196
203
  }
197
204
  if (!record(parsed) ||
198
- Object.keys(parsed).sort().join(',') !==
199
- 'canonicalAccountId,deviceId,deviceToken,generation,mailboxGeneration,relayScopeId' ||
200
- typeof parsed.canonicalAccountId !== 'string' ||
205
+ Object.keys(parsed).sort().join(",") !==
206
+ "canonicalAccountId,deviceId,deviceToken,generation,mailboxGeneration,pendingPreKeyPublication,preKeyPublication,relayScopeId" ||
207
+ typeof parsed.canonicalAccountId !== "string" ||
201
208
  !parsed.canonicalAccountId ||
202
209
  !Number.isSafeInteger(parsed.deviceId) ||
203
210
  parsed.deviceId < 1 ||
204
- typeof parsed.deviceToken !== 'string' ||
211
+ typeof parsed.deviceToken !== "string" ||
205
212
  !parsed.deviceToken ||
206
213
  !Number.isSafeInteger(parsed.generation) ||
207
214
  parsed.generation < 0 ||
208
215
  !Number.isSafeInteger(parsed.mailboxGeneration) ||
209
216
  parsed.mailboxGeneration < 0 ||
210
217
  parsed.relayScopeId !== relayScopeId(connection)) {
211
- throw new Error('Stored hosted Relay session is invalid');
218
+ throw new Error("Stored Signal Protocol Relay session is invalid");
212
219
  }
213
- return parsed;
220
+ return {
221
+ canonicalAccountId: parsed.canonicalAccountId,
222
+ deviceId: parsed.deviceId,
223
+ deviceToken: parsed.deviceToken,
224
+ generation: parsed.generation,
225
+ mailboxGeneration: parsed.mailboxGeneration,
226
+ pendingPreKeyPublication: parseStoredPendingPublication(parsed.pendingPreKeyPublication),
227
+ preKeyPublication: parseStoredPublication(parsed.preKeyPublication),
228
+ relayScopeId: parsed.relayScopeId,
229
+ };
214
230
  }
215
231
  function tokenExpiration(token, session) {
216
- const parts = token.split('.');
232
+ const parts = token.split(".");
217
233
  if (parts.length !== 3)
218
234
  return 0;
219
235
  try {
220
- const claims = JSON.parse(new TextDecoder().decode(decodeBase64Url(parts[1], 'Device token')));
236
+ const claims = JSON.parse(new TextDecoder().decode(decodeBase64Url(parts[1], "Device token")));
221
237
  if (!record(claims) ||
222
238
  claims.account_id !== session.canonicalAccountId ||
223
239
  claims.device_id !== session.deviceId ||
@@ -236,24 +252,24 @@ function tokenExpiration(token, session) {
236
252
  function requiredNumber(object, key) {
237
253
  const value = object[key];
238
254
  if (!Number.isSafeInteger(value))
239
- throw new Error('Managed Relay returned invalid data');
255
+ throw new Error("Signal Protocol Relay returned invalid data");
240
256
  return value;
241
257
  }
242
258
  function requiredString(object, key) {
243
259
  const value = object[key];
244
- if (typeof value !== 'string' || !value)
245
- throw new Error('Managed Relay returned invalid data');
260
+ if (typeof value !== "string" || !value)
261
+ throw new Error("Signal Protocol Relay returned invalid data");
246
262
  return value;
247
263
  }
248
264
  function unsupported(operation) {
249
- throw new Error(`Managed Relay does not support ${operation} through this contract`);
265
+ throw new Error(`Signal Protocol Relay does not support ${operation} through this contract`);
250
266
  }
251
267
  function encodeDeliveryWire(envelope) {
252
268
  const ciphertext = envelope.ciphertext instanceof Uint8Array
253
269
  ? bytesToBase64(envelope.ciphertext)
254
270
  : envelope.ciphertext;
255
271
  if (bytesToBase64(base64ToBytes(ciphertext)) !== ciphertext) {
256
- throw new Error('Managed Relay envelope ciphertext is invalid');
272
+ throw new Error("Signal Protocol Relay envelope ciphertext is invalid");
257
273
  }
258
274
  const wire = {
259
275
  ciphertext,
@@ -272,16 +288,18 @@ function decodeDeliveryWire(value) {
272
288
  wire = JSON.parse(new TextDecoder().decode(value));
273
289
  }
274
290
  catch {
275
- throw new Error('Managed Relay mailbox envelope is invalid');
291
+ throw new Error("Signal Protocol Relay mailbox envelope is invalid");
276
292
  }
277
293
  if (!record(wire) ||
278
- typeof wire.ciphertext !== 'string' ||
279
- bytesToBase64(base64ToBytes(wire.ciphertext)) !== wire.ciphertext ||
280
- (wire.contentHint !== undefined && !Number.isSafeInteger(wire.contentHint)) ||
281
- typeof wire.messageType !== 'string' ||
294
+ typeof wire.ciphertext !== "string" ||
295
+ bytesToBase64(base64ToBytes(wire.ciphertext)) !==
296
+ wire.ciphertext ||
297
+ (wire.contentHint !== undefined &&
298
+ !Number.isSafeInteger(wire.contentHint)) ||
299
+ typeof wire.messageType !== "string" ||
282
300
  !Number.isSafeInteger(wire.timestamp) ||
283
301
  wire.version !== DELIVERY_WIRE_VERSION) {
284
- throw new Error('Managed Relay mailbox envelope is invalid');
302
+ throw new Error("Signal Protocol Relay mailbox envelope is invalid");
285
303
  }
286
304
  return wire;
287
305
  }
@@ -290,13 +308,34 @@ export class HostedRelayHttpTransport {
290
308
  storage;
291
309
  deviceAuthentication;
292
310
  session;
311
+ groups;
312
+ groupServer;
313
+ anonymousDelivery;
293
314
  refreshPromise;
294
315
  destinationGenerations = new Map();
316
+ ephemeralAcknowledgments = new Set();
317
+ subscription;
295
318
  constructor(connection, storage, deviceAuthentication, session) {
296
319
  this.connection = connection;
297
320
  this.storage = storage;
298
321
  this.deviceAuthentication = deviceAuthentication;
299
322
  this.session = session;
323
+ this.groups = new HostedGroupServer(connection);
324
+ this.groupServer = {
325
+ server: this.groups,
326
+ issueAuthCredential: (userId, authorityKeyId) => this.issueAuthCredential(userId, authorityKeyId),
327
+ issueProfileKeyCredential: (userId, request, authorityKeyId) => this.issueProfileKeyCredential(userId, request, authorityKeyId),
328
+ setUnidentifiedAccessKey: (userId, accessKey) => this.setUnidentifiedAccessKey(userId, accessKey),
329
+ };
330
+ this.anonymousDelivery = new HostedAnonymousDelivery(connection, async (accountAddress, deviceId) => {
331
+ const key = `${accountAddress}\0${deviceId}`;
332
+ if (!this.destinationGenerations.has(key))
333
+ await this.directory(accountAddress);
334
+ const generation = this.destinationGenerations.get(key);
335
+ if (generation === undefined)
336
+ throw new Error("Signal Protocol Relay destination device does not exist");
337
+ return { accountAddress, deviceId, generation };
338
+ });
300
339
  }
301
340
  get accountId() {
302
341
  return this.session.canonicalAccountId;
@@ -305,30 +344,105 @@ export class HostedRelayHttpTransport {
305
344
  return this.session.deviceId;
306
345
  }
307
346
  objectStore = {
308
- createUpload: async (input) => this.createObjectUpload(input),
347
+ createUpload: async (input) => {
348
+ try {
349
+ return await this.createObjectUpload(input);
350
+ }
351
+ catch (error) {
352
+ throw this.uploadError(error, "admission");
353
+ }
354
+ },
309
355
  createDownload: async (input) => this.createObjectDownload(input),
310
- completeUpload: async ({ objectId }) => {
311
- await this.authenticatedPost('/objects/commit-upload', {
312
- objectId,
356
+ abandonUpload: async ({ requestId, preparedAt }) => {
357
+ const result = await this.authenticatedPost("/objects/abandon-upload", {
358
+ requestId,
359
+ preparedAt,
313
360
  publishableKey: this.connection.publishableKey,
314
361
  });
362
+ if (!record(result) ||
363
+ result.abandoned !== true ||
364
+ Object.keys(result).length !== 1)
365
+ throw new Error("The upload abandonment receipt is invalid.");
366
+ },
367
+ completeUpload: async ({ objectId }) => {
368
+ try {
369
+ await this.commitObjectUpload(objectId);
370
+ }
371
+ catch (error) {
372
+ throw this.uploadError(error, "settlement");
373
+ }
374
+ },
375
+ reconcileUpload: async ({ objectId }) => {
376
+ try {
377
+ return await this.commitObjectUpload(objectId);
378
+ }
379
+ catch (error) {
380
+ if (error instanceof HostedRelayHttpError &&
381
+ error.code === "UPLOAD_INCOMPLETE")
382
+ return null;
383
+ throw this.uploadError(error, "settlement");
384
+ }
315
385
  },
316
386
  deleteObject: async ({ objectId }) => {
317
- await this.authenticatedPost('/objects/delete', {
387
+ await this.authenticatedPost("/objects/delete", {
318
388
  objectId,
319
389
  publishableKey: this.connection.publishableKey,
320
390
  });
321
391
  },
322
392
  };
393
+ uploadError(error, phase) {
394
+ if (!(error instanceof HostedRelayHttpError))
395
+ return error;
396
+ switch (error.code) {
397
+ case "UPLOAD_EXPIRED":
398
+ return new RemoteObjectUploadError("upload-expired");
399
+ case "UPLOAD_CLOCK_SKEW":
400
+ return new RemoteObjectUploadError("upload-clock-skew");
401
+ case "PERIOD_CLOSED":
402
+ // Accepted work can still require settlement repair. Do not terminalize it here.
403
+ return phase === "admission"
404
+ ? new RemoteObjectUploadError("upload-admission-closed")
405
+ : error;
406
+ case "NOT_FOUND":
407
+ return new RemoteObjectUploadError("upload-unavailable");
408
+ case "RETRY_CONFLICT":
409
+ return new RemoteObjectUploadError("upload-identity-conflict");
410
+ case "AUTHORITY_OVERRIDE":
411
+ case "AUTHORITY_DENIED":
412
+ case "SCOPE_MISMATCH":
413
+ return new RemoteObjectUploadError("upload-rejected");
414
+ default:
415
+ return error;
416
+ }
417
+ }
323
418
  async persistSession() {
324
419
  await this.storage.setMetadata(await sessionMetadataKey(this.connection), JSON.stringify(this.session));
325
420
  }
421
+ async commitObjectUpload(objectId) {
422
+ const value = await this.authenticatedPost("/objects/commit-upload", {
423
+ objectId,
424
+ publishableKey: this.connection.publishableKey,
425
+ });
426
+ if (!record(value) ||
427
+ value.available !== true ||
428
+ value.objectId !== objectId) {
429
+ throw new Error("Signal Protocol Relay returned an invalid upload receipt");
430
+ }
431
+ const contentLength = requiredNumber(value, "contentLength");
432
+ const digest = decodeBase64Url(requiredString(value, "digest"), "Attachment digest");
433
+ if (!Number.isSafeInteger(contentLength) ||
434
+ contentLength < 0 ||
435
+ digest.length !== 32) {
436
+ throw new Error("Signal Protocol Relay returned an invalid upload receipt");
437
+ }
438
+ return { objectId, contentLength, digest };
439
+ }
326
440
  async refreshToken() {
327
441
  const requestedAtSeconds = Math.floor(Date.now() / 1_000);
328
442
  const nonce = crypto.getRandomValues(new Uint8Array(32));
329
443
  const challenge = await sha256(concatBytes(TOKEN_REFRESH_CHALLENGE_LABEL, text(this.session.relayScopeId), text(this.session.canonicalAccountId), uint32be(this.session.deviceId), uint32be(this.session.generation), uint32be(this.session.mailboxGeneration), text(String(requestedAtSeconds)), lengthPrefixed(nonce)));
330
444
  const proof = await this.deviceAuthentication.signChallenge(challenge);
331
- const value = await postJson(this.connection, '/identity/token', {
445
+ const value = await postJson(this.connection, "/identity/token", {
332
446
  accountAddress: this.session.canonicalAccountId,
333
447
  deviceId: this.session.deviceId,
334
448
  deviceProof: bytesToBase64(proof),
@@ -336,12 +450,13 @@ export class HostedRelayHttpTransport {
336
450
  publishableKey: this.connection.publishableKey,
337
451
  requestedAtSeconds,
338
452
  });
339
- if (!record(value) || typeof value.deviceToken !== 'string') {
340
- throw new Error('Managed Relay returned an invalid device token');
453
+ if (!record(value) || typeof value.deviceToken !== "string") {
454
+ throw new Error("Signal Protocol Relay returned an invalid device token");
341
455
  }
342
456
  this.session = { ...this.session, deviceToken: value.deviceToken };
343
- if (tokenExpiration(this.session.deviceToken, this.session) <= requestedAtSeconds) {
344
- throw new Error('Managed Relay returned an invalid device token');
457
+ if (tokenExpiration(this.session.deviceToken, this.session) <=
458
+ requestedAtSeconds) {
459
+ throw new Error("Signal Protocol Relay returned an invalid device token");
345
460
  }
346
461
  await this.persistSession();
347
462
  }
@@ -358,7 +473,7 @@ export class HostedRelayHttpTransport {
358
473
  await this.refreshPromise;
359
474
  return this.session.deviceToken;
360
475
  }
361
- /** Verify that the stored device authority can obtain a current token. */
476
+ /** Verify that the stored device authority can get a current token. */
362
477
  async ensureAuthenticated(force = false) {
363
478
  await this.token(force);
364
479
  }
@@ -368,198 +483,268 @@ export class HostedRelayHttpTransport {
368
483
  return await postJson(this.connection, path, body, token);
369
484
  }
370
485
  catch (error) {
371
- if (!(error instanceof HostedRelayHttpError) || error.code !== 'TOKEN_INVALID') {
486
+ if (!(error instanceof HostedRelayHttpError) ||
487
+ error.code !== "TOKEN_INVALID") {
372
488
  throw error;
373
489
  }
374
490
  token = await this.token(true);
375
491
  return postJson(this.connection, path, body, token);
376
492
  }
377
493
  }
378
- assertCurrentIdentity(userId, deviceId, identityType = 'aci') {
494
+ assertCurrentIdentity(userId, deviceId, identityType = "aci") {
379
495
  if (userId !== this.session.canonicalAccountId ||
380
496
  deviceId !== this.session.deviceId ||
381
- identityType !== 'aci') {
382
- throw new Error('Managed Relay operation crossed the current device authority');
497
+ identityType !== "aci") {
498
+ throw new Error("Signal Protocol Relay operation crossed the current device authority");
383
499
  }
384
500
  }
385
501
  async directory(userId) {
386
- const value = await this.authenticatedPost('/identity/devices', {
502
+ const value = await this.authenticatedPost("/identity/devices", {
387
503
  accountAddress: userId,
388
504
  publishableKey: this.connection.publishableKey,
389
505
  });
390
- if (!record(value) || value.accountAddress !== userId || !Array.isArray(value.devices)) {
391
- throw new Error('Managed Relay returned an invalid device directory');
506
+ if (!record(value) ||
507
+ value.accountAddress !== userId ||
508
+ !Array.isArray(value.devices)) {
509
+ throw new Error("Signal Protocol Relay returned an invalid device directory");
392
510
  }
393
511
  return value.devices.map((candidate) => {
394
512
  if (!record(candidate))
395
- throw new Error('Managed Relay returned an invalid device directory');
513
+ throw new Error("Signal Protocol Relay returned an invalid device directory");
396
514
  const device = {
397
- deviceId: requiredNumber(candidate, 'deviceId'),
398
- generation: requiredNumber(candidate, 'generation'),
399
- mailboxGeneration: requiredNumber(candidate, 'mailboxGeneration'),
515
+ deviceId: requiredNumber(candidate, "deviceId"),
516
+ generation: requiredNumber(candidate, "generation"),
517
+ mailboxGeneration: requiredNumber(candidate, "mailboxGeneration"),
400
518
  };
401
- if (device.deviceId < 1 || device.generation < 0 || device.mailboxGeneration < 0) {
402
- throw new Error('Managed Relay returned an invalid device directory');
519
+ if (device.deviceId < 1 ||
520
+ device.generation < 0 ||
521
+ device.mailboxGeneration < 0) {
522
+ throw new Error("Signal Protocol Relay returned an invalid device directory");
403
523
  }
404
524
  this.destinationGenerations.set(`${userId}\0${String(device.deviceId)}`, device.mailboxGeneration);
405
525
  return device;
406
526
  });
407
527
  }
408
- async prekeyStatus(userId, deviceId, identityType = 'aci') {
409
- if (identityType !== 'aci')
410
- unsupported('PNI prekey authority');
411
- const value = await this.authenticatedPost('/prekeys/status', {
528
+ async prekeyStatus(userId, deviceId, identityType = "aci") {
529
+ if (identityType !== "aci")
530
+ unsupported("PNI prekey authority");
531
+ const value = await this.authenticatedPost("/prekeys/status", {
412
532
  accountAddress: userId,
413
533
  deviceId,
414
534
  identityType,
415
535
  publishableKey: this.connection.publishableKey,
416
536
  });
417
- if (!record(value) ||
418
- typeof value.identityPublicMaterial !== 'string' ||
419
- !record(value.oneTimePreKeyCounts) ||
420
- typeof value.profile !== 'string' ||
421
- !Array.isArray(value.signedPreKeys)) {
422
- throw new Error('Managed Relay returned invalid prekey status');
423
- }
424
- const signedPreKeys = value.signedPreKeys.map((candidate) => {
425
- if (!record(candidate))
426
- throw new Error('Managed Relay returned invalid prekey status');
427
- return {
428
- acceptedAtMilliseconds: requiredNumber(candidate, 'acceptedAtMilliseconds'),
429
- algorithm: requiredString(candidate, 'algorithm'),
430
- keyId: requiredNumber(candidate, 'keyId'),
431
- publicKey: decodeCanonicalBase64(candidate.publicKey, 'Prekey public key'),
432
- signature: decodeCanonicalBase64(candidate.signature, 'Prekey signature'),
433
- };
434
- });
435
- const counts = {};
436
- for (const [algorithm, count] of Object.entries(value.oneTimePreKeyCounts)) {
437
- if (!Number.isSafeInteger(count) || count < 0) {
438
- throw new Error('Managed Relay returned invalid prekey status');
439
- }
440
- counts[algorithm] = count;
441
- }
442
- return {
443
- identityPublicMaterial: decodeCanonicalBase64(value.identityPublicMaterial, 'Signal identity'),
444
- oneTimePreKeyCounts: counts,
445
- profile: value.profile,
446
- registrationId: requiredNumber(value, 'registrationId'),
447
- signedPreKeys,
448
- };
537
+ return parseHostedPreKeyStatus(value);
449
538
  }
450
- async currentRegistration() {
451
- const identity = await this.storage.getIdentityKey('aci');
452
- const ecSigned = await this.storage.getEcSignedPreKey(undefined, 'aci');
453
- const kemSigned = await this.storage.getKyberPreKey('aci');
454
- const [ecOneTime, kemOneTime] = await Promise.all([
455
- this.storage.getEcOneTimePreKeys('aci'),
456
- this.storage.getKemOneTimePreKeys('aci'),
457
- ]);
458
- if (!identity || !ecSigned || !kemSigned || ecOneTime.length === 0 || kemOneTime.length === 0) {
459
- throw new Error('Hosted Relay local prekey inventory is incomplete');
460
- }
461
- const boundedEcOneTime = [...ecOneTime]
462
- .sort((left, right) => right.keyId - left.keyId)
463
- .slice(0, HOSTED_ONE_TIME_PREKEY_LIMIT)
464
- .sort((left, right) => left.keyId - right.keyId);
465
- const boundedKemOneTime = [...kemOneTime]
466
- .sort((left, right) => right.keyId - left.keyId)
467
- .slice(0, HOSTED_ONE_TIME_PREKEY_LIMIT)
468
- .sort((left, right) => left.keyId - right.keyId);
539
+ async currentIdentity() {
540
+ const identity = await this.storage.getIdentityKey("aci");
541
+ if (!identity)
542
+ throw new Error("Signal Protocol Relay local Signal identity is unavailable");
469
543
  return {
470
544
  identity: createCompositeIdentityV1(identity),
471
545
  registrationId: identity.registrationId,
472
- prekeys: {
473
- signedPreKeys: [
474
- {
475
- algorithm: 'ec-x25519',
476
- keyId: ecSigned.keyId,
477
- publicKey: base64ToBytes(ecSigned.publicKey),
478
- signature: base64ToBytes(ecSigned.signature),
479
- },
480
- {
481
- algorithm: 'kem-ml-kem-1024',
482
- keyId: kemSigned.keyId,
483
- publicKey: base64ToBytes(kemSigned.publicKey),
484
- signature: base64ToBytes(kemSigned.signature),
485
- },
486
- ],
487
- oneTimePreKeys: [
488
- ...boundedEcOneTime.map((prekey) => ({
489
- algorithm: 'ec-x25519',
490
- keyId: prekey.keyId,
491
- publicKey: base64ToBytes(prekey.publicKey),
492
- })),
493
- ...boundedKemOneTime.map((prekey) => ({
494
- algorithm: 'kem-ml-kem-1024',
495
- keyId: prekey.keyId,
496
- publicKey: base64ToBytes(prekey.publicKey),
497
- signature: base64ToBytes(prekey.signature),
498
- })),
499
- ],
500
- },
501
546
  };
502
547
  }
503
- async publishCurrentPrekeys() {
504
- const current = await this.currentRegistration();
505
- const fingerprint = await registrationMaterialFingerprint(current.identity, current.registrationId, current.prekeys);
506
- const result = await this.authenticatedPost('/prekeys/publish', {
507
- operationId: fingerprint,
508
- publishableKey: this.connection.publishableKey,
509
- signalRegistration: signalRegistration(current.identity, current.registrationId, current.prekeys),
548
+ async acceptPublicationStatus(status) {
549
+ this.session.preKeyPublication = storedPublication(status.authorityGeneration, status.materialFingerprint, status.currentOperationId, status.publicationRevision, statusPreKeys(status));
550
+ this.session.pendingPreKeyPublication = null;
551
+ await this.persistSession();
552
+ }
553
+ async publishCurrentPrekeys(uploads) {
554
+ await hostedPreKeyPublicationLock.acquire(await sessionMetadataKey(this.connection), async () => {
555
+ const current = await this.currentIdentity();
556
+ let status = await this.prekeyStatus(this.session.canonicalAccountId, this.session.deviceId);
557
+ if (status.authorityGeneration !== this.session.generation ||
558
+ status.registrationId !== current.registrationId ||
559
+ !equalBytes(status.identityPublicMaterial, encodeCompositeIdentityV1(current.identity))) {
560
+ throw new Error("Signal Protocol Relay prekey publication authority does not match local state");
561
+ }
562
+ const pending = this.session.pendingPreKeyPublication;
563
+ let retryPending;
564
+ if (pending !== null) {
565
+ if (status.currentOperationId === pending.operationId &&
566
+ status.materialFingerprint === pending.materialFingerprint &&
567
+ status.publicationRevision === pending.predecessorRevision + 1) {
568
+ await this.acceptPublicationStatus(status);
569
+ }
570
+ else if (!publicationMatchesStatus(this.session.preKeyPublication, status) ||
571
+ status.publicationRevision !== pending.predecessorRevision) {
572
+ throw new Error("Signal Protocol Relay prekey publication state is newer than local state");
573
+ }
574
+ else
575
+ retryPending = pending;
576
+ }
577
+ else if (!publicationMatchesStatus(this.session.preKeyPublication, status)) {
578
+ throw new Error("Signal Protocol Relay prekey publication state is newer than local state");
579
+ }
580
+ const target = retryPending === undefined
581
+ ? applyPreKeyUploads(statusPreKeys(status), uploads)
582
+ : {
583
+ oneTimePreKeys: retryPending.oneTimePreKeys.map(registrationPreKey),
584
+ signedPreKeys: retryPending.signedPreKeys.map(registrationPreKey),
585
+ };
586
+ const fingerprint = await registrationMaterialFingerprint(current.identity, current.registrationId, target);
587
+ if (retryPending !== undefined) {
588
+ const repeatedFingerprint = await registrationMaterialFingerprint(current.identity, current.registrationId, applyPreKeyUploads(target, uploads));
589
+ if (repeatedFingerprint !== retryPending.materialFingerprint) {
590
+ throw new Error("A different Signal Protocol Relay prekey publication is already pending");
591
+ }
592
+ }
593
+ if (fingerprint === status.materialFingerprint) {
594
+ await this.acceptPublicationStatus(status);
595
+ return;
596
+ }
597
+ if (retryPending !== undefined &&
598
+ fingerprint !== retryPending.materialFingerprint) {
599
+ throw new Error("Stored Signal Protocol Relay prekey publication is invalid");
600
+ }
601
+ const operationId = retryPending?.operationId ?? fingerprint;
602
+ const predecessorRevision = retryPending?.predecessorRevision ?? status.publicationRevision;
603
+ this.session.pendingPreKeyPublication = {
604
+ materialFingerprint: fingerprint,
605
+ oneTimePreKeys: target.oneTimePreKeys.map(storedPreKey),
606
+ operationId,
607
+ predecessorRevision,
608
+ signedPreKeys: target.signedPreKeys.map(storedPreKey),
609
+ };
610
+ await this.persistSession();
611
+ const result = await this.authenticatedPost("/prekeys/publish", {
612
+ operationId,
613
+ predecessorRevision,
614
+ publishableKey: this.connection.publishableKey,
615
+ signalRegistration: signalRegistration(current.identity, current.registrationId, target),
616
+ });
617
+ if (!record(result) ||
618
+ result.published !== true ||
619
+ requiredNumber(result, "publicationRevision") !==
620
+ predecessorRevision + 1) {
621
+ throw new Error("Signal Protocol Relay returned an invalid prekey publication");
622
+ }
623
+ status = await this.prekeyStatus(this.session.canonicalAccountId, this.session.deviceId);
624
+ if (status.currentOperationId !== operationId ||
625
+ status.materialFingerprint !== fingerprint ||
626
+ status.publicationRevision !== result.publicationRevision ||
627
+ status.authorityGeneration !== this.session.generation) {
628
+ throw new Error("Signal Protocol Relay returned an invalid prekey publication");
629
+ }
630
+ await this.acceptPublicationStatus(status);
510
631
  });
511
- if (!record(result) || result.published !== true) {
512
- throw new Error('Managed Relay returned an invalid prekey publication');
513
- }
514
632
  }
515
633
  async pullIncoming() {
516
- const value = await this.authenticatedPost('/mailbox/pull', {
634
+ const value = await this.authenticatedPost("/mailbox/pull", {
517
635
  publishableKey: this.connection.publishableKey,
518
636
  });
519
637
  if (!record(value) || !Array.isArray(value.messages)) {
520
- throw new Error('Managed Relay returned an invalid mailbox page');
638
+ throw new Error("Signal Protocol Relay returned an invalid mailbox page");
521
639
  }
522
- return value.messages.map((candidate) => {
523
- if (!record(candidate) || !record(candidate.sender)) {
524
- throw new Error('Managed Relay returned an invalid mailbox message');
525
- }
526
- const wire = decodeDeliveryWire(decodeCanonicalBase64(candidate.envelope, 'Mailbox envelope'));
640
+ return value.messages.map((candidate) => this.incomingEnvelope(candidate));
641
+ }
642
+ /** One retained mailbox message, from a pull page or a `durable-message` frame. */
643
+ incomingEnvelope(candidate) {
644
+ if (!record(candidate) || !record(candidate.sender)) {
645
+ throw new Error("Signal Protocol Relay returned an invalid mailbox message");
646
+ }
647
+ const decoded = this.decodeMailboxEnvelope(candidate);
648
+ return {
649
+ id: requiredString(candidate, "messageId"),
650
+ ...decoded,
651
+ serverTimestamp: requiredNumber(candidate, "enqueuedAt"),
652
+ };
653
+ }
654
+ decodeMailboxEnvelope(candidate) {
655
+ if (!record(candidate.sender))
656
+ throw new Error("Signal Protocol Relay mailbox sender is invalid");
657
+ const encoded = decodeCanonicalBase64(candidate.envelope, "Mailbox envelope");
658
+ const anonymous = candidate.sender.accountId === "" && candidate.sender.deviceId === 0;
659
+ if (anonymous)
527
660
  return {
528
- id: requiredString(candidate, 'messageId'),
529
- senderUserId: requiredString(candidate.sender, 'accountId'),
530
- senderDeviceId: requiredNumber(candidate.sender, 'deviceId'),
531
- ciphertext: wire.ciphertext,
532
- timestamp: wire.timestamp,
533
- serverTimestamp: requiredNumber(candidate, 'enqueuedAt'),
534
- messageType: wire.messageType,
535
- ...(wire.contentHint === undefined ? {} : { contentHint: wire.contentHint }),
661
+ ...decodeHostedAnonymousEnvelope(encoded),
662
+ senderUserId: "",
663
+ senderDeviceId: 0,
536
664
  };
665
+ const senderDeviceId = requiredNumber(candidate.sender, "deviceId");
666
+ if (senderDeviceId < 1)
667
+ throw new Error("Signal Protocol Relay mailbox sender is invalid");
668
+ return {
669
+ ...decodeDeliveryWire(encoded),
670
+ senderUserId: requiredString(candidate.sender, "accountId"),
671
+ senderDeviceId,
672
+ };
673
+ }
674
+ async fetchSenderCertificate(deviceId) {
675
+ this.assertCurrentIdentity(this.session.canonicalAccountId, deviceId);
676
+ for (let attempt = 0; attempt < 2; attempt += 1) {
677
+ const token = await this.token(attempt > 0);
678
+ const claims = JSON.parse(new TextDecoder().decode(decodeBase64Url(token.split(".")[1], "Device token")));
679
+ if (!record(claims) ||
680
+ typeof claims.jti !== "string" ||
681
+ !claims.jti ||
682
+ claims.jti.includes("\0"))
683
+ throw new Error("Signal Protocol Relay certificate token is invalid");
684
+ const nonce = bytesToUrlSafeBase64(crypto.getRandomValues(new Uint8Array(32)));
685
+ const proof = await this.deviceAuthentication.signCertificateRequest(claims.jti, nonce);
686
+ if (proof.byteLength !== 64)
687
+ throw new Error("Signal Protocol Relay certificate proof is invalid");
688
+ try {
689
+ const result = await postJson(this.connection, "/certificates/issue", {
690
+ publishableKey: this.connection.publishableKey,
691
+ nonce,
692
+ deviceProof: bytesToBase64(proof),
693
+ }, token);
694
+ if (!record(result) ||
695
+ typeof result.senderCertificate !== "string" ||
696
+ decodeCanonicalBase64(result.senderCertificate, "Sender certificate")
697
+ .length === 0)
698
+ throw new Error("Signal Protocol Relay certificate response is invalid");
699
+ return result.senderCertificate;
700
+ }
701
+ catch (error) {
702
+ if (attempt > 0 ||
703
+ !(error instanceof HostedRelayHttpError) ||
704
+ error.code !== "TOKEN_INVALID")
705
+ throw error;
706
+ }
707
+ }
708
+ throw new Error("Signal Protocol Relay certificate request failed");
709
+ }
710
+ async setUnidentifiedAccessKey(userId, accessKey) {
711
+ this.assertCurrentIdentity(userId, this.session.deviceId);
712
+ if (accessKey.byteLength !== 16)
713
+ throw new Error("Signal Protocol Relay access key is invalid");
714
+ const value = await this.authenticatedPost("/anonymous/access-key", {
715
+ publishableKey: this.connection.publishableKey,
716
+ unidentifiedAccessKey: bytesToBase64(accessKey),
537
717
  });
718
+ if (value !== undefined)
719
+ throw new Error("Signal Protocol Relay access-key receipt is invalid");
720
+ }
721
+ async sendMultiRecipientUnidentified(sentMessageBase64, auth, timestamp, deliveryClass, recipientUserIds, clientMessageId) {
722
+ return this.anonymousDelivery.send(sentMessageBase64, auth, timestamp, deliveryClass, recipientUserIds, clientMessageId);
538
723
  }
539
724
  async acknowledge(messageIds) {
540
- const value = await this.authenticatedPost('/mailbox/acknowledge', {
725
+ const value = await this.authenticatedPost("/mailbox/acknowledge", {
541
726
  messageIds: [...messageIds],
542
727
  publishableKey: this.connection.publishableKey,
543
728
  });
544
- if (!record(value) || requiredNumber(value, 'acknowledged') < 0) {
545
- throw new Error('Managed Relay returned an invalid acknowledgment');
729
+ if (!record(value) || requiredNumber(value, "acknowledged") < 0) {
730
+ throw new Error("Signal Protocol Relay returned an invalid acknowledgment");
546
731
  }
547
732
  }
548
733
  async registerPush(registration) {
549
- const value = await this.authenticatedPost('/push/register', {
734
+ const value = await this.authenticatedPost("/push/register", {
550
735
  ...registration,
551
736
  publishableKey: this.connection.publishableKey,
552
737
  });
553
738
  if (value !== undefined) {
554
- throw new Error('Managed Relay returned an invalid push result');
739
+ throw new Error("Signal Protocol Relay returned an invalid push result");
555
740
  }
556
741
  }
557
742
  async removePush() {
558
- const value = await this.authenticatedPost('/push/remove', {
743
+ const value = await this.authenticatedPost("/push/remove", {
559
744
  publishableKey: this.connection.publishableKey,
560
745
  });
561
746
  if (value !== undefined) {
562
- throw new Error('Managed Relay returned an invalid push result');
747
+ throw new Error("Signal Protocol Relay returned an invalid push result");
563
748
  }
564
749
  }
565
750
  async pullMailbox() {
@@ -569,44 +754,53 @@ export class HostedRelayHttpTransport {
569
754
  await this.acknowledge(messageIds);
570
755
  }
571
756
  async createObjectUpload(input) {
572
- const value = await this.authenticatedPost('/objects/authorize-upload', {
757
+ if (!(input.readCapabilityDigest instanceof Uint8Array) ||
758
+ input.readCapabilityDigest.length !== 32)
759
+ throw new Error("The hosted attachment requires a read-capability commitment.");
760
+ const value = await this.authenticatedPost("/objects/authorize-upload", {
573
761
  contentLength: input.contentLength,
574
762
  digest: bytesToUrlSafeBase64(input.digest),
763
+ readCapabilityDigest: bytesToUrlSafeBase64(input.readCapabilityDigest),
575
764
  publishableKey: this.connection.publishableKey,
576
765
  requestId: input.requestId,
766
+ preparedAt: input.preparedAt,
577
767
  });
578
768
  if (!record(value) || !record(value.headers)) {
579
- throw new Error('Managed Relay returned an invalid upload grant');
769
+ throw new Error("Signal Protocol Relay returned an invalid upload grant");
580
770
  }
581
771
  return {
582
- expiresAt: requiredNumber(value, 'expiresAt'),
772
+ expiresAt: requiredNumber(value, "expiresAt"),
583
773
  headers: Object.fromEntries(Object.entries(value.headers).map(([name, header]) => {
584
- if (typeof header !== 'string')
585
- throw new Error('Managed Relay returned an invalid upload grant');
774
+ if (typeof header !== "string")
775
+ throw new Error("Signal Protocol Relay returned an invalid upload grant");
586
776
  return [name, header];
587
777
  })),
588
- objectId: requiredString(value, 'objectId'),
589
- protocol: 'put',
590
- uploadUrl: requiredString(value, 'uploadUrl'),
778
+ objectId: requiredString(value, "objectId"),
779
+ protocol: "put",
780
+ uploadUrl: requiredString(value, "uploadUrl"),
591
781
  };
592
782
  }
593
783
  async createObjectDownload(input) {
594
- const value = await this.authenticatedPost('/objects/authorize-download', {
595
- objectId: input.objectId,
596
- publishableKey: this.connection.publishableKey,
597
- });
598
- if (!record(value))
599
- throw new Error('Managed Relay returned an invalid download grant');
784
+ if (input.readCapability === undefined ||
785
+ !/^[A-Za-z0-9_-]{43}$/.test(input.readCapability))
786
+ throw new Error("The hosted attachment requires its read capability.");
787
+ const token = await this.token();
600
788
  return {
601
- downloadUrl: requiredString(value, 'downloadUrl'),
602
- expiresAt: requiredNumber(value, 'expiresAt'),
789
+ downloadUrl: `${identifiedEndpoint(this.connection)}/objects/download`,
790
+ expiresAt: tokenExpiration(token, this.session) * 1_000,
791
+ headers: {
792
+ authorization: `Bearer ${token}`,
793
+ "x-open-e2ee-publishable-key": this.connection.publishableKey,
794
+ "x-open-e2ee-object-id": input.objectId,
795
+ "x-open-e2ee-attachment-capability": input.readCapability,
796
+ },
603
797
  };
604
798
  }
605
799
  async send(envelope) {
606
800
  if (envelope.senderUserId !== this.session.canonicalAccountId ||
607
801
  envelope.senderDeviceId !== this.session.deviceId ||
608
802
  envelope.clientMessageId === '') {
609
- throw new Error('Managed Relay send authority or operation ID is invalid');
803
+ throw new Error("Signal Protocol Relay send authority or operation ID is invalid");
610
804
  }
611
805
  const messageId = envelope.clientMessageId ?? await generateUuidV4();
612
806
  const key = `${envelope.targetUserId}\0${String(envelope.targetDeviceId)}`;
@@ -616,10 +810,10 @@ export class HostedRelayHttpTransport {
616
810
  generation = this.destinationGenerations.get(key);
617
811
  }
618
812
  if (generation === undefined)
619
- throw new Error('Managed Relay destination device does not exist');
813
+ throw new Error("Signal Protocol Relay destination device does not exist");
620
814
  let value;
621
815
  try {
622
- value = await this.authenticatedPost('/delivery/send', {
816
+ value = await this.authenticatedPost("/delivery/send", {
623
817
  deliveryClass: envelope.deliveryClass,
624
818
  destination: {
625
819
  accountAddress: envelope.targetUserId,
@@ -636,54 +830,88 @@ export class HostedRelayHttpTransport {
636
830
  });
637
831
  }
638
832
  catch (error) {
639
- if (error instanceof HostedRelayHttpError && error.code === 'STALE_DEVICE') {
833
+ if (error instanceof HostedRelayHttpError &&
834
+ error.code === "STALE_DEVICE") {
640
835
  throw new HostedRelayHttpError(error.status, error.code, error.message, {
641
- code: 'STALE_DEVICE',
836
+ code: "STALE_DEVICE",
642
837
  message: error.message,
643
- reason: 'device_reinstalled',
838
+ reason: "device_reinstalled",
644
839
  staleDevices: [envelope.targetDeviceId],
645
840
  });
646
841
  }
647
842
  throw error;
648
843
  }
649
- if (!record(value) || requiredString(value, 'messageId') !== messageId) {
650
- throw new Error('Managed Relay returned an invalid delivery receipt');
844
+ if (!record(value) || requiredString(value, "messageId") !== messageId) {
845
+ throw new Error("Signal Protocol Relay returned an invalid delivery receipt");
651
846
  }
652
847
  return {
653
848
  messageId,
654
- serverTimestamp: typeof value.enqueuedAt === 'number' ? value.enqueuedAt : envelope.timestamp,
849
+ serverTimestamp: typeof value.enqueuedAt === "number"
850
+ ? value.enqueuedAt
851
+ : envelope.timestamp,
655
852
  };
656
853
  }
657
854
  subscribe(userId, deviceId, onEnvelope, options) {
658
855
  this.assertCurrentIdentity(userId, deviceId);
659
- let active = true;
660
- let timer;
661
- const poll = async () => {
662
- try {
663
- const messages = await this.pullIncoming();
664
- if (messages.length > 0)
665
- options?.onBatchStart?.();
666
- for (const message of messages)
667
- onEnvelope(message);
668
- if (messages.length > 0)
669
- options?.onBatchEnd?.();
670
- }
671
- catch {
672
- // The durable mailbox keeps the messages. Retry on the next poll.
673
- }
674
- finally {
675
- if (active)
676
- timer = setTimeout(() => void poll(), POLL_MILLISECONDS);
677
- }
678
- };
679
- void poll();
856
+ const subscription = subscribeHostedMailbox({
857
+ ...options,
858
+ authenticate: async () => {
859
+ const token = await this.token();
860
+ const url = new URL(`${identifiedEndpoint(this.connection)}/mailbox/connect`);
861
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
862
+ url.searchParams.set("publishableKey", this.connection.publishableKey);
863
+ return {
864
+ url: url.toString(),
865
+ token,
866
+ renewAt: (tokenExpiration(token, this.session) -
867
+ DEVICE_TOKEN_REFRESH_SECONDS) *
868
+ 1_000,
869
+ };
870
+ },
871
+ decodeDurable: (message) => this.incomingEnvelope(message),
872
+ pull: async () => (await this.pullIncoming()),
873
+ acknowledge: (messageIds) => this.acknowledge(messageIds),
874
+ receive: onEnvelope,
875
+ receiveEphemeral: async (candidate, current) => {
876
+ if (!record(candidate) || !record(candidate.sender))
877
+ throw new Error("Invalid ephemeral mailbox message.");
878
+ const wire = this.decodeMailboxEnvelope(candidate);
879
+ const messageId = requiredString(candidate, "messageId");
880
+ const envelope = {
881
+ ...wire,
882
+ id: messageId,
883
+ deliveryClass: "ephemeral",
884
+ targetUserId: this.session.canonicalAccountId,
885
+ targetDeviceId: this.session.deviceId,
886
+ };
887
+ if (!current())
888
+ return messageId;
889
+ this.ephemeralAcknowledgments.add(messageId);
890
+ try {
891
+ await onEnvelope(envelope);
892
+ }
893
+ finally {
894
+ this.ephemeralAcknowledgments.delete(messageId);
895
+ }
896
+ return messageId;
897
+ },
898
+ });
899
+ this.subscription = subscription;
680
900
  return () => {
681
- active = false;
682
- if (timer !== undefined)
683
- clearTimeout(timer);
901
+ if (this.subscription === subscription)
902
+ this.subscription = undefined;
903
+ subscription.unsubscribe();
684
904
  };
685
905
  }
906
+ /**
907
+ * Acknowledges over the live mailbox socket when one exists, in one frame per
908
+ * drained burst, and over HTTP otherwise.
909
+ */
686
910
  async markDelivered(envelopeId) {
911
+ if (this.ephemeralAcknowledgments.has(envelopeId))
912
+ return;
913
+ if (this.subscription?.acknowledge(envelopeId) === true)
914
+ return;
687
915
  await this.acknowledge([envelopeId]);
688
916
  }
689
917
  async getDevices(userId) {
@@ -705,29 +933,30 @@ export class HostedRelayHttpTransport {
705
933
  const status = await this.prekeyStatus(request.userId, request.deviceId, request.identityType);
706
934
  if (status.registrationId !== request.registrationId ||
707
935
  !equalBytes(status.identityPublicMaterial, encodeCompositeIdentityV1(request.identity))) {
708
- throw new Error('Managed Relay canonical Signal identity does not match local state');
936
+ throw new Error("Signal Protocol Relay canonical Signal identity does not match local state");
709
937
  }
710
938
  }
711
- async getIdentityKey(userId, identityType = 'aci') {
939
+ async getIdentityKey(userId, identityType = "aci") {
712
940
  try {
713
- return decodeCompositeIdentityV1((await this.prekeyStatus(userId, 1, identityType)).identityPublicMaterial);
941
+ return decodeCompositeIdentityV1((await this.prekeyStatus(userId, 1, identityType))
942
+ .identityPublicMaterial);
714
943
  }
715
944
  catch (error) {
716
- if (error instanceof HostedRelayHttpError && error.code === 'NOT_FOUND')
945
+ if (error instanceof HostedRelayHttpError && error.code === "NOT_FOUND")
717
946
  return null;
718
947
  throw error;
719
948
  }
720
949
  }
721
- async uploadPreKeys(userId, deviceId, _keys, identityType = 'aci') {
950
+ async uploadPreKeys(userId, deviceId, keys, identityType = "aci") {
722
951
  this.assertCurrentIdentity(userId, deviceId, identityType);
723
- await this.publishCurrentPrekeys();
952
+ await this.publishCurrentPrekeys(keys);
724
953
  }
725
- async fetchPreKeyBundle(userId, deviceId, _fetcherUserId, identityType = 'aci') {
726
- if (identityType !== 'aci')
727
- unsupported('PNI prekey authority');
954
+ async fetchPreKeyBundle(userId, deviceId, _fetcherUserId, identityType = "aci") {
955
+ if (identityType !== "aci")
956
+ unsupported("PNI prekey authority");
728
957
  let value;
729
958
  try {
730
- value = await this.authenticatedPost('/prekeys/consume', {
959
+ value = await this.authenticatedPost("/prekeys/consume", {
731
960
  accountAddress: userId,
732
961
  deviceId,
733
962
  identityType,
@@ -735,52 +964,57 @@ export class HostedRelayHttpTransport {
735
964
  });
736
965
  }
737
966
  catch (error) {
738
- if (error instanceof HostedRelayHttpError && error.code === 'NOT_FOUND')
967
+ if (error instanceof HostedRelayHttpError && error.code === "NOT_FOUND")
739
968
  return null;
740
969
  throw error;
741
970
  }
742
- if (!record(value) || !Array.isArray(value.signedPreKeys) || !Array.isArray(value.oneTimePreKeys)) {
743
- throw new Error('Managed Relay returned an invalid prekey bundle');
971
+ if (!record(value) ||
972
+ !Array.isArray(value.signedPreKeys) ||
973
+ !Array.isArray(value.oneTimePreKeys)) {
974
+ throw new Error("Signal Protocol Relay returned an invalid prekey bundle");
744
975
  }
745
976
  const signed = value.signedPreKeys.map((candidate) => {
746
977
  if (!record(candidate))
747
- throw new Error('Managed Relay returned an invalid prekey bundle');
978
+ throw new Error("Signal Protocol Relay returned an invalid prekey bundle");
748
979
  return {
749
- algorithm: requiredString(candidate, 'algorithm'),
750
- keyId: requiredNumber(candidate, 'keyId'),
751
- publicKey: requiredString(candidate, 'publicKey'),
752
- signature: requiredString(candidate, 'signature'),
980
+ algorithm: requiredString(candidate, "algorithm"),
981
+ keyId: requiredNumber(candidate, "keyId"),
982
+ publicKey: requiredString(candidate, "publicKey"),
983
+ signature: requiredString(candidate, "signature"),
753
984
  };
754
985
  });
755
986
  const oneTime = value.oneTimePreKeys.map((candidate) => {
756
987
  if (!record(candidate))
757
- throw new Error('Managed Relay returned an invalid prekey bundle');
988
+ throw new Error("Signal Protocol Relay returned an invalid prekey bundle");
758
989
  return {
759
- algorithm: requiredString(candidate, 'algorithm'),
760
- keyId: requiredNumber(candidate, 'keyId'),
761
- publicKey: requiredString(candidate, 'publicKey'),
990
+ algorithm: requiredString(candidate, "algorithm"),
991
+ keyId: requiredNumber(candidate, "keyId"),
992
+ publicKey: requiredString(candidate, "publicKey"),
762
993
  ...(candidate.signature === undefined
763
994
  ? {}
764
- : { signature: requiredString(candidate, 'signature') }),
995
+ : { signature: requiredString(candidate, "signature") }),
765
996
  };
766
997
  });
767
- const ecSigned = signed.find((key) => key.algorithm === 'ec-x25519');
768
- const kemSigned = signed.find((key) => key.algorithm === 'kem-ml-kem-1024');
998
+ const ecSigned = signed.find((key) => key.algorithm === "ec-x25519");
999
+ const kemSigned = signed.find((key) => key.algorithm === "kem-ml-kem-1024");
769
1000
  if (!ecSigned || !kemSigned)
770
- throw new Error('Managed Relay returned an invalid prekey bundle');
771
- const ecOneTime = oneTime.find((key) => key.algorithm === 'ec-x25519');
772
- const kemOneTime = oneTime.find((key) => key.algorithm === 'kem-ml-kem-1024');
1001
+ throw new Error("Signal Protocol Relay returned an invalid prekey bundle");
1002
+ const ecOneTime = oneTime.find((key) => key.algorithm === "ec-x25519");
1003
+ const kemOneTime = oneTime.find((key) => key.algorithm === "kem-ml-kem-1024");
773
1004
  return {
774
1005
  deviceId,
775
- registrationId: requiredNumber(value, 'registrationId'),
776
- identity: decodeCompositeIdentityV1(decodeCanonicalBase64(value.identityPublicMaterial, 'Signal identity')),
1006
+ registrationId: requiredNumber(value, "registrationId"),
1007
+ identity: decodeCompositeIdentityV1(decodeCanonicalBase64(value.identityPublicMaterial, "Signal identity")),
777
1008
  ecSignedPreKey: {
778
1009
  keyId: ecSigned.keyId,
779
1010
  publicKey: ecSigned.publicKey,
780
1011
  signature: ecSigned.signature,
781
1012
  },
782
1013
  ecOneTimePreKey: ecOneTime
783
- ? { keyId: ecOneTime.keyId, publicKey: ecOneTime.publicKey }
1014
+ ? {
1015
+ keyId: ecOneTime.keyId,
1016
+ publicKey: ecOneTime.publicKey,
1017
+ }
784
1018
  : null,
785
1019
  kemLastResortPreKey: {
786
1020
  keyId: kemSigned.keyId,
@@ -796,79 +1030,165 @@ export class HostedRelayHttpTransport {
796
1030
  : null,
797
1031
  };
798
1032
  }
799
- async getPreKeyCount(userId, deviceId, type, identityType = 'aci') {
1033
+ async getPreKeyInventory(userId, deviceId, identityType = "aci") {
800
1034
  const status = await this.prekeyStatus(userId, deviceId, identityType);
801
- return status.oneTimePreKeyCounts[type === 'ec' ? 'ec-x25519' : 'kem-ml-kem-1024'] ?? 0;
1035
+ const metadata = (algorithm) => {
1036
+ const key = status.signedPreKeys.find((candidate) => candidate.algorithm === algorithm);
1037
+ return key
1038
+ ? {
1039
+ keyId: key.keyId,
1040
+ createdAt: key.acceptedAtMilliseconds,
1041
+ expiresAt: key.acceptedAtMilliseconds + PREKEY_EXPIRY_MILLISECONDS,
1042
+ publicKey: bytesToBase64(key.publicKey),
1043
+ }
1044
+ : null;
1045
+ };
1046
+ return {
1047
+ ecSignedPreKey: metadata("ec-x25519"),
1048
+ kemLastResortPreKey: metadata("kem-ml-kem-1024"),
1049
+ ecOneTimePreKeyCount: status.oneTimePreKeyCounts["ec-x25519"] ?? 0,
1050
+ kemOneTimePreKeyCount: status.oneTimePreKeyCounts["kem-ml-kem-1024"] ?? 0,
1051
+ };
802
1052
  }
803
- async getEcSignedPreKeyMetadata(userId, deviceId, identityType = 'aci') {
804
- const key = (await this.prekeyStatus(userId, deviceId, identityType)).signedPreKeys.find((candidate) => candidate.algorithm === 'ec-x25519');
805
- return key
806
- ? {
807
- keyId: key.keyId,
808
- createdAt: key.acceptedAtMilliseconds,
809
- expiresAt: key.acceptedAtMilliseconds + PREKEY_EXPIRY_MILLISECONDS,
810
- publicKey: bytesToBase64(key.publicKey),
811
- }
812
- : null;
1053
+ async getPreKeyCount(userId, deviceId, type, identityType = "aci") {
1054
+ const status = await this.prekeyStatus(userId, deviceId, identityType);
1055
+ return (status.oneTimePreKeyCounts[type === "ec" ? "ec-x25519" : "kem-ml-kem-1024"] ?? 0);
813
1056
  }
814
- async getKemLastResortPreKeyMetadata(userId, deviceId, identityType = 'aci') {
815
- const key = (await this.prekeyStatus(userId, deviceId, identityType)).signedPreKeys.find((candidate) => candidate.algorithm === 'kem-ml-kem-1024');
816
- return key
817
- ? {
818
- keyId: key.keyId,
819
- createdAt: key.acceptedAtMilliseconds,
820
- expiresAt: key.acceptedAtMilliseconds + PREKEY_EXPIRY_MILLISECONDS,
821
- publicKey: bytesToBase64(key.publicKey),
822
- }
823
- : null;
1057
+ async getEcSignedPreKeyMetadata(userId, deviceId, identityType = "aci") {
1058
+ return (await this.getPreKeyInventory(userId, deviceId, identityType))
1059
+ .ecSignedPreKey;
824
1060
  }
825
- async clearStaleKemPreKeys(userId, deviceId, identityType = 'aci') {
1061
+ async getKemLastResortPreKeyMetadata(userId, deviceId, identityType = "aci") {
1062
+ return (await this.getPreKeyInventory(userId, deviceId, identityType))
1063
+ .kemLastResortPreKey;
1064
+ }
1065
+ async clearStaleKemPreKeys(userId, deviceId, identityType = "aci") {
826
1066
  this.assertCurrentIdentity(userId, deviceId, identityType);
827
- const value = await this.authenticatedPost('/prekeys/clear-stale-kem', {
1067
+ const value = await this.authenticatedPost("/prekeys/clear-stale-kem", {
828
1068
  publishableKey: this.connection.publishableKey,
829
1069
  });
830
1070
  if (!record(value))
831
- throw new Error('Managed Relay returned an invalid prekey result');
832
- return { cleared: requiredNumber(value, 'cleared') };
1071
+ throw new Error("Signal Protocol Relay returned an invalid prekey result");
1072
+ return { cleared: requiredNumber(value, "cleared") };
833
1073
  }
834
- async uploadEcSignedPreKey(userId, _key, identityType = 'aci') {
1074
+ async uploadEcSignedPreKey(userId, key, identityType = "aci") {
835
1075
  this.assertCurrentIdentity(userId, this.session.deviceId, identityType);
836
- await this.publishCurrentPrekeys();
1076
+ await this.publishCurrentPrekeys([
1077
+ {
1078
+ keyId: key.keyId,
1079
+ publicKey: key.publicKey,
1080
+ signature: key.signature,
1081
+ type: "ecSignedPreKey",
1082
+ },
1083
+ ]);
837
1084
  }
838
- async uploadKemLastResortPreKey(userId, _key, identityType = 'aci') {
1085
+ async uploadKemLastResortPreKey(userId, key, identityType = "aci") {
839
1086
  this.assertCurrentIdentity(userId, this.session.deviceId, identityType);
840
- await this.publishCurrentPrekeys();
1087
+ await this.publishCurrentPrekeys([
1088
+ {
1089
+ keyId: key.keyId,
1090
+ publicKey: key.publicKey,
1091
+ signature: key.signature,
1092
+ type: "kemLastResortPreKey",
1093
+ },
1094
+ ]);
841
1095
  }
842
1096
  async rotateIdentityKey(_request) {
843
- unsupported('identity rotation outside the hosted recovery flow');
1097
+ unsupported("identity rotation outside the hosted recovery flow");
844
1098
  }
845
1099
  async registerDevice(_userId, _device) {
846
- unsupported('direct device registration');
847
- }
848
- async removeDevice(_userId, _deviceId) { unsupported('direct device removal'); }
849
- async markDeviceConnected(_deviceId) { unsupported('connection presence'); }
850
- async markDeviceDisconnected(_deviceId) { unsupported('connection presence'); }
851
- async heartbeat(_deviceId) { unsupported('connection presence'); }
852
- async createProvisioningSession(_userId, _key) { unsupported('legacy provisioning sessions'); }
853
- async connectNewDevice(_sessionId, _key, _metadata) { unsupported('legacy provisioning sessions'); }
854
- async sendProvisioningMessage(_sessionId, _message, _userId) { unsupported('legacy provisioning sessions'); }
855
- async getProvisioningMessage(_sessionId) { unsupported('legacy provisioning sessions'); }
856
- async completeProvisioning(_sessionId, _metadata) { unsupported('legacy provisioning sessions'); }
857
- async acknowledgeProvisioning(_sessionId) { unsupported('legacy provisioning sessions'); }
858
- async rollbackProvisioning(_sessionId) { unsupported('legacy provisioning sessions'); }
859
- async deleteProvisioningSession(_sessionId, _userId) { unsupported('legacy provisioning sessions'); }
860
- async createGroupState(_groupId, _state, _authorization) { unsupported('hosted group-state transport'); }
861
- async getGroupState(_groupId, _authorization, _version) { unsupported('hosted group-state transport'); }
862
- async getGroupJoinInfo(_groupId, _password, _authorization) { unsupported('hosted group-state transport'); }
863
- async getGroupChanges(_groupId, _fromVersion, _authorization) { unsupported('hosted group-state transport'); }
864
- async submitGroupChange(_groupId, _expectedVersion, _actions, _password, _authorization) { unsupported('hosted group-state transport'); }
865
- async issueAuthCredential(_userId) { unsupported('hosted group credentials'); }
1100
+ unsupported("direct device registration");
1101
+ }
1102
+ async removeDevice(_userId, _deviceId) {
1103
+ unsupported("direct device removal");
1104
+ }
1105
+ async markDeviceConnected(_deviceId) {
1106
+ unsupported("connection presence");
1107
+ }
1108
+ async markDeviceDisconnected(_deviceId) {
1109
+ unsupported("connection presence");
1110
+ }
1111
+ async heartbeat(_deviceId) {
1112
+ unsupported("connection presence");
1113
+ }
1114
+ async createProvisioningSession(_userId, _key) {
1115
+ unsupported("legacy provisioning sessions");
1116
+ }
1117
+ async connectNewDevice(_sessionId, _key, _metadata) {
1118
+ unsupported("legacy provisioning sessions");
1119
+ }
1120
+ async sendProvisioningMessage(_sessionId, _message, _userId) {
1121
+ unsupported("legacy provisioning sessions");
1122
+ }
1123
+ async getProvisioningMessage(_sessionId) {
1124
+ unsupported("legacy provisioning sessions");
1125
+ }
1126
+ async completeProvisioning(_sessionId, _metadata) {
1127
+ unsupported("legacy provisioning sessions");
1128
+ }
1129
+ async acknowledgeProvisioning(_sessionId) {
1130
+ unsupported("legacy provisioning sessions");
1131
+ }
1132
+ async rollbackProvisioning(_sessionId) {
1133
+ unsupported("legacy provisioning sessions");
1134
+ }
1135
+ async deleteProvisioningSession(_sessionId, _userId) {
1136
+ unsupported("legacy provisioning sessions");
1137
+ }
1138
+ async createGroupState(groupId, state, authorization) {
1139
+ return this.groups.createGroup(groupId, state, authorization);
1140
+ }
1141
+ async getGroupState(groupId, authorization, version) {
1142
+ return this.groups.getGroup(groupId, authorization, version);
1143
+ }
1144
+ async getGroupJoinInfo(groupId, password, authorization) {
1145
+ return this.groups.getGroupJoinInfo(groupId, password, authorization);
1146
+ }
1147
+ async getGroupChanges(groupId, fromVersion, authorization) {
1148
+ return this.groups.getGroupChanges(groupId, fromVersion, authorization);
1149
+ }
1150
+ async submitGroupChange(groupId, expectedVersion, actions, password, authorization) {
1151
+ if (arguments.length !== 5)
1152
+ throw new Error("INVALID_REQUEST: Group change submission must not carry an epoch");
1153
+ return this.groups.submitGroupChange(groupId, expectedVersion, actions, password, authorization);
1154
+ }
1155
+ async issueAuthCredential(userId, authorityKeyId) {
1156
+ this.assertCurrentIdentity(userId, this.session.deviceId);
1157
+ return this.groupCredential("auth", { authorityKeyId });
1158
+ }
1159
+ async refreshGroupSendEndorsements(groupId, authorization) {
1160
+ return this.groups.refreshGroupSendEndorsements(groupId, authorization);
1161
+ }
1162
+ async issueProfileKeyCredential(userId, request, authorityKeyId) {
1163
+ this.assertCurrentIdentity(userId, this.session.deviceId);
1164
+ if (request.byteLength !== 160)
1165
+ throw new Error("Invalid blinded profile credential request");
1166
+ return this.groupCredential("profile-key", { authorityKeyId, blindedRequest: bytesToBase64(request) });
1167
+ }
1168
+ async groupCredential(kind, request) {
1169
+ if (typeof request.authorityKeyId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(request.authorityKeyId))
1170
+ throw new Error("Managed group credentials require a verified authority selection");
1171
+ const value = await this.authenticatedPost(`/groups/credentials/${kind}`, {
1172
+ publishableKey: this.connection.publishableKey, ...request,
1173
+ });
1174
+ if (!record(value) || Object.keys(value).length !== 1 || typeof value.credential !== "string")
1175
+ throw new Error("Relay returned an invalid group credential");
1176
+ try {
1177
+ const credential = base64ToBytes(value.credential);
1178
+ if (credential.byteLength < 1 || credential.byteLength > 2048 || bytesToBase64(credential) !== value.credential)
1179
+ throw new Error("Invalid credential encoding");
1180
+ return credential;
1181
+ }
1182
+ catch {
1183
+ throw new Error("Relay returned an invalid group credential");
1184
+ }
1185
+ }
866
1186
  }
867
1187
  export async function bootstrapHostedRelayTransport(request) {
868
1188
  const proof = await request.deviceAuthentication.signChallenge(await registrationChallenge(request));
869
- const value = await postJson(request.connection, request.assertionPurpose === 'recover'
870
- ? '/identity/recover'
871
- : '/identity/register', {
1189
+ const value = await postJson(request.connection, request.assertionPurpose === "recover"
1190
+ ? "/identity/recover"
1191
+ : "/identity/register", {
872
1192
  assertion: request.assertion,
873
1193
  assertionPurpose: request.assertionPurpose,
874
1194
  deviceAuthenticationPublicKey: bytesToBase64(request.deviceAuthentication.publicKey),
@@ -878,23 +1198,28 @@ export async function bootstrapHostedRelayTransport(request) {
878
1198
  signalRegistration: signalRegistration(request.signalIdentity, request.registrationId, request.registrationPreKeys),
879
1199
  });
880
1200
  if (!record(value))
881
- throw new Error('Managed Relay returned an invalid registration');
1201
+ throw new Error("Signal Protocol Relay returned an invalid registration");
1202
+ const materialFingerprint = await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys);
1203
+ const generation = requiredNumber(value, request.assertionPurpose === "recover"
1204
+ ? "deviceAuthorizationGeneration"
1205
+ : "generation");
882
1206
  const session = {
883
- canonicalAccountId: requiredString(value, 'canonicalAccountId'),
884
- deviceId: requiredNumber(value, 'deviceId'),
885
- deviceToken: requiredString(value, 'deviceToken'),
886
- generation: requiredNumber(value, request.assertionPurpose === 'recover'
887
- ? 'deviceAuthorizationGeneration'
888
- : 'generation'),
889
- mailboxGeneration: requiredNumber(value, 'mailboxGeneration'),
890
- relayScopeId: requiredString(value, 'relayScopeId'),
1207
+ canonicalAccountId: requiredString(value, "canonicalAccountId"),
1208
+ deviceId: requiredNumber(value, "deviceId"),
1209
+ deviceToken: requiredString(value, "deviceToken"),
1210
+ generation,
1211
+ mailboxGeneration: requiredNumber(value, "mailboxGeneration"),
1212
+ pendingPreKeyPublication: null,
1213
+ preKeyPublication: storedPublication(generation, materialFingerprint, request.operationId, 0, request.registrationPreKeys),
1214
+ relayScopeId: requiredString(value, "relayScopeId"),
891
1215
  };
892
1216
  if (session.relayScopeId !== relayScopeId(request.connection) ||
893
1217
  session.deviceId < 1 ||
894
1218
  session.generation < 0 ||
895
1219
  session.mailboxGeneration < 0 ||
896
- tokenExpiration(session.deviceToken, session) <= Math.floor(Date.now() / 1_000)) {
897
- throw new Error('Managed Relay returned an invalid registration');
1220
+ tokenExpiration(session.deviceToken, session) <=
1221
+ Math.floor(Date.now() / 1_000)) {
1222
+ throw new Error("Signal Protocol Relay returned an invalid registration");
898
1223
  }
899
1224
  await request.storage.setMetadata(await sessionMetadataKey(request.connection), JSON.stringify(session));
900
1225
  const transport = new HostedRelayHttpTransport(request.connection, request.storage, request.deviceAuthentication, session);