@open-e2ee/signal-protocol-sdk 11.0.0 → 12.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 (583) hide show
  1. package/ADAPTERS.md +4 -4
  2. package/ARCHITECTURE.md +6 -8
  3. package/CHANGELOG.md +1315 -0
  4. package/README.md +1 -1
  5. package/SECURITY.md +2 -2
  6. package/TROUBLESHOOTING.md +1 -1
  7. package/client/README.md +70 -37
  8. package/device/README.md +39 -85
  9. package/dist/client/client.d.ts +334 -63
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +1168 -184
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/client/config.d.ts +40 -32
  14. package/dist/client/config.d.ts.map +1 -1
  15. package/dist/client/config.js +1 -1
  16. package/dist/client/config.js.map +1 -1
  17. package/dist/client/constants.d.ts +42 -8
  18. package/dist/client/constants.d.ts.map +1 -1
  19. package/dist/client/constants.js +48 -3
  20. package/dist/client/constants.js.map +1 -1
  21. package/dist/client/content-adapter.d.ts +80 -0
  22. package/dist/client/content-adapter.d.ts.map +1 -1
  23. package/dist/client/content-adapter.js +225 -12
  24. package/dist/client/content-adapter.js.map +1 -1
  25. package/dist/client/delivery-error.d.ts +150 -0
  26. package/dist/client/delivery-error.d.ts.map +1 -0
  27. package/dist/client/delivery-error.js +226 -0
  28. package/dist/client/delivery-error.js.map +1 -0
  29. package/dist/client/delivery-status.d.ts +32 -6
  30. package/dist/client/delivery-status.d.ts.map +1 -1
  31. package/dist/client/delivery-status.js +61 -13
  32. package/dist/client/delivery-status.js.map +1 -1
  33. package/dist/client/device-set-reconciliation.d.ts +196 -0
  34. package/dist/client/device-set-reconciliation.d.ts.map +1 -0
  35. package/dist/client/device-set-reconciliation.js +282 -0
  36. package/dist/client/device-set-reconciliation.js.map +1 -0
  37. package/dist/client/distribution-records.d.ts +29 -0
  38. package/dist/client/distribution-records.d.ts.map +1 -0
  39. package/dist/client/distribution-records.js +33 -0
  40. package/dist/client/distribution-records.js.map +1 -0
  41. package/dist/client/event-hooks.d.ts +280 -14
  42. package/dist/client/event-hooks.d.ts.map +1 -1
  43. package/dist/client/event-hooks.js +8 -0
  44. package/dist/client/event-hooks.js.map +1 -1
  45. package/dist/client/group-device-set.d.ts +47 -0
  46. package/dist/client/group-device-set.d.ts.map +1 -0
  47. package/dist/client/group-device-set.js +65 -0
  48. package/dist/client/group-device-set.js.map +1 -0
  49. package/dist/client/group-fetcher.d.ts +116 -0
  50. package/dist/client/group-fetcher.d.ts.map +1 -0
  51. package/dist/client/group-fetcher.js +598 -0
  52. package/dist/client/group-fetcher.js.map +1 -0
  53. package/dist/client/group-outbox.d.ts +172 -10
  54. package/dist/client/group-outbox.d.ts.map +1 -1
  55. package/dist/client/group-outbox.js +915 -74
  56. package/dist/client/group-outbox.js.map +1 -1
  57. package/dist/client/group-receive-authorization.d.ts +127 -4
  58. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  59. package/dist/client/group-receive-authorization.js +270 -20
  60. package/dist/client/group-receive-authorization.js.map +1 -1
  61. package/dist/client/group-sealed-sender.d.ts +3 -0
  62. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  63. package/dist/client/group-sealed-sender.js +1 -0
  64. package/dist/client/group-sealed-sender.js.map +1 -1
  65. package/dist/client/group-sender-key-operations.d.ts +14 -3
  66. package/dist/client/group-sender-key-operations.d.ts.map +1 -1
  67. package/dist/client/group-sender-key-operations.js +26 -5
  68. package/dist/client/group-sender-key-operations.js.map +1 -1
  69. package/dist/client/groups.d.ts +5 -5
  70. package/dist/client/groups.d.ts.map +1 -1
  71. package/dist/client/groups.js +5 -4
  72. package/dist/client/groups.js.map +1 -1
  73. package/dist/client/hosted-anonymous-delivery.d.ts +61 -9
  74. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  75. package/dist/client/hosted-anonymous-delivery.js +242 -48
  76. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  77. package/dist/client/hosted-assertion-id.d.ts +7 -0
  78. package/dist/client/hosted-assertion-id.d.ts.map +1 -0
  79. package/dist/client/hosted-assertion-id.js +51 -0
  80. package/dist/client/hosted-assertion-id.js.map +1 -0
  81. package/dist/client/hosted-mailbox-subscription.d.ts +34 -2
  82. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  83. package/dist/client/hosted-mailbox-subscription.js +87 -17
  84. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  85. package/dist/client/hosted-push.d.ts +22 -4
  86. package/dist/client/hosted-push.d.ts.map +1 -1
  87. package/dist/client/hosted-push.js +75 -22
  88. package/dist/client/hosted-push.js.map +1 -1
  89. package/dist/client/hosted-transport.d.ts +22 -28
  90. package/dist/client/hosted-transport.d.ts.map +1 -1
  91. package/dist/client/hosted-transport.js +115 -55
  92. package/dist/client/hosted-transport.js.map +1 -1
  93. package/dist/client/hosted.d.ts +10 -4
  94. package/dist/client/hosted.d.ts.map +1 -1
  95. package/dist/client/hosted.js +10 -4
  96. package/dist/client/hosted.js.map +1 -1
  97. package/dist/client/index.d.ts +5 -3
  98. package/dist/client/index.d.ts.map +1 -1
  99. package/dist/client/index.js +2 -0
  100. package/dist/client/index.js.map +1 -1
  101. package/dist/client/messages.d.ts +25 -3
  102. package/dist/client/messages.d.ts.map +1 -1
  103. package/dist/client/messages.js +111 -20
  104. package/dist/client/messages.js.map +1 -1
  105. package/dist/client/receive-admission.d.ts +58 -0
  106. package/dist/client/receive-admission.d.ts.map +1 -0
  107. package/dist/client/receive-admission.js +78 -0
  108. package/dist/client/receive-admission.js.map +1 -0
  109. package/dist/client/receive-expiry.d.ts +31 -0
  110. package/dist/client/receive-expiry.d.ts.map +1 -0
  111. package/dist/client/receive-expiry.js +35 -0
  112. package/dist/client/receive-expiry.js.map +1 -0
  113. package/dist/client/receive-hook-bound.d.ts +50 -0
  114. package/dist/client/receive-hook-bound.d.ts.map +1 -0
  115. package/dist/client/receive-hook-bound.js +115 -0
  116. package/dist/client/receive-hook-bound.js.map +1 -0
  117. package/dist/client/receive-queue.d.ts +299 -0
  118. package/dist/client/receive-queue.d.ts.map +1 -0
  119. package/dist/client/receive-queue.js +1420 -0
  120. package/dist/client/receive-queue.js.map +1 -0
  121. package/dist/client/receive-work-seed.d.ts +54 -0
  122. package/dist/client/receive-work-seed.d.ts.map +1 -0
  123. package/dist/client/receive-work-seed.js +116 -0
  124. package/dist/client/receive-work-seed.js.map +1 -0
  125. package/dist/client/recovery-driver.d.ts +25 -0
  126. package/dist/client/recovery-driver.d.ts.map +1 -0
  127. package/dist/client/recovery-driver.js +121 -0
  128. package/dist/client/recovery-driver.js.map +1 -0
  129. package/dist/client/relay-acceptance.d.ts +20 -7
  130. package/dist/client/relay-acceptance.d.ts.map +1 -1
  131. package/dist/client/relay-acceptance.js +30 -12
  132. package/dist/client/relay-acceptance.js.map +1 -1
  133. package/dist/client/relay-device-refusal.d.ts +18 -0
  134. package/dist/client/relay-device-refusal.d.ts.map +1 -1
  135. package/dist/client/relay-device-refusal.js +31 -0
  136. package/dist/client/relay-device-refusal.js.map +1 -1
  137. package/dist/client/relay-sealed-route.d.ts +36 -0
  138. package/dist/client/relay-sealed-route.d.ts.map +1 -0
  139. package/dist/client/relay-sealed-route.js +45 -0
  140. package/dist/client/relay-sealed-route.js.map +1 -0
  141. package/dist/client/relay-subscription.d.ts +56 -13
  142. package/dist/client/relay-subscription.d.ts.map +1 -1
  143. package/dist/client/relay-subscription.js +193 -123
  144. package/dist/client/relay-subscription.js.map +1 -1
  145. package/dist/client/resendable-content.d.ts +98 -0
  146. package/dist/client/resendable-content.d.ts.map +1 -0
  147. package/dist/client/resendable-content.js +136 -0
  148. package/dist/client/resendable-content.js.map +1 -0
  149. package/dist/client/retry-family.d.ts +57 -10
  150. package/dist/client/retry-family.d.ts.map +1 -1
  151. package/dist/client/retry-family.js +54 -12
  152. package/dist/client/retry-family.js.map +1 -1
  153. package/dist/client/retry-request-envelope.d.ts +107 -8
  154. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  155. package/dist/client/retry-request-envelope.js +172 -23
  156. package/dist/client/retry-request-envelope.js.map +1 -1
  157. package/dist/client/retry-request-lifecycle.d.ts +70 -14
  158. package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
  159. package/dist/client/retry-request-lifecycle.js +162 -32
  160. package/dist/client/retry-request-lifecycle.js.map +1 -1
  161. package/dist/client/retry-terminal-recovery.d.ts +100 -0
  162. package/dist/client/retry-terminal-recovery.d.ts.map +1 -0
  163. package/dist/client/retry-terminal-recovery.js +164 -0
  164. package/dist/client/retry-terminal-recovery.js.map +1 -0
  165. package/dist/client/retry-utils.d.ts +27 -0
  166. package/dist/client/retry-utils.d.ts.map +1 -1
  167. package/dist/client/retry-utils.js +46 -0
  168. package/dist/client/retry-utils.js.map +1 -1
  169. package/dist/client/retry.d.ts +100 -12
  170. package/dist/client/retry.d.ts.map +1 -1
  171. package/dist/client/retry.js +619 -116
  172. package/dist/client/retry.js.map +1 -1
  173. package/dist/client/sealed-sender.d.ts +23 -6
  174. package/dist/client/sealed-sender.d.ts.map +1 -1
  175. package/dist/client/sealed-sender.js +30 -6
  176. package/dist/client/sealed-sender.js.map +1 -1
  177. package/dist/client/sessions.d.ts +2 -2
  178. package/dist/client/sessions.js +2 -2
  179. package/dist/client/signal-service-cipher.d.ts +726 -19
  180. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  181. package/dist/client/signal-service-cipher.js +2260 -342
  182. package/dist/client/signal-service-cipher.js.map +1 -1
  183. package/dist/client/state.d.ts +5 -0
  184. package/dist/client/state.d.ts.map +1 -1
  185. package/dist/client/state.js +11 -1
  186. package/dist/client/state.js.map +1 -1
  187. package/dist/client/storage-protection.d.ts +64 -0
  188. package/dist/client/storage-protection.d.ts.map +1 -0
  189. package/dist/client/storage-protection.js +150 -0
  190. package/dist/client/storage-protection.js.map +1 -0
  191. package/dist/client/types.d.ts +149 -15
  192. package/dist/client/types.d.ts.map +1 -1
  193. package/dist/client/types.js +1 -1
  194. package/dist/client/types.js.map +1 -1
  195. package/dist/device/constants.d.ts +0 -5
  196. package/dist/device/constants.d.ts.map +1 -1
  197. package/dist/device/constants.js +0 -5
  198. package/dist/device/constants.js.map +1 -1
  199. package/dist/device/expo/index.d.ts +4 -17
  200. package/dist/device/expo/index.d.ts.map +1 -1
  201. package/dist/device/expo/index.js +4 -23
  202. package/dist/device/expo/index.js.map +1 -1
  203. package/dist/device/index.d.ts +0 -2
  204. package/dist/device/index.d.ts.map +1 -1
  205. package/dist/device/index.js +0 -7
  206. package/dist/device/index.js.map +1 -1
  207. package/dist/device/lifecycle/manager.d.ts +5 -4
  208. package/dist/device/lifecycle/manager.d.ts.map +1 -1
  209. package/dist/device/lifecycle/manager.js +16 -16
  210. package/dist/device/lifecycle/manager.js.map +1 -1
  211. package/dist/device/lifecycle/types.d.ts +2 -2
  212. package/dist/device/lifecycle/types.d.ts.map +1 -1
  213. package/dist/device/react-native/index.d.ts +4 -15
  214. package/dist/device/react-native/index.d.ts.map +1 -1
  215. package/dist/device/react-native/index.js +4 -21
  216. package/dist/device/react-native/index.js.map +1 -1
  217. package/dist/device/types.d.ts +1 -1
  218. package/dist/groups/index.d.ts +1 -1
  219. package/dist/groups/index.d.ts.map +1 -1
  220. package/dist/index.d.ts +8 -6
  221. package/dist/index.d.ts.map +1 -1
  222. package/dist/index.js +2 -1
  223. package/dist/index.js.map +1 -1
  224. package/dist/internal/crypto/ec/x25519-validation.d.ts +0 -1
  225. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  226. package/dist/internal/crypto/ec/x25519-validation.js +0 -1
  227. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  228. package/dist/internal/crypto/validation.d.ts +2 -2
  229. package/dist/internal/groups/index.d.ts +1 -0
  230. package/dist/internal/groups/index.d.ts.map +1 -1
  231. package/dist/internal/groups/index.js +1 -0
  232. package/dist/internal/groups/index.js.map +1 -1
  233. package/dist/internal/groups/manager.d.ts +37 -16
  234. package/dist/internal/groups/manager.d.ts.map +1 -1
  235. package/dist/internal/groups/manager.js +46 -1
  236. package/dist/internal/groups/manager.js.map +1 -1
  237. package/dist/internal/groups/receive-record.d.ts +78 -0
  238. package/dist/internal/groups/receive-record.d.ts.map +1 -0
  239. package/dist/internal/groups/receive-record.js +43 -0
  240. package/dist/internal/groups/receive-record.js.map +1 -0
  241. package/dist/internal/groups/sdk-store.d.ts +27 -3
  242. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  243. package/dist/internal/groups/sdk-store.js +151 -19
  244. package/dist/internal/groups/sdk-store.js.map +1 -1
  245. package/dist/internal/groups/wire.d.ts +12 -1
  246. package/dist/internal/groups/wire.d.ts.map +1 -1
  247. package/dist/internal/groups/wire.js +36 -0
  248. package/dist/internal/groups/wire.js.map +1 -1
  249. package/dist/internal/manager/index.d.ts +1 -1
  250. package/dist/internal/manager/manager.d.ts +20 -19
  251. package/dist/internal/manager/manager.d.ts.map +1 -1
  252. package/dist/internal/manager/manager.js +56 -39
  253. package/dist/internal/manager/manager.js.map +1 -1
  254. package/dist/internal/protocol/double-ratchet/chains.d.ts +4 -18
  255. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  256. package/dist/internal/protocol/double-ratchet/chains.js +23 -74
  257. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  258. package/dist/internal/protocol/double-ratchet/index.d.ts +1 -1
  259. package/dist/internal/protocol/double-ratchet/index.d.ts.map +1 -1
  260. package/dist/internal/protocol/double-ratchet/index.js +1 -1
  261. package/dist/internal/protocol/double-ratchet/index.js.map +1 -1
  262. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +5 -7
  263. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  264. package/dist/internal/protocol/double-ratchet/ratchet.js +4 -6
  265. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  266. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  267. package/dist/internal/protocol/pqxdh/pqxdh.js +2 -1
  268. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  269. package/dist/internal/protocol/sealed-sender/types.d.ts +6 -8
  270. package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
  271. package/dist/internal/protocol/sealed-sender/types.js +8 -9
  272. package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
  273. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts +110 -0
  274. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts.map +1 -0
  275. package/dist/internal/protocol/sender-keys/handoff-ledger.js +124 -0
  276. package/dist/internal/protocol/sender-keys/handoff-ledger.js.map +1 -0
  277. package/dist/internal/protocol/sender-keys/manager.d.ts +71 -62
  278. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  279. package/dist/internal/protocol/sender-keys/manager.js +228 -175
  280. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  281. package/dist/internal/protocol/spqr/index.d.ts +2 -2
  282. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  283. package/dist/internal/protocol/spqr/index.js +2 -2
  284. package/dist/internal/protocol/spqr/index.js.map +1 -1
  285. package/dist/internal/protocol/spqr/serialize.d.ts +9 -1
  286. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  287. package/dist/internal/protocol/spqr/serialize.js +56 -16
  288. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  289. package/dist/internal/protocol/spqr/spqr.d.ts +1 -14
  290. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  291. package/dist/internal/protocol/spqr/spqr.js +54 -42
  292. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  293. package/dist/internal/protocol/spqr/validate.d.ts +26 -6
  294. package/dist/internal/protocol/spqr/validate.d.ts.map +1 -1
  295. package/dist/internal/protocol/spqr/validate.js +49 -21
  296. package/dist/internal/protocol/spqr/validate.js.map +1 -1
  297. package/dist/internal/sesame/index.d.ts +1 -1
  298. package/dist/internal/sesame/index.d.ts.map +1 -1
  299. package/dist/internal/sesame/index.js.map +1 -1
  300. package/dist/internal/sesame/manager.d.ts +66 -13
  301. package/dist/internal/sesame/manager.d.ts.map +1 -1
  302. package/dist/internal/sesame/manager.js +221 -87
  303. package/dist/internal/sesame/manager.js.map +1 -1
  304. package/dist/internal/sesame/types.d.ts +95 -17
  305. package/dist/internal/sesame/types.d.ts.map +1 -1
  306. package/dist/internal/sesame/types.js +17 -0
  307. package/dist/internal/sesame/types.js.map +1 -1
  308. package/dist/internal/session/builder.d.ts +5 -5
  309. package/dist/internal/session/builder.d.ts.map +1 -1
  310. package/dist/internal/session/builder.js +12 -17
  311. package/dist/internal/session/builder.js.map +1 -1
  312. package/dist/internal/session/cipher.d.ts +13 -11
  313. package/dist/internal/session/cipher.d.ts.map +1 -1
  314. package/dist/internal/session/cipher.js +40 -22
  315. package/dist/internal/session/cipher.js.map +1 -1
  316. package/dist/internal/session/factory.d.ts +5 -5
  317. package/dist/internal/session/factory.d.ts.map +1 -1
  318. package/dist/internal/session/factory.js +4 -4
  319. package/dist/internal/session/factory.js.map +1 -1
  320. package/dist/internal/session/handshake.d.ts +14 -16
  321. package/dist/internal/session/handshake.d.ts.map +1 -1
  322. package/dist/internal/session/handshake.js +18 -75
  323. package/dist/internal/session/handshake.js.map +1 -1
  324. package/dist/internal/session/index.d.ts +1 -1
  325. package/dist/internal/session/index.js +1 -1
  326. package/dist/internal/session/record-locks.d.ts +17 -6
  327. package/dist/internal/session/record-locks.d.ts.map +1 -1
  328. package/dist/internal/session/record-locks.js +43 -7
  329. package/dist/internal/session/record-locks.js.map +1 -1
  330. package/dist/internal/session/session-resolver.d.ts +1 -1
  331. package/dist/internal/session/session-resolver.js +1 -1
  332. package/dist/internal/session/state.d.ts +2 -2
  333. package/dist/internal/session/state.js +1 -1
  334. package/dist/internal/session/types.d.ts +4 -12
  335. package/dist/internal/session/types.d.ts.map +1 -1
  336. package/dist/internal/session/types.js +1 -1
  337. package/dist/keys/generation.d.ts +2 -2
  338. package/dist/keys/generation.js +2 -2
  339. package/dist/keys/types.d.ts +5 -5
  340. package/dist/keys/types.d.ts.map +1 -1
  341. package/dist/keys/types.js +1 -1
  342. package/dist/layers.d.ts +1 -1
  343. package/dist/layers.js +2 -2
  344. package/dist/layers.js.map +1 -1
  345. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  346. package/dist/local/store/expo/adapter.js +12 -8
  347. package/dist/local/store/expo/adapter.js.map +1 -1
  348. package/dist/local/store/key-value/adapter.d.ts +76 -10
  349. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  350. package/dist/local/store/key-value/adapter.js +367 -61
  351. package/dist/local/store/key-value/adapter.js.map +1 -1
  352. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
  353. package/dist/local/store/key-value/backend-conformance.js +74 -0
  354. package/dist/local/store/key-value/backend-conformance.js.map +1 -1
  355. package/dist/local/store/key-value/batch.d.ts +2 -0
  356. package/dist/local/store/key-value/batch.d.ts.map +1 -1
  357. package/dist/local/store/key-value/batch.js +26 -0
  358. package/dist/local/store/key-value/batch.js.map +1 -1
  359. package/dist/local/store/key-value/receive-work.d.ts +55 -0
  360. package/dist/local/store/key-value/receive-work.d.ts.map +1 -0
  361. package/dist/local/store/key-value/receive-work.js +162 -0
  362. package/dist/local/store/key-value/receive-work.js.map +1 -0
  363. package/dist/local/store/key-value/send-log.d.ts +61 -0
  364. package/dist/local/store/key-value/send-log.d.ts.map +1 -0
  365. package/dist/local/store/key-value/send-log.js +430 -0
  366. package/dist/local/store/key-value/send-log.js.map +1 -0
  367. package/dist/local/store/key-value/sender-key-handoff.d.ts +68 -0
  368. package/dist/local/store/key-value/sender-key-handoff.d.ts.map +1 -0
  369. package/dist/local/store/key-value/sender-key-handoff.js +189 -0
  370. package/dist/local/store/key-value/sender-key-handoff.js.map +1 -0
  371. package/dist/local/store/key-value/storage.d.ts +15 -0
  372. package/dist/local/store/key-value/storage.d.ts.map +1 -1
  373. package/dist/local/store/keyed-index.d.ts +23 -0
  374. package/dist/local/store/keyed-index.d.ts.map +1 -0
  375. package/dist/local/store/keyed-index.js +41 -0
  376. package/dist/local/store/keyed-index.js.map +1 -0
  377. package/dist/local/store/memory/adapter.d.ts +44 -12
  378. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  379. package/dist/local/store/memory/adapter.js +197 -46
  380. package/dist/local/store/memory/adapter.js.map +1 -1
  381. package/dist/local/store/memory/send-log.d.ts +42 -0
  382. package/dist/local/store/memory/send-log.d.ts.map +1 -0
  383. package/dist/local/store/memory/send-log.js +190 -0
  384. package/dist/local/store/memory/send-log.js.map +1 -0
  385. package/dist/local/store/node/adapter.d.ts.map +1 -1
  386. package/dist/local/store/node/adapter.js +8 -6
  387. package/dist/local/store/node/adapter.js.map +1 -1
  388. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  389. package/dist/local/store/react-native/adapter.js +12 -8
  390. package/dist/local/store/react-native/adapter.js.map +1 -1
  391. package/dist/local/store/receive-work.d.ts +87 -0
  392. package/dist/local/store/receive-work.d.ts.map +1 -0
  393. package/dist/local/store/receive-work.js +204 -0
  394. package/dist/local/store/receive-work.js.map +1 -0
  395. package/dist/local/store/received-content.d.ts +3 -3
  396. package/dist/local/store/received-content.d.ts.map +1 -1
  397. package/dist/local/store/received-content.js +2 -11
  398. package/dist/local/store/received-content.js.map +1 -1
  399. package/dist/local/store/reliability.d.ts +317 -18
  400. package/dist/local/store/reliability.d.ts.map +1 -1
  401. package/dist/local/store/reliability.js +371 -46
  402. package/dist/local/store/reliability.js.map +1 -1
  403. package/dist/local/store/send-log-order.d.ts +15 -0
  404. package/dist/local/store/send-log-order.d.ts.map +1 -0
  405. package/dist/local/store/send-log-order.js +24 -0
  406. package/dist/local/store/send-log-order.js.map +1 -0
  407. package/dist/local/store/sender-key-handoff-index.d.ts +38 -0
  408. package/dist/local/store/sender-key-handoff-index.d.ts.map +1 -0
  409. package/dist/local/store/sender-key-handoff-index.js +101 -0
  410. package/dist/local/store/sender-key-handoff-index.js.map +1 -0
  411. package/dist/local/store/sender-key-handoff-table.d.ts +29 -0
  412. package/dist/local/store/sender-key-handoff-table.d.ts.map +1 -0
  413. package/dist/local/store/sender-key-handoff-table.js +97 -0
  414. package/dist/local/store/sender-key-handoff-table.js.map +1 -0
  415. package/dist/local/store/sqlite/encryption.d.ts +8 -1
  416. package/dist/local/store/sqlite/encryption.d.ts.map +1 -1
  417. package/dist/local/store/sqlite/encryption.js +9 -0
  418. package/dist/local/store/sqlite/encryption.js.map +1 -1
  419. package/dist/local/store/sqlite/key-storage/index.d.ts +25 -4
  420. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  421. package/dist/local/store/sqlite/key-storage/index.js +68 -7
  422. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  423. package/dist/local/store/sqlite/key-storage/message-records.d.ts +16 -4
  424. package/dist/local/store/sqlite/key-storage/message-records.d.ts.map +1 -1
  425. package/dist/local/store/sqlite/key-storage/message-records.js +49 -6
  426. package/dist/local/store/sqlite/key-storage/message-records.js.map +1 -1
  427. package/dist/local/store/sqlite/key-storage/metadata.d.ts +8 -7
  428. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  429. package/dist/local/store/sqlite/key-storage/metadata.js +17 -15
  430. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  431. package/dist/local/store/sqlite/key-storage/receive-work.d.ts +27 -0
  432. package/dist/local/store/sqlite/key-storage/receive-work.d.ts.map +1 -0
  433. package/dist/local/store/sqlite/key-storage/receive-work.js +98 -0
  434. package/dist/local/store/sqlite/key-storage/receive-work.js.map +1 -0
  435. package/dist/local/store/sqlite/key-storage/send-log.d.ts +27 -0
  436. package/dist/local/store/sqlite/key-storage/send-log.d.ts.map +1 -0
  437. package/dist/local/store/sqlite/key-storage/send-log.js +178 -0
  438. package/dist/local/store/sqlite/key-storage/send-log.js.map +1 -0
  439. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts +27 -0
  440. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts.map +1 -0
  441. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js +75 -0
  442. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js.map +1 -0
  443. package/dist/local/store/sqlite/key-storage/session-trust.d.ts +2 -2
  444. package/dist/local/store/sqlite/key-storage/session-trust.js +5 -5
  445. package/dist/local/store/sqlite/key-storage/session-trust.js.map +1 -1
  446. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  447. package/dist/local/store/sqlite/migrations.js +101 -0
  448. package/dist/local/store/sqlite/migrations.js.map +1 -1
  449. package/dist/local/store/sqlite/models/index.d.ts +2 -1
  450. package/dist/local/store/sqlite/models/index.d.ts.map +1 -1
  451. package/dist/local/store/sqlite/models/index.js +5 -1
  452. package/dist/local/store/sqlite/models/index.js.map +1 -1
  453. package/dist/local/store/sqlite/models/message-record.d.ts +15 -0
  454. package/dist/local/store/sqlite/models/message-record.d.ts.map +1 -1
  455. package/dist/local/store/sqlite/models/message-record.js +24 -0
  456. package/dist/local/store/sqlite/models/message-record.js.map +1 -1
  457. package/dist/local/store/sqlite/models/send-log.d.ts +51 -0
  458. package/dist/local/store/sqlite/models/send-log.d.ts.map +1 -0
  459. package/dist/local/store/sqlite/models/send-log.js +206 -0
  460. package/dist/local/store/sqlite/models/send-log.js.map +1 -0
  461. package/dist/local/store/sqlite/open-store.d.ts +9 -1
  462. package/dist/local/store/sqlite/open-store.d.ts.map +1 -1
  463. package/dist/local/store/sqlite/open-store.js +20 -1
  464. package/dist/local/store/sqlite/open-store.js.map +1 -1
  465. package/dist/local/store/sqlite/schema.d.ts +34 -1
  466. package/dist/local/store/sqlite/schema.d.ts.map +1 -1
  467. package/dist/local/store/sqlite/schema.js +14 -0
  468. package/dist/local/store/sqlite/schema.js.map +1 -1
  469. package/dist/local/store/sqlite/store.d.ts +61 -11
  470. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  471. package/dist/local/store/sqlite/store.js +191 -27
  472. package/dist/local/store/sqlite/store.js.map +1 -1
  473. package/dist/local/store/web/adapter.d.ts +76 -8
  474. package/dist/local/store/web/adapter.d.ts.map +1 -1
  475. package/dist/local/store/web/adapter.js +579 -127
  476. package/dist/local/store/web/adapter.js.map +1 -1
  477. package/dist/local/store/web/receive-work.d.ts +57 -0
  478. package/dist/local/store/web/receive-work.d.ts.map +1 -0
  479. package/dist/local/store/web/receive-work.js +99 -0
  480. package/dist/local/store/web/receive-work.js.map +1 -0
  481. package/dist/local/store/web/send-log.d.ts +92 -0
  482. package/dist/local/store/web/send-log.d.ts.map +1 -0
  483. package/dist/local/store/web/send-log.js +267 -0
  484. package/dist/local/store/web/send-log.js.map +1 -0
  485. package/dist/local/store/web/sender-key-handoff.d.ts +81 -0
  486. package/dist/local/store/web/sender-key-handoff.d.ts.map +1 -0
  487. package/dist/local/store/web/sender-key-handoff.js +156 -0
  488. package/dist/local/store/web/sender-key-handoff.js.map +1 -0
  489. package/dist/local/store/web-sqlite/adapter.d.ts +2 -0
  490. package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -1
  491. package/dist/local/store/web-sqlite/adapter.js +12 -6
  492. package/dist/local/store/web-sqlite/adapter.js.map +1 -1
  493. package/dist/local/vault/custody.d.ts +8 -0
  494. package/dist/local/vault/custody.d.ts.map +1 -0
  495. package/dist/local/vault/custody.js +9 -0
  496. package/dist/local/vault/custody.js.map +1 -0
  497. package/dist/local/vault/electron-safe-storage.d.ts +3 -1
  498. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  499. package/dist/local/vault/electron-safe-storage.js +2 -0
  500. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  501. package/dist/local/vault/expo-secure-store.d.ts +3 -1
  502. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  503. package/dist/local/vault/expo-secure-store.js +2 -0
  504. package/dist/local/vault/expo-secure-store.js.map +1 -1
  505. package/dist/local/vault/indexed-db.d.ts +3 -1
  506. package/dist/local/vault/indexed-db.d.ts.map +1 -1
  507. package/dist/local/vault/indexed-db.js +2 -0
  508. package/dist/local/vault/indexed-db.js.map +1 -1
  509. package/dist/local/vault/react-native-keychain.d.ts +3 -1
  510. package/dist/local/vault/react-native-keychain.d.ts.map +1 -1
  511. package/dist/local/vault/react-native-keychain.js +2 -0
  512. package/dist/local/vault/react-native-keychain.js.map +1 -1
  513. package/dist/remote/relay/device-set.d.ts +94 -0
  514. package/dist/remote/relay/device-set.d.ts.map +1 -0
  515. package/dist/remote/relay/device-set.js +156 -0
  516. package/dist/remote/relay/device-set.js.map +1 -0
  517. package/dist/remote/relay/types.d.ts +92 -107
  518. package/dist/remote/relay/types.d.ts.map +1 -1
  519. package/dist/safety/core.d.ts +15 -6
  520. package/dist/safety/core.d.ts.map +1 -1
  521. package/dist/safety/core.js +41 -27
  522. package/dist/safety/core.js.map +1 -1
  523. package/dist/safety/index.d.ts +2 -1
  524. package/dist/safety/index.d.ts.map +1 -1
  525. package/dist/safety/index.js +12 -18
  526. package/dist/safety/index.js.map +1 -1
  527. package/dist/types/api.d.ts +707 -62
  528. package/dist/types/api.d.ts.map +1 -1
  529. package/dist/types/errors.d.ts +14 -33
  530. package/dist/types/errors.d.ts.map +1 -1
  531. package/dist/types/errors.js +14 -24
  532. package/dist/types/errors.js.map +1 -1
  533. package/dist/types/messages.d.ts +2 -2
  534. package/dist/types/messages.js +1 -1
  535. package/dist/types/protocol-config.d.ts +175 -42
  536. package/dist/types/protocol-config.d.ts.map +1 -1
  537. package/dist/types/protocol-config.js +19 -38
  538. package/dist/types/protocol-config.js.map +1 -1
  539. package/dist/types/protocol-constants.d.ts +6 -6
  540. package/dist/types/protocol-constants.js +6 -6
  541. package/dist/types/session.d.ts +7 -7
  542. package/dist/types/session.d.ts.map +1 -1
  543. package/dist/types/session.js +39 -21
  544. package/dist/types/session.js.map +1 -1
  545. package/dist/username/link.d.ts +2 -2
  546. package/dist/username/link.js +2 -2
  547. package/dist/utils/origin-lock.d.ts +45 -0
  548. package/dist/utils/origin-lock.d.ts.map +1 -0
  549. package/dist/utils/origin-lock.js +80 -0
  550. package/dist/utils/origin-lock.js.map +1 -0
  551. package/docs/ASSURANCE.md +6 -6
  552. package/docs/CLIENT_COMPOSITION.md +2 -2
  553. package/docs/DEVIATIONS.md +677 -182
  554. package/docs/E2EE.md +1 -1
  555. package/docs/ERROR_HANDLING.md +165 -2
  556. package/docs/GETTING_STARTED.md +7 -4
  557. package/docs/INTERFACES.md +1 -1
  558. package/docs/PACKAGE_SURFACE.md +6 -5
  559. package/docs/PROTOCOL_POLICY.md +102 -22
  560. package/docs/RECIPES.md +3 -15
  561. package/docs/SECURITY.md +90 -5
  562. package/keys/README.md +3 -3
  563. package/local/store/README.md +78 -14
  564. package/local/store/key-value/README.md +14 -3
  565. package/local/store/node/README.md +8 -3
  566. package/local/store/web/README.md +9 -0
  567. package/local/store/web-sqlite/README.md +14 -2
  568. package/local/vault/README.md +21 -0
  569. package/package.json +1 -6
  570. package/remote/README.md +0 -1
  571. package/remote/relay/README.md +2 -2
  572. package/dist/device/provisioning.d.ts +0 -242
  573. package/dist/device/provisioning.d.ts.map +0 -1
  574. package/dist/device/provisioning.js +0 -421
  575. package/dist/device/provisioning.js.map +0 -1
  576. package/dist/internal/protocol/x3dh/index.d.ts +0 -15
  577. package/dist/internal/protocol/x3dh/index.d.ts.map +0 -1
  578. package/dist/internal/protocol/x3dh/index.js +0 -13
  579. package/dist/internal/protocol/x3dh/index.js.map +0 -1
  580. package/dist/internal/protocol/x3dh/x3dh.d.ts +0 -131
  581. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +0 -1
  582. package/dist/internal/protocol/x3dh/x3dh.js +0 -261
  583. package/dist/internal/protocol/x3dh/x3dh.js.map +0 -1
@@ -19,21 +19,31 @@ import { SealedSenderAuthError } from '../types/errors.js';
19
19
  import { base64ToBytes } from '../internal/crypto/index.js';
20
20
  import { recordServerClockSample } from '../server-clock.js';
21
21
  import { ProtocolAddress } from '../types/address.js';
22
+ import { isRemovedDevice, } from '../internal/sesame/types.js';
22
23
  import { defaultSignalProtocolLogger } from '../logger.js';
24
+ import { SenderKeyHandoffLedger, } from '../internal/protocol/sender-keys/handoff-ledger.js';
23
25
  import { isGroupId, extractGroupId } from '../internal/groups/index.js';
26
+ import { GroupReceiveRefusedError, GroupReceiveUnavailableError, refuseSyncFromOtherAccount, classifyGroupContent, groupOfContext, } from './group-receive-authorization.js';
27
+ import { sizedReceiveWork } from '../local/store/receive-work.js';
28
+ import { envelopeCiphertextBytes } from './delivery-error.js';
24
29
  import { GroupSenderKeyOperations } from './group-sender-key-operations.js';
25
30
  import { ContentHint } from '../types/messages.js';
26
31
  import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
27
32
  import * as CryptoUtils from '../internal/crypto/index.js';
28
- import { completeOutgoingMessageIntent, getOutgoingMessageIntent, getRetryResend, reconcileOutgoingDirectDeviceMessages, replaceOutgoingDirectDeviceMessage, retryAttemptClientMessageId, retryNullMessageClientMessageId, retryRequestAttempt, retryResendClientMessageId, storeOutgoingMessageIntent, storeRetryResend, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
33
+ import { completeOutgoingMessageIntent, completeOutgoingSyncPhase, getOutgoingMessageIntent, markOutgoingDeviceSetUnresolved, outgoingMessageIntentResult, repairOutgoingDeviceSet, restartOutgoingDeviceSet, getRetryResend, getSentClientMessageIds, reconcileOutgoingDirectDeviceMessages, reconcileOutgoingSyncMessages, replaceOutgoingDirectDeviceMessage, replaceOutgoingGroupPreMessages, retryAttemptClientMessageId, retryNullMessageClientMessageId, retryRequestAttempt, retryResendClientMessageId, storeOutgoingMessageIntent, storeRetryResend, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
29
34
  import { FanOutError, firstItemError } from '../utils/bounded-fan-out.js';
30
35
  import { withRetry } from '../utils/retry.js';
31
36
  import { acquireUntilStopped, createRelayFanOut, RelayWorkStopped, relaySendsSealedUnderItsBound, rethrowRelayWorkStopped, } from './relay-work.js';
32
- import { refusesRemovedDevices, relayDeviceRefusal } from './relay-device-refusal.js';
37
+ import { markRelayDeviceRefusal, refusesRemovedDevices, relayDeviceRefusal, } from './relay-device-refusal.js';
33
38
  import { aggregateRelayAcceptance, relayOperationRefusal, } from './relay-acceptance.js';
39
+ import { forDirectSealedRoute, usedGroupRouteFallback } from './relay-sealed-route.js';
40
+ import { comparesDeviceSets, markDeviceSetRefusal } from '../remote/relay/device-set.js';
41
+ import { markRelayProtocolError, runDeviceSetPhase, waitUnlessStopped, syncPostReceipts, uncheckedDeclaredPost, } from './device-set-reconciliation.js';
34
42
  import { prepareGroupSharedMessage } from './group-sealed-sender.js';
35
- import { sendGroupWithExactOutbox } from './group-outbox.js';
36
- import { attachUnsealedEnvelope, reconstructEnvelope, resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, unsealMessage, } from './sealed-sender.js';
43
+ import { attachFailedGroup } from './retry-terminal-recovery.js';
44
+ import { sendGroupWithExactOutbox, } from './group-outbox.js';
45
+ import { groupDeviceKey, listedOwnDeviceChange } from './group-device-set.js';
46
+ import { attachUnsealedEnvelope, reconstructEnvelope, resolveSealedSenderContext as resolveSealedSenderSendContext, SealedRetryRequestReceived, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, unsealMessage, } from './sealed-sender.js';
37
47
  import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
38
48
  import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
39
49
  /**
@@ -42,6 +52,14 @@ import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
42
52
  * first send after it ends.
43
53
  */
44
54
  export const RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS = 60_000;
55
+ /**
56
+ * The Relay message ID of the sync copy of a send to one own device. The ID
57
+ * names the device, so a replay that adds or drops an own device keeps the
58
+ * ID of each other copy.
59
+ */
60
+ function syncMessageId(clientMessageId, message) {
61
+ return `${clientMessageId}:sync:device:${message.recipientDeviceId}`;
62
+ }
45
63
  /**
46
64
  * How old a recipient's device list can be for a direct send to post before
47
65
  * it reads the list again. Only a relay that refuses a removed device's
@@ -49,6 +67,38 @@ export const RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS = 60_000;
49
67
  * list that no read confirmed, not how long a removed device receives.
50
68
  */
51
69
  const RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS = 300_000;
70
+ /** The stored form of the terminal record of a declared phase. */
71
+ function storedDeviceSetUnresolved(unresolved) {
72
+ return {
73
+ phase: unresolved.phase,
74
+ reason: unresolved.reason,
75
+ restarts: unresolved.restarts,
76
+ ...(unresolved.lastRefusal && {
77
+ lastRefusal: {
78
+ code: unresolved.lastRefusal.code,
79
+ accounts: unresolved.lastRefusal.accounts.map((account) => ({
80
+ userId: account.userId,
81
+ missingDeviceIds: [...account.missingDeviceIds],
82
+ extraDeviceIds: [...account.extraDeviceIds],
83
+ staleDeviceIds: [...account.staleDeviceIds],
84
+ })),
85
+ },
86
+ }),
87
+ };
88
+ }
89
+ function declaredDeviceKey(device) {
90
+ return `${device.userId}\u0000${String(device.deviceId)}`;
91
+ }
92
+ /**
93
+ * The device IDs of a user record that are not marked removed. A removed
94
+ * record gets no fan-out, so a declared send neither declares it nor counts
95
+ * it as a held device.
96
+ */
97
+ function unremovedDeviceIds(record) {
98
+ return Array.from(record?.devices.entries() ?? [])
99
+ .filter(([, device]) => !isRemovedDevice(device))
100
+ .map(([deviceId]) => deviceId);
101
+ }
52
102
  /** A send-first post that waits for the reconcile pass. */
53
103
  class DeferredPost extends Error {
54
104
  constructor() {
@@ -91,7 +141,11 @@ function getEnvelopeMessageType(ciphertext) {
91
141
  }
92
142
  return 'ciphertext';
93
143
  }
94
- function attachClientMessageId(error, clientMessageId) {
144
+ /**
145
+ * Give a send error the logical-send identifier of its send, so
146
+ * `isOutgoingMessageError` is true for it.
147
+ */
148
+ export function attachClientMessageId(error, clientMessageId) {
95
149
  const normalized = error instanceof Error ? error : new Error(String(error));
96
150
  try {
97
151
  Object.defineProperty(normalized, 'clientMessageId', {
@@ -149,6 +203,16 @@ function isRefusalOfDevice(error, message) {
149
203
  const refusal = relayDeviceRefusal(error);
150
204
  return (refusal?.userId === message.recipientUserId && refusal.deviceId === message.recipientDeviceId);
151
205
  }
206
+ /**
207
+ * The transport identity of the repair of a refused pre-message or sync copy.
208
+ * The repair payload changed, so it needs an identity that the relay has not
209
+ * seen: `<id>:repair:1` for the first repair, and the next number for each
210
+ * later one.
211
+ */
212
+ function repairMessageId(refusedId) {
213
+ const repair = /^(.*):repair:(\d+)$/u.exec(refusedId);
214
+ return repair ? `${repair[1]}:repair:${Number(repair[2]) + 1}` : `${refusedId}:repair:1`;
215
+ }
152
216
  /** The client message ID of one attempt of a stored resend or null message. */
153
217
  function retryResendAttemptId(resend) {
154
218
  const id = resend.kind === 'resend'
@@ -189,18 +253,21 @@ export class SignalProtocolServiceCipher {
189
253
  fanOut;
190
254
  lock = new AsyncLock();
191
255
  groupSenderKeys;
256
+ senderKeyHandoffs;
192
257
  sessionCallbacks;
193
258
  recipientDeviceListCheckedAt = new Map();
194
259
  sealedSenderProvider;
195
260
  sealedSenderDeliveryMode = 'preferred';
196
261
  sealedSenderIdentifiedFallback;
262
+ relayProtocolErrorReporter;
197
263
  contactProfileStateStore;
198
264
  endorsementManager;
199
265
  endorsementManagerResolver;
200
266
  endorsementRefresher;
201
267
  groupSendBarrierChecker;
202
- groupReceiveAuthorizer;
268
+ groupReceiveEvaluator;
203
269
  groupSecretParamsProvider;
270
+ groupContextProvider;
204
271
  constructor(userId, deviceId, sesameManager, senderKeyManager, storage, relay, remoteObjectStore, contentAdapter, logger = defaultSignalProtocolLogger, fanOut = createRelayFanOut()) {
205
272
  this.userId = userId;
206
273
  this.deviceId = deviceId;
@@ -213,6 +280,7 @@ export class SignalProtocolServiceCipher {
213
280
  this.logger = logger;
214
281
  this.fanOut = fanOut;
215
282
  this.groupSenderKeys = new GroupSenderKeyOperations(storage, userId, deviceId);
283
+ this.senderKeyHandoffs = new SenderKeyHandoffLedger(storage);
216
284
  }
217
285
  getResolvedContentAdapter() {
218
286
  return this.contentAdapter ?? createDefaultSignalProtocolContentAdapter();
@@ -238,23 +306,142 @@ export class SignalProtocolServiceCipher {
238
306
  }
239
307
  return CryptoUtils.bytesToBase64(plaintextBytes);
240
308
  }
241
- async uploadSyncMessages(syncMessages) {
309
+ async uploadSyncMessages(syncMessages, payloadBytes, timestamp) {
242
310
  const relay = this.relay;
243
311
  if (!relay || syncMessages.length === 0) {
244
312
  return;
245
313
  }
246
- await this.sendPhase(syncMessages, (syncMsg) => this.fanOut.request(() => relay.send({
247
- targetUserId: syncMsg.recipientUserId,
248
- targetDeviceId: syncMsg.recipientDeviceId,
314
+ const prepared = await Promise.all(syncMessages.map((message) => this.prepareStoredSyncMessage(message)));
315
+ const repair = {
316
+ sessions: this.sessionCallbacks,
317
+ rebuild: async (deviceId) => {
318
+ const [message] = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
319
+ clientTimestamp: timestamp,
320
+ includeSyncMessages: false,
321
+ listedDeviceIds: [deviceId],
322
+ });
323
+ return message && this.prepareStoredSyncMessage(message);
324
+ },
325
+ };
326
+ await this.sendPhase(prepared, (message) => this.postSyncMessage(relay, message, {}, repair), 'sync');
327
+ }
328
+ /** A stored sync copy that names the registration of the own device's current session. */
329
+ async prepareStoredSyncMessage(message, clientMessageId) {
330
+ const stored = {
331
+ recipientUserId: message.recipientUserId,
332
+ recipientDeviceId: message.recipientDeviceId,
333
+ timestamp: message.timestamp,
334
+ ...(clientMessageId !== undefined && { clientMessageId }),
335
+ ciphertext: typeof message.ciphertext === 'string'
336
+ ? message.ciphertext
337
+ : CryptoUtils.bytesToBase64(message.ciphertext),
338
+ messageType: getEnvelopeMessageType(message.ciphertext),
339
+ };
340
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(message.recipientUserId, message.recipientDeviceId);
341
+ if (registrationId !== undefined)
342
+ stored.recipientRegistrationId = registrationId;
343
+ return stored;
344
+ }
345
+ /**
346
+ * Post one sync copy to an own device, identified, with the registration
347
+ * of the device's session. When the relay refuses the device as stale, the
348
+ * session of the device is refreshed once, `repair.rebuild` encrypts the
349
+ * transcript again for the device, the new copy replaces the refused copy
350
+ * in the intent named by `repair.intentId`, and the new copy is posted
351
+ * under a repair ID. When the relay refuses the new copy as stale too, the
352
+ * session of the device is archived, the copy leaves the intent, and a
353
+ * warning is logged. The post then resolves, so the send completes without
354
+ * the copy.
355
+ *
356
+ * @throws {EncryptionError} SESSION_ESTABLISHMENT_FAILED when the refresh
357
+ * fails or the rebuild gives the device no copy. The copy stays in the
358
+ * intent, so a replay posts it again.
359
+ */
360
+ async postSyncMessage(relay, message, control, repair) {
361
+ try {
362
+ await this.postSyncCopy(relay, message, control);
363
+ return;
364
+ }
365
+ catch (error) {
366
+ if (!isConclusiveDeviceRejection(error))
367
+ throw error;
368
+ }
369
+ let refused = message;
370
+ const sessions = repair.sessions;
371
+ const replacement = sessions
372
+ ? await this.inRepairTurn(message.recipientUserId, () => this.repairRefusedSyncCopyInTurn(message, repair, sessions))
373
+ : undefined;
374
+ if (replacement) {
375
+ try {
376
+ await this.postSyncCopy(relay, replacement, control);
377
+ return;
378
+ }
379
+ catch (error) {
380
+ if (!isConclusiveDeviceRejection(error))
381
+ throw error;
382
+ }
383
+ refused = replacement;
384
+ }
385
+ await this.archiveDeviceSession(refused.recipientUserId, refused.recipientDeviceId, control.stopSignal);
386
+ if (repair.intentId !== undefined) {
387
+ const removed = [refused.recipientDeviceId];
388
+ await reconcileOutgoingSyncMessages(this.storage, repair.intentId, removed, []);
389
+ }
390
+ this.logger.warn('The relay refused a sync copy to a stale own device', {
391
+ category: 'E2EE',
392
+ data: { deviceId: refused.recipientDeviceId },
393
+ });
394
+ }
395
+ /**
396
+ * Refresh the session of an own device that refused a sync copy as stale,
397
+ * encrypt the transcript again for the device, and replace the stored copy
398
+ * before its post. The refused ciphertext is never posted again.
399
+ *
400
+ * @throws {EncryptionError} SESSION_ESTABLISHMENT_FAILED when the refresh
401
+ * fails or the rebuild gives the device no copy. The stored copy stays,
402
+ * and the refreshed session is not archived.
403
+ */
404
+ async repairRefusedSyncCopyInTurn(refused, repair, sessions) {
405
+ const refreshed = await sessions.refreshStaleSession(refused.recipientUserId, refused.recipientDeviceId);
406
+ if (!refreshed) {
407
+ throw new EncryptionError('Failed to refresh a rejected own device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: refused.recipientUserId });
408
+ }
409
+ const fresh = await repair.rebuild(refused.recipientDeviceId);
410
+ if (!fresh) {
411
+ throw new EncryptionError('Failed to encrypt a sync copy again for a refreshed own device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: refused.recipientUserId });
412
+ }
413
+ if (refused.clientMessageId !== undefined) {
414
+ fresh.clientMessageId = repairMessageId(refused.clientMessageId);
415
+ }
416
+ if (repair.intentId !== undefined) {
417
+ const removed = [refused.recipientDeviceId];
418
+ await reconcileOutgoingSyncMessages(this.storage, repair.intentId, removed, [fresh]);
419
+ }
420
+ return fresh;
421
+ }
422
+ /**
423
+ * Send one relay request of a sync copy to an own device.
424
+ *
425
+ * @returns The relay receipt of the post
426
+ */
427
+ async postSyncCopy(relay, message, control) {
428
+ return this.postToRelay(() => relay.send({
429
+ targetUserId: message.recipientUserId,
430
+ targetDeviceId: message.recipientDeviceId,
249
431
  senderUserId: this.userId,
250
432
  senderDeviceId: this.deviceId,
251
- ciphertext: typeof syncMsg.ciphertext === 'string'
252
- ? syncMsg.ciphertext
253
- : CryptoUtils.bytesToBase64(syncMsg.ciphertext),
254
- messageType: getEnvelopeMessageType(syncMsg.ciphertext),
433
+ ciphertext: message.ciphertext,
434
+ messageType: message.messageType,
255
435
  deliveryClass: 'background-sync',
256
- timestamp: syncMsg.timestamp,
257
- })), 'sync');
436
+ timestamp: message.timestamp,
437
+ ...(message.clientMessageId !== undefined && {
438
+ clientMessageId: message.clientMessageId,
439
+ }),
440
+ ...(message.recipientRegistrationId !== undefined && {
441
+ recipientRegistrationId: message.recipientRegistrationId,
442
+ }),
443
+ ...(control.declaredDeviceIds && { declaredDeviceIds: control.declaredDeviceIds }),
444
+ }), false, control);
258
445
  }
259
446
  /**
260
447
  * Run one relay phase of a send: a task for each device message, at the same
@@ -307,11 +494,17 @@ export class SignalProtocolServiceCipher {
307
494
  if (!this.relay) {
308
495
  return;
309
496
  }
497
+ if (this.declaresDeviceSets()) {
498
+ await this.sendDeclaredSyncPayload(payloadBytes, timestamp);
499
+ return;
500
+ }
501
+ const listed = await this.readOwnDeviceList(this.sessionCallbacks, undefined);
310
502
  const syncMessages = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
311
503
  clientTimestamp: timestamp,
312
504
  includeSyncMessages: false,
505
+ listedDeviceIds: listed.map((device) => device.deviceId),
313
506
  });
314
- await this.uploadSyncMessages(syncMessages);
507
+ await this.uploadSyncMessages(syncMessages, payloadBytes, timestamp);
315
508
  }
316
509
  async sendReadSyncToLocalOtherDevices(entries) {
317
510
  if (entries.length === 0) {
@@ -381,6 +574,14 @@ export class SignalProtocolServiceCipher {
381
574
  setSealedSenderIdentifiedFallback(callback) {
382
575
  this.sealedSenderIdentifiedFallback = callback;
383
576
  }
577
+ /**
578
+ * Set the reporter of a protocol error that no send result carries.
579
+ * Called by SignalProtocolClient after construction. A sync payload has no
580
+ * send result, so the reporter gives its error to the app.
581
+ */
582
+ setRelayProtocolErrorReporter(report) {
583
+ this.relayProtocolErrorReporter = report;
584
+ }
384
585
  async reportIdentifiedFallback(recipientUserId) {
385
586
  try {
386
587
  await this.sealedSenderIdentifiedFallback?.({
@@ -398,6 +599,55 @@ export class SignalProtocolServiceCipher {
398
599
  });
399
600
  }
400
601
  }
602
+ /**
603
+ * Restrict the cached unidentified access mode of a recipient after the
604
+ * relay rejects a sealed-sender authorization. A failure to update the mode
605
+ * does not block delivery.
606
+ */
607
+ async restrictUnidentifiedAccessMode(recipientUserId) {
608
+ try {
609
+ const contactProfileStateStore = this.contactProfileStateStore;
610
+ if (!contactProfileStateStore) {
611
+ this.logger.debug('No contact profile state store configured after sealed sender failure', {
612
+ category: 'E2EE',
613
+ data: { recipientUserId },
614
+ });
615
+ return;
616
+ }
617
+ // The device posts of a send run at the same time. The lock orders
618
+ // their steps, so two failures step down twice, as posts in device
619
+ // order do.
620
+ await this.lock.acquire(`unidentified-access-mode:${recipientUserId}`, async () => {
621
+ const currentMode = await contactProfileStateStore.getUnidentifiedAccessMode(recipientUserId);
622
+ let newMode;
623
+ switch (currentMode) {
624
+ case UnidentifiedAccessMode.UNRESTRICTED:
625
+ newMode = UnidentifiedAccessMode.UNKNOWN;
626
+ break;
627
+ case UnidentifiedAccessMode.ENABLED:
628
+ case UnidentifiedAccessMode.UNKNOWN:
629
+ default:
630
+ newMode = UnidentifiedAccessMode.DISABLED;
631
+ break;
632
+ }
633
+ await contactProfileStateStore.updateUnidentifiedAccessMode(recipientUserId, newMode);
634
+ this.logger.info('Sealed sender auth failed, transitioned unidentified access mode', {
635
+ category: 'E2EE',
636
+ data: { recipientUserId, previousMode: currentMode, newMode },
637
+ });
638
+ });
639
+ }
640
+ catch (modeError) {
641
+ // Non-fatal: mode transition failure should not block message delivery
642
+ this.logger.warn('Failed to update unidentified access mode after auth failure', {
643
+ category: 'E2EE',
644
+ data: {
645
+ recipientUserId,
646
+ error: modeError.message,
647
+ },
648
+ });
649
+ }
650
+ }
401
651
  useIdentifiedDeliveryOrThrow(recipientUserId, reason) {
402
652
  if (this.sealedSenderDeliveryMode === 'required') {
403
653
  throw new EncryptionError(`Sealed sender is required but unavailable: ${reason}`, EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId, operation: 'resolveSealedSenderContext', reason });
@@ -445,55 +695,103 @@ export class SignalProtocolServiceCipher {
445
695
  setGroupSecretParamsProvider(provider) {
446
696
  this.groupSecretParamsProvider = provider;
447
697
  }
698
+ /**
699
+ * Set the provider of the group context that each new send to a managed
700
+ * group carries. It answers null for a group with no master key.
701
+ */
702
+ setGroupContextProvider(provider) {
703
+ this.groupContextProvider = provider;
704
+ }
705
+ /** The content of a new group send, with the context of a managed group in it. */
706
+ async contentWithGroupContext(groupId, plaintextBytes) {
707
+ const context = await this.groupContextProvider?.(groupId);
708
+ return context
709
+ ? this.getResolvedContentAdapter().serializeContentWithGroupContext(plaintextBytes, context)
710
+ : plaintextBytes;
711
+ }
448
712
  // ============================================================================
449
713
  // Public API
450
714
  // ============================================================================
451
- /** Bind received group content to verified local membership. */
452
- setGroupReceiveAuthorizer(authorize) {
453
- this.groupReceiveAuthorizer = authorize;
715
+ /**
716
+ * Decide on received managed-group content against verified group state.
717
+ * Without an evaluator, managed-group content is refused.
718
+ */
719
+ setGroupReceiveEvaluator(evaluate) {
720
+ this.groupReceiveEvaluator = evaluate;
454
721
  }
455
722
  /**
456
723
  * Decrypt incoming envelope - routes to appropriate cipher
457
724
  *
458
725
  * Routes based on envelope type:
459
- * - ciphertext + groupId → Group cipher (Sender Keys)
726
+ * - sender_key → Group cipher (Sender Keys)
460
727
  * - otherwise → Pairwise cipher (SESAME/Double Ratchet)
461
728
  *
729
+ * The decrypt commits no receive record. It installs a distribution that
730
+ * the content carries, and it runs the group decision of managed-group
731
+ * content before it returns, as `commitEnvelope`, `decideGroupContent`,
732
+ * and `decryptedEnvelopeOf` tell.
733
+ *
462
734
  * @param envelope - Encrypted envelope from relay
735
+ * @param sealedSenderConfig - The trust roots of an unidentified_sender envelope
736
+ * @param stopSignal - When it aborts while the decrypt waits for a lock,
737
+ * the decrypt throws RelayWorkStopped
463
738
  * @returns Decrypted envelope ready for ContentManager
464
739
  * @throws {EncryptionError} DECRYPTION_FAILED if decryption fails
740
+ * @throws {SealedRetryRequestReceived} for a seal that holds a retry request
465
741
  *
466
742
  * @see https://signal.org/docs/specifications/sesame/
467
743
  */
468
- async decrypt(envelope, sealedSenderConfig, receiveId, stopSignal) {
744
+ async decrypt(envelope, sealedSenderConfig, stopSignal) {
745
+ const commit = await this.commitEnvelope(envelope, {
746
+ ...(sealedSenderConfig !== undefined && { sealedSender: sealedSenderConfig }),
747
+ ...(stopSignal !== undefined && { stopSignal }),
748
+ });
749
+ if (commit.kind === 'denied')
750
+ throw commit.error;
751
+ if (commit.kind !== 'committed') {
752
+ throw new Error(`A decrypt with no receive record cannot end ${commit.kind}`);
753
+ }
754
+ const decision = await this.decideGroupContent(commit.content);
755
+ if (decision.kind !== 'authorized')
756
+ throw decision.error;
757
+ return this.decryptedEnvelopeOf(commit.content, decision.groupId);
758
+ }
759
+ /**
760
+ * Decrypt one envelope and commit its receive record in the same store
761
+ * transaction as the ratchet step. Then check the content and install a
762
+ * distribution that it carries. The group decision does not run here.
763
+ *
764
+ * With `work`, the commit first reads the record of `work.workId`. A
765
+ * record that holds plaintext is a redelivery: the commit reuses the
766
+ * plaintext, spends no ratchet step, and installs the distribution of a
767
+ * Relay record again. A caller record installs nothing.
768
+ * A record that holds no plaintext ends `settled`. With no record, the
769
+ * admission of `work` runs the decrypt, so a full queue ends `refused`
770
+ * with nothing decrypted. A check that fails after the commit ends
771
+ * `denied`, because the ratchet step is spent.
772
+ *
773
+ * @throws {EncryptionError} when the decrypt fails. Nothing is committed.
774
+ * @throws {SealedRetryRequestReceived} for a seal that holds a retry request
775
+ */
776
+ async commitEnvelope(envelope, options = {}) {
777
+ return this.commitAt(envelope, false, options);
778
+ }
779
+ async commitAt(envelope, arrivedSealed, options) {
780
+ const { stopSignal, work } = options;
469
781
  // Handle sealed sender (unidentified_sender) envelopes by unsealing first
470
782
  if (envelope.messageType === 'unidentified_sender') {
471
- if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
472
- throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
473
- }
474
- // Get recipient's X25519 identity private key for unsealing
475
- const identityKeyPair = await this.storage.getIdentityKey();
476
- if (!identityKeyPair) {
477
- throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
783
+ const innerEnvelope = await this.unsealEnvelope(envelope, options.sealedSender);
784
+ // A retry request has no ratchet ciphertext. The caller routes it.
785
+ if (innerEnvelope.messageType === 'retry_request') {
786
+ throw new SealedRetryRequestReceived(innerEnvelope);
478
787
  }
479
- // Convert branded Base64 private key to Uint8Array for sealed sender
480
- const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
481
- const ciphertextStr = typeof envelope.ciphertext === 'string'
482
- ? envelope.ciphertext
483
- : CryptoUtils.bytesToBase64(envelope.ciphertext);
484
- const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, envelope.serverTimestamp, this.logger);
485
- // Reconstruct envelope with revealed sender identity
486
- const innerEnvelope = reconstructEnvelope(envelope, unsealed);
487
- // Recursively decrypt the inner message (now a standard ciphertext)
488
- let decrypted;
489
788
  try {
490
- decrypted = await this.decrypt(innerEnvelope, undefined, receiveId, stopSignal);
789
+ return await this.commitAt(innerEnvelope, true, { ...options, sealedSender: undefined });
491
790
  }
492
791
  catch (error) {
493
792
  attachUnsealedEnvelope(error, innerEnvelope);
494
793
  throw error;
495
794
  }
496
- return { ...decrypted, arrivedSealed: true };
497
795
  }
498
796
  // Validate message type before processing
499
797
  // Server only sends the 5 envelope types. Client-to-client types (typing_indicator,
@@ -518,81 +816,337 @@ export class SignalProtocolServiceCipher {
518
816
  messageType: envelope.messageType,
519
817
  },
520
818
  });
819
+ const existing = work ? await this.storage.getReceiveWork(work.workId) : null;
820
+ // The application got the content. Only its receipt can wait.
821
+ if (existing && existing.plaintext === undefined)
822
+ return { kind: 'settled', record: existing };
823
+ const seed = work?.seed(envelope, arrivedSealed);
521
824
  let plaintext;
522
825
  // Set for group messages once the frame's distribution identifier has
523
826
  // been resolved against the local sender key store. The envelope carries
524
827
  // no group, so this is the only place a group becomes known on receive.
525
- let resolvedGroupId = null;
526
- const received = receiveId ? await this.storage.getReceivedContent(receiveId) : null;
527
- // Route on the envelope type. `sender_key` says "decrypt this as a
528
- // framed SenderKeyMessage". It does not say which group, and cannot.
529
- // That is the point of not putting a group on the envelope.
530
- if (envelope.messageType === 'sender_key') {
531
- const group = await this.decryptGroup(envelope, receiveId, received ?? undefined, stopSignal);
532
- plaintext = group.plaintext;
533
- resolvedGroupId = group.groupId;
828
+ let transportGroupId = null;
829
+ let record = existing;
830
+ if (existing) {
831
+ // A redelivery of committed content spends no ratchet step.
832
+ plaintext = existing.plaintext;
833
+ if (envelope.messageType === 'sender_key') {
834
+ transportGroupId =
835
+ existing.groupId ??
836
+ (await this.resolveFramedGroup(envelope, envelopeCiphertextBytes(envelope.ciphertext)));
837
+ }
838
+ if (existing.awaitingEnvelope && seed) {
839
+ record = await this.fillAwaitingEnvelope(existing, seed, transportGroupId);
840
+ }
534
841
  }
535
842
  else {
536
- // Pairwise message - use SESAME for session convergence
537
- const sesameMessage = this.toSesameMessage(envelope);
538
- plaintext = received?.plaintext ?? (await this.decryptPairwise(sesameMessage, receiveId));
539
- }
540
- // Create decrypted envelope for hook
541
- const receivedAt = received?.receivedAt ?? Date.now();
542
- const inspectedContent = this.getResolvedContentAdapter().inspectContent(plaintext);
543
- const distribution = inspectedContent.senderKeyDistribution;
544
- if (distribution) {
545
- if (resolvedGroupId !== null) {
546
- throw new EncryptionError('Sender-key distributions require pairwise encryption', EncryptionErrorCode.INVALID_CIPHERTEXT);
843
+ // Route on the envelope type. `sender_key` says "decrypt this as a
844
+ // framed SenderKeyMessage". It does not say which group, and cannot.
845
+ // That is the point of not putting a group on the envelope.
846
+ if (envelope.messageType === 'sender_key') {
847
+ const group = await this.decryptGroup(envelope, seed, work?.admit, stopSignal);
848
+ if (group === null)
849
+ return { kind: 'refused' };
850
+ plaintext = group.plaintext;
851
+ transportGroupId = group.groupId;
547
852
  }
548
- if (!this.groupReceiveAuthorizer) {
549
- throw new Error('Configure verified group membership before receiving sender keys');
853
+ else {
854
+ // Pairwise message - use SESAME for session convergence
855
+ const sesameMessage = this.toSesameMessage(envelope);
856
+ const decrypt = () => this.decryptPairwise(sesameMessage, seed);
857
+ const pairwise = work ? await work.admit(null, decrypt) : { value: await decrypt() };
858
+ if (pairwise === null)
859
+ return { kind: 'refused' };
860
+ plaintext = pairwise.value;
550
861
  }
551
- await this.groupSenderKeys.run(distribution.groupId, async (rawGroupId) => {
552
- await this.groupReceiveAuthorizer(rawGroupId, envelope.senderUserId, 'distribution');
553
- await this.senderKeyManager.processSenderKeyDistribution(rawGroupId, envelope.senderUserId, envelope.senderDeviceId, distribution.distribution);
554
- }, stopSignal);
555
- }
556
- // For DMs, compute canonical conversation ID: dm:${sorted(user1, user2)}
557
- // Groups use their group ID directly. Sent sync transcripts override this
558
- // with the transcript's destination conversation.
559
- const conversationId = inspectedContent?.conversationId ||
560
- resolvedGroupId ||
561
- this.getDirectConversationId(envelope.senderUserId);
562
- // Extract client timestamp from decrypted content
563
- // Text messages: dataMessage.timestamp, Attachments: timestamp at top level
564
- let clientTimestamp = receivedAt;
565
- let hasContentTimestamp = false;
566
- const contentTimestamp = inspectedContent?.timestamp;
567
- if (typeof contentTimestamp === 'number') {
568
- clientTimestamp = contentTimestamp;
569
- hasContentTimestamp = true;
570
- }
571
- // Replay attack prevention
572
- // Validate envelope.timestamp matches content timestamp after decryption
573
- if (envelope.timestamp !== undefined && hasContentTimestamp) {
574
- if (envelope.timestamp !== clientTimestamp) {
575
- throw new EncryptionError(`Timestamp mismatch: envelope=${envelope.timestamp}, content=${clientTimestamp}. Potential replay attack.`, EncryptionErrorCode.REPLAY_DETECTED);
862
+ if (work) {
863
+ record = await this.storage.getReceiveWork(work.workId);
864
+ // An ack after this point must find the content stored.
865
+ if (!record)
866
+ throw new Error('The store did not commit the receive record');
576
867
  }
577
868
  }
578
- recordServerClockSample(envelope.serverTimestamp, receivedAt);
579
- const decryptedEnvelope = {
869
+ // The admission time is the time of the first commit. A retry, a
870
+ // redelivery, and a restart read the same value, so the receipt
871
+ // fallback timestamp and the age of waiting content stay fixed.
872
+ const receivedAt = record?.receivedAt ?? Date.now();
873
+ const sender = {
580
874
  messageId: envelope.id || `${envelope.senderUserId}-${receivedAt}`,
581
- sessionId: ProtocolAddress.toString(ProtocolAddress.create(envelope.senderUserId, envelope.senderDeviceId)),
582
- senderId: envelope.senderUserId,
875
+ senderUserId: envelope.senderUserId,
583
876
  senderDeviceId: envelope.senderDeviceId,
584
- conversationId,
585
- content: plaintext,
586
- timestamp: clientTimestamp, // Use client timestamp for receipt matching
587
- serverTimestamp: envelope.serverTimestamp,
588
- receivedAt,
589
- isGroup: resolvedGroupId !== null,
590
- arrivedSealed: false,
591
- messageType: envelope.messageType,
592
877
  };
593
- return decryptedEnvelope;
878
+ let inspected;
879
+ try {
880
+ inspected = this.getResolvedContentAdapter().inspectContent(plaintext);
881
+ this.checkCommittedContent(envelope.senderUserId, envelope.timestamp, inspected, transportGroupId);
882
+ }
883
+ catch (error) {
884
+ // The ratchet step is spent, so a resend cannot repair the content.
885
+ return { kind: 'denied', error: error, record, ...sender };
886
+ }
887
+ // Signal installs a distribution from an authenticated session before
888
+ // it looks at the group: the key decrypts nothing until group content
889
+ // that names it passes the group checks. A caller record installs
890
+ // nothing, as in restoreCommitted, so a Relay redelivery that reuses
891
+ // it gives the distribution to the caller only.
892
+ const distribution = inspected.senderKeyDistribution;
893
+ let distributionGroupId = null;
894
+ if (distribution && (record === null || record.origin === 'relay')) {
895
+ distributionGroupId = await this.installDistribution(envelope.senderUserId, envelope.senderDeviceId, distribution, stopSignal);
896
+ }
897
+ else if (distribution) {
898
+ distributionGroupId = extractGroupId(distribution.groupId);
899
+ }
900
+ recordServerClockSample(envelope.serverTimestamp, receivedAt);
901
+ return {
902
+ kind: 'committed',
903
+ record,
904
+ reused: existing !== null,
905
+ content: {
906
+ ...sender,
907
+ messageType: envelope.messageType,
908
+ ...(envelope.serverTimestamp !== undefined && {
909
+ serverTimestamp: envelope.serverTimestamp,
910
+ }),
911
+ arrivedSealed,
912
+ plaintext,
913
+ inspected,
914
+ transportGroupId,
915
+ distributionGroupId,
916
+ receivedAt,
917
+ },
918
+ };
919
+ }, stopSignal);
920
+ }
921
+ /** Open a sealed envelope and return the envelope that it holds. */
922
+ async unsealEnvelope(envelope, sealedSenderConfig) {
923
+ if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
924
+ throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
925
+ }
926
+ // Get recipient's X25519 identity private key for unsealing
927
+ const identityKeyPair = await this.storage.getIdentityKey();
928
+ if (!identityKeyPair) {
929
+ throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
930
+ }
931
+ // Convert branded Base64 private key to Uint8Array for sealed sender
932
+ const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
933
+ const ciphertextStr = typeof envelope.ciphertext === 'string'
934
+ ? envelope.ciphertext
935
+ : CryptoUtils.bytesToBase64(envelope.ciphertext);
936
+ const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, envelope.serverTimestamp, this.logger);
937
+ // Reconstruct envelope with revealed sender identity
938
+ return reconstructEnvelope(envelope, unsealed);
939
+ }
940
+ /**
941
+ * Fill the sender fields of a converted legacy record from its
942
+ * redelivered envelope. The record keeps its age and its arrival order.
943
+ */
944
+ async fillAwaitingEnvelope(existing, seed, groupId) {
945
+ const seeded = seed({
946
+ plaintext: existing.plaintext,
947
+ ...(groupId !== null && { groupId }),
948
+ });
949
+ const filled = sizedReceiveWork({
950
+ ...seeded,
951
+ workId: existing.workId,
952
+ revision: existing.revision + 1,
953
+ stage: existing.stage,
954
+ arrivalSeq: existing.arrivalSeq,
955
+ receivedAt: existing.receivedAt,
956
+ dueAt: existing.dueAt,
957
+ plaintext: existing.plaintext,
958
+ ...(existing.groupId !== undefined && { groupId: existing.groupId }),
959
+ ...(existing.blockedOn !== undefined && { blockedOn: existing.blockedOn }),
960
+ });
961
+ if (await this.storage.putReceiveWork(filled, existing.revision))
962
+ return filled;
963
+ return (await this.storage.getReceiveWork(existing.workId)) ?? existing;
964
+ }
965
+ /**
966
+ * The checks of committed content that run before its distribution
967
+ * installs: the replay check, sync content from another account, and a
968
+ * distribution inside a sender-key message.
969
+ */
970
+ checkCommittedContent(senderUserId, envelopeTimestamp, inspected, transportGroupId) {
971
+ // Replay attack prevention
972
+ // Validate envelope.timestamp matches content timestamp after decryption.
973
+ // A replayed envelope installs no sender key, so the check runs first.
974
+ const contentTimestamp = inspected?.timestamp;
975
+ if (envelopeTimestamp !== undefined &&
976
+ typeof contentTimestamp === 'number' &&
977
+ envelopeTimestamp !== contentTimestamp) {
978
+ throw new EncryptionError(`Timestamp mismatch: envelope=${envelopeTimestamp}, content=${contentTimestamp}. Potential replay attack.`, EncryptionErrorCode.REPLAY_DETECTED);
979
+ }
980
+ // Sync content is content of the own account. Content from another
981
+ // account that carries a sync message is refused before it installs a
982
+ // distribution or any group decision runs.
983
+ refuseSyncFromOtherAccount(inspected, senderUserId, this.userId);
984
+ if (inspected.senderKeyDistribution && transportGroupId !== null) {
985
+ throw new EncryptionError('Sender-key distributions require pairwise encryption', EncryptionErrorCode.INVALID_CIPHERTEXT);
986
+ }
987
+ }
988
+ /**
989
+ * The committed content of a stored receive record, for the receive queue
990
+ * after the release of the record and for a helper receive. It decrypts nothing.
991
+ * It runs the content checks again, so a crash between a failed check and
992
+ * its denied record denies again.
993
+ *
994
+ * For a Relay record it installs the distribution of the content again.
995
+ * One Signal client puts the install in the buffered store of the ratchet step
996
+ * and writes both in one transaction before the acknowledgment. The local
997
+ * store contract commits a session
998
+ * with its receive record, and sender keys apart from it under the group
999
+ * lock, so the commit stores the record before its install, and an install
1000
+ * can fail after the commit. A redelivery replays the install, but a pass
1001
+ * can complete the record before the redelivery comes, and the key is then
1002
+ * lost. A replay of an installed distribution changes nothing while its
1003
+ * key is the current state or one of the kept previous states. When the
1004
+ * key is neither, the replay installs it again as the current state, and
1005
+ * when the record already holds 5 states, the oldest state goes. Test: "the
1006
+ * subscription handler returns true only after the commit, the sender key
1007
+ * install, and the outcome-1 write". A caller record installs nothing: its
1008
+ * commit gives the distribution to the caller and installs no sender key.
1009
+ * Test: "gives the content once, and the failed message is a duplicate
1010
+ * after a restart".
1011
+ *
1012
+ * @param record - A record that holds plaintext and its sender. A
1013
+ * converted legacy record waits for its envelope, and has no sender.
1014
+ * @param stopSignal - Stops the wait for the sender key lock.
1015
+ * @returns `committed` with the content, or `denied` when a check fails
1016
+ */
1017
+ async restoreCommitted(record, stopSignal) {
1018
+ const { plaintext, senderUserId, senderDeviceId, messageType, messageId } = record;
1019
+ if (plaintext === undefined ||
1020
+ senderUserId === undefined ||
1021
+ senderDeviceId === undefined ||
1022
+ messageType === undefined ||
1023
+ messageId === undefined) {
1024
+ throw new Error('A receive record without content or sender cannot be restored');
1025
+ }
1026
+ const sender = { messageId, senderUserId, senderDeviceId };
1027
+ const transportGroupId = messageType === 'sender_key' ? (record.groupId ?? null) : null;
1028
+ let inspected;
1029
+ try {
1030
+ inspected = this.getResolvedContentAdapter().inspectContent(plaintext);
1031
+ this.checkCommittedContent(senderUserId, record.senderTimestamp, inspected, transportGroupId);
1032
+ }
1033
+ catch (error) {
1034
+ return { kind: 'denied', error: error, record, ...sender };
1035
+ }
1036
+ const distribution = inspected.senderKeyDistribution;
1037
+ let distributionGroupId = null;
1038
+ if (distribution && record.origin === 'relay') {
1039
+ distributionGroupId = await this.installDistribution(senderUserId, senderDeviceId, distribution, stopSignal);
1040
+ }
1041
+ else if (distribution) {
1042
+ distributionGroupId = extractGroupId(distribution.groupId);
1043
+ }
1044
+ return {
1045
+ kind: 'committed',
1046
+ record,
1047
+ reused: true,
1048
+ content: {
1049
+ ...sender,
1050
+ messageType,
1051
+ ...(record.serverTimestamp !== undefined && { serverTimestamp: record.serverTimestamp }),
1052
+ arrivedSealed: record.arrivedSealed === true,
1053
+ plaintext,
1054
+ inspected,
1055
+ transportGroupId,
1056
+ distributionGroupId,
1057
+ receivedAt: record.receivedAt,
1058
+ },
1059
+ };
1060
+ }
1061
+ /**
1062
+ * Install an authenticated distribution. A copy of an installed
1063
+ * distribution changes nothing while its key is the current state or a
1064
+ * kept previous state, so a replay of the install is safe. A copy of a key
1065
+ * that is neither installs again as the current state, and when the
1066
+ * record already holds 5 states, the oldest state goes.
1067
+ *
1068
+ * @returns The raw group of the distribution
1069
+ */
1070
+ async installDistribution(senderUserId, senderDeviceId, distribution, stopSignal) {
1071
+ return this.groupSenderKeys.run(distribution.groupId, async (rawGroupId) => {
1072
+ await this.senderKeyManager.processSenderKeyDistribution(rawGroupId, senderUserId, senderDeviceId, distribution.distribution);
1073
+ return rawGroupId;
594
1074
  }, stopSignal);
595
1075
  }
1076
+ /**
1077
+ * Decide on committed managed-group content against verified group state.
1078
+ * Content that names no managed group and carries no context needs no
1079
+ * decision.
1080
+ *
1081
+ * @returns `authorized` with the group of the content, or null for content
1082
+ * of no group. `denied` with the refusal. `unavailable` with the raw
1083
+ * group whose state must update first.
1084
+ */
1085
+ async decideGroupContent(content) {
1086
+ // Content beside a distribution is content of that group: a retry
1087
+ // resend carries the logged group message with the current sender key.
1088
+ const resolvedGroupId = content.transportGroupId ??
1089
+ (content.inspected.senderKeyDistributionOnly === false ? content.distributionGroupId : null);
1090
+ // Managed-group content is delivered only when verified group state at
1091
+ // the revision of its context authorizes it.
1092
+ const claim = classifyGroupContent(content.messageType === 'sender_key' ? content.transportGroupId : null, content.inspected);
1093
+ if (!claim)
1094
+ return { kind: 'authorized', groupId: resolvedGroupId };
1095
+ if (!this.groupReceiveEvaluator) {
1096
+ return { kind: 'denied', error: new GroupReceiveRefusedError('configuration') };
1097
+ }
1098
+ const verdict = await this.groupReceiveEvaluator({
1099
+ claim,
1100
+ senderId: content.senderUserId,
1101
+ senderDeviceId: content.senderDeviceId,
1102
+ });
1103
+ if (verdict.kind === 'authorized') {
1104
+ return { kind: 'authorized', groupId: claim.transcript ? resolvedGroupId : verdict.groupId };
1105
+ }
1106
+ if (verdict.kind === 'denied') {
1107
+ return { kind: 'denied', error: new GroupReceiveRefusedError(verdict.reason) };
1108
+ }
1109
+ const group = groupOfContext(claim);
1110
+ return {
1111
+ kind: 'unavailable',
1112
+ error: new GroupReceiveUnavailableError(verdict.reason, verdict.retryAfterMs, content.messageId),
1113
+ groupId: 'groupId' in group ? group.groupId : claim.groupId,
1114
+ };
1115
+ }
1116
+ /**
1117
+ * The envelope that the application gets for authorized content.
1118
+ *
1119
+ * @param resolvedGroupId - The group of the content, from `decideGroupContent`
1120
+ */
1121
+ decryptedEnvelopeOf(content, resolvedGroupId) {
1122
+ // For DMs, compute canonical conversation ID: dm:${sorted(user1, user2)}
1123
+ // Groups, and group content beside a distribution, use their group ID
1124
+ // directly. A sent sync transcript of this account overrides this with
1125
+ // the transcript's destination conversation. Sender-key content from
1126
+ // another account is content of its transport group.
1127
+ const transportGroupOnly = content.messageType === 'sender_key' && content.senderUserId !== this.userId;
1128
+ const conversationId = (transportGroupOnly ? resolvedGroupId : content.inspected?.conversationId) ||
1129
+ resolvedGroupId ||
1130
+ this.getDirectConversationId(content.senderUserId);
1131
+ // Extract client timestamp from decrypted content
1132
+ // Text messages: dataMessage.timestamp, Attachments: timestamp at top level
1133
+ const contentTimestamp = content.inspected?.timestamp;
1134
+ return {
1135
+ messageId: content.messageId,
1136
+ sessionId: ProtocolAddress.toString(ProtocolAddress.create(content.senderUserId, content.senderDeviceId)),
1137
+ senderId: content.senderUserId,
1138
+ senderDeviceId: content.senderDeviceId,
1139
+ conversationId,
1140
+ content: content.plaintext,
1141
+ // Use client timestamp for receipt matching
1142
+ timestamp: typeof contentTimestamp === 'number' ? contentTimestamp : content.receivedAt,
1143
+ ...(content.serverTimestamp !== undefined && { serverTimestamp: content.serverTimestamp }),
1144
+ receivedAt: content.receivedAt,
1145
+ isGroup: resolvedGroupId !== null,
1146
+ arrivedSealed: content.arrivedSealed,
1147
+ messageType: content.messageType,
1148
+ };
1149
+ }
596
1150
  /**
597
1151
  * Encrypt outgoing message - routes based on recipient type
598
1152
  *
@@ -667,7 +1221,12 @@ export class SignalProtocolServiceCipher {
667
1221
  * @param options - The client timestamp and the content hint of the
668
1222
  * message, and the retry request that a retry resend answers. Without a
669
1223
  * retry target, the client message ID is a new UUID and nothing is
670
- * stored. The timestamp goes in the envelope
1224
+ * stored. The timestamp goes in the envelope. With `senderKeyHandoff`,
1225
+ * the content carries that own sender key of the raw group: each
1226
+ * encryption keeps the key, and when the Relay accepts the bytes, the
1227
+ * send records a handoff row of the key that they carry. A post that the
1228
+ * Relay answers with RETRY_CONFLICT records no row, because the Relay
1229
+ * holds an earlier encryption
671
1230
  * @param stopSignal - The stop signal of the relay work that sends. When it
672
1231
  * aborts while the send waits for the recipient's lock, the send throws
673
1232
  * RelayWorkStopped
@@ -686,6 +1245,7 @@ export class SignalProtocolServiceCipher {
686
1245
  }
687
1246
  // The answer carries the attempt number of its request.
688
1247
  const target = retry && { ...retry, attempt: retryRequestAttempt(retry) };
1248
+ const handoffGroupId = options.senderKeyHandoff?.groupId;
689
1249
  const post = async (resend) => {
690
1250
  try {
691
1251
  await this.postResend(resend, retryResendAttemptId(resend), stopSignal);
@@ -700,12 +1260,19 @@ export class SignalProtocolServiceCipher {
700
1260
  category: 'E2EE',
701
1261
  data: { retryId: resend.retryId, kind: resend.kind, attempt: resend.attempt },
702
1262
  });
1263
+ return;
1264
+ }
1265
+ if (handoffGroupId !== undefined) {
1266
+ await this.recordSenderKeyHandoff(handoffGroupId, resend.message);
703
1267
  }
704
1268
  };
705
1269
  return await acquireUntilStopped(this.lock, `encrypt:${recipientUserId}`, async () => {
706
1270
  if (target === undefined) {
707
1271
  const resend = await this.encryptResend(recipientUserId, recipientDeviceId, content, options);
708
1272
  await this.postResend(resend, await CryptoUtils.generateUuidV4(), stopSignal);
1273
+ if (handoffGroupId !== undefined) {
1274
+ await this.recordSenderKeyHandoff(handoffGroupId, resend.message);
1275
+ }
709
1276
  return true;
710
1277
  }
711
1278
  const stored = await getRetryResend(this.storage, recipientUserId, recipientDeviceId, target.failedEnvelopeId);
@@ -750,23 +1317,85 @@ export class SignalProtocolServiceCipher {
750
1317
  (!message.sealedSenderMessage || !resend.sealedSenderAuth)) {
751
1318
  throw new Error('Corrupt retry-resend record');
752
1319
  }
753
- await this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, resend.contentHint, clientMessageId, resend.transportMode === 'identified'
1320
+ const required = resend.transportMode === 'sealed_sender_required';
1321
+ const auth = await this.resolveResendAuthorization(resend);
1322
+ if (auth === null && required) {
1323
+ throw new EncryptionError('Required group sealed-sender authorization is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: message.recipientUserId });
1324
+ }
1325
+ await this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, resend.contentHint, clientMessageId, auth === null
754
1326
  ? undefined
755
1327
  : {
756
1328
  sentMessageBase64: message.sealedSenderMessage,
757
- auth: resend.sealedSenderAuth,
758
- deliveryMode: resend.transportMode === 'sealed_sender_required' ? 'required' : 'preferred',
1329
+ auth,
1330
+ deliveryMode: required ? 'required' : 'preferred',
759
1331
  }, {
760
1332
  ...(stopSignal && { stopSignal }),
761
1333
  operationEpochMilliseconds: resend.operationEpochMilliseconds,
762
1334
  });
763
1335
  }
764
- /** Encrypt one attempt of a resend, with the current time as its operation epoch. */
1336
+ /**
1337
+ * The sealed authorization of one resend post, or null when the post goes
1338
+ * identified. A stored group endorsement resolves again for the device's
1339
+ * account, and resolves to null when the group has none for it.
1340
+ */
1341
+ async resolveResendAuthorization(resend) {
1342
+ const stored = resend.transportMode === 'identified' ? undefined : resend.sealedSenderAuth;
1343
+ if (stored === undefined)
1344
+ return null;
1345
+ if (stored.type === 'accessKey')
1346
+ return { ...stored };
1347
+ return this.resolveGroupSendAuthorization(stored.groupId, [resend.message.recipientUserId]);
1348
+ }
1349
+ /**
1350
+ * The group of the group send that this client sent to the user at this
1351
+ * client timestamp, if any. A retry request names the failed message by
1352
+ * its timestamp, and the pre-messages of a group send have the timestamp
1353
+ * of the send. The members of a send name only its recipients. They are
1354
+ * never a source of current membership.
1355
+ */
1356
+ async findSentGroupId(recipientUserId, clientTimestamp) {
1357
+ for (const clientMessageId of await getSentClientMessageIds(this.storage, clientTimestamp)) {
1358
+ const intent = await getOutgoingMessageIntent(this.storage, clientMessageId);
1359
+ if (intent?.kind === 'group' && intent.groupMemberUserIds?.includes(recipientUserId)) {
1360
+ return intent.recipientId;
1361
+ }
1362
+ }
1363
+ return undefined;
1364
+ }
1365
+ /**
1366
+ * The current sender-key distribution of this device for a group, at the
1367
+ * current chain index, or null when the device has no sender key for the
1368
+ * group. It is read in the group operation, so no send or rotation of the
1369
+ * group runs at the same time.
1370
+ */
1371
+ async currentGroupDistribution(groupId, stopSignal) {
1372
+ return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
1373
+ const distribution = await this.senderKeyManager.getCurrentSenderKeyDistribution(rawGroupId, this.userId, this.deviceId);
1374
+ return distribution && { groupId: rawGroupId, distribution };
1375
+ }, stopSignal);
1376
+ }
1377
+ /**
1378
+ * Encrypt one attempt of a resend, with the current time as its operation
1379
+ * epoch. The resend of a group send's message takes the sealed
1380
+ * authorization of a pre-message: the recipient's access key first, then
1381
+ * the group endorsement of the recipient's account.
1382
+ */
765
1383
  async encryptResend(recipientUserId, recipientDeviceId, content, options) {
766
1384
  const operationEpochMilliseconds = Date.now();
767
- const sealedSender = await this.resolveSealedSenderContext(recipientUserId);
1385
+ const groupId = await this.findSentGroupId(recipientUserId, options.timestamp);
1386
+ const sealedSender = groupId === undefined
1387
+ ? await this.resolveSealedSenderContext(recipientUserId)
1388
+ : await this.resolveDistributionSealedSender(recipientUserId, groupId);
768
1389
  const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
769
- if (directSealedSender && directSealedSender.auth.type !== 'accessKey') {
1390
+ let sealedSenderAuth;
1391
+ if (directSealedSender?.auth.type === 'accessKey') {
1392
+ sealedSenderAuth = { ...directSealedSender.auth };
1393
+ }
1394
+ else if (directSealedSender && groupId !== undefined) {
1395
+ sealedSenderAuth = { type: 'groupSendToken', groupId };
1396
+ }
1397
+ else if (directSealedSender) {
1398
+ // Only a group send resolves an endorsement.
770
1399
  throw new Error('Direct sealed-sender delivery requires access-key authorization');
771
1400
  }
772
1401
  const message = await this.sesameManager.sendMessage(recipientUserId, recipientDeviceId, new TextEncoder().encode(content), { clientTimestamp: options.timestamp, includeSyncMessages: false });
@@ -777,11 +1406,17 @@ export class SignalProtocolServiceCipher {
777
1406
  ? 'sealed_sender_required'
778
1407
  : 'sealed_sender_preferred'
779
1408
  : 'identified',
780
- ...(directSealedSender?.auth.type === 'accessKey' && {
781
- sealedSenderAuth: { ...directSealedSender.auth },
782
- }),
1409
+ ...(sealedSenderAuth && { sealedSenderAuth }),
783
1410
  ...(options.contentHint !== undefined && { contentHint: options.contentHint }),
784
- message: await this.prepareStoredDirectDeviceMessage(message, directSealedSender, options.contentHint),
1411
+ message: {
1412
+ ...(await this.prepareStoredDirectDeviceMessage(message, directSealedSender, options.contentHint)),
1413
+ ...(options.senderKeyHandoff && {
1414
+ senderKeyHandoff: {
1415
+ senderKeyId: options.senderKeyHandoff.senderKeyId,
1416
+ generation: options.senderKeyHandoff.generation,
1417
+ },
1418
+ }),
1419
+ },
785
1420
  };
786
1421
  }
787
1422
  /**
@@ -808,14 +1443,30 @@ export class SignalProtocolServiceCipher {
808
1443
  sessionId,
809
1444
  // Ciphertext is base64-encoded on relay, convert back to Uint8Array
810
1445
  // SESAME will deserialize it back to Ciphertext (branded base64 string) internally
811
- ciphertext: typeof envelope.ciphertext === 'string'
812
- ? base64ToBytes(envelope.ciphertext)
813
- : envelope.ciphertext,
1446
+ ciphertext: envelopeCiphertextBytes(envelope.ciphertext),
814
1447
  isInitiating: envelope.messageType === 'prekey_bundle',
815
1448
  initHeader: null, // Extracted from ciphertext by SESAME
816
1449
  timestamp: envelope.timestamp,
817
1450
  };
818
1451
  }
1452
+ /**
1453
+ * Archive the session with one device, for the session reset of a retry
1454
+ * request that ended as `expired-content`.
1455
+ *
1456
+ * The archive takes the decrypt lock of the device first, so each decrypt
1457
+ * from the device in progress ends before it, and a decrypt that starts
1458
+ * later reads the archived state. Under the device locks of the session
1459
+ * manager, it then archives the session in the protocol store and in the
1460
+ * device record. The next send to the user reads its device list again
1461
+ * and starts a new session with the device.
1462
+ *
1463
+ * @param stopSignal - When it aborts while the archive waits for the
1464
+ * decrypt lock, nothing is archived and the call throws RelayWorkStopped
1465
+ */
1466
+ async archiveDeviceSession(userId, deviceId, stopSignal) {
1467
+ await acquireUntilStopped(this.lock, `decrypt:${userId}:${deviceId}`, () => this.sesameManager.archiveSession(userId, deviceId, () => this.storage.archiveCurrentSession(ProtocolAddress.create(userId, deviceId), null)), stopSignal);
1468
+ this.recipientDeviceListCheckedAt.delete(userId);
1469
+ }
819
1470
  /**
820
1471
  * Decrypt a pairwise message via SESAME
821
1472
  *
@@ -823,9 +1474,9 @@ export class SignalProtocolServiceCipher {
823
1474
  *
824
1475
  * @throws {EncryptionError} DECRYPTION_FAILED if decryption fails
825
1476
  */
826
- async decryptPairwise(sesameMessage, receiveId) {
1477
+ async decryptPairwise(sesameMessage, seed) {
827
1478
  try {
828
- const plaintextBytes = await this.sesameManager.receive(sesameMessage, receiveId);
1479
+ const plaintextBytes = await this.sesameManager.receive(sesameMessage, seed);
829
1480
  const plaintext = this.encodeLosslessPlaintext(plaintextBytes);
830
1481
  this.logger.debug('Message received and decrypted', {
831
1482
  category: 'E2EE',
@@ -847,63 +1498,76 @@ export class SignalProtocolServiceCipher {
847
1498
  });
848
1499
  }
849
1500
  }
1501
+ /**
1502
+ * Resolve the group of a framed SenderKeyMessage from the distribution
1503
+ * identifier inside the frame.
1504
+ *
1505
+ * @throws {EncryptionError} SESSION_NOT_FOUND when no stored sender key
1506
+ * claims the identifier
1507
+ */
1508
+ async resolveFramedGroup(envelope, framedBytes) {
1509
+ const groupId = await this.senderKeyManager.resolveGroupForFramedMessage(framedBytes, envelope.senderUserId, envelope.senderDeviceId);
1510
+ if (groupId === null) {
1511
+ // No stored sender key claims this distribution identifier, so there is
1512
+ // nothing to decrypt against. Same remedy as a missing key: ask the
1513
+ // sender to redistribute.
1514
+ throw new EncryptionError(`No sender key from ${envelope.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
1515
+ }
1516
+ return groupId;
1517
+ }
850
1518
  /**
851
1519
  * Decrypt a group message via Sender Keys.
852
1520
  *
853
1521
  * The envelope names no group, so the group is resolved from the opaque
854
1522
  * distribution identifier inside the frame and returned alongside the
855
1523
  * plaintext. Callers need it for the conversation ID and cannot read it off
856
- * the envelope.
1524
+ * the envelope. The admission runs inside the group lock, so it sees the
1525
+ * group before the decrypt.
857
1526
  *
1527
+ * @param seed - Builds the receive record that commits with the ratchet step
1528
+ * @param admit - Runs the decrypt under the receive admission
1529
+ * @returns Null when the admission refuses the decrypt
858
1530
  * @throws {EncryptionError} DECRYPTION_FAILED if decryption fails
859
1531
  */
860
- async decryptGroup(envelope, receiveId, received, stopSignal) {
1532
+ async decryptGroup(envelope, seed, admit, stopSignal) {
861
1533
  // Get the framed SenderKeyMessage bytes
862
- let framedBytes;
863
- if (typeof envelope.ciphertext === 'string') {
864
- // Base64-encoded framed SenderKeyMessage
865
- framedBytes = CryptoUtils.base64ToBytes(envelope.ciphertext);
866
- }
867
- else {
868
- framedBytes = envelope.ciphertext;
869
- }
870
- const groupId = received?.groupId ??
871
- (await this.senderKeyManager.resolveGroupForFramedMessage(framedBytes, envelope.senderUserId, envelope.senderDeviceId));
872
- if (groupId === null) {
873
- // No stored sender key claims this distribution identifier, so there is
874
- // nothing to decrypt against. Same remedy as a missing key: ask the
875
- // sender to redistribute.
876
- throw new EncryptionError(`No sender key from ${envelope.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
877
- }
1534
+ const framedBytes = envelopeCiphertextBytes(envelope.ciphertext);
1535
+ const groupId = await this.resolveFramedGroup(envelope, framedBytes);
878
1536
  return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
879
- await this.groupReceiveAuthorizer?.(rawGroupId, envelope.senderUserId, 'message');
880
- if (received)
881
- return { plaintext: received.plaintext, groupId: rawGroupId };
882
- try {
883
- const plaintext = await this.senderKeyManager.decryptGroupMessage(rawGroupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes, receiveId);
884
- this.logger.debug('Decrypted group message', {
885
- category: 'E2EE',
886
- data: {
887
- groupId: rawGroupId,
888
- senderId: envelope.senderUserId,
889
- },
890
- });
891
- return { plaintext, groupId: rawGroupId };
892
- }
893
- catch (error) {
894
- const err = error;
895
- if (err.message?.includes('SENDER_KEY_NOT_FOUND')) {
896
- throw new EncryptionError(`No sender key from ${envelope.senderUserId} for group ${rawGroupId} - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND, { originalError: err });
897
- }
898
- if (err.message?.includes('INVALID_SIGNATURE')) {
899
- throw new EncryptionError(`Invalid signature on group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
1537
+ const decrypt = async () => {
1538
+ try {
1539
+ return await this.senderKeyManager.decryptGroupMessage(rawGroupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes, seed);
900
1540
  }
901
- if (err.message?.includes('MESSAGE_TOO_OLD')) {
902
- throw new EncryptionError('Cannot decrypt old group message (forward secrecy)', EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
1541
+ catch (error) {
1542
+ const err = error;
1543
+ if (err.message?.includes('SENDER_KEY_NOT_FOUND')) {
1544
+ throw new EncryptionError(`No sender key from ${envelope.senderUserId} for group ${rawGroupId} - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND, { originalError: err });
1545
+ }
1546
+ if (err.message?.includes('INVALID_SIGNATURE')) {
1547
+ throw new EncryptionError(`Invalid signature on group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
1548
+ }
1549
+ if (err.message?.includes('MESSAGE_TOO_OLD')) {
1550
+ throw new EncryptionError('Cannot decrypt old group message (forward secrecy)', EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
1551
+ }
1552
+ throw new EncryptionError(`Failed to decrypt group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
903
1553
  }
904
- throw new EncryptionError(`Failed to decrypt group message from ${envelope.senderUserId}`, EncryptionErrorCode.DECRYPTION_FAILED, { originalError: err });
905
- }
906
- }, stopSignal);
1554
+ };
1555
+ const admitted = admit ? await admit(rawGroupId, decrypt) : { value: await decrypt() };
1556
+ if (admitted === null)
1557
+ return null;
1558
+ this.logger.debug('Decrypted group message', {
1559
+ category: 'E2EE',
1560
+ data: {
1561
+ groupId: rawGroupId,
1562
+ senderId: envelope.senderUserId,
1563
+ },
1564
+ });
1565
+ return { plaintext: admitted.value, groupId: rawGroupId };
1566
+ }, stopSignal).catch((error) => {
1567
+ // The retry request record of the failed envelope keeps its group.
1568
+ attachFailedGroup(error, extractGroupId(groupId));
1569
+ throw error;
1570
+ });
907
1571
  }
908
1572
  // ============================================================================
909
1573
  // PRIVATE - Encryption
@@ -920,6 +1584,11 @@ export class SignalProtocolServiceCipher {
920
1584
  * without a relay read. The relay gives no device-set version, so the window
921
1585
  * is the only bound on how long a linked or removed device goes unseen.
922
1586
  *
1587
+ * A relay that compares device sets refuses a declared post that misses a
1588
+ * device or names a removed one, so on such a relay a recipient with an
1589
+ * active session is sent to without a relay read at any age. Only a
1590
+ * recipient with no session has its list read.
1591
+ *
923
1592
  * A direct send may post before the read when the relay refuses every post
924
1593
  * to a removed device's mailbox, this client read the list in this process,
925
1594
  * and that read is younger than
@@ -937,6 +1606,10 @@ export class SignalProtocolServiceCipher {
937
1606
  */
938
1607
  async ensureSessionsForUser(recipientUserId, sessions, sendFirst = false, readDevices) {
939
1608
  const hasActiveSession = await this.hasActiveSession(recipientUserId);
1609
+ // A relay that compares device sets refuses a declared post that misses
1610
+ // a device, so a recipient with a session needs no list read.
1611
+ if (hasActiveSession && this.declaresDeviceSets())
1612
+ return false;
940
1613
  const listAge = this.recipientDeviceListAge(recipientUserId);
941
1614
  if (hasActiveSession && listAge < RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS) {
942
1615
  return false;
@@ -967,7 +1640,7 @@ export class SignalProtocolServiceCipher {
967
1640
  async hasActiveSession(recipientUserId) {
968
1641
  const userRecord = await this.sesameManager.getUserRecord(recipientUserId);
969
1642
  return (!!userRecord &&
970
- Array.from(userRecord.devices.values()).some((device) => device.session?.currentSession != null));
1643
+ Array.from(userRecord.devices.values()).some((device) => !isRemovedDevice(device) && device.session?.currentSession != null));
971
1644
  }
972
1645
  /** The age of this process's last successful read. A read in the future has no age. */
973
1646
  recipientDeviceListAge(recipientUserId) {
@@ -1027,14 +1700,7 @@ export class SignalProtocolServiceCipher {
1027
1700
  }
1028
1701
  const listedDevices = new Set(result.activeDevices);
1029
1702
  onList?.(listedDevices);
1030
- const removedDevices = [];
1031
- const reconciledRecord = await this.sesameManager.getUserRecord(recipientUserId);
1032
- for (const deviceId of Array.from(reconciledRecord?.devices.keys() ?? [])) {
1033
- if (listedDevices.has(deviceId))
1034
- continue;
1035
- await this.sesameManager.removeDevice(recipientUserId, deviceId);
1036
- removedDevices.push(deviceId);
1037
- }
1703
+ const removedDevices = await this.reconcileDeviceRecords(recipientUserId, listedDevices);
1038
1704
  if (result.establishedDevices.length === 0) {
1039
1705
  throw new EncryptionError(`Recipient ${recipientUserId} has no available prekey bundles - they may not have registered encryption keys`, EncryptionErrorCode.RECIPIENT_NOT_REGISTERED, { recipientUserId, failedDevices: result.failedDevices });
1040
1706
  }
@@ -1053,7 +1719,73 @@ export class SignalProtocolServiceCipher {
1053
1719
  return { listed: listedDevices, established: result.establishedDevices };
1054
1720
  }
1055
1721
  /**
1056
- * Encrypt to a single user (all their devices) via SESAME
1722
+ * Read the sender's own device list.
1723
+ *
1724
+ * A listed own device with no session gets one first, and each own device
1725
+ * record that the list does not show is removed. With no relay there is no
1726
+ * list and no sync copy.
1727
+ *
1728
+ * On a relay that compares device sets, a send declares the own devices
1729
+ * that it holds records for, and reads no own list before its recipient
1730
+ * post. A 409 or a declared 410 answer to a sync post repairs the own
1731
+ * records, as Signal learns of a new or removed own device. A declared
1732
+ * direct send reads the own list only when a recipient receipt sets
1733
+ * `needsSync` and the send holds no own device record, and a failed read
1734
+ * leaves the sync phase pending without failing the send. On a relay that
1735
+ * does not compare, each send reads the own list before its recipient
1736
+ * post, and a failed read fails the send.
1737
+ *
1738
+ * @returns The listed own devices other than this device, in list order
1739
+ */
1740
+ async readOwnDeviceList(sessions, stopSignal) {
1741
+ const relay = this.relay;
1742
+ if (!relay)
1743
+ return [];
1744
+ const listed = await this.fanOut.request(() => relay.getActiveDevices(this.userId), stopSignal);
1745
+ const others = listed.filter((device) => device.userId === this.userId && device.deviceId !== this.deviceId);
1746
+ if (others.length > 0 && sessions) {
1747
+ try {
1748
+ // A device that fails gets no copy from this send.
1749
+ await sessions.establishSessions(this.userId, others);
1750
+ }
1751
+ catch (error) {
1752
+ rethrowRelayWorkStopped(error);
1753
+ this.logger.warn('Could not start sessions with listed own devices', {
1754
+ category: 'E2EE',
1755
+ error: error,
1756
+ });
1757
+ }
1758
+ }
1759
+ const listedIds = new Set(others.map((device) => device.deviceId));
1760
+ listedIds.add(this.deviceId);
1761
+ await this.reconcileDeviceRecords(this.userId, listedIds);
1762
+ return others;
1763
+ }
1764
+ /**
1765
+ * Remove each device record that the device list does not name, and
1766
+ * relist each removed record that it names again. A record that is already
1767
+ * removed and still unlisted stays as it is, so a second sweep writes no
1768
+ * archive and emits no event.
1769
+ *
1770
+ * @returns The devices that this sweep removed
1771
+ */
1772
+ async reconcileDeviceRecords(userId, listed) {
1773
+ const removed = [];
1774
+ const record = await this.sesameManager.getUserRecord(userId);
1775
+ for (const [deviceId, device] of Array.from(record?.devices ?? [])) {
1776
+ if (listed.has(deviceId)) {
1777
+ if (isRemovedDevice(device))
1778
+ await this.sesameManager.relistDevice(userId, deviceId);
1779
+ }
1780
+ else if (!isRemovedDevice(device)) {
1781
+ await this.sesameManager.removeDevice(userId, deviceId);
1782
+ removed.push(deviceId);
1783
+ }
1784
+ }
1785
+ return removed;
1786
+ }
1787
+ /**
1788
+ * Encrypt to a single user (all their devices) via SESAME
1057
1789
  */
1058
1790
  async encryptToUser(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
1059
1791
  return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal);
@@ -1071,9 +1803,13 @@ export class SignalProtocolServiceCipher {
1071
1803
  existing.contentHint !== options.contentHint) {
1072
1804
  throw new Error('A clientMessageId cannot identify two different logical sends');
1073
1805
  }
1806
+ if (this.declaresDeviceSets() && existing.kind === 'direct') {
1807
+ return this.replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal);
1808
+ }
1074
1809
  if (existing.result)
1075
1810
  return existing.result;
1076
- return this.sendStoredDirectIntent(await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions), plaintextBytes, sessions, stopSignal);
1811
+ const reconciled = await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions);
1812
+ return this.sendStoredDirectIntent(await this.reconcileDirectSyncDevices(reconciled, plaintextBytes, sessions, stopSignal), plaintextBytes, sessions, stopSignal);
1077
1813
  }
1078
1814
  const sendFirst = await this.ensureSessionsForUser(recipientUserId, sessions, true);
1079
1815
  const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
@@ -1089,12 +1825,21 @@ export class SignalProtocolServiceCipher {
1089
1825
  const sealedSenderAuth = directSealedSender?.auth.type === 'accessKey' ? { ...directSealedSender.auth } : undefined;
1090
1826
  const clientTimestamp = options.timestamp ?? Date.now();
1091
1827
  const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
1828
+ const declared = this.declaresDeviceSets();
1829
+ const ownDevices = declared
1830
+ ? await this.localOwnDevices()
1831
+ : await this.readOwnDeviceList(sessions, stopSignal);
1092
1832
  let batch;
1093
1833
  try {
1094
1834
  batch = await this.sesameManager.send(recipientUserId, plaintextBytes, {
1095
1835
  clientTimestamp,
1096
- syncPlaintext,
1836
+ includeSyncMessages: false,
1097
1837
  });
1838
+ batch.syncMessages.push(...(await this.sesameManager.sendToLocalOtherDevices(syncPlaintext, {
1839
+ clientTimestamp,
1840
+ includeSyncMessages: false,
1841
+ listedDeviceIds: ownDevices.map((device) => device.deviceId),
1842
+ })));
1098
1843
  }
1099
1844
  catch (error) {
1100
1845
  if (error instanceof EncryptionError)
@@ -1115,16 +1860,7 @@ export class SignalProtocolServiceCipher {
1115
1860
  .catch((error) => {
1116
1861
  throw firstItemError(error);
1117
1862
  });
1118
- const syncMessages = batch.syncMessages.map((msg, index) => ({
1119
- recipientUserId: msg.recipientUserId,
1120
- recipientDeviceId: msg.recipientDeviceId,
1121
- timestamp: msg.timestamp,
1122
- clientMessageId: `${options.clientMessageId}:sync:${index}`,
1123
- ciphertext: typeof msg.ciphertext === 'string'
1124
- ? msg.ciphertext
1125
- : CryptoUtils.bytesToBase64(msg.ciphertext),
1126
- messageType: getEnvelopeMessageType(msg.ciphertext),
1127
- }));
1863
+ const syncMessages = await Promise.all(batch.syncMessages.map((message) => this.prepareStoredSyncMessage(message, syncMessageId(options.clientMessageId, message))));
1128
1864
  const intent = {
1129
1865
  kind: 'direct',
1130
1866
  clientMessageId: options.clientMessageId,
@@ -1142,6 +1878,8 @@ export class SignalProtocolServiceCipher {
1142
1878
  syncMessages,
1143
1879
  };
1144
1880
  await storeOutgoingMessageIntent(this.storage, intent);
1881
+ if (declared)
1882
+ return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
1145
1883
  if (sendFirst && sessions) {
1146
1884
  return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal);
1147
1885
  }
@@ -1247,6 +1985,35 @@ export class SignalProtocolServiceCipher {
1247
1985
  return intent;
1248
1986
  return reconcileOutgoingDirectDeviceMessages(this.storage, intent.clientMessageId, removed, added);
1249
1987
  }
1988
+ /**
1989
+ * Apply a read of the sender's own device list to a direct intent on
1990
+ * replay: drop the sync copy of each own device that the list does not
1991
+ * show, and add a sent transcript of the caller's content for each listed
1992
+ * own device that the intent does not address.
1993
+ */
1994
+ async reconcileDirectSyncDevices(intent, plaintextBytes, sessions, stopSignal) {
1995
+ if (!this.relay)
1996
+ return intent;
1997
+ const listed = await this.readOwnDeviceList(sessions, stopSignal);
1998
+ const { unlisted, added } = listedOwnDeviceChange(intent.syncMessages, listed.map((device) => device.deviceId));
1999
+ if (unlisted.length === 0 && added.length === 0)
2000
+ return intent;
2001
+ const additions = await this.prepareDirectSyncMessages(intent, plaintextBytes, added);
2002
+ return reconcileOutgoingSyncMessages(this.storage, intent.clientMessageId, unlisted, additions);
2003
+ }
2004
+ /**
2005
+ * A sent transcript of a stored direct send for each own device in
2006
+ * `deviceIds` that has a session.
2007
+ */
2008
+ async prepareDirectSyncMessages(intent, plaintextBytes, deviceIds) {
2009
+ const transcript = this.buildSentSyncTranscript(this.getDirectConversationId(intent.recipientId), plaintextBytes, intent.clientTimestamp, intent.recipientId);
2010
+ const copies = await this.sesameManager.sendToLocalOtherDevices(transcript, {
2011
+ clientTimestamp: intent.clientTimestamp,
2012
+ includeSyncMessages: false,
2013
+ listedDeviceIds: deviceIds,
2014
+ });
2015
+ return Promise.all(copies.map((message) => this.prepareStoredSyncMessage(message, syncMessageId(intent.clientMessageId, message))));
2016
+ }
1250
2017
  /** The sealed-sender context of a new transmission for a stored direct intent. */
1251
2018
  async resolveStoredDirectSealedSender(intent) {
1252
2019
  if (intent.transportMode === 'identified')
@@ -1259,9 +2026,9 @@ export class SignalProtocolServiceCipher {
1259
2026
  }
1260
2027
  async prepareStoredDirectDeviceMessage(message, sealedSender, contentHint) {
1261
2028
  const messageType = getEnvelopeMessageType(message.ciphertext);
1262
- const session = messageType === 'prekey_bundle'
1263
- ? await this.sesameManager.getSession(message.recipientUserId, message.recipientDeviceId)
1264
- : null;
2029
+ // Each post names the registration of the current session, so the Relay
2030
+ // refuses it when the device was reinstalled.
2031
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(message.recipientUserId, message.recipientDeviceId);
1265
2032
  const storedMessage = {
1266
2033
  recipientUserId: message.recipientUserId,
1267
2034
  recipientDeviceId: message.recipientDeviceId,
@@ -1270,9 +2037,7 @@ export class SignalProtocolServiceCipher {
1270
2037
  ? message.ciphertext
1271
2038
  : CryptoUtils.bytesToBase64(message.ciphertext),
1272
2039
  messageType,
1273
- ...(session?.currentSession?.remoteRegistrationId !== undefined && {
1274
- recipientRegistrationId: session.currentSession.remoteRegistrationId,
1275
- }),
2040
+ ...(registrationId !== undefined && { recipientRegistrationId: registrationId }),
1276
2041
  };
1277
2042
  if (sealedSender) {
1278
2043
  storedMessage.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(storedMessage, storedMessage.ciphertext, storedMessage.messageType, storedMessage.recipientRegistrationId, sealedSender, contentHint);
@@ -1280,16 +2045,19 @@ export class SignalProtocolServiceCipher {
1280
2045
  return storedMessage;
1281
2046
  }
1282
2047
  /**
1283
- * Refresh the session of a rejected device and replace its transmission.
1284
- * The device posts of a send run at the same time, so the repairs for one
1285
- * recipient take turns: the first session commit with a user pins the
1286
- * user's contact identity, and a concurrent commit that read the store
1287
- * before it fails.
2048
+ * Run the session repair of one recipient in turn. The device posts of a
2049
+ * send run at the same time, so the repairs for one recipient take turns:
2050
+ * the first session commit with a user pins the user's contact identity,
2051
+ * and a concurrent commit that read the store before it fails.
1288
2052
  */
2053
+ inRepairTurn(recipientUserId, repair) {
2054
+ return this.lock.acquire(`session-repair:${recipientUserId}`, repair);
2055
+ }
2056
+ /** Refresh the session of a rejected device and replace its transmission. */
1289
2057
  async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes, sessions) {
1290
2058
  if (!sessions)
1291
2059
  throw new Error('Stale-session refresh is not configured');
1292
- return this.lock.acquire(`direct-repair:${rejected.recipientUserId}`, () => this.repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions));
2060
+ return this.inRepairTurn(rejected.recipientUserId, () => this.repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions));
1293
2061
  }
1294
2062
  async repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions) {
1295
2063
  const refreshed = await sessions.refreshStaleSession(rejected.recipientUserId, rejected.recipientDeviceId);
@@ -1364,17 +2132,12 @@ export class SignalProtocolServiceCipher {
1364
2132
  }
1365
2133
  }
1366
2134
  // The sync copies start only after every device post settled.
1367
- await this.sendPhase(intent.syncMessages, (msg) => this.fanOut.request(() => relay.send({
1368
- targetUserId: msg.recipientUserId,
1369
- targetDeviceId: msg.recipientDeviceId,
1370
- senderUserId: this.userId,
1371
- senderDeviceId: this.deviceId,
1372
- ciphertext: msg.ciphertext,
1373
- messageType: msg.messageType,
1374
- deliveryClass: 'background-sync',
1375
- timestamp: msg.timestamp,
1376
- clientMessageId: msg.clientMessageId,
1377
- }), stopSignal), 'sync', stopSignal);
2135
+ const syncRepair = {
2136
+ sessions,
2137
+ intentId: intent.clientMessageId,
2138
+ rebuild: async (deviceId) => (await this.prepareDirectSyncMessages(intent, plaintextBytes, [deviceId]))[0],
2139
+ };
2140
+ await this.sendPhase(intent.syncMessages, (message) => this.postSyncMessage(relay, message, control, syncRepair), 'sync', stopSignal);
1378
2141
  const result = {
1379
2142
  clientMessageId: intent.clientMessageId,
1380
2143
  messageId,
@@ -1385,8 +2148,551 @@ export class SignalProtocolServiceCipher {
1385
2148
  await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
1386
2149
  return result;
1387
2150
  }
2151
+ /** True when the relay compares declared device sets, so each send declares them. */
2152
+ declaresDeviceSets() {
2153
+ return this.relay !== undefined && this.relay !== null && comparesDeviceSets(this.relay);
2154
+ }
2155
+ /**
2156
+ * The own devices other than this device that have a local device record
2157
+ * not marked removed.
2158
+ */
2159
+ async localOwnDevices() {
2160
+ const record = await this.sesameManager.getUserRecord(this.userId);
2161
+ return unremovedDeviceIds(record)
2162
+ .filter((deviceId) => deviceId !== this.deviceId)
2163
+ .sort((a, b) => a - b)
2164
+ .map((deviceId) => ({ userId: this.userId, deviceId }));
2165
+ }
2166
+ /**
2167
+ * Run one declared phase of a send until the relay accepts every post.
2168
+ *
2169
+ * Each pass posts every message of the phase, and each post declares every
2170
+ * device of its account that the phase addresses. A device that an earlier
2171
+ * pass posted gets its stored bytes again. After a refusal, the repair
2172
+ * archives and removes each extra device, refreshes the session of each
2173
+ * stale device, starts a session with each missing device, and encrypts the
2174
+ * message again only for each refreshed or added device. A listed device
2175
+ * with no prekey bundle gets no message, so the next pass declares the
2176
+ * account without it and the relay refuses the account again. The repair
2177
+ * write stores each such device in the intent, so a replay after a restart
2178
+ * or a stop starts a session with it before its first post.
2179
+ *
2180
+ * An account whose stored devices all lack a bundle has no post, so the
2181
+ * pass refuses it here. For such an account, a bundle fetch that answers
2182
+ * NOT_FOUND removes the device record. Each other device that the record
2183
+ * still holds gets a message in the same repair when it has a session or a
2184
+ * bundle. An account left with no device record gets one list read.
2185
+ *
2186
+ * @returns The answers of the last pass and the messages that it posted
2187
+ * @throws {DeviceSetReconciliationError} when the phase ends unresolved
2188
+ */
2189
+ async runDeclaredPhase(run) {
2190
+ // A declared post never names the sender device, so a send to the own
2191
+ // account posts only to the other own devices.
2192
+ const postable = (list) => list.filter((message) => message.recipientUserId !== this.userId || message.recipientDeviceId !== this.deviceId);
2193
+ let messages = postable(run.messages);
2194
+ let unposted = [...(run.bundleMissing ?? [])];
2195
+ // The accounts that the last pass refused here, because they had no post.
2196
+ let unpostedAccounts = new Set();
2197
+ const posts = await runDeviceSetPhase({
2198
+ phase: run.phase,
2199
+ clientMessageId: run.clientMessageId,
2200
+ restarts: run.restarts,
2201
+ pass: async () => {
2202
+ const declared = new Map();
2203
+ for (const message of messages) {
2204
+ const deviceIds = declared.get(message.recipientUserId) ?? [];
2205
+ deviceIds.push(message.recipientDeviceId);
2206
+ declared.set(message.recipientUserId, deviceIds);
2207
+ }
2208
+ for (const deviceIds of declared.values())
2209
+ deviceIds.sort((a, b) => a - b);
2210
+ // An account whose devices all lack a bundle has no post to refuse.
2211
+ // It is refused here as missing those devices, so the pass counts.
2212
+ const refusedHere = new Map();
2213
+ for (const device of unposted) {
2214
+ if (declared.has(device.userId))
2215
+ continue;
2216
+ refusedHere.set(device.userId, [...(refusedHere.get(device.userId) ?? []), device.deviceId]);
2217
+ }
2218
+ unpostedAccounts = new Set(refusedHere.keys());
2219
+ if (messages.length === 0 && refusedHere.size === 0 && run.requirePostTo !== undefined) {
2220
+ throw new EncryptionError('The send has no device to post to', EncryptionErrorCode.SESSION_NOT_FOUND, { recipientUserId: run.requirePostTo });
2221
+ }
2222
+ const posted = await this.fanOut.all(messages, async (message) => {
2223
+ const device = {
2224
+ userId: message.recipientUserId,
2225
+ deviceId: message.recipientDeviceId,
2226
+ };
2227
+ try {
2228
+ const value = await run.post(message, declared.get(message.recipientUserId));
2229
+ return { device, outcome: { ok: true, value } };
2230
+ }
2231
+ catch (error) {
2232
+ return { device, outcome: { ok: false, error } };
2233
+ }
2234
+ }, run.stopSignal);
2235
+ const refused = [...refusedHere].map(([userId, missingDeviceIds]) => ({
2236
+ device: { userId, deviceId: missingDeviceIds[0] },
2237
+ outcome: {
2238
+ ok: false,
2239
+ error: markDeviceSetRefusal(new Error('No device of the account has a session'), {
2240
+ kind: 'mismatch',
2241
+ accounts: [{ userId, missingDeviceIds, extraDeviceIds: [] }],
2242
+ }),
2243
+ },
2244
+ }));
2245
+ return [...posted, ...refused];
2246
+ },
2247
+ repair: async (repairs, restarts) => {
2248
+ const sessions = run.sessions;
2249
+ if (!sessions) {
2250
+ throw new EncryptionError('Session establishment is not configured', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: repairs[0]?.userId ?? '' });
2251
+ }
2252
+ const removed = [];
2253
+ const added = [];
2254
+ const bundleMissing = [];
2255
+ const posted = new Map(messages.map((message) => [
2256
+ declaredDeviceKey({
2257
+ userId: message.recipientUserId,
2258
+ deviceId: message.recipientDeviceId,
2259
+ }),
2260
+ message.recipientRegistrationId,
2261
+ ]));
2262
+ for (const repair of repairs) {
2263
+ await this.inRepairTurn(repair.userId, async () => {
2264
+ const repaired = await this.repairRefusedDevices(sessions, repair, {
2265
+ phase: run.phase,
2266
+ stopSignal: run.stopSignal,
2267
+ postedRegistration: (device) => posted.get(declaredDeviceKey(device)),
2268
+ unposted: unpostedAccounts.has(repair.userId),
2269
+ ...(run.forget && { forget: run.forget }),
2270
+ });
2271
+ removed.push(...repaired.removed);
2272
+ bundleMissing.push(...repaired.bundleMissing);
2273
+ for (const device of repaired.ready) {
2274
+ const message = await run.encrypt(device);
2275
+ if (message)
2276
+ added.push(message);
2277
+ else
2278
+ bundleMissing.push(device);
2279
+ }
2280
+ });
2281
+ }
2282
+ if (run.intentId !== undefined) {
2283
+ const intent = await repairOutgoingDeviceSet(this.storage, run.intentId, {
2284
+ phase: run.phase,
2285
+ restarts,
2286
+ removed,
2287
+ bundleMissing,
2288
+ ...(run.phase === 'recipient' ? { deviceMessages: added } : { syncMessages: added }),
2289
+ });
2290
+ messages = postable(run.phase === 'recipient' ? intent.deviceMessages : intent.syncMessages);
2291
+ }
2292
+ else {
2293
+ const gone = new Set(removed.map(declaredDeviceKey));
2294
+ messages = [
2295
+ ...messages.filter((message) => !gone.has(declaredDeviceKey({
2296
+ userId: message.recipientUserId,
2297
+ deviceId: message.recipientDeviceId,
2298
+ }))),
2299
+ ...added,
2300
+ ];
2301
+ }
2302
+ unposted = bundleMissing;
2303
+ return { bundleMissing };
2304
+ },
2305
+ unresolve: async (unresolved) => {
2306
+ if (run.intentId === undefined)
2307
+ return;
2308
+ await markOutgoingDeviceSetUnresolved(this.storage, run.intentId, storedDeviceSetUnresolved(unresolved));
2309
+ },
2310
+ wait: (milliseconds) => waitUnlessStopped(milliseconds, run.stopSignal),
2311
+ logFailure: (device, error) => {
2312
+ this.logger.warn('A device post of a send failed', {
2313
+ category: 'E2EE',
2314
+ error: error,
2315
+ data: { phase: run.phase, recipientUserId: device.userId, deviceId: device.deviceId },
2316
+ });
2317
+ },
2318
+ });
2319
+ return {
2320
+ values: posts.flatMap((post) => (post.outcome.ok ? [post.outcome.value] : [])),
2321
+ messages,
2322
+ };
2323
+ }
2324
+ /**
2325
+ * Repair the devices of one account that a refusal names. The caller runs
2326
+ * it in the repair turn of the account. An extra device loses its session,
2327
+ * its handoff rows, and its record. A stale device gets a new session,
2328
+ * unless its current session already has a registration other than the
2329
+ * one that the refused post named. A missing device gets a session.
2330
+ *
2331
+ * Only a listed device with no prekey bundle is bundle-missing, and the
2332
+ * loop waits for it. Any other failure to start a session, such as an
2333
+ * identity that the store does not trust, ends the send with its error.
2334
+ *
2335
+ * An unposted account is one that the pass refused here, because each of
2336
+ * its stored devices lacked a bundle. The Relay answers NOT_FOUND for the
2337
+ * bundle of a device that it does not register, and for a registered
2338
+ * device that has no uploaded prekeys. Thus such a device of an unposted
2339
+ * account loses its record and leaves the send. The repair then starts a
2340
+ * session with each other device that the account record still holds. A
2341
+ * device that has a session already counts as started, so it gets a
2342
+ * message in the same repair turn. When the account holds no device
2343
+ * record, the repair reads its device list once and starts a session with
2344
+ * each listed device. A device with no bundle is bundle-missing again, and
2345
+ * the restart bound stops the loop.
2346
+ *
2347
+ * @returns The devices that leave the send, the refreshed or added devices
2348
+ * that have a current session, and the devices that got no session
2349
+ * @throws The first error of a session start that failed for a reason other
2350
+ * than a missing prekey bundle
2351
+ */
2352
+ async repairRefusedDevices(sessions, repair, options) {
2353
+ const { userId } = repair;
2354
+ const removed = [];
2355
+ const ready = [];
2356
+ const bundleMissing = [];
2357
+ /**
2358
+ * Start sessions with devices that have none. A missing bundle is not an
2359
+ * error. A started session clears the removed marker of its record, so
2360
+ * the next pass declares the device.
2361
+ */
2362
+ const establish = async (deviceIds) => {
2363
+ const result = await sessions.establishSessions(userId, deviceIds.map((deviceId) => ({ userId, deviceId })));
2364
+ const failure = result.failedDeviceErrors[0];
2365
+ if (failure)
2366
+ throw failure.error;
2367
+ const established = new Set(result.establishedDevices);
2368
+ for (const deviceId of deviceIds) {
2369
+ if (established.has(deviceId)) {
2370
+ await this.sesameManager.relistDevice(userId, deviceId);
2371
+ ready.push({ userId, deviceId });
2372
+ }
2373
+ else {
2374
+ bundleMissing.push({ userId, deviceId });
2375
+ }
2376
+ }
2377
+ };
2378
+ for (const deviceId of repair.extraDeviceIds) {
2379
+ const device = { userId, deviceId };
2380
+ await this.archiveDeviceSession(userId, deviceId, options.stopSignal);
2381
+ await this.sesameManager.removeDevice(userId, deviceId);
2382
+ await options.forget?.(device);
2383
+ removed.push(device);
2384
+ }
2385
+ for (const deviceId of repair.staleDeviceIds) {
2386
+ const device = { userId, deviceId };
2387
+ removed.push(device);
2388
+ await options.forget?.(device);
2389
+ // A repair earlier in the send can have refreshed the session already.
2390
+ const posted = options.postedRegistration(device);
2391
+ const current = await this.sesameManager.getRemoteRegistrationId(userId, deviceId);
2392
+ let refreshed = posted !== undefined && current !== undefined && current !== posted;
2393
+ if (!refreshed) {
2394
+ try {
2395
+ refreshed = await sessions.refreshStaleSession(userId, deviceId);
2396
+ }
2397
+ catch (error) {
2398
+ rethrowRelayWorkStopped(error);
2399
+ this.logger.warn('Could not refresh the session of a stale device', {
2400
+ category: 'E2EE',
2401
+ error: error,
2402
+ data: { phase: options.phase, recipientUserId: userId, deviceId },
2403
+ });
2404
+ }
2405
+ }
2406
+ if (refreshed) {
2407
+ ready.push(device);
2408
+ }
2409
+ else {
2410
+ // The refresh archived the stale session or found none. A second
2411
+ // start tells a missing bundle from a session start that failed.
2412
+ await establish([deviceId]);
2413
+ }
2414
+ }
2415
+ if (repair.missingDeviceIds.length > 0)
2416
+ await establish(repair.missingDeviceIds);
2417
+ if (options.unposted && bundleMissing.length > 0) {
2418
+ for (const device of bundleMissing.splice(0)) {
2419
+ await this.sesameManager.removeDevice(userId, device.deviceId);
2420
+ await options.forget?.(device);
2421
+ removed.push(device);
2422
+ }
2423
+ const own = (deviceId) => userId === this.userId && deviceId === this.deviceId;
2424
+ const record = await this.sesameManager.getUserRecord(userId);
2425
+ const held = unremovedDeviceIds(record).filter((id) => !own(id));
2426
+ const handled = new Set(ready.map((device) => device.deviceId));
2427
+ const remainingIds = held.filter((id) => !handled.has(id));
2428
+ const relay = this.relay;
2429
+ if (remainingIds.length > 0) {
2430
+ await establish(remainingIds);
2431
+ }
2432
+ else if (relay && held.length === 0) {
2433
+ const listed = await this.fanOut.request(() => relay.getActiveDevices(userId), options.stopSignal);
2434
+ const deviceIds = listed
2435
+ .filter((device) => device.userId === userId && !own(device.deviceId))
2436
+ .map((device) => device.deviceId);
2437
+ if (deviceIds.length > 0)
2438
+ await establish(deviceIds);
2439
+ }
2440
+ }
2441
+ return { removed, ready, bundleMissing };
2442
+ }
2443
+ /**
2444
+ * Mark a send result whose relay accepted a declared post without the
2445
+ * `deviceSetChecked` mark. The send is delivered, and a second post could
2446
+ * deliver it twice, so the result does not change. The client reports the
2447
+ * error once through `onRelayProtocolError`.
2448
+ */
2449
+ markUncheckedDeclaredPosts(result, receipts, clientMessageId) {
2450
+ const error = this.uncheckedDeclaredPostError(receipts, clientMessageId);
2451
+ return error ? markRelayProtocolError(result, error) : result;
2452
+ }
2453
+ /**
2454
+ * The protocol error of declared posts that the relay accepted without the
2455
+ * `deviceSetChecked` mark. The client logs one warning for it.
2456
+ */
2457
+ uncheckedDeclaredPostError(receipts, clientMessageId) {
2458
+ const error = uncheckedDeclaredPost(receipts, clientMessageId);
2459
+ if (error) {
2460
+ this.logger.warn('The Relay accepted a declared post without comparing its device set', {
2461
+ category: 'E2EE',
2462
+ data: { code: error.code, route: error.route },
2463
+ });
2464
+ }
2465
+ return error;
2466
+ }
2467
+ /**
2468
+ * Replay a stored direct send on a relay that compares device sets. A
2469
+ * terminal send starts a new run at 0 restarts. A completed send with a
2470
+ * pending sync phase posts only its sync messages. It first reads the own
2471
+ * device list when the send could not read it: the phase has no sync
2472
+ * message and stores no own device with no bundle. A stored device with no
2473
+ * bundle goes through the sync phase, which refuses it as missing and
2474
+ * retries it as the live run does. A send that is not terminal resumes
2475
+ * with its stored restart counts.
2476
+ */
2477
+ async replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal) {
2478
+ const intent = await restartOutgoingDeviceSet(this.storage, existing.clientMessageId);
2479
+ const stored = outgoingMessageIntentResult(intent);
2480
+ if (!stored)
2481
+ return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
2482
+ if (!intent.syncPending)
2483
+ return stored;
2484
+ const { syncPending: _pending, ...result } = stored;
2485
+ let current = intent;
2486
+ if (current.syncMessages.length === 0 &&
2487
+ (current.deviceSetBundleMissing?.sync ?? []).length === 0) {
2488
+ const added = await this.addDeclaredDirectSync(current, plaintextBytes, sessions, stopSignal);
2489
+ if (added.unread)
2490
+ return stored;
2491
+ current = added.intent;
2492
+ if (current.syncMessages.length === 0) {
2493
+ await completeOutgoingSyncPhase(this.storage, current.clientMessageId);
2494
+ return result;
2495
+ }
2496
+ }
2497
+ const sync = await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal);
2498
+ return this.markUncheckedDeclaredPosts(sync.synced ? result : { ...result, syncPending: true }, syncPostReceipts(sync.accepted), current.clientMessageId);
2499
+ }
2500
+ /**
2501
+ * Add the sync copies of a direct intent from one read of the own device
2502
+ * list. A failed read is logged and does not fail the send.
2503
+ *
2504
+ * @returns The intent, and true when the read failed
2505
+ */
2506
+ async addDeclaredDirectSync(intent, plaintextBytes, sessions, stopSignal) {
2507
+ try {
2508
+ const listed = await this.readOwnDeviceList(sessions, stopSignal);
2509
+ const additions = await this.prepareDirectSyncMessages(intent, plaintextBytes, listed.map((device) => device.deviceId));
2510
+ if (additions.length === 0)
2511
+ return { intent, unread: false };
2512
+ return {
2513
+ intent: await reconcileOutgoingSyncMessages(this.storage, intent.clientMessageId, [], additions),
2514
+ unread: false,
2515
+ };
2516
+ }
2517
+ catch (error) {
2518
+ this.logger.warn('Could not read the own device list for the sync phase of a send', {
2519
+ category: 'E2EE',
2520
+ error: error,
2521
+ });
2522
+ return { intent, unread: true };
2523
+ }
2524
+ }
2525
+ /**
2526
+ * Post a stored direct intent on a relay that compares device sets: the
2527
+ * recipient phase first, then the sync phase (§5.4, §5.6). The recipient
2528
+ * result is stored before the sync phase starts. A failed sync phase gives
2529
+ * `syncPending` and does not fail the send, and the intent keeps the sync
2530
+ * messages for a replay.
2531
+ */
2532
+ async sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal) {
2533
+ const control = { ...(stopSignal && { stopSignal }) };
2534
+ let sealedSender;
2535
+ const recipient = await this.runDeclaredPhase({
2536
+ phase: 'recipient',
2537
+ clientMessageId: intent.clientMessageId,
2538
+ intentId: intent.clientMessageId,
2539
+ restarts: intent.deviceSetRestarts?.recipient ?? 0,
2540
+ messages: intent.deviceMessages,
2541
+ bundleMissing: intent.deviceSetBundleMissing?.recipient ?? [],
2542
+ ...(intent.recipientId !== this.userId && { requirePostTo: intent.recipientId }),
2543
+ post: (message, declaredDeviceIds) => this.sendStoredDirectDeviceMessage(intent, message, { ...control, declaredDeviceIds }),
2544
+ encrypt: async (device) => {
2545
+ const message = await this.sesameManager.sendMessage(device.userId, device.deviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
2546
+ if (sealedSender === undefined) {
2547
+ sealedSender = await this.resolveStoredDirectSealedSender(intent);
2548
+ }
2549
+ return this.prepareStoredDirectDeviceMessage(message, sealedSender, intent.contentHint);
2550
+ },
2551
+ sessions,
2552
+ stopSignal,
2553
+ });
2554
+ const accepted = recipient.values;
2555
+ let messageId = `local-${intent.clientTimestamp}`;
2556
+ let timestamp = intent.clientTimestamp;
2557
+ for (const acceptance of accepted) {
2558
+ if (messageId.startsWith('local-')) {
2559
+ messageId = acceptance.messageId;
2560
+ timestamp = acceptance.serverTimestamp;
2561
+ }
2562
+ }
2563
+ const result = {
2564
+ clientMessageId: intent.clientMessageId,
2565
+ messageId,
2566
+ timestamp,
2567
+ recipientDeviceCount: recipient.messages.length,
2568
+ ...aggregateRelayAcceptance(accepted),
2569
+ };
2570
+ // The sync phase runs when a recipient receipt sets needsSync or the
2571
+ // send holds an own device record. With needsSync and no own record,
2572
+ // the send reads the own list once. When that read fails, the sync
2573
+ // phase stays pending with no sync messages, and a replay reads it.
2574
+ let current = (await getOutgoingMessageIntent(this.storage, intent.clientMessageId)) ?? intent;
2575
+ let syncUnread = false;
2576
+ if (current.syncMessages.length === 0 &&
2577
+ accepted.some((acceptance) => acceptance.needsSync === true)) {
2578
+ const added = await this.addDeclaredDirectSync(current, plaintextBytes, sessions, stopSignal);
2579
+ current = added.intent;
2580
+ syncUnread = added.unread;
2581
+ }
2582
+ const syncPhase = current.syncMessages.length > 0;
2583
+ await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result, {
2584
+ syncPending: syncPhase || syncUnread,
2585
+ });
2586
+ const sync = syncPhase
2587
+ ? await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal)
2588
+ : { synced: true, accepted: [] };
2589
+ const route = intent.transportMode === 'identified' ? 'identified-direct' : 'anonymous-direct';
2590
+ return this.markUncheckedDeclaredPosts({ ...result, ...((!sync.synced || syncUnread) && { syncPending: true }) }, [
2591
+ ...accepted.map((acceptance) => [acceptance, route]),
2592
+ ...syncPostReceipts(sync.accepted),
2593
+ ], intent.clientMessageId);
2594
+ }
2595
+ /** Encrypt the sync copy of a direct intent again for one own device. */
2596
+ directSyncEncrypt(intent, plaintextBytes) {
2597
+ return async (device) => (await this.prepareDirectSyncMessages(intent, plaintextBytes, [device.deviceId]))[0];
2598
+ }
2599
+ /**
2600
+ * Run the declared sync phase of a completed intent. The phase has its own
2601
+ * restart count. A failure or an unresolved end is logged and leaves the
2602
+ * phase pending. The outcome keeps the receipt of each accepted sync post,
2603
+ * also when the phase fails, so the send reports a receipt without the
2604
+ * `deviceSetChecked` mark.
2605
+ */
2606
+ async finishDeclaredSync(intent, encrypt, sessions, stopSignal) {
2607
+ const relay = this.relay;
2608
+ const control = { ...(stopSignal && { stopSignal }) };
2609
+ const accepted = [];
2610
+ try {
2611
+ await this.runDeclaredPhase({
2612
+ phase: 'sync',
2613
+ clientMessageId: intent.clientMessageId,
2614
+ intentId: intent.clientMessageId,
2615
+ restarts: intent.deviceSetRestarts?.sync ?? 0,
2616
+ messages: intent.syncMessages,
2617
+ bundleMissing: intent.deviceSetBundleMissing?.sync ?? [],
2618
+ post: async (message, declaredDeviceIds) => {
2619
+ accepted.push(await this.postSyncCopy(relay, message, { ...control, declaredDeviceIds }));
2620
+ },
2621
+ encrypt,
2622
+ sessions,
2623
+ stopSignal,
2624
+ });
2625
+ await completeOutgoingSyncPhase(this.storage, intent.clientMessageId);
2626
+ return { synced: true, accepted };
2627
+ }
2628
+ catch (error) {
2629
+ this.logger.warn('The sync phase of a send did not complete', {
2630
+ category: 'E2EE',
2631
+ error: error,
2632
+ data: { phase: 'sync' },
2633
+ });
2634
+ return { synced: false, accepted };
2635
+ }
2636
+ }
2637
+ /**
2638
+ * Post a sync payload to the own devices that this device holds records
2639
+ * for, on a relay that compares device sets. The posts share one operation
2640
+ * ID, so a restart posts the stored bytes of an accepted device again
2641
+ * under the same ID. With no own device record, nothing is posted. A sync
2642
+ * payload has no send result, so the reporter gives the protocol error of
2643
+ * an accepted post without the `deviceSetChecked` mark to the app.
2644
+ *
2645
+ * @throws {DeviceSetReconciliationError} when the phase ends unresolved
2646
+ */
2647
+ async sendDeclaredSyncPayload(payloadBytes, timestamp) {
2648
+ const relay = this.relay;
2649
+ const ownDevices = await this.localOwnDevices();
2650
+ if (ownDevices.length === 0)
2651
+ return;
2652
+ const copies = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
2653
+ clientTimestamp: timestamp,
2654
+ includeSyncMessages: false,
2655
+ listedDeviceIds: ownDevices.map((device) => device.deviceId),
2656
+ });
2657
+ if (copies.length === 0)
2658
+ return;
2659
+ const operationId = await CryptoUtils.generateUuidV4();
2660
+ const prepare = (message) => this.prepareStoredSyncMessage(message, syncMessageId(operationId, message));
2661
+ const accepted = [];
2662
+ try {
2663
+ await this.runDeclaredPhase({
2664
+ phase: 'sync',
2665
+ clientMessageId: operationId,
2666
+ restarts: 0,
2667
+ messages: await Promise.all(copies.map(prepare)),
2668
+ post: async (message, declaredDeviceIds) => {
2669
+ accepted.push(await this.postSyncCopy(relay, message, { declaredDeviceIds }));
2670
+ },
2671
+ encrypt: async (device) => {
2672
+ const [message] = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
2673
+ clientTimestamp: timestamp,
2674
+ includeSyncMessages: false,
2675
+ listedDeviceIds: [device.deviceId],
2676
+ });
2677
+ return message && prepare(message);
2678
+ },
2679
+ sessions: this.sessionCallbacks,
2680
+ stopSignal: undefined,
2681
+ });
2682
+ }
2683
+ finally {
2684
+ // The payload is delivered to each accepted device, also when the
2685
+ // phase fails. The app knows no clientMessageId for the payload.
2686
+ const error = this.uncheckedDeclaredPostError(syncPostReceipts(accepted), undefined);
2687
+ if (error)
2688
+ await this.relayProtocolErrorReporter?.(error);
2689
+ }
2690
+ }
1388
2691
  async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal) {
1389
2692
  const control = { ...(stopSignal && { stopSignal }) };
2693
+ // A send prepared in this attempt keeps its distribution for a repair.
2694
+ const repair = { ...(sessions && { sessions }) };
2695
+ const declared = this.declaresDeviceSets();
1390
2696
  return sendGroupWithExactOutbox({
1391
2697
  storage: this.storage,
1392
2698
  ...(this.relay && { relay: this.relay }),
@@ -1395,6 +2701,8 @@ export class SignalProtocolServiceCipher {
1395
2701
  deliveryMode: this.sealedSenderDeliveryMode,
1396
2702
  preparePayload: async (groupId, bytes, sendOptions, readMembers) => {
1397
2703
  const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions, sessions, readMembers, stopSignal);
2704
+ if (prepared.distribution)
2705
+ repair.distribution = prepared.distribution;
1398
2706
  return {
1399
2707
  ciphertext: CryptoUtils.bytesToBase64(prepared.ciphertext),
1400
2708
  preMessages: prepared.preMessages,
@@ -1403,9 +2711,12 @@ export class SignalProtocolServiceCipher {
1403
2711
  }),
1404
2712
  };
1405
2713
  },
1406
- confirmSenderKeyDistributionSent: (groupId, senderKeyId) => this.senderKeyManager.confirmSenderKeyDistributionSent(groupId, this.userId, this.deviceId, senderKeyId),
1407
- resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions, stopSignal),
1408
- prepareSharedMessage: async (groupId, members, ciphertext) => {
2714
+ prepareContent: (groupId, bytes) => this.contentWithGroupContext(groupId, bytes),
2715
+ recordSenderKeyHandoff: (groupId, message) => this.recordSenderKeyHandoff(groupId, message),
2716
+ resolveMemberDevices: (groupId, sendOptions) => declared
2717
+ ? this.localGroupMemberDevices(groupId, sendOptions, stopSignal)
2718
+ : this.resolveGroupMemberDevices(groupId, sendOptions, stopSignal),
2719
+ prepareSharedMessage: async (groupId, members, ciphertext, contentHint) => {
1409
2720
  if (members.length === 0 ||
1410
2721
  this.sealedSenderDeliveryMode === 'disabled' ||
1411
2722
  !this.sealedSenderProvider ||
@@ -1418,6 +2729,7 @@ export class SignalProtocolServiceCipher {
1418
2729
  senderKeys: await this.sealedSenderProvider(),
1419
2730
  members,
1420
2731
  encryptedMessageBase64: ciphertext,
2732
+ contentHint,
1421
2733
  });
1422
2734
  return prepared
1423
2735
  ? {
@@ -1428,41 +2740,116 @@ export class SignalProtocolServiceCipher {
1428
2740
  }
1429
2741
  : undefined;
1430
2742
  },
1431
- prepareDeviceMessage: (member, groupId, ciphertext, timestamp) => this.prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp),
1432
- prepareSyncMessages: async (groupId, bytes, timestamp, clientMessageId) => {
1433
- if (!this.relay)
2743
+ prepareDeviceMessage: (member, groupId, ciphertext, timestamp, contentHint) => this.prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp, contentHint),
2744
+ resolveOwnDevices: () => declared ? this.localOwnDevices() : this.readOwnDeviceList(sessions, stopSignal),
2745
+ prepareSyncMessages: async (groupId, bytes, timestamp, clientMessageId, ownDevices) => {
2746
+ if (!this.relay || ownDevices.length === 0)
1434
2747
  return [];
1435
2748
  const syncPayload = this.buildSentSyncTranscript(groupId, bytes, timestamp);
1436
2749
  const prepared = await this.sesameManager.sendToLocalOtherDevices(syncPayload, {
1437
2750
  clientTimestamp: timestamp,
1438
2751
  includeSyncMessages: false,
2752
+ listedDeviceIds: ownDevices.map((device) => device.deviceId),
1439
2753
  });
1440
- return prepared.map((message, index) => ({
1441
- recipientUserId: message.recipientUserId,
1442
- recipientDeviceId: message.recipientDeviceId,
1443
- timestamp: message.timestamp,
1444
- clientMessageId: `${clientMessageId}:sync:${index}`,
1445
- ciphertext: typeof message.ciphertext === 'string'
1446
- ? message.ciphertext
1447
- : CryptoUtils.bytesToBase64(message.ciphertext),
1448
- messageType: getEnvelopeMessageType(message.ciphertext),
1449
- }));
2754
+ return Promise.all(prepared.map((message) => this.prepareStoredSyncMessage(message, syncMessageId(clientMessageId, message))));
1450
2755
  },
2756
+ postSyncMessage: (intent, message, rebuild) => this.postSyncMessage(this.relay, message, control, {
2757
+ sessions: repair.sessions,
2758
+ intentId: intent.clientMessageId,
2759
+ rebuild,
2760
+ }),
1451
2761
  resolveGroupAuthorization: (groupId, recipients) => this.resolveGroupSendAuthorization(groupId, recipients),
1452
2762
  reportIdentifiedFallback: (recipientUserId) => this.reportIdentifiedFallback(recipientUserId),
1453
- sendPreparedSealedDevice: (intent, message, auth) => this.sendToDevice(message, message.ciphertext, message.messageType, undefined, null, undefined, intent.clientMessageId, {
2763
+ refreshPreMessageEndorsements: (groupId, recipientUserIds) => this.refreshPreMessageEndorsements(groupId, recipientUserIds),
2764
+ authorizePreMessage: (groupId, message, required) => this.authorizePreMessage(groupId, message, required),
2765
+ postPreMessage: (intent, transport, required) => this.postPreMessage(intent, transport, required, repair, control),
2766
+ prepareSenderKeyHandoffs: (intent, listed) => this.prepareIntentSenderKeyHandoffs(intent, listed, repair, repair.sessions, stopSignal),
2767
+ remoteRegistrationId: (device) => this.sesameManager.getRemoteRegistrationId(device.userId, device.deviceId),
2768
+ isConclusiveDeviceRejection: (error) => isConclusiveDeviceRejection(error),
2769
+ repairStaleDevice: (intent, message) => this.repairStaleGroupDevice(intent, message, repair, stopSignal),
2770
+ sendPreparedSealedDevice: (intent, message, auth, declaredDeviceIds) => this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, undefined, intent.clientMessageId, {
1454
2771
  sentMessageBase64: message.sealedSenderMessage,
1455
2772
  auth,
1456
2773
  deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
1457
- }, control),
2774
+ }, { ...control, ...(declaredDeviceIds && { declaredDeviceIds }) }),
1458
2775
  prepareEach: (items, task) => this.fanOut.all(items, task).catch((error) => {
1459
2776
  throw firstItemError(error);
1460
2777
  }),
1461
2778
  sendPhase: (messages, task, phase) => this.sendPhase(messages, task, phase, stopSignal),
1462
2779
  postToRelay: (send, sealed) => this.postToRelay(send, sealed, control),
2780
+ ...(declared && {
2781
+ deviceSets: this.groupDeviceSetContext(sessions, stopSignal),
2782
+ }),
1463
2783
  }, actualGroupId, plaintextBytes, options);
1464
2784
  }
1465
- async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp) {
2785
+ /**
2786
+ * The declared work of a group send on a relay that compares device sets
2787
+ * (§5.5 of the device-set contract).
2788
+ */
2789
+ groupDeviceSetContext(sessions, stopSignal) {
2790
+ return {
2791
+ repairDevices: (account, postedRegistration, unposted) => {
2792
+ if (!sessions) {
2793
+ throw new EncryptionError('Session establishment is not configured', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: account.userId });
2794
+ }
2795
+ return this.inRepairTurn(account.userId, () => this.repairRefusedDevices(sessions, account, {
2796
+ phase: 'recipient',
2797
+ stopSignal,
2798
+ postedRegistration,
2799
+ unposted,
2800
+ }));
2801
+ },
2802
+ readOwnDevices: () => this.readOwnDeviceList(sessions, stopSignal),
2803
+ runSyncPhase: (intent, rebuild) => this.finishDeclaredSync(intent, rebuild, sessions, stopSignal),
2804
+ unresolve: async (clientMessageId, unresolved) => {
2805
+ await markOutgoingDeviceSetUnresolved(this.storage, clientMessageId, storedDeviceSetUnresolved(unresolved));
2806
+ },
2807
+ wait: (milliseconds) => waitUnlessStopped(milliseconds, stopSignal),
2808
+ logFailure: (device, error) => {
2809
+ this.logger.warn('A device post of a send failed', {
2810
+ category: 'E2EE',
2811
+ error: error,
2812
+ data: { phase: 'recipient', recipientUserId: device.userId, deviceId: device.deviceId },
2813
+ });
2814
+ },
2815
+ warn: (message, error) => {
2816
+ this.logger.warn(message, { category: 'E2EE', error: error });
2817
+ },
2818
+ markUnchecked: (result, receipts, clientMessageId) => this.markUncheckedDeclaredPosts(result, receipts, clientMessageId),
2819
+ };
2820
+ }
2821
+ /**
2822
+ * The devices of the group members on a relay that compares device sets.
2823
+ * Each member with a local device record gives the devices of that record,
2824
+ * and the sender device is left out. Only another member with no record
2825
+ * has its device list read (§5.2 of the device-set contract).
2826
+ */
2827
+ async localGroupMemberDevices(groupId, options, stopSignal) {
2828
+ const memberUserIds = options?.groupMemberUserIds ?? [];
2829
+ if (memberUserIds.length === 0) {
2830
+ return this.resolveGroupMemberDevices(groupId, options, stopSignal);
2831
+ }
2832
+ const local = await Promise.all(memberUserIds.map(async (userId) => {
2833
+ const record = await this.sesameManager.getUserRecord(userId);
2834
+ const held = unremovedDeviceIds(record);
2835
+ const deviceIds = held
2836
+ .filter((deviceId) => userId !== this.userId || deviceId !== this.deviceId)
2837
+ .sort((a, b) => a - b);
2838
+ // The own account is never read here. The send leaves it out of the
2839
+ // members, and the sync phase reads the own list only on needsSync.
2840
+ const own = userId === this.userId;
2841
+ return { userId, deviceIds, known: own || held.length > 0 };
2842
+ }));
2843
+ const unknown = local.filter((member) => !member.known).map((member) => member.userId);
2844
+ const listed = unknown.length > 0
2845
+ ? await this.resolveGroupMemberDevices(groupId, { ...options, groupMemberUserIds: unknown }, stopSignal)
2846
+ : [];
2847
+ return [
2848
+ ...local.flatMap((member) => member.deviceIds.map((deviceId) => ({ userId: member.userId, deviceId }))),
2849
+ ...listed,
2850
+ ];
2851
+ }
2852
+ async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp, contentHint) {
1466
2853
  const stored = {
1467
2854
  recipientUserId: member.userId,
1468
2855
  recipientDeviceId: member.deviceId,
@@ -1470,22 +2857,370 @@ export class SignalProtocolServiceCipher {
1470
2857
  ciphertext,
1471
2858
  messageType: 'sender_key',
1472
2859
  };
2860
+ // The post names the registration of the current session, so the Relay
2861
+ // refuses it when the device was reinstalled.
2862
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(member.userId, member.deviceId);
2863
+ if (registrationId !== undefined)
2864
+ stored.recipientRegistrationId = registrationId;
1473
2865
  const sealedSender = await this.resolveSealedSenderContext(member.userId, groupId);
1474
2866
  if (!sealedSender || !this.relay?.sendMultiRecipientUnidentified)
1475
2867
  return stored;
1476
- stored.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(stored, ciphertext, 'sender_key', undefined, sealedSender, undefined);
1477
- stored.sealedSenderDeliveryMode =
1478
- sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred';
2868
+ return this.sealStoredDeviceMessage(stored, sealedSender, sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred', contentHint);
2869
+ }
2870
+ /** A copy of a stored device message with the sealed transport of its ciphertext. */
2871
+ async sealStoredDeviceMessage(message, sealedSender, deliveryMode, contentHint) {
2872
+ const sealed = { ...message };
2873
+ sealed.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(message, message.ciphertext, message.messageType, message.recipientRegistrationId, sealedSender, contentHint);
2874
+ sealed.sealedSenderDeliveryMode = deliveryMode;
1479
2875
  if (sealedSender.auth.type === 'accessKey') {
1480
- stored.sealedSenderAuthorization = 'access_key';
1481
- stored.sealedSenderAccessKey = sealedSender.auth.unidentifiedAccessKey;
2876
+ sealed.sealedSenderAuthorization = 'access_key';
2877
+ sealed.sealedSenderAccessKey = sealedSender.auth.unidentifiedAccessKey;
1482
2878
  }
1483
2879
  else {
1484
- stored.sealedSenderAuthorization = 'group_send_token';
2880
+ sealed.sealedSenderAuthorization = 'group_send_token';
1485
2881
  }
1486
- return stored;
2882
+ return sealed;
1487
2883
  }
1488
- async resolveGroupSendAuthorization(groupId, recipientUserIds) {
2884
+ /**
2885
+ * The sealed-sender context of a sender-key pre-message. A pre-message goes
2886
+ * to one recipient, so the recipient's access key comes first, and the
2887
+ * group endorsement serves a member with no access key. Resolves to null
2888
+ * when the pre-message goes identified, and throws SEALED_SENDER_REQUIRED
2889
+ * in required mode when neither authorization resolves.
2890
+ */
2891
+ async resolveDistributionSealedSender(recipientUserId, groupId) {
2892
+ try {
2893
+ const accessKey = await this.resolveSealedSenderContext(recipientUserId);
2894
+ if (accessKey)
2895
+ return accessKey;
2896
+ }
2897
+ catch (error) {
2898
+ if (!(error instanceof EncryptionError) ||
2899
+ error.code !== EncryptionErrorCode.SEALED_SENDER_REQUIRED) {
2900
+ throw error;
2901
+ }
2902
+ }
2903
+ return this.resolveSealedSenderContext(recipientUserId, groupId);
2904
+ }
2905
+ /**
2906
+ * The transport of one stored pre-message for this dispatch. The
2907
+ * authorization resolves again at each dispatch, so a required send checks
2908
+ * its privacy before any post. A pre-message that has no sealed transport
2909
+ * is sealed from its stored ciphertext, with no new ratchet effect.
2910
+ */
2911
+ async authorizePreMessage(groupId, message, required) {
2912
+ const sealedSender = await this.resolveDistributionSealedSender(message.recipientUserId, groupId);
2913
+ if (!sealedSender || !this.relay?.sendMultiRecipientUnidentified) {
2914
+ if (required) {
2915
+ throw new EncryptionError('Required group sealed-sender authorization is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: message.recipientUserId, groupId });
2916
+ }
2917
+ return { message };
2918
+ }
2919
+ return {
2920
+ message: message.sealedSenderMessage
2921
+ ? message
2922
+ : await this.sealStoredDeviceMessage(message, sealedSender, required ? 'required' : 'preferred'),
2923
+ auth: sealedSender.auth,
2924
+ };
2925
+ }
2926
+ /**
2927
+ * Post one pre-message once, sealed when its transport has an
2928
+ * authorization. The relay can reject an access key that the client
2929
+ * guessed, for a recipient whose access mode it never learned. The
2930
+ * rejection restricts the cached mode, and the post goes again with the
2931
+ * group endorsement. A preferred post goes identified only when no sealed
2932
+ * authorization is accepted. A required post fails then.
2933
+ */
2934
+ async sendPreMessage(intent, { message, auth }, required, control) {
2935
+ if (auth?.type !== 'accessKey' || !message.sealedSenderMessage) {
2936
+ return this.postStoredPreMessage(intent, message, auth, required, control);
2937
+ }
2938
+ let rejection;
2939
+ try {
2940
+ return await this.postStoredPreMessage(intent, message, auth, true, control);
2941
+ }
2942
+ catch (error) {
2943
+ if (!(error instanceof SealedSenderAuthError))
2944
+ throw error;
2945
+ rejection = error;
2946
+ }
2947
+ await this.restrictUnidentifiedAccessMode(message.recipientUserId);
2948
+ // The rejected post started, so the next post continues it.
2949
+ const continued = {
2950
+ ...(control.stopSignal && { stopSignal: control.stopSignal }),
2951
+ ...(control.operationEpochMilliseconds !== undefined && {
2952
+ operationEpochMilliseconds: control.operationEpochMilliseconds,
2953
+ }),
2954
+ };
2955
+ const endorsement = await this.resolveDistributionEndorsement(message.recipientUserId, intent.recipientId);
2956
+ if (endorsement) {
2957
+ try {
2958
+ return await this.postStoredPreMessage(intent, message, endorsement, true, continued);
2959
+ }
2960
+ catch (error) {
2961
+ if (!(error instanceof SealedSenderAuthError))
2962
+ throw error;
2963
+ rejection = error;
2964
+ }
2965
+ }
2966
+ if (required)
2967
+ throw rejection;
2968
+ await this.reportIdentifiedFallback(message.recipientUserId);
2969
+ return this.postStoredPreMessage(intent, message, undefined, false, continued);
2970
+ }
2971
+ /**
2972
+ * The group endorsement of one pre-message recipient, or null when the
2973
+ * group has none for the recipient.
2974
+ */
2975
+ async resolveDistributionEndorsement(recipientUserId, groupId) {
2976
+ let context;
2977
+ try {
2978
+ context = await this.resolveSealedSenderContext(recipientUserId, groupId);
2979
+ }
2980
+ catch (error) {
2981
+ if (error instanceof EncryptionError &&
2982
+ error.code === EncryptionErrorCode.SEALED_SENDER_REQUIRED) {
2983
+ return null;
2984
+ }
2985
+ throw error;
2986
+ }
2987
+ return context?.auth.type === 'groupSendToken' ? context.auth : null;
2988
+ }
2989
+ /** One relay post of a stored pre-message, sealed when `auth` is given. */
2990
+ postStoredPreMessage(intent, message, auth, required, control) {
2991
+ return this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, undefined, intent.clientMessageId, auth && message.sealedSenderMessage
2992
+ ? {
2993
+ sentMessageBase64: message.sealedSenderMessage,
2994
+ auth,
2995
+ deliveryMode: required ? 'required' : 'preferred',
2996
+ }
2997
+ : undefined, { ...control, deliveryClass: 'background-sync' });
2998
+ }
2999
+ /**
3000
+ * Post one pre-message, and repair its session once if the device refuses
3001
+ * it conclusively. A NOT_FOUND refusal of a device that the recipient's
3002
+ * device list no longer shows drops the pre-message, as a direct send
3003
+ * drops a removed device. A replay whose sender key rotated since the send
3004
+ * refreshes the session and drops the pre-message, because it has no
3005
+ * distribution of the key of the send. Resolves to the pre-message that the
3006
+ * relay accepted or that the send dropped, with the outcome.
3007
+ */
3008
+ async postPreMessage(intent, transport, required, repair, control) {
3009
+ try {
3010
+ await this.sendPreMessage(intent, transport, required, control);
3011
+ return { message: transport.message, outcome: 'accepted' };
3012
+ }
3013
+ catch (error) {
3014
+ if (await this.isRemovedDeviceRefusal(error, transport.message, control)) {
3015
+ return { message: transport.message, outcome: 'removed' };
3016
+ }
3017
+ if (!isConclusiveDeviceRejection(error))
3018
+ throw error;
3019
+ }
3020
+ if (!repair.sessions)
3021
+ throw new Error('Stale-session refresh is not configured');
3022
+ const sessions = repair.sessions;
3023
+ const repaired = await this.inRepairTurn(transport.message.recipientUserId, () => this.repairRejectedPreMessageInTurn(intent, transport.message, required, repair, sessions));
3024
+ if (!repaired)
3025
+ return { message: transport.message, outcome: 'dropped', refreshed: true };
3026
+ try {
3027
+ await this.sendPreMessage(intent, repaired, required, control);
3028
+ }
3029
+ catch (error) {
3030
+ if (!(await this.isRemovedDeviceRefusal(error, repaired.message, control)))
3031
+ throw error;
3032
+ return { message: repaired.message, outcome: 'removed' };
3033
+ }
3034
+ return { message: repaired.message, outcome: 'accepted', refreshed: true };
3035
+ }
3036
+ /**
3037
+ * Delete the sender-key handoff rows of one device in one group, so the
3038
+ * next send gives the current key to that device. True when a row was
3039
+ * deleted. The caller runs it in the sender-key turn of the group.
3040
+ */
3041
+ invalidateSenderKeyHandoff(groupId, device) {
3042
+ return this.senderKeyHandoffs.invalidate(groupId, device);
3043
+ }
3044
+ /**
3045
+ * Delete the sender-key handoff rows of every device of one account in
3046
+ * every group. True when a row was deleted.
3047
+ */
3048
+ invalidateAccountSenderKeyHandoffs(userId) {
3049
+ return this.senderKeyHandoffs.invalidateAccount(userId);
3050
+ }
3051
+ /**
3052
+ * Delete the sender-key handoff rows that no current own key covers: every
3053
+ * row of a group with no own sender key, and each row whose senderKeyId is
3054
+ * not the current one. Each group runs in its own sender-key turn.
3055
+ *
3056
+ * @returns The count of deleted rows.
3057
+ */
3058
+ sweepSenderKeyHandoffs() {
3059
+ return this.senderKeyHandoffs.sweep({
3060
+ currentSenderKeyId: async (groupId) => (await this.senderKeyManager.getCurrentSenderKeyDistribution(groupId, this.userId, this.deviceId))?.senderKeyId ?? null,
3061
+ inTurn: (groupId, task) => this.groupSenderKeys.run(groupId, () => task()),
3062
+ });
3063
+ }
3064
+ /**
3065
+ * Record the handoff row of a pre-message that the Relay accepted. A
3066
+ * pre-message with no handoff key or no registration ID, as an intent from
3067
+ * an earlier SDK version stores it, records no row, so the next send gives
3068
+ * the key again.
3069
+ */
3070
+ async recordSenderKeyHandoff(groupId, message) {
3071
+ if (!message.senderKeyHandoff || message.recipientRegistrationId === undefined)
3072
+ return;
3073
+ await this.senderKeyHandoffs.record(groupId, message.senderKeyHandoff, { userId: message.recipientUserId, deviceId: message.recipientDeviceId }, message.recipientRegistrationId);
3074
+ }
3075
+ /**
3076
+ * True when the relay refused this pre-message with NOT_FOUND and the
3077
+ * recipient's device list no longer shows the device. A device that the
3078
+ * list still shows keeps the refusal as a failure.
3079
+ */
3080
+ async isRemovedDeviceRefusal(error, message, control) {
3081
+ if (relayDeviceRefusal(error)?.code !== 'NOT_FOUND' || !isRefusalOfDevice(error, message)) {
3082
+ return false;
3083
+ }
3084
+ const listed = await this.fanOut.request(() => this.relay.getActiveDevices(message.recipientUserId), control.stopSignal);
3085
+ if (listed.some(({ deviceId }) => deviceId === message.recipientDeviceId))
3086
+ return false;
3087
+ this.logger.info('Dropped the sender-key pre-message of a removed device', {
3088
+ category: 'E2EE',
3089
+ data: {
3090
+ recipientUserId: message.recipientUserId,
3091
+ recipientDeviceId: message.recipientDeviceId,
3092
+ },
3093
+ });
3094
+ return true;
3095
+ }
3096
+ /**
3097
+ * Refresh the session of a device that refused a pre-message, encrypt the
3098
+ * distribution again, and replace the stored pre-message before its post.
3099
+ * The saved refused ciphertext is never posted again. Resolves to
3100
+ * undefined when a replay has no distribution of the key of the send.
3101
+ */
3102
+ async repairRejectedPreMessageInTurn(intent, rejected, required, repair, sessions) {
3103
+ const refreshed = await sessions.refreshStaleSession(rejected.recipientUserId, rejected.recipientDeviceId);
3104
+ if (!refreshed) {
3105
+ throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: rejected.recipientUserId });
3106
+ }
3107
+ const distribution = repair.distribution ?? (await this.currentDistribution(intent));
3108
+ if (!distribution)
3109
+ return undefined;
3110
+ const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, distribution.bytes(), { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
3111
+ const fresh = await this.prepareStoredDirectDeviceMessage(freshMessage, null, undefined);
3112
+ fresh.clientMessageId = repairMessageId(rejected.clientMessageId ?? intent.clientMessageId);
3113
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(rejected.recipientUserId, rejected.recipientDeviceId);
3114
+ if (registrationId !== undefined)
3115
+ fresh.recipientRegistrationId = registrationId;
3116
+ if (rejected.senderKeyHandoff)
3117
+ fresh.senderKeyHandoff = rejected.senderKeyHandoff;
3118
+ const transport = await this.authorizePreMessage(intent.recipientId, fresh, required);
3119
+ await replaceOutgoingGroupPreMessages(this.storage, intent.clientMessageId, [
3120
+ { expected: rejected, replacement: transport.message },
3121
+ ]);
3122
+ return transport;
3123
+ }
3124
+ /**
3125
+ * The distribution of a replayed send. The attempt that prepared the send
3126
+ * kept its distribution in memory only, because the outbox is not
3127
+ * encrypted and must hold no chain key. A replay rebuilds the distribution
3128
+ * from the current sender key. Its chain index is past the group message
3129
+ * of the send, so a device that installs it decrypts the later group
3130
+ * messages of the sender, but not this one. Resolves to undefined when the
3131
+ * current sender key is not the key of the send: a rotation since the
3132
+ * send deleted the handoff rows of the group, and the next send gives the
3133
+ * current key to each device.
3134
+ */
3135
+ async currentDistribution(intent) {
3136
+ const groupId = intent.recipientId;
3137
+ const current = await this.senderKeyManager.getCurrentSenderKeyDistribution(groupId, this.userId, this.deviceId);
3138
+ if (!current || current.senderKeyId !== intent.groupSenderKeyDistributionId) {
3139
+ this.logger.info('The sender key of a replayed group send is no longer current', {
3140
+ category: 'E2EE',
3141
+ data: { groupId, behavior: 'REPLAY_SENDER_KEY_ROTATED' },
3142
+ });
3143
+ return undefined;
3144
+ }
3145
+ return {
3146
+ key: { senderKeyId: current.senderKeyId, generation: current.generation },
3147
+ bytes: () => this.serializeSenderKeyDistribution(groupId, current),
3148
+ };
3149
+ }
3150
+ /**
3151
+ * The sender-key pre-messages that give the key of a stored group send to
3152
+ * the listed devices of other members that need it. The attempt that
3153
+ * prepared the send gives the distribution at the chain index of its group
3154
+ * message. A replay gives the current distribution when the current key is
3155
+ * still the key of the send. When the key rotated, a replay gives no
3156
+ * pre-message. The added devices recover through a retry request, and the
3157
+ * next send gives them the current key. `listed` holds only the devices
3158
+ * that can get a pre-message, as `GroupOutboxContext.prepareSenderKeyHandoffs`
3159
+ * states. A device that a stored pre-message of the intent targets gets no
3160
+ * second one. Each pre-message gets a new transport identity.
3161
+ */
3162
+ async prepareIntentSenderKeyHandoffs(intent, listed, repair, sessions, stopSignal) {
3163
+ const otherMembers = listed.filter((member) => member.userId !== this.userId);
3164
+ if (otherMembers.length === 0)
3165
+ return [];
3166
+ const distribution = repair.distribution ?? (await this.currentDistribution(intent));
3167
+ if (!distribution)
3168
+ return [];
3169
+ const preMessages = await this.prepareSenderKeyHandoffMessages(intent.recipientId, otherMembers, distribution.key, distribution.bytes, intent.clientTimestamp, sessions, stopSignal, intent.preMessages ?? []);
3170
+ for (const message of preMessages) {
3171
+ const handoffId = await CryptoUtils.generateUuidV4();
3172
+ message.clientMessageId = `${intent.clientMessageId}:sender-key-distribution:${handoffId}`;
3173
+ }
3174
+ return preMessages;
3175
+ }
3176
+ /**
3177
+ * Repair a group device post that the Relay refused as a stale device. When
3178
+ * the session still has the refused registration, the repair refreshes the
3179
+ * session, and the archive deletes the handoff rows of the device. When an
3180
+ * earlier repair of this attempt already refreshed it, the session stays.
3181
+ * Then the device gets the key of the send when it has no row, and a new
3182
+ * device message with the registration of the current session.
3183
+ */
3184
+ async repairStaleGroupDevice(intent, refused, repair, stopSignal) {
3185
+ const groupCiphertext = intent.groupCiphertext;
3186
+ if (!groupCiphertext)
3187
+ throw new Error('Corrupt group outbox intent');
3188
+ const sessions = repair.sessions;
3189
+ if (!sessions)
3190
+ throw new Error('Stale-session refresh is not configured');
3191
+ const device = { userId: refused.recipientUserId, deviceId: refused.recipientDeviceId };
3192
+ return this.inRepairTurn(device.userId, async () => {
3193
+ const current = await this.sesameManager.getRemoteRegistrationId(device.userId, device.deviceId);
3194
+ if (current === undefined || current === refused.recipientRegistrationId) {
3195
+ const refreshed = await sessions.refreshStaleSession(device.userId, device.deviceId);
3196
+ if (!refreshed) {
3197
+ throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: device.userId });
3198
+ }
3199
+ }
3200
+ // The device has a session now, so the preparation reads no device
3201
+ // list and needs no session callbacks.
3202
+ const preMessages = await this.prepareIntentSenderKeyHandoffs(intent, [device], repair, undefined, stopSignal);
3203
+ const deviceMessage = await this.prepareStoredGroupDeviceMessage(device, intent.recipientId, groupCiphertext, intent.clientTimestamp, intent.contentHint);
3204
+ return { preMessages, deviceMessage };
3205
+ });
3206
+ }
3207
+ /** The plaintext bytes of a sender-key distribution pre-message. */
3208
+ serializeSenderKeyDistribution(groupId, distributionMessage) {
3209
+ return this.contentAdapter
3210
+ ? this.contentAdapter.serializeSenderKeyDistributionBytes(groupId, distributionMessage)
3211
+ : new TextEncoder().encode(JSON.stringify({
3212
+ senderKeyDistributionMessage: JSON.stringify({
3213
+ groupId,
3214
+ ...distributionMessage,
3215
+ }),
3216
+ }));
3217
+ }
3218
+ /**
3219
+ * Refresh the group's endorsements when the cache lacks one of the
3220
+ * recipients or expires soon. Resolves to the endorsement manager, or to
3221
+ * null when the client has none.
3222
+ */
3223
+ async refreshGroupSendEndorsements(groupId, recipientUserIds) {
1489
3224
  const manager = this.endorsementManagerResolver ? await this.endorsementManagerResolver() : this.endorsementManager;
1490
3225
  if (!manager || recipientUserIds.length === 0)
1491
3226
  return null;
@@ -1502,6 +3237,27 @@ export class SignalProtocolServiceCipher {
1502
3237
  });
1503
3238
  }
1504
3239
  });
3240
+ return manager;
3241
+ }
3242
+ /**
3243
+ * Refresh the endorsements of a send's pre-messages before their
3244
+ * authorization resolves. A membership change clears the endorsements, and
3245
+ * a pre-message to a member with no access key needs one to stay sealed.
3246
+ * The refresh takes every recipient at once, so the group message reuses
3247
+ * it. It runs only when the send can seal a post with an endorsement.
3248
+ */
3249
+ async refreshPreMessageEndorsements(groupId, recipientUserIds) {
3250
+ if (this.sealedSenderDeliveryMode === 'disabled' ||
3251
+ !this.sealedSenderProvider ||
3252
+ !this.relay?.sendMultiRecipientUnidentified) {
3253
+ return;
3254
+ }
3255
+ await this.refreshGroupSendEndorsements(groupId, recipientUserIds);
3256
+ }
3257
+ async resolveGroupSendAuthorization(groupId, recipientUserIds) {
3258
+ const manager = await this.refreshGroupSendEndorsements(groupId, recipientUserIds);
3259
+ if (!manager)
3260
+ return null;
1505
3261
  const groupSecretParams = this.groupSecretParamsProvider
1506
3262
  ? await this.groupSecretParamsProvider(groupId)
1507
3263
  : null;
@@ -1574,18 +3330,51 @@ export class SignalProtocolServiceCipher {
1574
3330
  * group send endorsement.
1575
3331
  */
1576
3332
  async sealReceipt(recipientUserId, recipientDeviceId, ciphertextBase64) {
3333
+ return this.sealWithAccessKey(recipientUserId, recipientDeviceId, ciphertextBase64, 'ciphertext');
3334
+ }
3335
+ /**
3336
+ * Seal a retry request for anonymous delivery. The seal holds the payload
3337
+ * of the identified envelope as `PLAINTEXT_CONTENT`, and the certificate in
3338
+ * the seal names the requester. A retry request follows the sealed sender
3339
+ * delivery mode, as a receipt does. Resolves to undefined when the request
3340
+ * goes identified: sealed sender is disabled, or it is preferred and the
3341
+ * relay has no anonymous delivery or this client knows no access key of
3342
+ * the recipient. In `'required'` mode a request that cannot be sealed
3343
+ * throws `SEALED_SENDER_REQUIRED`, and the sealed request permits no
3344
+ * identified fallback. A retry request never uses a group send
3345
+ * endorsement.
3346
+ */
3347
+ async sealRetryRequest(recipientUserId, recipientDeviceId, payloadBase64) {
3348
+ return this.sealWithAccessKey(recipientUserId, recipientDeviceId, payloadBase64, 'retry_request');
3349
+ }
3350
+ /**
3351
+ * The registration ID of the current session with one device. A receipt
3352
+ * and a retry request name it, in the sealed body and on the identified
3353
+ * envelope, so the Relay refuses the post to a reinstalled device.
3354
+ * Undefined when this client has no session with the device.
3355
+ */
3356
+ recipientRegistrationId(userId, deviceId) {
3357
+ return this.sesameManager.getRemoteRegistrationId(userId, deviceId);
3358
+ }
3359
+ /**
3360
+ * Seal one direct control envelope under the access key of its recipient.
3361
+ * The body names the registration of the current session with the device.
3362
+ */
3363
+ async sealWithAccessKey(recipientUserId, recipientDeviceId, contentBase64, messageType) {
1577
3364
  // The resolver returns null, or throws in required mode, when the relay
1578
- // has no anonymous delivery.
3365
+ // has no anonymous delivery. Without a group ID it never uses an
3366
+ // endorsement.
1579
3367
  const sealedSender = await this.resolveSealedSenderContext(recipientUserId);
1580
3368
  if (!sealedSender)
1581
3369
  return undefined;
1582
3370
  if (sealedSender.auth.type !== 'accessKey') {
1583
3371
  // A direct context carries an access key. This guards the type.
1584
- this.useIdentifiedDeliveryOrThrow(recipientUserId, 'receipt needs an access key');
3372
+ const what = messageType === 'retry_request' ? 'retry request' : 'receipt';
3373
+ this.useIdentifiedDeliveryOrThrow(recipientUserId, `${what} needs an access key`);
1585
3374
  return undefined;
1586
3375
  }
1587
3376
  return {
1588
- sentMessageBase64: await this.serializeDirectSealedSenderMessage({ recipientUserId, recipientDeviceId }, ciphertextBase64, 'ciphertext', undefined, sealedSender, ContentHint.Implicit),
3377
+ sentMessageBase64: await this.serializeDirectSealedSenderMessage({ recipientUserId, recipientDeviceId }, contentBase64, messageType, await this.recipientRegistrationId(recipientUserId, recipientDeviceId), sealedSender, ContentHint.Implicit),
1589
3378
  auth: sealedSender.auth,
1590
3379
  identifiedFallback: sealedSender.config.deliveryMode !== 'required',
1591
3380
  };
@@ -1621,6 +3410,8 @@ export class SignalProtocolServiceCipher {
1621
3410
  // no two-recipient minimum; its recipient-count field permits this exact
1622
3411
  // direct-delivery shape.
1623
3412
  if ((sealedSender || preparedSealedSender) && this.relay.sendMultiRecipientUnidentified) {
3413
+ // The sealed body names the registration of its device, as the
3414
+ // identified post does.
1624
3415
  const prepared = preparedSealedSender ??
1625
3416
  (sealedSender
1626
3417
  ? {
@@ -1631,19 +3422,57 @@ export class SignalProtocolServiceCipher {
1631
3422
  : undefined);
1632
3423
  if (!prepared)
1633
3424
  throw new Error('Missing sealed-sender delivery state');
3425
+ // This post has one destination device, so a group endorsement takes
3426
+ // the direct sealed route.
3427
+ const sealedAuth = prepared.auth.type === 'groupSendToken'
3428
+ ? forDirectSealedRoute(prepared.auth)
3429
+ : prepared.auth;
3430
+ // The identified fallback declares the same device set as the sealed
3431
+ // post, because both name the same account.
1634
3432
  identifiedControl = {
1635
3433
  ...(control.stopSignal && { stopSignal: control.stopSignal }),
1636
3434
  ...(control.operationEpochMilliseconds !== undefined && {
1637
3435
  operationEpochMilliseconds: control.operationEpochMilliseconds,
1638
3436
  }),
3437
+ ...(control.deliveryClass && { deliveryClass: control.deliveryClass }),
3438
+ ...(control.declaredDeviceIds && { declaredDeviceIds: control.declaredDeviceIds }),
1639
3439
  };
3440
+ const declaredDeviceIds = control.declaredDeviceIds;
1640
3441
  try {
1641
- const result = await this.postToRelay(() => this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId, ...(control.operationEpochMilliseconds === undefined
1642
- ? []
1643
- : [control.operationEpochMilliseconds])), true, control);
3442
+ const result = await this.postToRelay(() => declaredDeviceIds
3443
+ ? this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, control.operationEpochMilliseconds, undefined, [{ userId: msg.recipientUserId, deviceIds: declaredDeviceIds }])
3444
+ : this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, ...(control.operationEpochMilliseconds !== undefined
3445
+ ? [control.operationEpochMilliseconds]
3446
+ : [])), true, control);
1644
3447
  if (result.uuids404.length > 0) {
1645
3448
  throw new SealedSenderRecipientRejectedError();
1646
3449
  }
3450
+ if (usedGroupRouteFallback(result)) {
3451
+ // The privacy of the post is the same on both routes. The record
3452
+ // shows that the Relay does not take the endorsement on the
3453
+ // direct route.
3454
+ this.logger.info('The Relay refused the group endorsement on the direct sealed route', {
3455
+ category: 'E2EE',
3456
+ data: {
3457
+ recipientUserId: msg.recipientUserId,
3458
+ recipientDeviceId: msg.recipientDeviceId,
3459
+ behavior: 'GROUP_ROUTE_FALLBACK',
3460
+ },
3461
+ });
3462
+ }
3463
+ // The group-token receipt names each refused destination with its
3464
+ // code. A declared post gets a whole-post refusal for a stale
3465
+ // registration instead. The refused count alone names no device, so
3466
+ // the send infers nothing from it.
3467
+ if (result.refusals?.some((refusal) => refusal.code === 'STALE_DEVICE' &&
3468
+ refusal.userId === msg.recipientUserId &&
3469
+ refusal.deviceId === msg.recipientDeviceId)) {
3470
+ throw markRelayDeviceRefusal(new Error('Recipient device registration changed'), {
3471
+ code: 'STALE_DEVICE',
3472
+ userId: msg.recipientUserId,
3473
+ deviceId: msg.recipientDeviceId,
3474
+ });
3475
+ }
1647
3476
  return result;
1648
3477
  }
1649
3478
  catch (error) {
@@ -1653,54 +3482,7 @@ export class SignalProtocolServiceCipher {
1653
3482
  if (prepared.deliveryMode === 'required') {
1654
3483
  throw error;
1655
3484
  }
1656
- // Restrict the cached mode after authorization fails.
1657
- try {
1658
- const contactProfileStateStore = this.contactProfileStateStore;
1659
- if (contactProfileStateStore) {
1660
- // The device posts of a send run at the same time. The lock
1661
- // orders their steps, so two failures step down twice, as posts
1662
- // in device order do.
1663
- await this.lock.acquire(`unidentified-access-mode:${msg.recipientUserId}`, async () => {
1664
- const currentMode = await contactProfileStateStore.getUnidentifiedAccessMode(msg.recipientUserId);
1665
- let newMode;
1666
- switch (currentMode) {
1667
- case UnidentifiedAccessMode.UNRESTRICTED:
1668
- newMode = UnidentifiedAccessMode.UNKNOWN;
1669
- break;
1670
- case UnidentifiedAccessMode.ENABLED:
1671
- case UnidentifiedAccessMode.UNKNOWN:
1672
- default:
1673
- newMode = UnidentifiedAccessMode.DISABLED;
1674
- break;
1675
- }
1676
- await contactProfileStateStore.updateUnidentifiedAccessMode(msg.recipientUserId, newMode);
1677
- this.logger.info('Sealed sender auth failed, transitioned mode and falling back to identified delivery', {
1678
- category: 'E2EE',
1679
- data: {
1680
- recipientUserId: msg.recipientUserId,
1681
- previousMode: currentMode,
1682
- newMode,
1683
- },
1684
- });
1685
- });
1686
- }
1687
- else {
1688
- this.logger.debug('No contact profile state store configured after sealed sender failure', {
1689
- category: 'E2EE',
1690
- data: { recipientUserId: msg.recipientUserId },
1691
- });
1692
- }
1693
- }
1694
- catch (modeError) {
1695
- // Non-fatal: mode transition failure should not block message delivery
1696
- this.logger.warn('Failed to update unidentified access mode after auth failure', {
1697
- category: 'E2EE',
1698
- data: {
1699
- recipientUserId: msg.recipientUserId,
1700
- error: modeError.message,
1701
- },
1702
- });
1703
- }
3485
+ await this.restrictUnidentifiedAccessMode(msg.recipientUserId);
1704
3486
  await this.reportIdentifiedFallback(msg.recipientUserId);
1705
3487
  // Fall through to identified path below
1706
3488
  }
@@ -1717,7 +3499,7 @@ export class SignalProtocolServiceCipher {
1717
3499
  senderDeviceId: this.deviceId,
1718
3500
  ciphertext: ciphertextBase64,
1719
3501
  messageType,
1720
- deliveryClass: 'user-visible',
3502
+ deliveryClass: identifiedControl.deliveryClass ?? 'user-visible',
1721
3503
  timestamp: msg.timestamp,
1722
3504
  ...(identifiedControl.operationEpochMilliseconds !== undefined && {
1723
3505
  operationEpochMilliseconds: identifiedControl.operationEpochMilliseconds,
@@ -1725,6 +3507,9 @@ export class SignalProtocolServiceCipher {
1725
3507
  clientMessageId: effectiveClientMessageId,
1726
3508
  recipientRegistrationId,
1727
3509
  contentHint,
3510
+ ...(identifiedControl.declaredDeviceIds && {
3511
+ declaredDeviceIds: identifiedControl.declaredDeviceIds,
3512
+ }),
1728
3513
  }), false, identifiedControl);
1729
3514
  }
1730
3515
  /**
@@ -1758,69 +3543,202 @@ export class SignalProtocolServiceCipher {
1758
3543
  deviceId: this.deviceId,
1759
3544
  });
1760
3545
  }
1761
- let distributionMessage = await this.senderKeyManager.getPendingSenderKeyDistribution(actualGroupId, this.userId, this.deviceId);
1762
- if (!distributionMessage) {
3546
+ // The age bound refuses an expired key at the encrypt below. An expired
3547
+ // key therefore rotates first. The rotation deletes the handoff rows of
3548
+ // the group, so every listed device gets the new key.
3549
+ if (await this.senderKeyManager.isOwnSenderKeyExpired(actualGroupId, this.userId, this.deviceId)) {
3550
+ this.logger.info('Sender key expired, auto-rotating', {
3551
+ category: 'E2EE',
3552
+ data: { groupId: actualGroupId },
3553
+ });
3554
+ await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId);
3555
+ }
3556
+ let encrypted;
3557
+ try {
3558
+ encrypted = await this.encryptWithCurrentDistribution(actualGroupId, plaintextBytes);
3559
+ }
3560
+ catch (error) {
3561
+ if (!(error instanceof EncryptionError) ||
3562
+ error.code !== EncryptionErrorCode.SENDER_KEY_EXPIRED) {
3563
+ throw error;
3564
+ }
3565
+ this.logger.info('Sender key expired, auto-rotating', {
3566
+ category: 'E2EE',
3567
+ data: { groupId: actualGroupId },
3568
+ });
3569
+ await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId);
3570
+ encrypted = await this.encryptWithCurrentDistribution(actualGroupId, plaintextBytes);
3571
+ }
3572
+ const { distribution, ciphertext } = encrypted;
3573
+ if (!this.relay)
3574
+ return { ciphertext, preMessages: [] };
3575
+ // The distribution is at the chain index of this message, so a device
3576
+ // that installs it decrypts this message. The bytes hold the chain key:
3577
+ // they stay in memory and never reach the outbox.
3578
+ const serialized = this.serializeSenderKeyDistribution(actualGroupId, distribution);
3579
+ const distributionBytes = () => serialized;
3580
+ const key = {
3581
+ senderKeyId: distribution.senderKeyId,
3582
+ generation: distribution.generation,
3583
+ };
3584
+ const members = await readMembers();
3585
+ const preMessages = await this.prepareSenderKeyHandoffMessages(actualGroupId, members.filter((member) => member.userId !== this.userId), key, distributionBytes, options.timestamp, sessions, stopSignal);
3586
+ // The index of each pre-message follows the member order.
3587
+ preMessages.forEach((message, index) => {
3588
+ message.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${index}`;
3589
+ });
3590
+ return {
3591
+ ciphertext,
3592
+ preMessages,
3593
+ senderKeyDistributionId: distribution.senderKeyId,
3594
+ distribution: { key, bytes: distributionBytes },
3595
+ };
3596
+ }
3597
+ /**
3598
+ * Read the current distribution of the own sender key, then encrypt the
3599
+ * group message with that key. The distribution is at the chain index of
3600
+ * the message.
3601
+ */
3602
+ async encryptWithCurrentDistribution(groupId, plaintextBytes) {
3603
+ const distribution = await this.senderKeyManager.getCurrentSenderKeyDistribution(groupId, this.userId, this.deviceId);
3604
+ if (!distribution) {
3605
+ throw new EncryptionError(`No sender key for group ${groupId}. Call createGroupSenderKey() first to create and distribute the key.`, EncryptionErrorCode.SESSION_NOT_FOUND, { groupId, userId: this.userId, deviceId: this.deviceId });
3606
+ }
3607
+ const ciphertext = await this.senderKeyManager.encryptGroupMessage(groupId, this.userId, this.deviceId, plaintextBytes);
3608
+ return { distribution, ciphertext };
3609
+ }
3610
+ /**
3611
+ * The sender-key pre-messages of a send: one distribution pre-message for
3612
+ * each listed device of another member that has no handoff row for the
3613
+ * current key and the current session with the device. A device with no
3614
+ * session gets one first, and the freshness window of the device list
3615
+ * does not apply to it. The sender's own devices are never targets: they
3616
+ * get the transcript.
3617
+ *
3618
+ * Each recipient has a session and a resolved privacy policy before the
3619
+ * first distribution encryption, so a required send that cannot seal a
3620
+ * pre-message makes no peer ratchet effect.
3621
+ *
3622
+ * A device that cannot take the distribution is skipped, and the next send
3623
+ * tries it again, because it has no row. Only the listed devices count for
3624
+ * the failure rule. The send fails for a member when each listed device of
3625
+ * the member that needs the key fails, and no other listed device of the
3626
+ * member has the key. A listed device has the key when it has a row, or
3627
+ * when a `pending` pre-message targets it, so such a device is not a
3628
+ * target. `GroupOutboxContext.prepareSenderKeyHandoffs` states the same
3629
+ * rule.
3630
+ */
3631
+ async prepareSenderKeyHandoffMessages(groupId, otherMembers, key, distributionBytes, timestamp, sessions, stopSignal, pending = []) {
3632
+ const targets = await this.senderKeyHandoffTargets(otherMembers);
3633
+ const pendingDevices = new Set(pending.map((message) => groupDeviceKey({ userId: message.recipientUserId, deviceId: message.recipientDeviceId })));
3634
+ const needing = (await this.senderKeyHandoffs.devicesNeedingKey(groupId, key, targets)).filter((target) => !pendingDevices.has(groupDeviceKey(target)));
3635
+ if (needing.length === 0)
3636
+ return [];
3637
+ const bytes = distributionBytes();
3638
+ const recipientUserIds = [...new Set(needing.map((target) => target.userId))];
3639
+ await this.refreshPreMessageEndorsements(groupId, recipientUserIds);
3640
+ const sealedSenders = await this.fanOut
3641
+ .all(recipientUserIds, async (recipientUserId) => {
3642
+ await this.ensureSenderKeyHandoffSessions(recipientUserId, needing.filter((target) => target.userId === recipientUserId), otherMembers.filter((member) => member.userId === recipientUserId), sessions);
3643
+ return this.relay?.sendMultiRecipientUnidentified
3644
+ ? this.resolveDistributionSealedSender(recipientUserId, groupId)
3645
+ : this.useIdentifiedDeliveryOrThrow(recipientUserId, 'anonymous relay capability is not configured');
3646
+ }, stopSignal)
3647
+ .catch((error) => {
3648
+ throw firstItemError(error);
3649
+ });
3650
+ const prepared = await this.fanOut
3651
+ .all(recipientUserIds, (recipientUserId, index) => this.prepareUserSenderKeyHandoffs(groupId, recipientUserId, needing.filter((target) => target.userId === recipientUserId), targets.filter((target) => target.userId === recipientUserId && !needing.includes(target)).length, key, bytes, timestamp, sealedSenders[index] ?? null), stopSignal)
3652
+ .catch((error) => {
3653
+ throw firstItemError(error);
3654
+ });
3655
+ return prepared.flat();
3656
+ }
3657
+ /**
3658
+ * Each member device with the registration ID of its current session. A
3659
+ * device whose record is marked removed has none, so it needs the key and
3660
+ * the session step reads its device list again, which relists it.
3661
+ */
3662
+ senderKeyHandoffTargets(members) {
3663
+ return Promise.all(members.map(async ({ userId, deviceId }) => {
3664
+ const record = await this.sesameManager.getDeviceRecord(userId, deviceId);
3665
+ return {
3666
+ userId,
3667
+ deviceId,
3668
+ registrationId: record && !isRemovedDevice(record)
3669
+ ? record.session?.currentSession?.remoteRegistrationId
3670
+ : undefined,
3671
+ };
3672
+ }));
3673
+ }
3674
+ /**
3675
+ * Give a session to each device of one member that needs the sender key
3676
+ * and has none. The freshness window of the device list does not apply.
3677
+ * The list is the one that this send read.
3678
+ */
3679
+ async ensureSenderKeyHandoffSessions(recipientUserId, needing, listed, sessions) {
3680
+ if (needing.every((target) => target.registrationId !== undefined))
3681
+ return;
3682
+ const hasActiveSession = await this.hasActiveSession(recipientUserId);
3683
+ if (!sessions) {
3684
+ if (hasActiveSession)
3685
+ return;
3686
+ throw new EncryptionError(`No session with ${recipientUserId} and auto-establishment not configured`, EncryptionErrorCode.SESSION_NOT_FOUND, { recipientUserId });
3687
+ }
3688
+ await this.readRecipientDeviceList(recipientUserId, sessions, hasActiveSession, undefined, listed);
3689
+ }
3690
+ /**
3691
+ * Encrypt the distribution for each device of one member that needs it.
3692
+ * Each pre-message carries the registration ID of the session that
3693
+ * encrypted it and the key that it gives, for the handoff row.
3694
+ *
3695
+ * @param handedOff - The count of listed devices of the member that have a
3696
+ * row or that a pending pre-message targets
3697
+ */
3698
+ async prepareUserSenderKeyHandoffs(groupId, recipientUserId, needing, handedOff, key, distributionBytes, timestamp, sealedSender) {
3699
+ const stored = [];
3700
+ const failures = [];
3701
+ for (const { deviceId } of needing) {
3702
+ let message;
3703
+ let registrationId;
1763
3704
  try {
1764
- return {
1765
- ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
1766
- preMessages: [],
1767
- };
3705
+ // A device that is still removed after the session step gets no
3706
+ // distribution. Its device list read failed, and the next send tries
3707
+ // it again, because it has no row.
3708
+ const record = await this.sesameManager.getDeviceRecord(recipientUserId, deviceId);
3709
+ if (record && isRemovedDevice(record)) {
3710
+ throw new Error('the device record is marked removed');
3711
+ }
3712
+ message = await this.sesameManager.sendMessage(recipientUserId, deviceId, distributionBytes, {
3713
+ clientTimestamp: timestamp,
3714
+ includeSyncMessages: false,
3715
+ });
3716
+ registrationId = await this.sesameManager.getRemoteRegistrationId(recipientUserId, deviceId);
1768
3717
  }
1769
3718
  catch (error) {
1770
- if (!(error instanceof EncryptionError) ||
1771
- error.code !== EncryptionErrorCode.SENDER_KEY_EXPIRED) {
3719
+ if (error instanceof RelayWorkStopped)
1772
3720
  throw error;
1773
- }
1774
- this.logger.info('Sender key expired, auto-rotating', {
3721
+ const reason = error instanceof Error ? error.message : String(error);
3722
+ failures.push(`${String(deviceId)}: ${reason}`);
3723
+ this.logger.warn('Skipped the sender-key distribution of a device', {
1775
3724
  category: 'E2EE',
1776
- data: { groupId: actualGroupId },
3725
+ error: error instanceof Error ? error : new Error(reason),
3726
+ data: { groupId, recipientUserId, recipientDeviceId: deviceId },
1777
3727
  });
1778
- ({ distributionMessage } = await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId, { distributionPending: true }));
3728
+ continue;
1779
3729
  }
3730
+ const identified = await this.prepareStoredDirectDeviceMessage(message, null, undefined);
3731
+ if (registrationId !== undefined)
3732
+ identified.recipientRegistrationId = registrationId;
3733
+ identified.senderKeyHandoff = { senderKeyId: key.senderKeyId, generation: key.generation };
3734
+ stored.push(sealedSender
3735
+ ? await this.sealStoredDeviceMessage(identified, sealedSender, sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred')
3736
+ : identified);
1780
3737
  }
1781
- const preMessages = [];
1782
- if (this.relay) {
1783
- const members = await readMembers();
1784
- const otherMembers = members.filter((member) => member.userId !== this.userId);
1785
- const recipientUserIds = [...new Set(otherMembers.map((member) => member.userId))];
1786
- const skdmBytes = this.contentAdapter
1787
- ? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
1788
- : new TextEncoder().encode(JSON.stringify({
1789
- senderKeyDistributionMessage: JSON.stringify({
1790
- groupId: actualGroupId,
1791
- ...distributionMessage,
1792
- }),
1793
- }));
1794
- // The recipients are prepared at the same time. The session work of one
1795
- // recipient stays in turn, and its session setup reuses the devices that
1796
- // this send read.
1797
- const prepared = await this.fanOut
1798
- .all(recipientUserIds, async (recipientUserId) => {
1799
- await this.ensureSessionsForUser(recipientUserId, sessions, false, otherMembers.filter((member) => member.userId === recipientUserId));
1800
- const batch = await this.sesameManager.send(recipientUserId, skdmBytes, {
1801
- clientTimestamp: options.timestamp,
1802
- includeSyncMessages: false,
1803
- });
1804
- const stored = [];
1805
- for (const message of batch.deviceMessages) {
1806
- stored.push(await this.prepareStoredDirectDeviceMessage(message, null, undefined));
1807
- }
1808
- return stored;
1809
- }, stopSignal)
1810
- .catch((error) => {
1811
- throw firstItemError(error);
1812
- });
1813
- // The index of each pre-message follows the recipient order.
1814
- for (const stored of prepared.flat()) {
1815
- stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
1816
- preMessages.push(stored);
1817
- }
3738
+ if (stored.length === 0 && failures.length > 0 && handedOff === 0) {
3739
+ throw new EncryptionError(`Failed to send the sender key to all ${String(failures.length)} devices of ${recipientUserId}: ${failures.join(', ')}`, EncryptionErrorCode.ENCRYPTION_FAILED, { groupId, recipientUserId });
1818
3740
  }
1819
- return {
1820
- ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
1821
- preMessages,
1822
- senderKeyDistributionId: distributionMessage.senderKeyId,
1823
- };
3741
+ return stored;
1824
3742
  }
1825
3743
  /**
1826
3744
  * Encrypt to a group via Sender Keys (O(1) encryption)