@open-e2ee/signal-protocol-sdk 8.1.0 → 9.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 (387) hide show
  1. package/ADAPTERS.md +13 -31
  2. package/ARCHITECTURE.md +5 -7
  3. package/CHANGELOG.md +258 -0
  4. package/README.md +36 -48
  5. package/SECURITY.md +2 -2
  6. package/client/README.md +9 -0
  7. package/device/README.md +16 -7
  8. package/dist/client/client.d.ts +25 -16
  9. package/dist/client/client.d.ts.map +1 -1
  10. package/dist/client/client.js +115 -95
  11. package/dist/client/client.js.map +1 -1
  12. package/dist/client/config.d.ts +10 -17
  13. package/dist/client/config.d.ts.map +1 -1
  14. package/dist/client/config.js.map +1 -1
  15. package/dist/client/event-hooks.js +27 -0
  16. package/dist/client/event-hooks.js.map +1 -1
  17. package/dist/client/group-outbox.d.ts +31 -1
  18. package/dist/client/group-outbox.d.ts.map +1 -1
  19. package/dist/client/group-outbox.js +67 -58
  20. package/dist/client/group-outbox.js.map +1 -1
  21. package/dist/client/group-receive-authorization.d.ts +5 -0
  22. package/dist/client/group-receive-authorization.d.ts.map +1 -0
  23. package/dist/client/group-receive-authorization.js +32 -0
  24. package/dist/client/group-receive-authorization.js.map +1 -0
  25. package/dist/client/group-sender-key-operations.d.ts +15 -0
  26. package/dist/client/group-sender-key-operations.d.ts.map +1 -0
  27. package/dist/client/group-sender-key-operations.js +31 -0
  28. package/dist/client/group-sender-key-operations.js.map +1 -0
  29. package/dist/client/groups.d.ts +3 -1
  30. package/dist/client/groups.d.ts.map +1 -1
  31. package/dist/client/groups.js +5 -2
  32. package/dist/client/groups.js.map +1 -1
  33. package/dist/client/hosted-anonymous-delivery.d.ts +9 -1
  34. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  35. package/dist/client/hosted-anonymous-delivery.js +61 -22
  36. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  37. package/dist/client/hosted-transport.d.ts +7 -0
  38. package/dist/client/hosted-transport.d.ts.map +1 -1
  39. package/dist/client/hosted-transport.js +44 -6
  40. package/dist/client/hosted-transport.js.map +1 -1
  41. package/dist/client/key-rotation.d.ts.map +1 -1
  42. package/dist/client/key-rotation.js +2 -4
  43. package/dist/client/key-rotation.js.map +1 -1
  44. package/dist/client/prekeys.d.ts.map +1 -1
  45. package/dist/client/prekeys.js +1 -1
  46. package/dist/client/prekeys.js.map +1 -1
  47. package/dist/client/relay-device-refusal.d.ts +32 -0
  48. package/dist/client/relay-device-refusal.d.ts.map +1 -0
  49. package/dist/client/relay-device-refusal.js +36 -0
  50. package/dist/client/relay-device-refusal.js.map +1 -0
  51. package/dist/client/relay-subscription.d.ts +2 -0
  52. package/dist/client/relay-subscription.d.ts.map +1 -1
  53. package/dist/client/relay-subscription.js +3 -1
  54. package/dist/client/relay-subscription.js.map +1 -1
  55. package/dist/client/relay-work.d.ts +26 -0
  56. package/dist/client/relay-work.d.ts.map +1 -1
  57. package/dist/client/relay-work.js +37 -0
  58. package/dist/client/relay-work.js.map +1 -1
  59. package/dist/client/sealed-sender.d.ts.map +1 -1
  60. package/dist/client/sealed-sender.js +12 -17
  61. package/dist/client/sealed-sender.js.map +1 -1
  62. package/dist/client/sender-key-distribution.d.ts.map +1 -1
  63. package/dist/client/sender-key-distribution.js +4 -1
  64. package/dist/client/sender-key-distribution.js.map +1 -1
  65. package/dist/client/sessions.d.ts.map +1 -1
  66. package/dist/client/sessions.js +2 -4
  67. package/dist/client/sessions.js.map +1 -1
  68. package/dist/client/signal-service-cipher.d.ts +94 -6
  69. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  70. package/dist/client/signal-service-cipher.js +483 -184
  71. package/dist/client/signal-service-cipher.js.map +1 -1
  72. package/dist/client/types.d.ts +7 -0
  73. package/dist/client/types.d.ts.map +1 -1
  74. package/dist/client/types.js.map +1 -1
  75. package/dist/index.d.ts +27 -21
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +8 -17
  78. package/dist/index.js.map +1 -1
  79. package/dist/internal/crypto/pq/kyber.d.ts +1 -1
  80. package/dist/internal/crypto/pq/kyber.js +1 -1
  81. package/dist/internal/encoding/proto/sender-key-message.d.ts +2 -2
  82. package/dist/internal/encoding/proto/sender-key-message.d.ts.map +1 -1
  83. package/dist/internal/encoding/proto/sender-key-message.js +5 -2
  84. package/dist/internal/encoding/proto/sender-key-message.js.map +1 -1
  85. package/dist/internal/groups/manager.d.ts.map +1 -1
  86. package/dist/internal/groups/manager.js +5 -2
  87. package/dist/internal/groups/manager.js.map +1 -1
  88. package/dist/internal/groups/wire.d.ts +0 -2
  89. package/dist/internal/groups/wire.d.ts.map +1 -1
  90. package/dist/internal/groups/wire.js +0 -6
  91. package/dist/internal/groups/wire.js.map +1 -1
  92. package/dist/internal/manager/manager.d.ts +8 -7
  93. package/dist/internal/manager/manager.d.ts.map +1 -1
  94. package/dist/internal/manager/manager.js +34 -37
  95. package/dist/internal/manager/manager.js.map +1 -1
  96. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +0 -17
  97. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  98. package/dist/internal/protocol/double-ratchet/ratchet.js +0 -4
  99. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  100. package/dist/internal/protocol/sealed-sender/certificate.d.ts +2 -32
  101. package/dist/internal/protocol/sealed-sender/certificate.d.ts.map +1 -1
  102. package/dist/internal/protocol/sealed-sender/certificate.js +4 -85
  103. package/dist/internal/protocol/sealed-sender/certificate.js.map +1 -1
  104. package/dist/internal/protocol/sealed-sender/index.d.ts +2 -2
  105. package/dist/internal/protocol/sealed-sender/index.d.ts.map +1 -1
  106. package/dist/internal/protocol/sealed-sender/index.js +2 -6
  107. package/dist/internal/protocol/sealed-sender/index.js.map +1 -1
  108. package/dist/internal/protocol/sealed-sender/proto/index.d.ts +0 -19
  109. package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
  110. package/dist/internal/protocol/sealed-sender/proto/index.js +1 -48
  111. package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
  112. package/dist/internal/protocol/sender-keys/manager.d.ts +9 -13
  113. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  114. package/dist/internal/protocol/sender-keys/manager.js +90 -95
  115. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  116. package/dist/internal/protocol/spqr/index.d.ts +1 -1
  117. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  118. package/dist/internal/protocol/spqr/index.js +2 -2
  119. package/dist/internal/protocol/spqr/index.js.map +1 -1
  120. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts +0 -2
  121. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts.map +1 -1
  122. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.js +4 -12
  123. package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.js.map +1 -1
  124. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.d.ts.map +1 -1
  125. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js +1 -3
  126. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js.map +1 -1
  127. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts +1 -0
  128. package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts.map +1 -1
  129. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  130. package/dist/internal/protocol/spqr/serialize.js +1 -4
  131. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  132. package/dist/internal/protocol/spqr/spqr.d.ts +1 -1
  133. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  134. package/dist/internal/protocol/spqr/spqr.js +2 -3
  135. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  136. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +1 -1
  137. package/dist/internal/protocol/x3dh/x3dh.js +1 -1
  138. package/dist/internal/protocol/x3dh/x3dh.js.map +1 -1
  139. package/dist/internal/protocol/zk/credentials/credentials.d.ts +3 -54
  140. package/dist/internal/protocol/zk/credentials/credentials.d.ts.map +1 -1
  141. package/dist/internal/protocol/zk/credentials/credentials.js +4 -91
  142. package/dist/internal/protocol/zk/credentials/credentials.js.map +1 -1
  143. package/dist/internal/protocol/zk/credentials/endorsements.d.ts +3 -64
  144. package/dist/internal/protocol/zk/credentials/endorsements.d.ts.map +1 -1
  145. package/dist/internal/protocol/zk/credentials/endorsements.js +4 -134
  146. package/dist/internal/protocol/zk/credentials/endorsements.js.map +1 -1
  147. package/dist/internal/protocol/zk/credentials/index.d.ts +3 -3
  148. package/dist/internal/protocol/zk/credentials/index.d.ts.map +1 -1
  149. package/dist/internal/protocol/zk/credentials/index.js +3 -3
  150. package/dist/internal/protocol/zk/credentials/index.js.map +1 -1
  151. package/dist/internal/protocol/zk/credentials/issuance.d.ts +3 -26
  152. package/dist/internal/protocol/zk/credentials/issuance.d.ts.map +1 -1
  153. package/dist/internal/protocol/zk/credentials/issuance.js +3 -80
  154. package/dist/internal/protocol/zk/credentials/issuance.js.map +1 -1
  155. package/dist/internal/protocol/zk/credentials/presentation.d.ts +4 -73
  156. package/dist/internal/protocol/zk/credentials/presentation.d.ts.map +1 -1
  157. package/dist/internal/protocol/zk/credentials/presentation.js +4 -152
  158. package/dist/internal/protocol/zk/credentials/presentation.js.map +1 -1
  159. package/dist/internal/protocol/zk/groups/auth-credential.d.ts +1 -61
  160. package/dist/internal/protocol/zk/groups/auth-credential.d.ts.map +1 -1
  161. package/dist/internal/protocol/zk/groups/auth-credential.js +2 -196
  162. package/dist/internal/protocol/zk/groups/auth-credential.js.map +1 -1
  163. package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts +1 -86
  164. package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts.map +1 -1
  165. package/dist/internal/protocol/zk/groups/group-send-endorsement.js +1 -152
  166. package/dist/internal/protocol/zk/groups/group-send-endorsement.js.map +1 -1
  167. package/dist/internal/protocol/zk/groups/index.d.ts +4 -4
  168. package/dist/internal/protocol/zk/groups/index.d.ts.map +1 -1
  169. package/dist/internal/protocol/zk/groups/index.js +4 -4
  170. package/dist/internal/protocol/zk/groups/index.js.map +1 -1
  171. package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts +2 -57
  172. package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts.map +1 -1
  173. package/dist/internal/protocol/zk/groups/profile-key-credential.js +2 -174
  174. package/dist/internal/protocol/zk/groups/profile-key-credential.js.map +1 -1
  175. package/dist/internal/protocol/zk/groups/server-params.d.ts +8 -72
  176. package/dist/internal/protocol/zk/groups/server-params.d.ts.map +1 -1
  177. package/dist/internal/protocol/zk/groups/server-params.js +8 -108
  178. package/dist/internal/protocol/zk/groups/server-params.js.map +1 -1
  179. package/dist/internal/protocol/zk/proofs/sign.d.ts +1 -2
  180. package/dist/internal/protocol/zk/proofs/sign.d.ts.map +1 -1
  181. package/dist/internal/protocol/zk/proofs/sign.js +2 -11
  182. package/dist/internal/protocol/zk/proofs/sign.js.map +1 -1
  183. package/dist/internal/sesame/device-registry.d.ts +24 -4
  184. package/dist/internal/sesame/device-registry.d.ts.map +1 -1
  185. package/dist/internal/sesame/device-registry.js +55 -28
  186. package/dist/internal/sesame/device-registry.js.map +1 -1
  187. package/dist/internal/sesame/manager.d.ts +79 -11
  188. package/dist/internal/sesame/manager.d.ts.map +1 -1
  189. package/dist/internal/sesame/manager.js +381 -280
  190. package/dist/internal/sesame/manager.js.map +1 -1
  191. package/dist/internal/session/cipher.d.ts +0 -5
  192. package/dist/internal/session/cipher.d.ts.map +1 -1
  193. package/dist/internal/session/cipher.js +3 -9
  194. package/dist/internal/session/cipher.js.map +1 -1
  195. package/dist/internal/session/ratchet.d.ts.map +1 -1
  196. package/dist/internal/session/ratchet.js +0 -2
  197. package/dist/internal/session/ratchet.js.map +1 -1
  198. package/dist/internal/session/record-locks.d.ts +46 -0
  199. package/dist/internal/session/record-locks.d.ts.map +1 -0
  200. package/dist/internal/session/record-locks.js +72 -0
  201. package/dist/internal/session/record-locks.js.map +1 -0
  202. package/dist/local/store/expo/adapter.d.ts +8 -2
  203. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  204. package/dist/local/store/expo/adapter.js +24 -3
  205. package/dist/local/store/expo/adapter.js.map +1 -1
  206. package/dist/local/store/expo/driver.d.ts +7 -0
  207. package/dist/local/store/expo/driver.d.ts.map +1 -1
  208. package/dist/local/store/expo/driver.js +16 -0
  209. package/dist/local/store/expo/driver.js.map +1 -1
  210. package/dist/local/store/key-value/adapter.d.ts +3 -3
  211. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  212. package/dist/local/store/key-value/adapter.js +91 -53
  213. package/dist/local/store/key-value/adapter.js.map +1 -1
  214. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
  215. package/dist/local/store/key-value/backend-conformance.js +25 -0
  216. package/dist/local/store/key-value/backend-conformance.js.map +1 -1
  217. package/dist/local/store/key-value/batch.d.ts +3 -1
  218. package/dist/local/store/key-value/batch.d.ts.map +1 -1
  219. package/dist/local/store/key-value/batch.js +9 -1
  220. package/dist/local/store/key-value/batch.js.map +1 -1
  221. package/dist/local/store/key-value/storage.d.ts +6 -0
  222. package/dist/local/store/key-value/storage.d.ts.map +1 -1
  223. package/dist/local/store/key-value/transactional-backend.d.ts +1 -1
  224. package/dist/local/store/key-value/transactional-backend.js +1 -1
  225. package/dist/local/store/memory/adapter.d.ts +13 -3
  226. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  227. package/dist/local/store/memory/adapter.js +122 -73
  228. package/dist/local/store/memory/adapter.js.map +1 -1
  229. package/dist/local/store/reliability.d.ts +16 -0
  230. package/dist/local/store/reliability.d.ts.map +1 -1
  231. package/dist/local/store/reliability.js +58 -28
  232. package/dist/local/store/reliability.js.map +1 -1
  233. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  234. package/dist/local/store/sqlite/migrations.js +18 -0
  235. package/dist/local/store/sqlite/migrations.js.map +1 -1
  236. package/dist/local/store/sqlite/models/skipped-sender-key.d.ts +3 -3
  237. package/dist/local/store/sqlite/models/skipped-sender-key.d.ts.map +1 -1
  238. package/dist/local/store/sqlite/models/skipped-sender-key.js +13 -17
  239. package/dist/local/store/sqlite/models/skipped-sender-key.js.map +1 -1
  240. package/dist/local/store/sqlite/store.d.ts +3 -3
  241. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  242. package/dist/local/store/sqlite/store.js +53 -23
  243. package/dist/local/store/sqlite/store.js.map +1 -1
  244. package/dist/local/store/web/adapter.d.ts +3 -3
  245. package/dist/local/store/web/adapter.d.ts.map +1 -1
  246. package/dist/local/store/web/adapter.js +122 -73
  247. package/dist/local/store/web/adapter.js.map +1 -1
  248. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  249. package/dist/local/vault/electron-safe-storage.js +15 -2
  250. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  251. package/dist/profile/index.d.ts +2 -1
  252. package/dist/profile/index.d.ts.map +1 -1
  253. package/dist/profile/index.js +2 -1
  254. package/dist/profile/index.js.map +1 -1
  255. package/dist/profile/own-profile-key.d.ts +42 -0
  256. package/dist/profile/own-profile-key.d.ts.map +1 -0
  257. package/dist/profile/own-profile-key.js +64 -0
  258. package/dist/profile/own-profile-key.js.map +1 -0
  259. package/dist/profile/profile-key.d.ts +1 -34
  260. package/dist/profile/profile-key.d.ts.map +1 -1
  261. package/dist/profile/profile-key.js +3 -63
  262. package/dist/profile/profile-key.js.map +1 -1
  263. package/dist/profile/update-service.js +1 -1
  264. package/dist/profile/update-service.js.map +1 -1
  265. package/dist/remote/relay/index.d.ts +4 -7
  266. package/dist/remote/relay/index.d.ts.map +1 -1
  267. package/dist/remote/relay/index.js +5 -7
  268. package/dist/remote/relay/index.js.map +1 -1
  269. package/dist/remote/relay/types.d.ts +3 -3
  270. package/dist/types/api.d.ts +29 -8
  271. package/dist/types/api.d.ts.map +1 -1
  272. package/dist/username/link.d.ts.map +1 -1
  273. package/dist/username/link.js +1 -5
  274. package/dist/username/link.js.map +1 -1
  275. package/dist/utils/bounded-fan-out.d.ts +99 -0
  276. package/dist/utils/bounded-fan-out.d.ts.map +1 -0
  277. package/dist/utils/bounded-fan-out.js +180 -0
  278. package/dist/utils/bounded-fan-out.js.map +1 -0
  279. package/dist/utils/keyed-lock.d.ts +16 -0
  280. package/dist/utils/keyed-lock.d.ts.map +1 -0
  281. package/dist/utils/keyed-lock.js +39 -0
  282. package/dist/utils/keyed-lock.js.map +1 -0
  283. package/dist/versions.d.ts +3 -3
  284. package/dist/versions.js +3 -3
  285. package/dist/zk/credentials.d.ts +2 -2
  286. package/dist/zk/credentials.js +2 -2
  287. package/dist/zk/groups.d.ts +3 -3
  288. package/dist/zk/groups.d.ts.map +1 -1
  289. package/dist/zk/groups.js +3 -3
  290. package/dist/zk/groups.js.map +1 -1
  291. package/docs/ASSURANCE.md +69 -28
  292. package/docs/CLIENT_COMPOSITION.md +9 -3
  293. package/docs/DEVIATIONS.md +45 -27
  294. package/docs/GETTING_STARTED.md +42 -320
  295. package/docs/INTERFACES.md +7 -7
  296. package/docs/PACKAGE_SURFACE.md +14 -16
  297. package/docs/RECIPES.md +6 -112
  298. package/groups/README.md +9 -1
  299. package/hooks/README.md +11 -2
  300. package/local/store/README.md +26 -6
  301. package/local/store/expo/README.md +18 -5
  302. package/local/store/key-value/README.md +5 -3
  303. package/local/store/node/README.md +2 -1
  304. package/local/store/web-sqlite/README.md +28 -8
  305. package/local/vault/README.md +21 -2
  306. package/package.json +1 -30
  307. package/remote/README.md +12 -78
  308. package/remote/object-store/convex-r2/README.md +20 -42
  309. package/remote/relay/README.md +21 -18
  310. package/zk/README.md +6 -7
  311. package/dist/client/dual-store.d.ts +0 -70
  312. package/dist/client/dual-store.d.ts.map +0 -1
  313. package/dist/client/dual-store.js +0 -123
  314. package/dist/client/dual-store.js.map +0 -1
  315. package/dist/client/multi-device.d.ts +0 -74
  316. package/dist/client/multi-device.d.ts.map +0 -1
  317. package/dist/client/multi-device.js +0 -105
  318. package/dist/client/multi-device.js.map +0 -1
  319. package/dist/groups/server.d.ts +0 -10
  320. package/dist/groups/server.d.ts.map +0 -1
  321. package/dist/groups/server.js +0 -6
  322. package/dist/groups/server.js.map +0 -1
  323. package/dist/internal/encoding/index.d.ts +0 -2
  324. package/dist/internal/encoding/index.d.ts.map +0 -1
  325. package/dist/internal/encoding/index.js +0 -2
  326. package/dist/internal/encoding/index.js.map +0 -1
  327. package/dist/internal/groups/server-engine.d.ts +0 -118
  328. package/dist/internal/groups/server-engine.d.ts.map +0 -1
  329. package/dist/internal/groups/server-engine.js +0 -1268
  330. package/dist/internal/groups/server-engine.js.map +0 -1
  331. package/dist/internal/protocol/index.d.ts +0 -24
  332. package/dist/internal/protocol/index.d.ts.map +0 -1
  333. package/dist/internal/protocol/index.js +0 -9
  334. package/dist/internal/protocol/index.js.map +0 -1
  335. package/dist/internal/protocol/sealed-sender/trust-root.d.ts +0 -56
  336. package/dist/internal/protocol/sealed-sender/trust-root.d.ts.map +0 -1
  337. package/dist/internal/protocol/sealed-sender/trust-root.js +0 -90
  338. package/dist/internal/protocol/sealed-sender/trust-root.js.map +0 -1
  339. package/dist/internal/protocol/triple-ratchet/index.d.ts +0 -21
  340. package/dist/internal/protocol/triple-ratchet/index.d.ts.map +0 -1
  341. package/dist/internal/protocol/triple-ratchet/index.js +0 -19
  342. package/dist/internal/protocol/triple-ratchet/index.js.map +0 -1
  343. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts +0 -233
  344. package/dist/internal/protocol/triple-ratchet/ratchet.d.ts.map +0 -1
  345. package/dist/internal/protocol/triple-ratchet/ratchet.js +0 -254
  346. package/dist/internal/protocol/triple-ratchet/ratchet.js.map +0 -1
  347. package/dist/internal/protocol/zk/proofs/index.d.ts +0 -13
  348. package/dist/internal/protocol/zk/proofs/index.d.ts.map +0 -1
  349. package/dist/internal/protocol/zk/proofs/index.js +0 -7
  350. package/dist/internal/protocol/zk/proofs/index.js.map +0 -1
  351. package/dist/local/store/sqlite/index.d.ts +0 -20
  352. package/dist/local/store/sqlite/index.d.ts.map +0 -1
  353. package/dist/local/store/sqlite/index.js +0 -18
  354. package/dist/local/store/sqlite/index.js.map +0 -1
  355. package/dist/remote/object-store/convex-r2/server/index.d.ts +0 -2
  356. package/dist/remote/object-store/convex-r2/server/index.d.ts.map +0 -1
  357. package/dist/remote/object-store/convex-r2/server/index.js +0 -2
  358. package/dist/remote/object-store/convex-r2/server/index.js.map +0 -1
  359. package/dist/remote/object-store/convex-r2/server.d.ts +0 -129
  360. package/dist/remote/object-store/convex-r2/server.d.ts.map +0 -1
  361. package/dist/remote/object-store/convex-r2/server.js +0 -244
  362. package/dist/remote/object-store/convex-r2/server.js.map +0 -1
  363. package/dist/remote/relay/memory/adapter.d.ts +0 -252
  364. package/dist/remote/relay/memory/adapter.d.ts.map +0 -1
  365. package/dist/remote/relay/memory/adapter.js +0 -1058
  366. package/dist/remote/relay/memory/adapter.js.map +0 -1
  367. package/dist/remote/relay/memory/failures.d.ts +0 -58
  368. package/dist/remote/relay/memory/failures.d.ts.map +0 -1
  369. package/dist/remote/relay/memory/failures.js +0 -124
  370. package/dist/remote/relay/memory/failures.js.map +0 -1
  371. package/dist/remote/relay/memory/group-server.d.ts +0 -13
  372. package/dist/remote/relay/memory/group-server.d.ts.map +0 -1
  373. package/dist/remote/relay/memory/group-server.js +0 -19
  374. package/dist/remote/relay/memory/group-server.js.map +0 -1
  375. package/dist/remote/relay/memory/index.d.ts +0 -11
  376. package/dist/remote/relay/memory/index.d.ts.map +0 -1
  377. package/dist/remote/relay/memory/index.js +0 -7
  378. package/dist/remote/relay/memory/index.js.map +0 -1
  379. package/examples/browser/README.md +0 -35
  380. package/examples/browser/index.html +0 -27
  381. package/examples/browser/src/exchange.ts +0 -69
  382. package/examples/browser/src/main.ts +0 -63
  383. package/examples/browser/src/style.css +0 -9
  384. package/examples/browser/src/worker.ts +0 -10
  385. package/examples/browser/vite.config.ts +0 -9
  386. package/remote/relay/memory/README.md +0 -72
  387. package/scripts/oe-groups.mjs +0 -166
@@ -21,14 +21,17 @@ import { recordServerClockSample } from '../server-clock.js';
21
21
  import { ProtocolAddress } from '../types/address.js';
22
22
  import { defaultSignalProtocolLogger } from '../logger.js';
23
23
  import { isGroupId, extractGroupId } from '../internal/groups/index.js';
24
+ import { GroupSenderKeyOperations } from './group-sender-key-operations.js';
24
25
  import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
25
26
  import * as CryptoUtils from '../internal/crypto/index.js';
26
- import { completeOutgoingMessageIntent, getOutgoingMessageIntent, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
27
+ import { completeOutgoingMessageIntent, getOutgoingMessageIntent, reconcileOutgoingDirectDeviceMessages, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
28
+ import { FanOutError, firstItemError } from '../utils/bounded-fan-out.js';
27
29
  import { withRetry } from '../utils/retry.js';
28
- import { acquireUntilStopped, RelayWorkStopped, rethrowRelayWorkStopped } from './relay-work.js';
30
+ import { acquireUntilStopped, createRelayFanOut, RelayWorkStopped, relaySendsSealedUnderItsBound, rethrowRelayWorkStopped, } from './relay-work.js';
31
+ import { refusesRemovedDevices, relayDeviceRefusal } from './relay-device-refusal.js';
29
32
  import { prepareGroupSharedMessage } from './group-sealed-sender.js';
30
33
  import { sendGroupWithExactOutbox } from './group-outbox.js';
31
- import { resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, } from './sealed-sender.js';
34
+ import { reconstructEnvelope, resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, unsealMessage, } from './sealed-sender.js';
32
35
  import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
33
36
  import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
34
37
  /**
@@ -37,6 +40,20 @@ import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
37
40
  * first send after it ends.
38
41
  */
39
42
  export const RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS = 60_000;
43
+ /**
44
+ * How old a recipient's device list can be for a direct send to post before
45
+ * it reads the list again. Only a relay that refuses a removed device's
46
+ * mailbox allows it, so the age bounds how long the client posts first on a
47
+ * list that no read confirmed, not how long a removed device receives.
48
+ */
49
+ const RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS = 300_000;
50
+ /** A send-first post that waits for the reconcile pass. */
51
+ class DeferredPost extends Error {
52
+ constructor() {
53
+ super('The post waits for the device-list read');
54
+ this.name = 'DeferredPost';
55
+ }
56
+ }
40
57
  export function sortEnvelopesForDecryption(envelopes) {
41
58
  return [...envelopes].sort((a, b) => {
42
59
  // Treat undefined messageType as non-prekey (ciphertext comes after prekey_bundle)
@@ -121,7 +138,14 @@ class SealedSenderRecipientRejectedError extends Error {
121
138
  }
122
139
  }
123
140
  function isConclusiveDeviceRejection(error) {
124
- return isStaleSessionError(error) || error instanceof SealedSenderRecipientRejectedError;
141
+ return (isStaleSessionError(error) ||
142
+ error instanceof SealedSenderRecipientRejectedError ||
143
+ relayDeviceRefusal(error)?.code === 'STALE_DEVICE');
144
+ }
145
+ /** True when the relay refused this post because of the device that it names. */
146
+ function isRefusalOfDevice(error, message) {
147
+ const refusal = relayDeviceRefusal(error);
148
+ return (refusal?.userId === message.recipientUserId && refusal.deviceId === message.recipientDeviceId);
125
149
  }
126
150
  /**
127
151
  * SignalProtocolServiceCipher - Routes encryption and decryption to appropriate ciphers
@@ -153,7 +177,9 @@ export class SignalProtocolServiceCipher {
153
177
  remoteObjectStore;
154
178
  contentAdapter;
155
179
  logger;
180
+ fanOut;
156
181
  lock = new AsyncLock();
182
+ groupSenderKeys;
157
183
  sessionCallbacks;
158
184
  recipientDeviceListCheckedAt = new Map();
159
185
  sealedSenderProvider;
@@ -166,7 +192,7 @@ export class SignalProtocolServiceCipher {
166
192
  groupSendBarrierChecker;
167
193
  groupReceiveAuthorizer;
168
194
  groupSecretParamsProvider;
169
- constructor(userId, deviceId, sesameManager, senderKeyManager, storage, relay, remoteObjectStore, contentAdapter, logger = defaultSignalProtocolLogger) {
195
+ constructor(userId, deviceId, sesameManager, senderKeyManager, storage, relay, remoteObjectStore, contentAdapter, logger = defaultSignalProtocolLogger, fanOut = createRelayFanOut()) {
170
196
  this.userId = userId;
171
197
  this.deviceId = deviceId;
172
198
  this.sesameManager = sesameManager;
@@ -176,6 +202,8 @@ export class SignalProtocolServiceCipher {
176
202
  this.remoteObjectStore = remoteObjectStore;
177
203
  this.contentAdapter = contentAdapter;
178
204
  this.logger = logger;
205
+ this.fanOut = fanOut;
206
+ this.groupSenderKeys = new GroupSenderKeyOperations(storage, userId, deviceId);
179
207
  }
180
208
  getResolvedContentAdapter() {
181
209
  return this.contentAdapter ?? createDefaultSignalProtocolContentAdapter();
@@ -202,24 +230,70 @@ export class SignalProtocolServiceCipher {
202
230
  return CryptoUtils.bytesToBase64(plaintextBytes);
203
231
  }
204
232
  async uploadSyncMessages(syncMessages) {
205
- if (!this.relay || syncMessages.length === 0) {
233
+ const relay = this.relay;
234
+ if (!relay || syncMessages.length === 0) {
206
235
  return;
207
236
  }
208
- for (const syncMsg of syncMessages) {
209
- await this.relay.send({
210
- targetUserId: syncMsg.recipientUserId,
211
- targetDeviceId: syncMsg.recipientDeviceId,
212
- senderUserId: this.userId,
213
- senderDeviceId: this.deviceId,
214
- ciphertext: typeof syncMsg.ciphertext === 'string'
215
- ? syncMsg.ciphertext
216
- : CryptoUtils.bytesToBase64(syncMsg.ciphertext),
217
- messageType: getEnvelopeMessageType(syncMsg.ciphertext),
218
- deliveryClass: 'background-sync',
219
- timestamp: syncMsg.timestamp,
220
- });
237
+ await this.sendPhase(syncMessages, (syncMsg) => this.fanOut.request(() => relay.send({
238
+ targetUserId: syncMsg.recipientUserId,
239
+ targetDeviceId: syncMsg.recipientDeviceId,
240
+ senderUserId: this.userId,
241
+ senderDeviceId: this.deviceId,
242
+ ciphertext: typeof syncMsg.ciphertext === 'string'
243
+ ? syncMsg.ciphertext
244
+ : CryptoUtils.bytesToBase64(syncMsg.ciphertext),
245
+ messageType: getEnvelopeMessageType(syncMsg.ciphertext),
246
+ deliveryClass: 'background-sync',
247
+ timestamp: syncMsg.timestamp,
248
+ })), 'sync');
249
+ }
250
+ /**
251
+ * Run one relay phase of a send: a task for each device message, at the same
252
+ * time, under the client's relay request bound. Every device is attempted.
253
+ * When devices fail, the phase rejects after every device settles, with the
254
+ * error of the first failed device in input order, so a caller sees the
255
+ * error type that a send in device order threw. Each other failure is logged.
256
+ */
257
+ async sendPhase(messages, task, phase, stopSignal) {
258
+ try {
259
+ return await this.fanOut.all(messages, task, stopSignal);
260
+ }
261
+ catch (error) {
262
+ if (!(error instanceof FanOutError))
263
+ throw error;
264
+ const failed = error.outcomes.flatMap((outcome, index) => outcome.ok ? [] : [{ message: messages[index], error: outcome.error }]);
265
+ for (const { message, error: other } of failed.slice(1)) {
266
+ this.logger.warn('A device post of a send failed', {
267
+ category: 'E2EE',
268
+ error: other,
269
+ data: {
270
+ phase,
271
+ recipientUserId: message.recipientUserId,
272
+ deviceId: message.recipientDeviceId,
273
+ failedDevices: failed.length,
274
+ },
275
+ });
276
+ }
277
+ throw failed[0].error;
221
278
  }
222
279
  }
280
+ /**
281
+ * Send one relay request of a device post under a slot of the client's
282
+ * bound. An adapter that bounds its own sealed-sender posts takes a slot of
283
+ * the same bound, so its sealed post runs without one here.
284
+ */
285
+ postToRelay(send, sealed, control) {
286
+ const post = () => {
287
+ control.admit?.();
288
+ return send();
289
+ };
290
+ if (sealed && relaySendsSealedUnderItsBound(this.relay)) {
291
+ if (control.stopSignal?.aborted)
292
+ return Promise.reject(new RelayWorkStopped());
293
+ return new Promise((resolve) => resolve(post()));
294
+ }
295
+ return this.fanOut.request(post, control.stopSignal);
296
+ }
223
297
  async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp) {
224
298
  if (!this.relay) {
225
299
  return;
@@ -382,13 +456,12 @@ export class SignalProtocolServiceCipher {
382
456
  *
383
457
  * @see https://signal.org/docs/specifications/sesame/
384
458
  */
385
- async decrypt(envelope, sealedSenderConfig, receiveId) {
459
+ async decrypt(envelope, sealedSenderConfig, receiveId, stopSignal) {
386
460
  // Handle sealed sender (unidentified_sender) envelopes by unsealing first
387
461
  if (envelope.messageType === 'unidentified_sender') {
388
462
  if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
389
463
  throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
390
464
  }
391
- const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender.js');
392
465
  // Get recipient's X25519 identity private key for unsealing
393
466
  const identityKeyPair = await this.storage.getIdentityKey();
394
467
  if (!identityKeyPair) {
@@ -403,7 +476,7 @@ export class SignalProtocolServiceCipher {
403
476
  // Reconstruct envelope with revealed sender identity
404
477
  const innerEnvelope = reconstructEnvelope(envelope, unsealed);
405
478
  // Recursively decrypt the inner message (now a standard ciphertext)
406
- return this.decrypt(innerEnvelope, undefined, receiveId);
479
+ return this.decrypt(innerEnvelope, undefined, receiveId, stopSignal);
407
480
  }
408
481
  // Validate message type before processing
409
482
  // Server only sends the 5 envelope types. Client-to-client types (typing_indicator,
@@ -419,7 +492,7 @@ export class SignalProtocolServiceCipher {
419
492
  throw new EncryptionError(`Unknown message type: ${envelope.messageType}`, EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
420
493
  }
421
494
  const lockKey = `decrypt:${envelope.senderUserId}:${envelope.senderDeviceId}`;
422
- return this.lock.acquire(lockKey, async () => {
495
+ return acquireUntilStopped(this.lock, lockKey, async () => {
423
496
  this.logger.debug('Handling incoming envelope', {
424
497
  category: 'E2EE',
425
498
  data: {
@@ -439,7 +512,7 @@ export class SignalProtocolServiceCipher {
439
512
  // framed SenderKeyMessage". It does not say which group, and cannot.
440
513
  // That is the point of not putting a group on the envelope.
441
514
  if (envelope.messageType === 'sender_key') {
442
- const group = await this.decryptGroup(envelope, receiveId, received ?? undefined);
515
+ const group = await this.decryptGroup(envelope, receiveId, received ?? undefined, stopSignal);
443
516
  plaintext = group.plaintext;
444
517
  resolvedGroupId = group.groupId;
445
518
  }
@@ -459,8 +532,10 @@ export class SignalProtocolServiceCipher {
459
532
  if (!this.groupReceiveAuthorizer) {
460
533
  throw new Error('Configure verified group membership before receiving sender keys');
461
534
  }
462
- await this.groupReceiveAuthorizer(distribution.groupId, envelope.senderUserId);
463
- await this.senderKeyManager.processSenderKeyDistribution(distribution.groupId, envelope.senderUserId, envelope.senderDeviceId, distribution.distribution);
535
+ await this.groupSenderKeys.run(distribution.groupId, async (rawGroupId) => {
536
+ await this.groupReceiveAuthorizer(rawGroupId, envelope.senderUserId, 'distribution');
537
+ await this.senderKeyManager.processSenderKeyDistribution(rawGroupId, envelope.senderUserId, envelope.senderDeviceId, distribution.distribution);
538
+ }, stopSignal);
464
539
  }
465
540
  // For DMs, compute canonical conversation ID: dm:${sorted(user1, user2)}
466
541
  // Groups use their group ID directly. Sent sync transcripts override this
@@ -499,7 +574,7 @@ export class SignalProtocolServiceCipher {
499
574
  messageType: envelope.messageType,
500
575
  };
501
576
  return decryptedEnvelope;
502
- });
577
+ }, stopSignal);
503
578
  }
504
579
  /**
505
580
  * Encrypt outgoing message - routes based on recipient type
@@ -524,20 +599,21 @@ export class SignalProtocolServiceCipher {
524
599
  async encrypt(recipientId, content, options, sessions = this.sessionCallbacks, stopSignal) {
525
600
  const clientMessageId = options?.clientMessageId ?? (await CryptoUtils.generateUuidV4());
526
601
  const durableOptions = { ...options, clientMessageId };
527
- const lockKey = `encrypt:${recipientId}`;
602
+ const encrypt = async () => {
603
+ if (durableOptions.isBinary) {
604
+ return this.encryptBinaryAttachment(recipientId, content, durableOptions, sessions, stopSignal);
605
+ }
606
+ if (isGroupId(recipientId)) {
607
+ return this.encryptToGroup(recipientId, content, durableOptions, sessions, stopSignal);
608
+ }
609
+ return this.encryptToUser(recipientId, content, durableOptions, sessions, stopSignal);
610
+ };
528
611
  try {
529
- return await acquireUntilStopped(this.lock, lockKey, async () => {
530
- // 1. Route binary file data (Uint8Array with isBinary flag) to blob encryption
531
- if (durableOptions.isBinary) {
532
- return this.encryptBinaryAttachment(recipientId, content, durableOptions, sessions);
533
- }
534
- // 2. Detect recipient type (group vs user)
535
- if (isGroupId(recipientId)) {
536
- return this.encryptToGroup(recipientId, content, durableOptions, sessions);
537
- }
538
- // 3. Send to user (existing SESAME path)
539
- return this.encryptToUser(recipientId, content, durableOptions, sessions);
540
- }, stopSignal);
612
+ // This lock keeps the sends to one recipient in order, also across an
613
+ // attachment upload. A group send takes the group's Sender Key lock
614
+ // only in encryptToGroup, so a receive does not wait for an upload.
615
+ const orderKey = isGroupId(recipientId) ? extractGroupId(recipientId) : recipientId;
616
+ return await acquireUntilStopped(this.lock, `encrypt:${orderKey}`, encrypt, stopSignal);
541
617
  }
542
618
  catch (error) {
543
619
  throw attachClientMessageId(error, clientMessageId);
@@ -616,7 +692,7 @@ export class SignalProtocolServiceCipher {
616
692
  *
617
693
  * @throws {EncryptionError} DECRYPTION_FAILED if decryption fails
618
694
  */
619
- async decryptGroup(envelope, receiveId, received) {
695
+ async decryptGroup(envelope, receiveId, received, stopSignal) {
620
696
  // Get the framed SenderKeyMessage bytes
621
697
  let framedBytes;
622
698
  if (typeof envelope.ciphertext === 'string') {
@@ -634,33 +710,35 @@ export class SignalProtocolServiceCipher {
634
710
  // sender to redistribute.
635
711
  throw new EncryptionError(`No sender key from ${envelope.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
636
712
  }
637
- await this.groupReceiveAuthorizer?.(groupId, envelope.senderUserId);
638
- if (received)
639
- return { plaintext: received.plaintext, groupId };
640
- try {
641
- const plaintext = await this.senderKeyManager.decryptGroupMessage(groupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes, receiveId);
642
- this.logger.debug('Decrypted group message', {
643
- category: 'E2EE',
644
- data: {
645
- groupId,
646
- senderId: envelope.senderUserId,
647
- },
648
- });
649
- return { plaintext, groupId };
650
- }
651
- catch (error) {
652
- const err = error;
653
- if (err.message?.includes('SENDER_KEY_NOT_FOUND')) {
654
- throw new EncryptionError(`No sender key from ${envelope.senderUserId} for group ${groupId} - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND, { originalError: err });
655
- }
656
- if (err.message?.includes('INVALID_SIGNATURE')) {
657
- throw new EncryptionError(`Invalid signature on group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
713
+ return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
714
+ await this.groupReceiveAuthorizer?.(rawGroupId, envelope.senderUserId, 'message');
715
+ if (received)
716
+ return { plaintext: received.plaintext, groupId: rawGroupId };
717
+ try {
718
+ const plaintext = await this.senderKeyManager.decryptGroupMessage(rawGroupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes, receiveId);
719
+ this.logger.debug('Decrypted group message', {
720
+ category: 'E2EE',
721
+ data: {
722
+ groupId: rawGroupId,
723
+ senderId: envelope.senderUserId,
724
+ },
725
+ });
726
+ return { plaintext, groupId: rawGroupId };
658
727
  }
659
- if (err.message?.includes('MESSAGE_TOO_OLD')) {
660
- throw new EncryptionError('Cannot decrypt old group message (forward secrecy)', EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
728
+ catch (error) {
729
+ const err = error;
730
+ if (err.message?.includes('SENDER_KEY_NOT_FOUND')) {
731
+ throw new EncryptionError(`No sender key from ${envelope.senderUserId} for group ${rawGroupId} - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND, { originalError: err });
732
+ }
733
+ if (err.message?.includes('INVALID_SIGNATURE')) {
734
+ throw new EncryptionError(`Invalid signature on group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
735
+ }
736
+ if (err.message?.includes('MESSAGE_TOO_OLD')) {
737
+ throw new EncryptionError('Cannot decrypt old group message (forward secrecy)', EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
738
+ }
739
+ throw new EncryptionError(`Failed to decrypt group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
661
740
  }
662
- throw new EncryptionError(`Failed to decrypt group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
663
- }
741
+ }, stopSignal);
664
742
  }
665
743
  // ============================================================================
666
744
  // PRIVATE - Encryption
@@ -677,17 +755,26 @@ export class SignalProtocolServiceCipher {
677
755
  * without a relay read. The relay gives no device-set version, so the window
678
756
  * is the only bound on how long a linked or removed device goes unseen.
679
757
  *
758
+ * A direct send may post before the read when the relay refuses every post
759
+ * to a removed device's mailbox, this client read the list in this process,
760
+ * and that read is younger than
761
+ * RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS. This method then returns
762
+ * true without a read, and the send reads the list while it posts and
763
+ * reconciles after the read. Other relays, and a list that this process did
764
+ * not read or that is too old, await the read. A list time later than the
765
+ * clock is too old.
766
+ *
767
+ * @param sendFirst - The caller can post before the read and reconcile after it
768
+ * @param readDevices - The recipient's devices that this send read. When
769
+ * they are given, a reconcile uses them and does not read the list again
770
+ * @returns True when the caller must read the list after it posts
680
771
  * @throws {EncryptionError} SESSION_NOT_FOUND if sessions cannot be established
681
772
  */
682
- async ensureSessionsForUser(recipientUserId, sessions) {
683
- const userRecord = await this.sesameManager.getUserRecord(recipientUserId);
684
- const hasActiveSession = !!userRecord &&
685
- Array.from(userRecord.devices.values()).some((device) => device.session?.currentSession != null);
686
- const checkedAt = this.recipientDeviceListCheckedAt.get(recipientUserId);
687
- if (hasActiveSession &&
688
- checkedAt !== undefined &&
689
- Date.now() - checkedAt < RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS) {
690
- return;
773
+ async ensureSessionsForUser(recipientUserId, sessions, sendFirst = false, readDevices) {
774
+ const hasActiveSession = await this.hasActiveSession(recipientUserId);
775
+ const listAge = this.recipientDeviceListAge(recipientUserId);
776
+ if (hasActiveSession && listAge < RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS) {
777
+ return false;
691
778
  }
692
779
  this.logger.debug('Reconciling recipient devices with the relay', {
693
780
  category: 'E2EE',
@@ -695,19 +782,51 @@ export class SignalProtocolServiceCipher {
695
782
  });
696
783
  if (!sessions) {
697
784
  if (hasActiveSession)
698
- return;
785
+ return false;
699
786
  throw new EncryptionError(`No session with ${recipientUserId} and auto-establishment not configured`, EncryptionErrorCode.SESSION_NOT_FOUND, { recipientUserId });
700
787
  }
701
788
  if (!this.relay) {
702
789
  if (hasActiveSession)
703
- return;
790
+ return false;
704
791
  throw new EncryptionError('Cannot auto-establish session: relay server not configured', EncryptionErrorCode.INITIALIZATION_FAILED, { recipientUserId });
705
792
  }
793
+ if (sendFirst &&
794
+ hasActiveSession &&
795
+ listAge < RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS &&
796
+ refusesRemovedDevices(this.relay)) {
797
+ return true;
798
+ }
799
+ await this.readRecipientDeviceList(recipientUserId, sessions, hasActiveSession, undefined, readDevices);
800
+ return false;
801
+ }
802
+ async hasActiveSession(recipientUserId) {
803
+ const userRecord = await this.sesameManager.getUserRecord(recipientUserId);
804
+ return (!!userRecord &&
805
+ Array.from(userRecord.devices.values()).some((device) => device.session?.currentSession != null));
806
+ }
807
+ /** The age of this process's last successful read. A read in the future has no age. */
808
+ recipientDeviceListAge(recipientUserId) {
809
+ const checkedAt = this.recipientDeviceListCheckedAt.get(recipientUserId);
810
+ const age = checkedAt === undefined ? Number.POSITIVE_INFINITY : Date.now() - checkedAt;
811
+ return age >= 0 ? age : Number.POSITIVE_INFINITY;
812
+ }
813
+ /**
814
+ * Read the recipient's device list, create the missing sessions, and remove
815
+ * each local device that the list does not show.
816
+ *
817
+ * @param onList - Called with the listed devices as soon as the list arrives,
818
+ * before the unlisted records are removed
819
+ * @param readDevices - The devices that this send read. When they are
820
+ * given, the list is not read again
821
+ * @returns The listed and established devices, or undefined when the read
822
+ * failed and the known devices still receive
823
+ */
824
+ async readRecipientDeviceList(recipientUserId, sessions, hasActiveSession, onList, readDevices) {
706
825
  let result;
707
826
  try {
708
827
  // Use retry logic for transient network failures
709
828
  result = await withRetry(async () => {
710
- const attempt = await sessions.establishSessions(recipientUserId);
829
+ const attempt = await sessions.establishSessions(recipientUserId, readDevices);
711
830
  if (attempt.establishedDevices.length === 0 && attempt.failedDeviceErrors.length > 0) {
712
831
  throw attempt.failedDeviceErrors[0].error;
713
832
  }
@@ -728,7 +847,7 @@ export class SignalProtocolServiceCipher {
728
847
  error: error,
729
848
  data: { recipientUserId },
730
849
  });
731
- return;
850
+ return undefined;
732
851
  }
733
852
  // Re-throw EncryptionErrors, wrap others
734
853
  if (error instanceof EncryptionError) {
@@ -742,6 +861,7 @@ export class SignalProtocolServiceCipher {
742
861
  throw new EncryptionError(`Failed to establish session with ${recipientUserId} after retries`, EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { originalError: error, recipientUserId });
743
862
  }
744
863
  const listedDevices = new Set(result.activeDevices);
864
+ onList?.(listedDevices);
745
865
  const removedDevices = [];
746
866
  const reconciledRecord = await this.sesameManager.getUserRecord(recipientUserId);
747
867
  for (const deviceId of Array.from(reconciledRecord?.devices.keys() ?? [])) {
@@ -765,17 +885,18 @@ export class SignalProtocolServiceCipher {
765
885
  removedDevices,
766
886
  },
767
887
  });
888
+ return { listed: listedDevices, established: result.establishedDevices };
768
889
  }
769
890
  /**
770
891
  * Encrypt to a single user (all their devices) via SESAME
771
892
  */
772
- async encryptToUser(recipientUserId, plaintextBytes, options, sessions) {
773
- return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions);
893
+ async encryptToUser(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
894
+ return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal);
774
895
  }
775
- async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions) {
776
- return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions));
896
+ async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
897
+ return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal));
777
898
  }
778
- async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions) {
899
+ async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
779
900
  const plaintextDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(plaintextBytes));
780
901
  const existing = await getOutgoingMessageIntent(this.storage, options.clientMessageId);
781
902
  if (existing) {
@@ -787,9 +908,9 @@ export class SignalProtocolServiceCipher {
787
908
  }
788
909
  if (existing.result)
789
910
  return existing.result;
790
- return this.sendStoredDirectIntent(existing, plaintextBytes, sessions);
911
+ return this.sendStoredDirectIntent(await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions), plaintextBytes, sessions, stopSignal);
791
912
  }
792
- await this.ensureSessionsForUser(recipientUserId, sessions);
913
+ const sendFirst = await this.ensureSessionsForUser(recipientUserId, sessions, true);
793
914
  const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
794
915
  const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
795
916
  const transportMode = directSealedSender
@@ -823,7 +944,12 @@ export class SignalProtocolServiceCipher {
823
944
  syncCount: batch.syncMessages.length,
824
945
  },
825
946
  });
826
- const deviceMessages = await Promise.all(batch.deviceMessages.map((message) => this.prepareStoredDirectDeviceMessage(message, directSealedSender)));
947
+ // Local work: a stop does not end it, so the intent keeps the ciphertext.
948
+ const deviceMessages = await this.fanOut
949
+ .all(batch.deviceMessages, (message) => this.prepareStoredDirectDeviceMessage(message, directSealedSender))
950
+ .catch((error) => {
951
+ throw firstItemError(error);
952
+ });
827
953
  const syncMessages = batch.syncMessages.map((msg, index) => ({
828
954
  recipientUserId: msg.recipientUserId,
829
955
  recipientDeviceId: msg.recipientDeviceId,
@@ -846,11 +972,125 @@ export class SignalProtocolServiceCipher {
846
972
  ...(options.contentHint !== undefined && {
847
973
  contentHint: options.contentHint,
848
974
  }),
975
+ ...(sendFirst && { reconcilePending: true }),
849
976
  deviceMessages,
850
977
  syncMessages,
851
978
  };
852
979
  await storeOutgoingMessageIntent(this.storage, intent);
853
- return this.sendStoredDirectIntent(intent, plaintextBytes, sessions);
980
+ if (sendFirst && sessions) {
981
+ return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal);
982
+ }
983
+ return this.sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
984
+ }
985
+ /**
986
+ * Post a direct intent to its known devices while the recipient's device
987
+ * list is read, then reconcile the intent with the list and post the rest.
988
+ *
989
+ * The known devices are posted at the same time. A post that the relay
990
+ * refuses because of its device waits for the read, and the read decides it:
991
+ * an unlisted device leaves the intent without a repair, a listed device
992
+ * with STALE_DEVICE is repaired, and a listed device with NOT_FOUND fails
993
+ * the send. A post that has not started when the list arrives waits for the
994
+ * reconcile pass, which starts after the read removes the unlisted device
995
+ * records, so no message goes to a device after the read that shows its
996
+ * removal.
997
+ */
998
+ async sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal) {
999
+ const arrived = {};
1000
+ const read = this.readRecipientDeviceList(intent.recipientId, sessions, true, (listed) => {
1001
+ arrived.listed = listed;
1002
+ });
1003
+ // Every path below awaits the read. This handler only covers the posts.
1004
+ read.catch(() => undefined);
1005
+ const posts = { accepted: new Map(), refused: new Map() };
1006
+ const control = {
1007
+ ...(stopSignal && { stopSignal }),
1008
+ admit: () => {
1009
+ if (arrived.listed)
1010
+ throw new DeferredPost();
1011
+ },
1012
+ };
1013
+ try {
1014
+ await this.sendPhase(intent.deviceMessages, async (message) => {
1015
+ try {
1016
+ posts.accepted.set(message.recipientDeviceId, await this.sendStoredDirectDeviceMessage(intent, message, control));
1017
+ }
1018
+ catch (error) {
1019
+ if (error instanceof DeferredPost)
1020
+ return;
1021
+ if (!isRefusalOfDevice(error, message))
1022
+ throw error;
1023
+ posts.refused.set(message.recipientDeviceId, { error });
1024
+ }
1025
+ }, 'device', stopSignal);
1026
+ }
1027
+ catch (error) {
1028
+ // The read commits sessions. It ends before the send fails.
1029
+ await read.catch(() => undefined);
1030
+ throw error;
1031
+ }
1032
+ const list = await read;
1033
+ const reconciled = list
1034
+ ? await this.reconcileDirectIntent(intent, list, plaintextBytes)
1035
+ : intent;
1036
+ return this.sendStoredDirectIntent(reconciled, plaintextBytes, sessions, stopSignal, posts);
1037
+ }
1038
+ /** A replay whose first attempt posted before its read reads and reconciles first. */
1039
+ async reconcilePendingDirectIntent(intent, plaintextBytes, sessions) {
1040
+ if (!intent.reconcilePending || !sessions || !this.relay)
1041
+ return intent;
1042
+ const list = await this.readRecipientDeviceList(intent.recipientId, sessions, await this.hasActiveSession(intent.recipientId));
1043
+ return list ? this.reconcileDirectIntent(intent, list, plaintextBytes) : intent;
1044
+ }
1045
+ /**
1046
+ * Apply a device-list read to a direct intent: remove each device that the
1047
+ * list does not show, and encrypt the message for each established device
1048
+ * that the intent does not address. A new transmission keeps the intent's
1049
+ * timestamp, so each device receives the same message.
1050
+ */
1051
+ async reconcileDirectIntent(intent, list, plaintextBytes) {
1052
+ const removed = intent.deviceMessages
1053
+ .map((message) => message.recipientDeviceId)
1054
+ .filter((deviceId) => !list.listed.has(deviceId));
1055
+ const addressed = new Set(intent.deviceMessages.map((message) => message.recipientDeviceId));
1056
+ const added = [];
1057
+ let sealedSender;
1058
+ for (const deviceId of list.established) {
1059
+ if (addressed.has(deviceId))
1060
+ continue;
1061
+ let message;
1062
+ try {
1063
+ message = await this.sesameManager.sendMessage(intent.recipientId, deviceId, plaintextBytes, {
1064
+ clientTimestamp: intent.clientTimestamp,
1065
+ includeSyncMessages: false,
1066
+ });
1067
+ }
1068
+ catch (error) {
1069
+ this.logger.warn('Could not encrypt a direct message for a newly listed device', {
1070
+ category: 'E2EE',
1071
+ error: error,
1072
+ data: { recipientUserId: intent.recipientId, deviceId },
1073
+ });
1074
+ continue;
1075
+ }
1076
+ if (sealedSender === undefined) {
1077
+ sealedSender = await this.resolveStoredDirectSealedSender(intent);
1078
+ }
1079
+ added.push(await this.prepareStoredDirectDeviceMessage(message, sealedSender));
1080
+ }
1081
+ if (removed.length === 0 && added.length === 0)
1082
+ return intent;
1083
+ return reconcileOutgoingDirectDeviceMessages(this.storage, intent.clientMessageId, removed, added);
1084
+ }
1085
+ /** The sealed-sender context of a new transmission for a stored direct intent. */
1086
+ async resolveStoredDirectSealedSender(intent) {
1087
+ if (intent.transportMode === 'identified')
1088
+ return null;
1089
+ const sealedSender = await this.resolveSealedSenderContext(intent.recipientId);
1090
+ if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
1091
+ throw new Error('Cannot build a sealed-sender transmission for a stored direct intent');
1092
+ }
1093
+ return sealedSender;
854
1094
  }
855
1095
  async prepareStoredDirectDeviceMessage(message, sealedSender) {
856
1096
  const messageType = getEnvelopeMessageType(message.ciphertext);
@@ -874,39 +1114,66 @@ export class SignalProtocolServiceCipher {
874
1114
  }
875
1115
  return storedMessage;
876
1116
  }
1117
+ /**
1118
+ * Refresh the session of a rejected device and replace its transmission.
1119
+ * The device posts of a send run at the same time, so the repairs for one
1120
+ * recipient take turns: the first session commit with a user pins the
1121
+ * user's contact identity, and a concurrent commit that read the store
1122
+ * before it fails.
1123
+ */
877
1124
  async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes, sessions) {
878
1125
  if (!sessions)
879
1126
  throw new Error('Stale-session refresh is not configured');
1127
+ return this.lock.acquire(`direct-repair:${rejected.recipientUserId}`, () => this.repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions));
1128
+ }
1129
+ async repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions) {
880
1130
  const refreshed = await sessions.refreshStaleSession(rejected.recipientUserId, rejected.recipientDeviceId);
881
1131
  if (!refreshed) {
882
1132
  throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: rejected.recipientUserId });
883
1133
  }
884
1134
  const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
885
- let sealedSender = null;
886
- if (intent.transportMode !== 'identified') {
887
- sealedSender = await this.resolveSealedSenderContext(rejected.recipientUserId);
888
- if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
889
- throw new Error('Cannot rebuild a sealed-sender transmission after session refresh');
890
- }
891
- }
892
- const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, sealedSender);
1135
+ const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, await this.resolveStoredDirectSealedSender(intent));
893
1136
  await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
894
1137
  return replacement;
895
1138
  }
896
- async sendStoredDirectDeviceMessage(intent, message) {
1139
+ async sendStoredDirectDeviceMessage(intent, message, control) {
897
1140
  if (intent.transportMode !== 'identified' &&
898
1141
  (!message.sealedSenderMessage || !intent.sealedSenderAuth)) {
899
1142
  throw new Error('Corrupt sealed-sender outbox intent');
900
1143
  }
901
1144
  return intent.transportMode === 'identified'
902
- ? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId)
1145
+ ? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, undefined, control)
903
1146
  : this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, {
904
1147
  sentMessageBase64: message.sealedSenderMessage,
905
1148
  auth: intent.sealedSenderAuth,
906
1149
  deliveryMode: intent.transportMode === 'sealed_sender_required' ? 'required' : 'preferred',
907
- });
1150
+ }, control);
1151
+ }
1152
+ /** Post one device message, and repair its session once if the device rejects it. */
1153
+ async postStoredDirectDeviceMessage(intent, message, plaintextBytes, sessions, control, refusal) {
1154
+ let rejection;
1155
+ if (refusal) {
1156
+ rejection = refusal.error;
1157
+ }
1158
+ else {
1159
+ try {
1160
+ return await this.sendStoredDirectDeviceMessage(intent, message, control);
1161
+ }
1162
+ catch (error) {
1163
+ rejection = error;
1164
+ }
1165
+ }
1166
+ if (!isConclusiveDeviceRejection(rejection))
1167
+ throw rejection;
1168
+ const replacement = await this.repairRejectedDirectDeviceMessage(intent, message, plaintextBytes, sessions);
1169
+ return this.sendStoredDirectDeviceMessage(intent, replacement, control);
908
1170
  }
909
- async sendStoredDirectIntent(intent, plaintextBytes, sessions) {
1171
+ /**
1172
+ * Post each device message of a direct intent, then the sync messages, and
1173
+ * complete the intent. A device that a send-first pass already posted keeps
1174
+ * its result or its refusal.
1175
+ */
1176
+ async sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, posts) {
910
1177
  if (intent.kind !== 'direct')
911
1178
  throw new Error('Expected a direct outbox intent');
912
1179
  if (!this.relay) {
@@ -919,37 +1186,30 @@ export class SignalProtocolServiceCipher {
919
1186
  await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
920
1187
  return result;
921
1188
  }
1189
+ const relay = this.relay;
922
1190
  let messageId = `local-${intent.clientTimestamp}`;
923
1191
  let timestamp = intent.clientTimestamp;
924
- for (const msg of intent.deviceMessages) {
925
- let result;
926
- try {
927
- result = await this.sendStoredDirectDeviceMessage(intent, msg);
928
- }
929
- catch (error) {
930
- if (!isConclusiveDeviceRejection(error))
931
- throw error;
932
- const replacement = await this.repairRejectedDirectDeviceMessage(intent, msg, plaintextBytes, sessions);
933
- result = await this.sendStoredDirectDeviceMessage(intent, replacement);
934
- }
1192
+ const control = { ...(stopSignal && { stopSignal }) };
1193
+ const results = await this.sendPhase(intent.deviceMessages, async (msg) => posts?.accepted.get(msg.recipientDeviceId) ??
1194
+ this.postStoredDirectDeviceMessage(intent, msg, plaintextBytes, sessions, control, posts?.refused.get(msg.recipientDeviceId)), 'device', stopSignal);
1195
+ for (const result of results) {
935
1196
  if (messageId.startsWith('local-')) {
936
1197
  messageId = result.messageId;
937
1198
  timestamp = result.serverTimestamp;
938
1199
  }
939
1200
  }
940
- for (const msg of intent.syncMessages) {
941
- await this.relay.send({
942
- targetUserId: msg.recipientUserId,
943
- targetDeviceId: msg.recipientDeviceId,
944
- senderUserId: this.userId,
945
- senderDeviceId: this.deviceId,
946
- ciphertext: msg.ciphertext,
947
- messageType: msg.messageType,
948
- deliveryClass: 'background-sync',
949
- timestamp: msg.timestamp,
950
- clientMessageId: msg.clientMessageId,
951
- });
952
- }
1201
+ // The sync copies start only after every device post settled.
1202
+ await this.sendPhase(intent.syncMessages, (msg) => this.fanOut.request(() => relay.send({
1203
+ targetUserId: msg.recipientUserId,
1204
+ targetDeviceId: msg.recipientDeviceId,
1205
+ senderUserId: this.userId,
1206
+ senderDeviceId: this.deviceId,
1207
+ ciphertext: msg.ciphertext,
1208
+ messageType: msg.messageType,
1209
+ deliveryClass: 'background-sync',
1210
+ timestamp: msg.timestamp,
1211
+ clientMessageId: msg.clientMessageId,
1212
+ }), stopSignal), 'sync', stopSignal);
953
1213
  const result = {
954
1214
  clientMessageId: intent.clientMessageId,
955
1215
  messageId,
@@ -959,15 +1219,16 @@ export class SignalProtocolServiceCipher {
959
1219
  await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
960
1220
  return result;
961
1221
  }
962
- async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions) {
1222
+ async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal) {
1223
+ const control = { ...(stopSignal && { stopSignal }) };
963
1224
  return sendGroupWithExactOutbox({
964
1225
  storage: this.storage,
965
1226
  ...(this.relay && { relay: this.relay }),
966
1227
  senderUserId: this.userId,
967
1228
  senderDeviceId: this.deviceId,
968
1229
  deliveryMode: this.sealedSenderDeliveryMode,
969
- preparePayload: async (groupId, bytes, sendOptions) => {
970
- const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions, sessions);
1230
+ preparePayload: async (groupId, bytes, sendOptions, readMembers) => {
1231
+ const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions, sessions, readMembers, stopSignal);
971
1232
  return {
972
1233
  ciphertext: CryptoUtils.bytesToBase64(prepared.ciphertext),
973
1234
  preMessages: prepared.preMessages,
@@ -977,7 +1238,7 @@ export class SignalProtocolServiceCipher {
977
1238
  };
978
1239
  },
979
1240
  confirmSenderKeyDistributionSent: (groupId, senderKeyId) => this.senderKeyManager.confirmSenderKeyDistributionSent(groupId, this.userId, this.deviceId, senderKeyId),
980
- resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions),
1241
+ resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions, stopSignal),
981
1242
  prepareSharedMessage: async (groupId, members, ciphertext) => {
982
1243
  if (members.length === 0 ||
983
1244
  this.sealedSenderDeliveryMode === 'disabled' ||
@@ -1027,7 +1288,12 @@ export class SignalProtocolServiceCipher {
1027
1288
  sentMessageBase64: message.sealedSenderMessage,
1028
1289
  auth,
1029
1290
  deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
1291
+ }, control),
1292
+ prepareEach: (items, task) => this.fanOut.all(items, task).catch((error) => {
1293
+ throw firstItemError(error);
1030
1294
  }),
1295
+ sendPhase: (messages, task, phase) => this.sendPhase(messages, task, phase, stopSignal),
1296
+ postToRelay: (send, sealed) => this.postToRelay(send, sealed, control),
1031
1297
  }, actualGroupId, plaintextBytes, options);
1032
1298
  }
1033
1299
  async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp) {
@@ -1057,14 +1323,19 @@ export class SignalProtocolServiceCipher {
1057
1323
  const manager = this.endorsementManagerResolver ? await this.endorsementManagerResolver() : this.endorsementManager;
1058
1324
  if (!manager || recipientUserIds.length === 0)
1059
1325
  return null;
1060
- const { needsRefresh, reason } = await manager.shouldRefreshEndorsements(groupId, recipientUserIds);
1061
- if (needsRefresh && this.endorsementRefresher) {
1062
- await this.endorsementRefresher(groupId, recipientUserIds);
1063
- this.logger.debug('Refreshed endorsements before durable group send', {
1064
- category: 'E2EE',
1065
- data: { groupId, reason },
1066
- });
1067
- }
1326
+ // The device posts of a send run at the same time. The lock makes them
1327
+ // check and refresh the group's endorsements one at a time, so one
1328
+ // refresh serves them all. The lock is taken before a slot.
1329
+ await this.lock.acquire(`group-send-endorsements:${groupId}`, async () => {
1330
+ const { needsRefresh, reason } = await manager.shouldRefreshEndorsements(groupId, recipientUserIds);
1331
+ if (needsRefresh && this.endorsementRefresher) {
1332
+ await this.endorsementRefresher(groupId, recipientUserIds);
1333
+ this.logger.debug('Refreshed endorsements before durable group send', {
1334
+ category: 'E2EE',
1335
+ data: { groupId, reason },
1336
+ });
1337
+ }
1338
+ });
1068
1339
  const groupSecretParams = this.groupSecretParamsProvider
1069
1340
  ? await this.groupSecretParamsProvider(groupId)
1070
1341
  : null;
@@ -1143,8 +1414,11 @@ export class SignalProtocolServiceCipher {
1143
1414
  * | UNKNOWN | DISABLED | Confirmed doesn't work |
1144
1415
  *
1145
1416
  */
1146
- async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender) {
1417
+ async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender, control = {}) {
1147
1418
  const effectiveClientMessageId = msg.clientMessageId ?? clientMessageId;
1419
+ // A fallback continues a post that started, so only the first request is
1420
+ // admitted.
1421
+ let identifiedControl = control;
1148
1422
  if (preparedSealedSender && !this.relay.sendMultiRecipientUnidentified) {
1149
1423
  if (preparedSealedSender.deliveryMode === 'required') {
1150
1424
  throw new EncryptionError('Required sealed-sender relay capability is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: msg.recipientUserId });
@@ -1164,8 +1438,9 @@ export class SignalProtocolServiceCipher {
1164
1438
  : undefined);
1165
1439
  if (!prepared)
1166
1440
  throw new Error('Missing sealed-sender delivery state');
1441
+ identifiedControl = { ...(control.stopSignal && { stopSignal: control.stopSignal }) };
1167
1442
  try {
1168
- const result = await this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId);
1443
+ const result = await this.postToRelay(() => this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId), true, control);
1169
1444
  if (result.uuids404.length > 0) {
1170
1445
  throw new SealedSenderRecipientRejectedError();
1171
1446
  }
@@ -1180,27 +1455,33 @@ export class SignalProtocolServiceCipher {
1180
1455
  }
1181
1456
  // Restrict the cached mode after authorization fails.
1182
1457
  try {
1183
- if (this.contactProfileStateStore) {
1184
- const currentMode = await this.contactProfileStateStore.getUnidentifiedAccessMode(msg.recipientUserId);
1185
- let newMode;
1186
- switch (currentMode) {
1187
- case UnidentifiedAccessMode.UNRESTRICTED:
1188
- newMode = UnidentifiedAccessMode.UNKNOWN;
1189
- break;
1190
- case UnidentifiedAccessMode.ENABLED:
1191
- case UnidentifiedAccessMode.UNKNOWN:
1192
- default:
1193
- newMode = UnidentifiedAccessMode.DISABLED;
1194
- break;
1195
- }
1196
- await this.contactProfileStateStore.updateUnidentifiedAccessMode(msg.recipientUserId, newMode);
1197
- this.logger.info('Sealed sender auth failed, transitioned mode and falling back to identified delivery', {
1198
- category: 'E2EE',
1199
- data: {
1200
- recipientUserId: msg.recipientUserId,
1201
- previousMode: currentMode,
1202
- newMode,
1203
- },
1458
+ const contactProfileStateStore = this.contactProfileStateStore;
1459
+ if (contactProfileStateStore) {
1460
+ // The device posts of a send run at the same time. The lock
1461
+ // orders their steps, so two failures step down twice, as posts
1462
+ // in device order do.
1463
+ await this.lock.acquire(`unidentified-access-mode:${msg.recipientUserId}`, async () => {
1464
+ const currentMode = await contactProfileStateStore.getUnidentifiedAccessMode(msg.recipientUserId);
1465
+ let newMode;
1466
+ switch (currentMode) {
1467
+ case UnidentifiedAccessMode.UNRESTRICTED:
1468
+ newMode = UnidentifiedAccessMode.UNKNOWN;
1469
+ break;
1470
+ case UnidentifiedAccessMode.ENABLED:
1471
+ case UnidentifiedAccessMode.UNKNOWN:
1472
+ default:
1473
+ newMode = UnidentifiedAccessMode.DISABLED;
1474
+ break;
1475
+ }
1476
+ await contactProfileStateStore.updateUnidentifiedAccessMode(msg.recipientUserId, newMode);
1477
+ this.logger.info('Sealed sender auth failed, transitioned mode and falling back to identified delivery', {
1478
+ category: 'E2EE',
1479
+ data: {
1480
+ recipientUserId: msg.recipientUserId,
1481
+ previousMode: currentMode,
1482
+ newMode,
1483
+ },
1484
+ });
1204
1485
  });
1205
1486
  }
1206
1487
  else {
@@ -1229,7 +1510,7 @@ export class SignalProtocolServiceCipher {
1229
1510
  }
1230
1511
  }
1231
1512
  // Identified sender path: standard relay send
1232
- return this.relay.send({
1513
+ return this.postToRelay(() => this.relay.send({
1233
1514
  targetUserId: msg.recipientUserId,
1234
1515
  targetDeviceId: msg.recipientDeviceId,
1235
1516
  senderUserId: this.userId,
@@ -1241,7 +1522,7 @@ export class SignalProtocolServiceCipher {
1241
1522
  clientMessageId: effectiveClientMessageId,
1242
1523
  recipientRegistrationId,
1243
1524
  contentHint,
1244
- });
1525
+ }), false, identifiedControl);
1245
1526
  }
1246
1527
  /**
1247
1528
  * Resolve the group roster to concrete devices via the relay.
@@ -1252,16 +1533,20 @@ export class SignalProtocolServiceCipher {
1252
1533
  * map. A groupId → member lookup would hand the relay the social graph
1253
1534
  * the zero-knowledge group design exists to hide.
1254
1535
  */
1255
- async resolveGroupMemberDevices(groupId, options) {
1536
+ async resolveGroupMemberDevices(groupId, options, stopSignal) {
1256
1537
  if (!options?.groupMemberUserIds?.length) {
1257
1538
  throw new EncryptionError(`Group send for ${groupId} requires options.groupMemberUserIds. ` +
1258
1539
  'The relay keeps no server-side membership map; resolve the roster ' +
1259
1540
  'from local group state and pass the member user IDs.', EncryptionErrorCode.ENCRYPTION_FAILED, { groupId });
1260
1541
  }
1261
- const deviceResults = await Promise.all(options.groupMemberUserIds.map((userId) => this.relay.getActiveDevices(userId)));
1542
+ const deviceResults = await this.fanOut
1543
+ .all(options.groupMemberUserIds, (userId) => this.fanOut.request(() => this.relay.getActiveDevices(userId), stopSignal), stopSignal)
1544
+ .catch((error) => {
1545
+ throw firstItemError(error);
1546
+ });
1262
1547
  return deviceResults.flat();
1263
1548
  }
1264
- async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options, sessions) {
1549
+ async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options, sessions, readMembers, stopSignal) {
1265
1550
  const existingKey = await this.storage.getSenderKey(actualGroupId, this.userId, this.deviceId);
1266
1551
  if (!existingKey) {
1267
1552
  throw new EncryptionError(`No sender key for group ${actualGroupId}. Call createGroupSenderKey() first to create and distribute the key.`, EncryptionErrorCode.SESSION_NOT_FOUND, {
@@ -1292,28 +1577,40 @@ export class SignalProtocolServiceCipher {
1292
1577
  }
1293
1578
  const preMessages = [];
1294
1579
  if (this.relay) {
1295
- const members = await this.resolveGroupMemberDevices(actualGroupId, options);
1580
+ const members = await readMembers();
1296
1581
  const otherMembers = members.filter((member) => member.userId !== this.userId);
1297
1582
  const recipientUserIds = [...new Set(otherMembers.map((member) => member.userId))];
1298
- for (const recipientUserId of recipientUserIds) {
1299
- await this.ensureSessionsForUser(recipientUserId, sessions);
1300
- const skdmBytes = this.contentAdapter
1301
- ? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
1302
- : new TextEncoder().encode(JSON.stringify({
1303
- senderKeyDistributionMessage: JSON.stringify({
1304
- groupId: actualGroupId,
1305
- ...distributionMessage,
1306
- }),
1307
- }));
1583
+ const skdmBytes = this.contentAdapter
1584
+ ? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
1585
+ : new TextEncoder().encode(JSON.stringify({
1586
+ senderKeyDistributionMessage: JSON.stringify({
1587
+ groupId: actualGroupId,
1588
+ ...distributionMessage,
1589
+ }),
1590
+ }));
1591
+ // The recipients are prepared at the same time. The session work of one
1592
+ // recipient stays in turn, and its session setup reuses the devices that
1593
+ // this send read.
1594
+ const prepared = await this.fanOut
1595
+ .all(recipientUserIds, async (recipientUserId) => {
1596
+ await this.ensureSessionsForUser(recipientUserId, sessions, false, otherMembers.filter((member) => member.userId === recipientUserId));
1308
1597
  const batch = await this.sesameManager.send(recipientUserId, skdmBytes, {
1309
1598
  clientTimestamp: options.timestamp,
1310
1599
  includeSyncMessages: false,
1311
1600
  });
1601
+ const stored = [];
1312
1602
  for (const message of batch.deviceMessages) {
1313
- const stored = await this.prepareStoredDirectDeviceMessage(message, null);
1314
- stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
1315
- preMessages.push(stored);
1603
+ stored.push(await this.prepareStoredDirectDeviceMessage(message, null));
1316
1604
  }
1605
+ return stored;
1606
+ }, stopSignal)
1607
+ .catch((error) => {
1608
+ throw firstItemError(error);
1609
+ });
1610
+ // The index of each pre-message follows the recipient order.
1611
+ for (const stored of prepared.flat()) {
1612
+ stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
1613
+ preMessages.push(stored);
1317
1614
  }
1318
1615
  }
1319
1616
  return {
@@ -1328,10 +1625,12 @@ export class SignalProtocolServiceCipher {
1328
1625
  * Uses the multi-recipient sealed-sender transport when anonymous delivery
1329
1626
  * is available, with exact per-device identified delivery otherwise.
1330
1627
  */
1331
- async encryptToGroup(groupId, plaintextBytes, options, sessions) {
1332
- const actualGroupId = extractGroupId(groupId);
1333
- await this.groupSendBarrierChecker?.(actualGroupId);
1334
- return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions);
1628
+ async encryptToGroup(groupId, plaintextBytes, options, sessions, stopSignal) {
1629
+ // The group operation owns preparation, persistence, posting, and key confirmation.
1630
+ return this.groupSenderKeys.run(groupId, async (actualGroupId) => {
1631
+ await this.groupSendBarrierChecker?.(actualGroupId);
1632
+ return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal);
1633
+ }, stopSignal);
1335
1634
  }
1336
1635
  /**
1337
1636
  * Encrypt binary attachment with two-layer encryption
@@ -1350,7 +1649,7 @@ export class SignalProtocolServiceCipher {
1350
1649
  *
1351
1650
  * @see https://developers.google.com/tink/streaming-aead/aes_gcm_hkdf_streaming
1352
1651
  */
1353
- async encryptBinaryAttachment(recipientId, data, options, sessions) {
1652
+ async encryptBinaryAttachment(recipientId, data, options, sessions, stopSignal) {
1354
1653
  if (!this.relay) {
1355
1654
  throw new EncryptionError('Relay server not configured. Cannot send attachments without server connection.', EncryptionErrorCode.INITIALIZATION_FAILED);
1356
1655
  }
@@ -1362,7 +1661,7 @@ export class SignalProtocolServiceCipher {
1362
1661
  const attachmentBytes = new TextEncoder().encode(attachmentPayload);
1363
1662
  let result;
1364
1663
  if (isGroupId(recipientId)) {
1365
- result = await this.encryptToGroup(recipientId, attachmentBytes, options, sessions);
1664
+ result = await this.encryptToGroup(recipientId, attachmentBytes, options, sessions, stopSignal);
1366
1665
  }
1367
1666
  else {
1368
1667
  result = await this.encryptToUser(recipientId, attachmentBytes, options, sessions);