@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
@@ -46,11 +46,13 @@ import { DefaultSignalProtocolManager } from '../internal/manager/index.js';
46
46
  import { DefaultSesameManager } from '../internal/sesame/index.js';
47
47
  import { createCompositeIdentityV1 } from '../keys/identity.js';
48
48
  import { EncryptionError, EncryptionErrorCode } from '../types/index.js';
49
+ import { ContentHint } from '../types/messages.js';
49
50
  import { base64ToBytes, bytesToBase64, constantTimeEqual, generateUuidV4 } from '../internal/crypto/index.js';
50
51
  import { deriveGroupSecretParams, getGroupPublicParams } from '../internal/protocol/zk/groups/index.js';
51
52
  import { SERVICE_ID_ACI } from '../internal/protocol/zk/groups/uid-struct.js';
52
53
  import { deserializeSenderCertificate, validateSenderCertificate, } from '../internal/protocol/sealed-sender/index.js';
53
54
  import { assertHookName, callHook, deferHooks, } from './event-hooks.js';
55
+ import { relayProtocolErrorOf } from './device-set-reconciliation.js';
54
56
  import { DeliveryStatusTracker } from './delivery-status.js';
55
57
  import { relayReceiptIntakeOf } from './relay-receipt-intake.js';
56
58
  import { ProtocolAddress } from '../types/address.js';
@@ -59,15 +61,19 @@ import { resolveSignalProtocolLogger } from '../logger.js';
59
61
  import { SenderKeyManager, } from '../internal/protocol/sender-keys/index.js';
60
62
  import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
61
63
  // Note: group utilities (isGroupId, extractGroupId, createGroupId) are used by SignalProtocolServiceCipher
62
- import { isGroupId } from '../internal/groups/index.js';
64
+ import { createGroupId, extractGroupId, isGroupId } from '../internal/groups/index.js';
65
+ import { removeDistributionsFromMessageRecords } from './distribution-records.js';
63
66
  import { GroupSenderKeyOperations } from './group-sender-key-operations.js';
64
- import { createGroupReceiveAuthorizer } from './group-receive-authorization.js';
67
+ import { GroupReceiveRefusedError, classifyGroupContent, createGroupMembershipChecker, createGroupReceiveEvaluator, groupOfContext, } from './group-receive-authorization.js';
68
+ import { GroupFetcher } from './group-fetcher.js';
69
+ import { envelopeCiphertextBytes, receiveRefusal, reportReceiveRefusal } from './delivery-error.js';
65
70
  import { profileKeyExchange } from './profile-key-exchange.js';
66
- import { SignalProtocolServiceCipher, sortEnvelopesForDecryption, } from './signal-service-cipher.js';
71
+ import { attachClientMessageId, SignalProtocolServiceCipher, sortEnvelopesForDecryption, } from './signal-service-cipher.js';
67
72
  import { establishMultiDeviceSessions } from '../internal/sesame/device-registry.js';
68
73
  import { isRetryableDecryptionError } from './retry-utils.js';
69
- import { envelopeTypeForContent, unsealMessage } from './sealed-sender.js';
70
- import { MESSAGE_RECORD_TTL_MS } from './constants.js';
74
+ import { envelopeTypeForContent, SealedRetryRequestReceived, unsealMessage } from './sealed-sender.js';
75
+ import { ResendableContent } from './resendable-content.js';
76
+ import { decideContentRecovery, readLocalStoreProtection, resolveContentRecoveryPolicy, resolveReceiveQueuePolicy, } from './storage-protection.js';
71
77
  import { ReceiptType } from './types.js';
72
78
  import * as MessageOps from './messages.js';
73
79
  import * as FileOps from './files.js';
@@ -78,18 +84,28 @@ import * as PreKeyOps from './prekeys.js';
78
84
  import * as RetryOps from './retry.js';
79
85
  import { receiveInRetryFamily } from './retry-family.js';
80
86
  import { RetryRequestScheduler } from './retry-request-lifecycle.js';
87
+ import { ResendJobDriver } from './recovery-driver.js';
88
+ import { retryRequestPost } from './retry-request-envelope.js';
81
89
  import { migrateRetryRequestRecords } from '../local/store/reliability.js';
82
90
  import { deliveredEnvelopeFingerprint } from '../local/store/received-content.js';
91
+ import { RECEIVE_WORK_DEFAULT_LIMIT, sizedReceiveWork } from '../local/store/receive-work.js';
92
+ import { awaitReceiveCompletion, blockReceiveWork, completeReceiveWork, denyReceiveWork, ReceiveQueue, } from './receive-queue.js';
93
+ import { receiveExpiresAt } from './receive-expiry.js';
94
+ import { boundReceiveHooks } from './receive-hook-bound.js';
95
+ import { createReceiveCommit } from './receive-work-seed.js';
83
96
  import * as RelaySubscriptionOps from './relay-subscription.js';
84
97
  import { relayReceiptJoinOf } from './relay-receipt-join.js';
85
98
  import { SignalProtocolClientState, SIGNAL_PROTOCOL_CLIENT_CONSTANTS } from './state.js';
86
99
  import { clientRelayFanOut, rethrowRelayWorkStopped, RelayWorkStopped, } from './relay-work.js';
100
+ import { StaleSessionRefreshError } from './relay-device-refusal.js';
101
+ import { createKeyedLocks, withKeyedLock } from '../utils/keyed-lock.js';
87
102
  import { deleteMediaAttachment, resolveMediaAttachment, } from '../media/index.js';
88
103
  import { StorageBackedSignalProtocolClientMedia } from './media.js';
89
104
  // Group state (Signal Private Group System)
90
105
  import { GroupManager, decodeGroupTrustRoot } from '../internal/groups/index.js';
91
106
  import { SignalProtocolGroupStateStore } from '../internal/groups/sdk-store.js';
92
107
  import { deriveAccessKey } from '../internal/protocol/sealed-sender/delivery-token.js';
108
+ import { SealedSenderContentType } from '../internal/protocol/sealed-sender/types.js';
93
109
  /**
94
110
  * Module-level lock for storage initialization.
95
111
  * Prevents multiple concurrent DefaultSignalProtocolClient.create() calls from creating
@@ -99,6 +115,20 @@ const storageLock = new AsyncLock({
99
115
  timeout: 30000, // 30 second timeout for storage initialization
100
116
  maxPending: 100, // Limit pending operations
101
117
  });
118
+ /**
119
+ * `decryptGroupMessage` calls for one group message run one at a time per
120
+ * local store, from the read of its receive record to its completion, so
121
+ * one content is given once.
122
+ */
123
+ const groupMessageReceiveLocks = createKeyedLocks();
124
+ /** The reason of a `denied` receive outcome. */
125
+ function receiveDenialReason(error) {
126
+ if (error instanceof GroupReceiveRefusedError)
127
+ return error.reason;
128
+ if (error instanceof EncryptionError)
129
+ return error.code;
130
+ return 'invalid';
131
+ }
102
132
  /**
103
133
  * Type guard: DataMessage is a plain object (not string or Uint8Array).
104
134
  * TypeScript enforces correct content types at compile time. This routes at runtime.
@@ -155,7 +185,14 @@ export class DefaultSignalProtocolClient {
155
185
  groupManager;
156
186
  groupSessionFor;
157
187
  groupStore;
158
- groupReceiveAuthorizer;
188
+ /** Decides on received managed-group content. Set with a group store. */
189
+ groupReceiveEvaluator;
190
+ /** The single fetcher that brings each group up to its claimed revision. */
191
+ groupFetcher;
192
+ /** The current membership that a retry resend of group content needs. */
193
+ groupMembership;
194
+ /** The processor of the stored receive records. */
195
+ receiveQueue;
159
196
  // Cipher coordination (encrypts/decrypts, routes to appropriate cipher)
160
197
  cipher;
161
198
  // The relay request bound that every fan-out of this client shares
@@ -175,6 +212,21 @@ export class DefaultSignalProtocolClient {
175
212
  get syncStatus() {
176
213
  return this._syncStatus;
177
214
  }
215
+ /** The validated content recovery policy, with its defaults applied. */
216
+ contentRecoveryPolicy;
217
+ _contentRecoveryStatus;
218
+ /** True after the client logged that a group send went out as `Default`, not `Resendable`. */
219
+ resendableDowngradeLogged = false;
220
+ /** The resendable content that this client keeps, and its retention. */
221
+ resendableContent;
222
+ /**
223
+ * Whether this client keeps resendable content to answer retry requests.
224
+ *
225
+ * @see SignalProtocolClient.contentRecoveryStatus
226
+ */
227
+ get contentRecoveryStatus() {
228
+ return this._contentRecoveryStatus;
229
+ }
178
230
  stoppedRelayConnection = {
179
231
  state: 'stopped',
180
232
  since: Date.now(),
@@ -227,14 +279,34 @@ export class DefaultSignalProtocolClient {
227
279
  */
228
280
  retryRequests = new RetryRequestScheduler(this.state.relayWork, (work) => {
229
281
  const relay = this.relay;
282
+ const context = { ...this.relayWorkContext(work), stopSignal: work.stopSignal };
230
283
  return {
231
284
  storage: this._storage,
232
285
  logger: this.logger,
233
286
  hooks: work.wrapHooks(this.hooks),
234
287
  local: { userId: this.userId, deviceId: this.deviceId },
235
- send: relay ? (envelope) => relay.send(envelope) : undefined,
288
+ send: relay
289
+ ? retryRequestPost((recipientUserId, recipientDeviceId, payloadBase64) => this.cipher.sealRetryRequest(recipientUserId, recipientDeviceId, payloadBase64), relay, (envelope) => relay.send(envelope), (recipientUserId, recipientDeviceId) => this.cipher.recipientRegistrationId(recipientUserId, recipientDeviceId), (recipientUserId, recipientDeviceId) => this.refreshRefusedSession(context, recipientUserId, recipientDeviceId))
290
+ : undefined,
291
+ reset: this.retryTerminalReset(context),
236
292
  };
237
293
  });
294
+ /**
295
+ * Runs the pending resend jobs that an answer to a retry request did not
296
+ * finish. It starts with the retry request scheduler and at each relay
297
+ * transition to connected, and stop() stops it. Each pass is relay work,
298
+ * so its hooks run through that work.
299
+ */
300
+ resendJobs = new ResendJobDriver(this.state.relayWork, (work) => {
301
+ const ctx = this.relayWorkContext(work);
302
+ return {
303
+ storage: this._storage,
304
+ logger: this.logger,
305
+ run: (jobId) => RetryOps.runResendJob(ctx, jobId, this.retryResponseState, this.retryCallbacks(work.stopSignal, ctx)),
306
+ };
307
+ });
308
+ /** Ends the subscription of the resend job driver to relay connection states. */
309
+ resendJobsOnConnect;
238
310
  /**
239
311
  * The stop() in progress. It is set before a step of stop() runs, so a
240
312
  * stop() call that overlaps it, also from a step, waits for it, and a
@@ -280,6 +352,30 @@ export class DefaultSignalProtocolClient {
280
352
  throw new Error('Storage must be provided by DefaultSignalProtocolClient.create() callers');
281
353
  }
282
354
  this._storage = config.storage;
355
+ // The store declares its protection. The policy decides from it whether
356
+ // the client keeps resendable content.
357
+ this.contentRecoveryPolicy = resolveContentRecoveryPolicy(config.protocol?.contentRecovery);
358
+ // Each queue pass runs as relay work, so its hooks call the app through
359
+ // that work and a stop ends it. Each hook runs under the receive hook bound.
360
+ this.receiveQueue = new ReceiveQueue(this.state.relayWork, resolveReceiveQueuePolicy(config.protocol?.receiveQueue), (work) => {
361
+ const ctx = this.receivePassContext(work);
362
+ return {
363
+ ctx: {
364
+ ...ctx,
365
+ cipher: this.cipher,
366
+ receiveQueue: this.receiveQueue,
367
+ stopSignal: work.stopSignal,
368
+ },
369
+ state: this.relaySubscriptionState,
370
+ callbacks: this.relaySubscriptionCallbacks(ctx, work.stopSignal),
371
+ };
372
+ }, () => this.cleanupStaleDeviceRecords());
373
+ this._contentRecoveryStatus = decideContentRecovery(readLocalStoreProtection(this._storage), this.contentRecoveryPolicy, config.groups?.resolveAciBytesByUserIds
374
+ ? 'managed'
375
+ : this.contentRecoveryPolicy.isCurrentMember
376
+ ? 'hook'
377
+ : 'none');
378
+ this.resendableContent = new ResendableContent(this._storage, this.contentRecoveryPolicy.retentionMs);
283
379
  this.deliveries = new DeliveryStatusTracker(this._storage);
284
380
  this._storage.setLogger?.(this.logger);
285
381
  this.media = new StorageBackedSignalProtocolClientMedia({
@@ -298,8 +394,13 @@ export class DefaultSignalProtocolClient {
298
394
  // Initialize Sesame manager for multi-device support
299
395
  this.sesameManager = new DefaultSesameManager(this._storage, {}, // Use default Sesame config
300
396
  this.manager, undefined, this.logger);
301
- // Wire up MessageRecord storage for retry request support (SESAME spec §6.2)
302
- this.sesameManager.setMessageRecordStore(this._storage);
397
+ // Wire up MessageRecord storage for retry request support (SESAME spec §6.2).
398
+ // A refused content recovery keeps no record, so a pairwise retry request
399
+ // resets the session with no content.
400
+ // A record keeps no sender key distribution, so no chain key rests in it.
401
+ if (this._contentRecoveryStatus.enabled) {
402
+ this.sesameManager.setMessageRecordStore(this._storage, (plaintext) => this.contentAdapter.withoutSenderKeyDistribution(plaintext));
403
+ }
303
404
  // Initialize Sender Key manager for group messaging
304
405
  this.senderKeyManager = new SenderKeyManager(this._storage, config?.senderKeys, this.logger);
305
406
  this.groupSenderKeys = new GroupSenderKeyOperations(this._storage, userId, deviceId);
@@ -353,7 +454,7 @@ export class DefaultSignalProtocolClient {
353
454
  profileKeyCredentialPublicKey: trustRoot.profileKeyCredentialPublicKey,
354
455
  profileKey: groupConfig.profileKey,
355
456
  onSenderKeyRotation: async (groupId) => {
356
- await this.groupSenderKeys.run(groupId, (rawGroupId) => GroupOps.rotateGroupSenderKey(this.ctx, this.senderKeyManager, rawGroupId, this.config.onGroupSenderKeyRotated, { distributionPending: true }));
457
+ await this.groupSenderKeys.run(groupId, (rawGroupId) => GroupOps.rotateGroupSenderKey(this.ctx, this.senderKeyManager, rawGroupId, this.config.onGroupSenderKeyRotated));
357
458
  },
358
459
  onEndorsementsInvalidated: endorsementManager
359
460
  ? async (groupId) => {
@@ -381,6 +482,8 @@ export class DefaultSignalProtocolClient {
381
482
  const sessions = this.sendSessionCallbacks(() => this.ctx);
382
483
  if (sessions)
383
484
  this.cipher.setSessionCallbacks(sessions);
485
+ // A sync payload has no send result, so the cipher reports its error.
486
+ this.cipher.setRelayProtocolErrorReporter((error) => callHook(this.hooks, 'onRelayProtocolError', error));
384
487
  if (config?.sealedSender) {
385
488
  this.cipher.setSealedSenderDeliveryMode(config.sealedSender.deliveryMode ?? 'preferred');
386
489
  if (config.sealedSender.onIdentifiedFallback) {
@@ -413,15 +516,49 @@ export class DefaultSignalProtocolClient {
413
516
  // Set up group secret params provider. Derives params from master key in store
414
517
  if (this.groupStore) {
415
518
  const store = this.groupStore;
416
- this.groupReceiveAuthorizer = createGroupReceiveAuthorizer(store, config.aci?.uuid, config.groups?.resolveAciBytesByUserIds);
417
- this.cipher.setGroupReceiveAuthorizer(this.groupReceiveAuthorizer);
519
+ const isGroupBlocked = config.groups?.isGroupBlocked;
520
+ // The fetcher's sync keeps the group server's denial errors, so it
521
+ // calls the manager directly. syncGroup() wraps them for the caller.
522
+ const fetcher = new GroupFetcher({
523
+ store,
524
+ sync: async (groupId) => (await this.groups).syncGroup(createGroupId(groupId)),
525
+ ...(isGroupBlocked && {
526
+ isBlocked: (groupId) => isGroupBlocked(createGroupId(groupId)),
527
+ }),
528
+ applyChange: async (groupId, revision, change) => (await this.groups).applyCarriedGroupChange(groupId, revision, change),
529
+ // The receive queue owns the content that waits on a group.
530
+ hasBlockedContent: async (groupId) => (await this._storage.receiveWorkUsage({ groupId })).items > 0,
531
+ onFetched: (groupId) => this.receiveQueue.wake(groupId),
532
+ runInBackground: (pass) => this.state.relayWork.run(() => pass()),
533
+ logger: this.logger,
534
+ });
535
+ this.groupFetcher = fetcher;
536
+ this.groupReceiveEvaluator = createGroupReceiveEvaluator({
537
+ store,
538
+ fetcher,
539
+ ownUserId: userId,
540
+ localAci: config.aci?.uuid,
541
+ resolveAcis: config.groups?.resolveAciBytesByUserIds,
542
+ ...(isGroupBlocked && { isGroupBlocked }),
543
+ });
544
+ this.cipher.setGroupReceiveEvaluator(this.groupReceiveEvaluator);
418
545
  this.cipher.setGroupSecretParamsProvider(async (groupId) => {
419
546
  const masterKey = await store.getMasterKey(groupId);
420
547
  if (!masterKey)
421
548
  return null;
422
549
  return deriveGroupSecretParams(masterKey);
423
550
  });
551
+ // Each send to a managed group carries its master key and the
552
+ // revision of the verified state, as Signal's GroupContextV2.
553
+ this.cipher.setGroupContextProvider(async (groupId) => {
554
+ const masterKey = await store.getMasterKey(groupId);
555
+ if (!masterKey)
556
+ return null;
557
+ const state = await store.getGroupState(groupId);
558
+ return { masterKey, revision: state?.revision ?? 0 };
559
+ });
424
560
  }
561
+ this.groupMembership = createGroupMembershipChecker(this.groupStore, config.groups?.resolveAciBytesByUserIds, this.contentRecoveryPolicy.isCurrentMember, this.groupFetcher);
425
562
  // Set up endorsement refresher for pre-send V2 sealed sender refresh.
426
563
  // Fetches fresh endorsements from server when cache is empty, expiring, or
427
564
  // missing members.
@@ -515,40 +652,44 @@ export class DefaultSignalProtocolClient {
515
652
  contentAdapter: this.contentAdapter,
516
653
  profileKeys: profileKeyExchange(this),
517
654
  deliveries: this.deliveries,
655
+ resendableContent: this.resendableContent,
518
656
  scheduleRetryRequest: (at) => this.retryRequests.schedule(at),
657
+ retryTerminalReset: (context) => this.retryTerminalReset(context),
658
+ recipientRegistrationId: (recipientUserId, recipientDeviceId) => this.cipher.recipientRegistrationId(recipientUserId, recipientDeviceId),
659
+ refreshStaleSession: (context, recipientUserId, recipientDeviceId) => this.refreshRefusedSession(context, recipientUserId, recipientDeviceId),
519
660
  sealReceipt: (recipientUserId, recipientDeviceId, ciphertextBase64) => this.cipher.sealReceipt(recipientUserId, recipientDeviceId, ciphertextBase64),
661
+ sealRetryRequest: (recipientUserId, recipientDeviceId, payloadBase64) => this.cipher.sealRetryRequest(recipientUserId, recipientDeviceId, payloadBase64),
520
662
  };
521
663
  }
522
664
  /**
523
665
  * Apply one Relay delivery receipt, then announce its deliveries. A
524
- * receipt that stop() kept from its write throws, so the Relay replays it.
666
+ * receipt whose write or announcement does not complete throws, so the
667
+ * Relay replays it: after a stop(), and after an error from the
668
+ * `onDelivered` hook. The replay announces each delivery whose hook did not
669
+ * return.
525
670
  */
526
671
  async receiveRelayReceipt(receipt) {
527
- let applied = false;
672
+ let announced = false;
528
673
  await this.state.relayWork.run(async (work) => {
529
674
  work.proceed();
530
675
  const events = await this.deliveries.applyRelayReceipt(receipt);
531
- applied = true;
532
- await this.announceDeliveries(work.wrapHooks(this.hooks), events);
676
+ await this.deliveries.announce(work.wrapHooks(this.hooks), events);
677
+ announced = true;
533
678
  });
534
- if (!applied)
679
+ if (!announced)
535
680
  throw new RelayWorkStopped();
536
681
  }
537
- /** Run the onDelivered hook once for each event, in order. */
538
- async announceDeliveries(hooks, events) {
539
- for (const event of events)
540
- await callHook(hooks, 'onDelivered', event);
541
- }
542
682
  /**
543
683
  * Announce the deliveries that waited for a send of this client message ID
544
- * to resolve.
684
+ * to resolve. A delivery whose hook throws or stops stays unannounced, and
685
+ * the next receipt for the message announces it again.
545
686
  */
546
687
  releaseDeliveries(clientMessageId) {
547
688
  void this.state.relayWork
548
689
  .run(async (work) => {
549
690
  work.proceed();
550
691
  const events = await this.deliveries.release(clientMessageId);
551
- await this.announceDeliveries(work.wrapHooks(this.hooks), events);
692
+ await this.deliveries.announce(work.wrapHooks(this.hooks), events);
552
693
  })
553
694
  .catch((error) => {
554
695
  this.logger.warn('Failed to announce deliveries', {
@@ -664,6 +805,10 @@ export class DefaultSignalProtocolClient {
664
805
  establishSession: (address, bundle) => SessionOps.establishSession(ctx, this.sesameManager, address, bundle),
665
806
  resend: (userId, deviceId, content, options) => this.cipher.resendToDevice(userId, deviceId, content, options, stopSignal),
666
807
  forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds(),
808
+ groupMembership: this.groupMembership,
809
+ findSentGroupId: (userId, clientTimestamp) => this.cipher.findSentGroupId(userId, clientTimestamp),
810
+ currentGroupDistribution: (groupId) => this.cipher.currentGroupDistribution(groupId, stopSignal),
811
+ invalidateSenderKeyHandoff: (groupId, device) => this.groupSenderKeys.run(groupId, (rawGroupId) => this.cipher.invalidateSenderKeyHandoff(rawGroupId, device), stopSignal),
667
812
  };
668
813
  }
669
814
  /**
@@ -693,9 +838,14 @@ export class DefaultSignalProtocolClient {
693
838
  * carries the stop signal of the tracker, which also aborts at a stop
694
839
  * after the work ends, so a retry timer of the send sees that stop. The
695
840
  * send is in deliveryReceiptSends while it runs.
841
+ *
842
+ * @throws RelayWorkStopped when a stop ended the send before it finished,
843
+ * so the receive queue keeps the receipt and sends it after the next
844
+ * start
696
845
  */
697
- sendDeliveryReceiptAsRelayWork(userId, timestamps) {
698
- return this.state.relayWork.run(async (work) => {
846
+ async sendDeliveryReceiptAsRelayWork(userId, timestamps) {
847
+ let sent = false;
848
+ await this.state.relayWork.run(async (work) => {
699
849
  const send = this.sendDeliveryReceipt(userId, timestamps, {
700
850
  ...this.relayWorkContext(work),
701
851
  stopSignal: this.state.relayWork.stopSignal,
@@ -703,11 +853,14 @@ export class DefaultSignalProtocolClient {
703
853
  this.deliveryReceiptSends.set(work, send);
704
854
  try {
705
855
  await send;
856
+ sent = true;
706
857
  }
707
858
  finally {
708
859
  this.deliveryReceiptSends.delete(work);
709
860
  }
710
861
  });
862
+ if (!sent)
863
+ throw new RelayWorkStopped();
711
864
  }
712
865
  /**
713
866
  * Start the send of every batched delivery receipt, once each. The batches
@@ -733,10 +886,112 @@ export class DefaultSignalProtocolClient {
733
886
  clearTimeout(timer);
734
887
  }
735
888
  }
889
+ /**
890
+ * The session reset steps of a retry request that ended as
891
+ * `expired-content`. Their session hooks run through the given context,
892
+ * and its stop signal stops their lock waits and relay requests. There are
893
+ * none without a relay.
894
+ */
895
+ retryTerminalReset(context) {
896
+ const relay = this.relay;
897
+ if (!relay)
898
+ return undefined;
899
+ const { stopSignal } = context;
900
+ return {
901
+ archiveSession: ({ userId, deviceId }) => this.cipher.archiveDeviceSession(userId, deviceId, stopSignal),
902
+ // No stop signal: a stop must not split the archive from the invalidation.
903
+ invalidateAccountSenderKeyHandoffs: async (userId, groupId) => {
904
+ if (groupId === undefined) {
905
+ await this.cipher.invalidateAccountSenderKeyHandoffs(userId);
906
+ return false;
907
+ }
908
+ return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
909
+ await this.cipher.invalidateAccountSenderKeyHandoffs(userId);
910
+ const current = await this.senderKeyManager.getCurrentSenderKeyDistribution(rawGroupId, this.userId, this.deviceId);
911
+ return current !== null;
912
+ });
913
+ },
914
+ sendNullMessage: async ({ userId, deviceId }) => {
915
+ const address = ProtocolAddress.create(userId, deviceId);
916
+ if (!(await SessionOps.hasSession(context, address))) {
917
+ const bundle = await this.fanOut.request(() => relay.fetchPreKeyBundle(userId, deviceId), stopSignal);
918
+ if (!bundle)
919
+ throw new Error('No prekey bundle for the device of a session reset');
920
+ await SessionOps.establishSession(context, this.sesameManager, address, bundle);
921
+ }
922
+ await this.cipher.resendToDevice(userId, deviceId, this.contentAdapter.serializeNullMessage(), { timestamp: Date.now(), contentHint: ContentHint.Implicit }, stopSignal);
923
+ },
924
+ };
925
+ }
926
+ /**
927
+ * Refresh the session with a device that the Relay refused as stale, for a
928
+ * receipt or a retry request. It fetches a fresh bundle first, then starts
929
+ * a new session from the bundle. The session start archives the stale
930
+ * session and promotes the new one in one record write. After a successful
931
+ * start, the onSessionArchived hook runs for the device. Resolves to true
932
+ * when the new session is ready. Resolves to false without a relay, and
933
+ * when the Relay has no bundle of the device: the session is then
934
+ * archived. Rejects with StaleSessionRefreshError when the fetch or the new
935
+ * session fails. A failure before the session record write keeps the
936
+ * stale session, so the next post is refused again and refreshes again. A
937
+ * failure after that write, in the SESAME registration, leaves the new
938
+ * session, and the next post uses it.
939
+ */
940
+ async refreshRefusedSession(context, recipientUserId, recipientDeviceId) {
941
+ const relay = this.relay;
942
+ if (!relay)
943
+ return false;
944
+ const address = ProtocolAddress.create(recipientUserId, recipientDeviceId);
945
+ try {
946
+ const freshBundle = await this.fanOut.request(() => relay.fetchPreKeyBundle(recipientUserId, recipientDeviceId), context.stopSignal);
947
+ if (!freshBundle) {
948
+ // Per SESAME §3.2: the session is archived, not deleted, to decrypt
949
+ // delayed messages. No bundle is terminal for the post.
950
+ await SessionOps.archiveSession(context, address);
951
+ this.logger.warn('No prekey bundle available for stale session refresh', {
952
+ category: 'E2EE',
953
+ data: { recipientUserId, recipientDeviceId },
954
+ });
955
+ return false;
956
+ }
957
+ // The session start archives the stale session in the same record write
958
+ // that stores the new one, so a start that fails before that write
959
+ // keeps the stale session.
960
+ // The hook runs only after the start succeeds, for the session that the
961
+ // write archived.
962
+ const staleSession = (await context.storage.getSessionRecord(address))?.currentSession;
963
+ await SessionOps.establishSession(context, this.sesameManager, address, freshBundle);
964
+ if (staleSession) {
965
+ await callHook(context.hooks, 'onSessionArchived', ProtocolAddress.toString(address));
966
+ }
967
+ this.logger.info('Refreshed stale session with fresh bundle', {
968
+ category: 'E2EE',
969
+ data: { recipientUserId, recipientDeviceId, newRegistrationId: freshBundle.registrationId },
970
+ });
971
+ return true;
972
+ }
973
+ catch (error) {
974
+ rethrowRelayWorkStopped(error);
975
+ this.logger.warn('Failed to refresh stale session, the post retries', {
976
+ category: 'E2EE',
977
+ data: { recipientUserId, recipientDeviceId, error: error.message },
978
+ });
979
+ throw new StaleSessionRefreshError(recipientUserId, recipientDeviceId, error);
980
+ }
981
+ }
736
982
  /** Client context whose hooks call the app through the given relay work. */
737
983
  relayWorkContext(work) {
738
984
  return { ...this.ctx, hooks: work.wrapHooks(this.hooks) };
739
985
  }
986
+ /**
987
+ * Client context of a receive queue pass. Its hooks run under the receive
988
+ * hook bound, inside the given relay work, so the work stops waiting in the
989
+ * app at a timeout.
990
+ */
991
+ receivePassContext(work) {
992
+ const bound = boundReceiveHooks(this.hooks, this.receiveQueue.policy.receiveHookTimeoutMs, this.logger);
993
+ return { ...this.ctx, hooks: work.wrapHooks(bound) };
994
+ }
740
995
  /**
741
996
  * Session callbacks of a send. Their session hooks run through the given
742
997
  * context, so a send in relay work calls the app through that work. Session
@@ -854,10 +1109,10 @@ export class DefaultSignalProtocolClient {
854
1109
  * storage,
855
1110
  * });
856
1111
  *
857
- * // Linked device; storage must already contain provisioned identity material.
1112
+ * // Linked device; storage must already contain the account identity.
858
1113
  * const signal = await DefaultSignalProtocolClient.create('user-123', {
859
1114
  * deviceId: 2,
860
- * storage: provisionedLinkedDeviceStorage
1115
+ * storage: linkedDeviceStorage
861
1116
  * });
862
1117
  *
863
1118
  * // With an application-owned authenticated relay transport.
@@ -915,7 +1170,8 @@ export class DefaultSignalProtocolClient {
915
1170
  const hasIdentityKey = await finalConfig.storage.hasIdentityKey(identityType);
916
1171
  if (!hasIdentityKey) {
917
1172
  throw new Error(`Linked device ${deviceId} requires a provisioned ${identityType.toUpperCase()} identity key in storage. ` +
918
- 'Provision the device first, then create the client with that storage.');
1173
+ 'Import the account identity by device transfer or by an application channel, ' +
1174
+ 'then create the client with that storage.');
919
1175
  }
920
1176
  }
921
1177
  }
@@ -923,12 +1179,27 @@ export class DefaultSignalProtocolClient {
923
1179
  await client.initialize();
924
1180
  await client.hydratePersistedState();
925
1181
  await migrateRetryRequestRecords(client._storage);
926
- // Cleanup expired sessions and message records on startup.
1182
+ await client.applyContentRecoveryDecision();
1183
+ // A failed sweep fails the start and runs again at the next start.
1184
+ await removeDistributionsFromMessageRecords(client._storage, client.contentAdapter, client.logger);
1185
+ // Delete the handoff rows that a crash or a key write outside the
1186
+ // sender-key manager left behind. A failed sweep does not fail the start,
1187
+ // because a row with an old senderKeyId never matches the current key.
1188
+ try {
1189
+ await client.cipher.sweepSenderKeyHandoffs();
1190
+ }
1191
+ catch (sweepError) {
1192
+ client.logger.warn('Startup sender-key handoff sweep failed', {
1193
+ category: 'E2EE',
1194
+ data: { error: sweepError.message },
1195
+ });
1196
+ }
1197
+ // Cleanup expired sessions and resendable content on startup.
927
1198
  // The reference implementation relies on event-driven cleanup (identity change, retry, end-session).
928
1199
  // We also enforce our maxRecv TTL here to prevent unbounded session growth.
929
1200
  try {
930
1201
  await client.sesameManager.cleanupExpiredSessions();
931
- await client._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
1202
+ await client.resendableContent.sweep();
932
1203
  }
933
1204
  catch (cleanupError) {
934
1205
  // Non-fatal: cleanup failures should not prevent client creation
@@ -958,9 +1229,14 @@ export class DefaultSignalProtocolClient {
958
1229
  client.startRelaySubscription();
959
1230
  }
960
1231
  // Post the stored retry requests whose next attempt time has come, and
961
- // end the requests past their deadlines. The pass runs in the background.
1232
+ // end the requests past their deadlines. Run the pending resend jobs.
1233
+ // The passes run in the background.
1234
+ // The receive queue resumes the stored receive records first. With no
1235
+ // relay, it serves the helper receives alone.
962
1236
  if (finalConfig?.relay)
963
1237
  client.startRetryRequests();
1238
+ else
1239
+ void client.receiveQueue.start();
964
1240
  // Validate sender keys config and warn on extreme values
965
1241
  if (finalConfig?.senderKeys) {
966
1242
  const sk = finalConfig.senderKeys;
@@ -1020,7 +1296,7 @@ export class DefaultSignalProtocolClient {
1020
1296
  /**
1021
1297
  * Explicitly rotate this account's relay identity using a caller-authenticated
1022
1298
  * compare-and-swap commitment, then publish fresh prekeys for that namespace.
1023
- * Normal sync and linked-device provisioning never call this operation.
1299
+ * Normal sync and the managed device link never call this operation.
1024
1300
  */
1025
1301
  async rotateAccountIdentity(expectedCurrentCommitment, identityType = 'aci') {
1026
1302
  if (!this.config.relay) {
@@ -1068,6 +1344,96 @@ export class DefaultSignalProtocolClient {
1068
1344
  /**
1069
1345
  * Hydrate state from persistent storage.
1070
1346
  */
1347
+ /**
1348
+ * Report the content recovery decision once, and delete the resendable
1349
+ * content that a refused store still holds from an earlier policy. The
1350
+ * clear deletes no sender key state, so the next group send needs no new
1351
+ * distribution.
1352
+ */
1353
+ async applyContentRecoveryDecision() {
1354
+ const status = this._contentRecoveryStatus;
1355
+ const data = {
1356
+ level: status.level,
1357
+ mode: status.mode,
1358
+ atRest: status.atRest,
1359
+ keyCustody: status.keyCustody,
1360
+ reason: status.reason,
1361
+ groupMembershipSource: status.groupMembershipSource,
1362
+ };
1363
+ if (status.enabled) {
1364
+ if (status.groupMembershipSource === 'none') {
1365
+ this.logger.warn('Content recovery has no group membership source, so the client refuses each group ' +
1366
+ 'resend. Configure `groups` for managed groups, or set ' +
1367
+ '`protocol.contentRecovery.isCurrentMember` for ad hoc groups', { category: 'E2EE', data });
1368
+ }
1369
+ if (status.level === 'co-located') {
1370
+ this.logger.warn('Content recovery keeps resendable content in a store whose key shares its storage ' +
1371
+ "(protocol.contentRecovery.mode 'allow-co-located-key')", { category: 'E2EE', data });
1372
+ }
1373
+ await this.resendableContent.keepContent();
1374
+ return;
1375
+ }
1376
+ if (status.reason === 'co-located-key-not-allowed') {
1377
+ this.logger.error('Content recovery is off: the local store key shares the storage of the data. ' +
1378
+ "Use a keychain or application vault, or set protocol.contentRecovery.mode to 'allow-co-located-key'", { category: 'E2EE', data });
1379
+ }
1380
+ else if (status.reason === 'unprotected-store') {
1381
+ this.logger.warn('Content recovery is off: the local store has no encryption at rest', {
1382
+ category: 'E2EE',
1383
+ data,
1384
+ });
1385
+ }
1386
+ else {
1387
+ this.logger.info('Content recovery is off by policy', { category: 'E2EE', data });
1388
+ }
1389
+ await this.resendableContent.clear();
1390
+ }
1391
+ /**
1392
+ * The content hint of a group send. A `DataMessage` send is `Resendable`
1393
+ * unless the application sets another hint. A `Resendable` send keeps its
1394
+ * content in the send log, so the sender can answer a retry request with
1395
+ * it. When content recovery is off, or the send is a string or bytes with
1396
+ * no content timestamp, the sender cannot answer. The send then goes out
1397
+ * as `Default`, so no recipient waits for an answer, and the client logs
1398
+ * the downgrade once.
1399
+ */
1400
+ groupContentHint(requested, dataMessage) {
1401
+ if (requested !== undefined && requested !== ContentHint.Resendable)
1402
+ return requested;
1403
+ if (requested === undefined && !dataMessage)
1404
+ return undefined;
1405
+ const status = this._contentRecoveryStatus;
1406
+ if (dataMessage && status.enabled)
1407
+ return ContentHint.Resendable;
1408
+ if (!this.resendableDowngradeLogged) {
1409
+ this.resendableDowngradeLogged = true;
1410
+ this.logger.info('A group send goes out as Default, because the sender keeps no content to resend', {
1411
+ category: 'E2EE',
1412
+ data: {
1413
+ contentRecovery: status.enabled ? 'enabled' : 'disabled',
1414
+ ...(status.reason && { reason: status.reason }),
1415
+ dataMessage,
1416
+ },
1417
+ });
1418
+ }
1419
+ return ContentHint.Default;
1420
+ }
1421
+ /**
1422
+ * Delete expired resendable content before the first resendable group
1423
+ * send of the day. A failed sweep does not stop the send. The next sweep
1424
+ * deletes the content.
1425
+ */
1426
+ async sweepResendableContentDaily() {
1427
+ try {
1428
+ await this.resendableContent.sweepDaily();
1429
+ }
1430
+ catch (error) {
1431
+ this.logger.warn('Error cleaning up resendable content', {
1432
+ category: 'E2EE',
1433
+ data: { error: error.message },
1434
+ });
1435
+ }
1436
+ }
1071
1437
  async hydratePersistedState() {
1072
1438
  try {
1073
1439
  const stored = await this._storage.getMetadata('lastForcedPreKeyRotation');
@@ -1297,150 +1663,598 @@ export class DefaultSignalProtocolClient {
1297
1663
  /**
1298
1664
  * Process an incoming encrypted message envelope.
1299
1665
  *
1300
- * Unified entry point for both foreground (relay) and background (HTTP) message processing.
1301
- * Handles decryption and automatically sends SESAME retry requests on retryable failures.
1302
- *
1303
- * This method:
1304
- * 1. Decodes base64 ciphertext from the envelope
1305
- * 2. Decrypts message using Double Ratchet
1306
- * 3. On retryable error: sends retry request via relay or options callback
1307
- * 4. Re-throws error for caller to handle
1666
+ * The receive helper for an application that pulls envelopes itself. It
1667
+ * decrypts the envelope and commits its content as a receive record with
1668
+ * the ratchet step, then decides the group of the content. The content
1669
+ * stays recoverable until the application calls `completeReceive`, or
1670
+ * until `onPersist` resolves.
1671
+ *
1672
+ * The outcome tells the caller what to do with the envelope:
1673
+ *
1674
+ * - `processed`: give the content to the application, then acknowledge
1675
+ * the envelope. A redelivery of the envelope before `completeReceive`
1676
+ * returns the same outcome again with no second decrypt.
1677
+ * - `pending`: the content is stored, and its group state must update
1678
+ * first. Acknowledge the envelope. The client decides the content again
1679
+ * when the group updates, and `listPendingReceives({ ready: true })`
1680
+ * then lists it.
1681
+ * - `duplicate`: this client processed the envelope, or the application
1682
+ * already has the content of the failed envelope of a retry request.
1683
+ * The client acknowledged the envelope.
1684
+ * - `null-message`: the envelope carries no content. The client consumed
1685
+ * it and acknowledged it. A null message for a failed envelope marks
1686
+ * that envelope processed, but a content resend for it that comes later
1687
+ * still gives its content.
1688
+ * - `denied`: the client refused the content. The ratchet step is spent,
1689
+ * and the client acknowledged the envelope. Content from another
1690
+ * account that carries a sync message is denied in any envelope.
1691
+ * - `refused`: the receive queue has no room. Nothing is decrypted or
1692
+ * stored. Do not acknowledge the envelope. Give it again later.
1693
+ *
1694
+ * On a retryable decrypt failure the client sends a SESAME retry request,
1695
+ * which acknowledges the envelope, and throws the error. A message with
1696
+ * the Implicit content hint gets no request and is acknowledged.
1308
1697
  *
1309
1698
  * A `retry_request` envelope holds no plaintext. This method rejects it
1310
1699
  * before decryption and sends no retry request. Give it to
1311
1700
  * `receiveIncomingEnvelopes`, which handles it.
1312
1701
  *
1313
- * A failed envelope that this client asked a resend for, and each resend
1314
- * or null message for it, gives plaintext at most once on both receive
1315
- * paths. When this client processed the envelope, or the application
1316
- * already has that content, this method acknowledges the envelope and
1317
- * throws MESSAGE_DUPLICATE with no decrypt.
1318
- *
1319
- * A null message carries no content. The client consumes a null message
1320
- * when the content adapter reports `nullMessage: true`, and a custom
1321
- * adapter must report it for its own null encoding. This method never
1322
- * returns a null message. It marks the null message processed,
1323
- * acknowledges it and throws MESSAGE_DUPLICATE. A null message for a
1324
- * failed envelope marks that envelope processed, so a redelivery of it
1325
- * is dropped, but a content resend for it that comes later still gives
1326
- * its plaintext.
1327
- *
1328
- * A resend or null message that fails to decrypt, or whose seal fails to
1329
- * open, asks again for its failed envelope under the same retry ID. When
1330
- * the processed record of the failed envelope fails to store after a
1331
- * decrypt, the client writes a warning with the behavior
1332
- * RETRY_FULFILL_WRITE_FAILED, as on every receive path, and this method
1333
- * returns the plaintext. A redelivery of the failed envelope or of
1334
- * another family member can then give the content again. When a
1335
- * processed record of a null message or of its failed envelope fails to
1336
- * store, the client writes a warning with the behavior
1337
- * RETRY_NULL_WRITE_FAILED, as on every receive path, and this method
1338
- * still throws MESSAGE_DUPLICATE. A redelivery of the failed envelope
1339
- * can then give the content.
1702
+ * A resend that brings only the sender key of a failed group message
1703
+ * gives no content. It does not mark the failed envelope processed, so a
1704
+ * redelivery of that envelope decrypts with the key.
1340
1705
  *
1341
1706
  * @param envelope - The encrypted message envelope
1342
- * @param options - Transport callbacks for background (no relay) scenarios
1343
- * @returns Decrypted plaintext
1707
+ * @param options - Transport callbacks for background (no relay)
1708
+ * scenarios, and `onPersist`
1709
+ * @returns The receive outcome
1344
1710
  * @throws EncryptionError after sending retry request if decryption fails
1345
- * @throws EncryptionError INVALID_CIPHERTEXT for a `retry_request` envelope
1346
- * @throws EncryptionError MESSAGE_DUPLICATE when this client processed the
1347
- * envelope, the application already has the content of the failed
1348
- * envelope of a retry request, or the envelope is a null message
1711
+ * @throws EncryptionError INVALID_CIPHERTEXT for a `retry_request` envelope,
1712
+ * identified or sealed
1349
1713
  */
1350
1714
  async processIncomingEnvelope(envelope, options) {
1715
+ return (await this.receiveForCaller(envelope, options)).outcome;
1716
+ }
1717
+ /**
1718
+ * Complete a helper receive: delete its receive record and mark its
1719
+ * envelope processed. Call it after the application stored the content
1720
+ * of a `processed` outcome. An unknown or completed message ID is a no-op.
1721
+ *
1722
+ * @param messageId - The `messageId` of the `processed` outcome
1723
+ */
1724
+ async completeReceive(messageId) {
1725
+ let after;
1726
+ for (;;) {
1727
+ const page = await this._storage.listReceiveWork({
1728
+ stage: 'awaiting-completion',
1729
+ ...(after !== undefined && { after }),
1730
+ limit: RECEIVE_WORK_DEFAULT_LIMIT,
1731
+ });
1732
+ const record = page.find((item) => item.origin === 'caller' && (item.messageId ?? item.workId) === messageId);
1733
+ if (record) {
1734
+ await this.completeCallerRecord(record.workId);
1735
+ return;
1736
+ }
1737
+ if (page.length < RECEIVE_WORK_DEFAULT_LIMIT)
1738
+ return;
1739
+ const last = page[page.length - 1];
1740
+ after = { arrivalSeq: last.arrivalSeq, workId: last.workId };
1741
+ }
1742
+ }
1743
+ /**
1744
+ * List the stored receives in arrival order, one page at a time. A receive
1745
+ * whose content the application has, and whose receipt waits, is not
1746
+ * listed.
1747
+ *
1748
+ * @param query - `ready` lists only the helper receives whose content
1749
+ * waits for `completeReceive`. `after` is the `next` value of the page
1750
+ * before. `limit` is the page size, 100 by default.
1751
+ * @returns The page, and `next` when a later page can follow
1752
+ * @throws Error when `after` is not a `next` value or `limit` is not a
1753
+ * positive integer
1754
+ */
1755
+ async listPendingReceives(query = {}) {
1756
+ const limit = query.limit ?? RECEIVE_WORK_DEFAULT_LIMIT;
1757
+ if (!Number.isSafeInteger(limit) || limit < 1) {
1758
+ throw new Error('listPendingReceives limit must be a positive integer');
1759
+ }
1760
+ let after;
1761
+ if (query.after !== undefined) {
1762
+ // The `next` value is `<arrivalSeq>:<workId>`. An `arrivalSeq` is not
1763
+ // unique, so the cursor holds both values.
1764
+ const match = /^(\d+):([\s\S]+)$/.exec(query.after);
1765
+ const arrivalSeq = match ? Number(match[1]) : Number.NaN;
1766
+ if (!Number.isSafeInteger(arrivalSeq)) {
1767
+ throw new Error('listPendingReceives after must be the next value of an earlier page');
1768
+ }
1769
+ after = { arrivalSeq, workId: match[2] };
1770
+ }
1771
+ const items = [];
1772
+ for (;;) {
1773
+ const page = await this._storage.listReceiveWork({
1774
+ ...(query.ready === true && { stage: 'awaiting-completion' }),
1775
+ ...(after !== undefined && { after }),
1776
+ limit,
1777
+ });
1778
+ for (const record of page) {
1779
+ after = { arrivalSeq: record.arrivalSeq, workId: record.workId };
1780
+ if (record.stage === 'receipt-due')
1781
+ continue;
1782
+ items.push(this.pendingReceiveOf(record));
1783
+ if (items.length === limit) {
1784
+ return { items, next: `${record.arrivalSeq}:${record.workId}` };
1785
+ }
1786
+ }
1787
+ if (page.length < limit)
1788
+ return { items };
1789
+ }
1790
+ }
1791
+ /**
1792
+ * Remove one stored receive that the application gives up on, such as a
1793
+ * receive whose `onMessageDecrypted` hook fails at each start. The client
1794
+ * deletes the receive and marks its envelope processed, so a redelivery
1795
+ * of the envelope is a duplicate. The call sends no receipt, calls no
1796
+ * hook, and runs no `onReceiveExpired`. A hook call that already started
1797
+ * for the receive still runs, and no receipt follows it.
1798
+ *
1799
+ * @param messageId - The `messageId` of a receive that
1800
+ * `listPendingReceives` lists
1801
+ * @returns The removed receive, or null when the client removed nothing:
1802
+ * no listed receive has the ID, or another path wrote the receive during
1803
+ * the call and again after one read
1804
+ */
1805
+ async discardPendingReceive(messageId) {
1806
+ let record;
1807
+ let after;
1808
+ while (record === undefined) {
1809
+ const page = await this._storage.listReceiveWork({
1810
+ ...(after !== undefined && { after }),
1811
+ limit: RECEIVE_WORK_DEFAULT_LIMIT,
1812
+ });
1813
+ record = page.find((item) => item.stage !== 'receipt-due' && (item.messageId ?? item.workId) === messageId);
1814
+ if (record === undefined && page.length < RECEIVE_WORK_DEFAULT_LIMIT)
1815
+ return null;
1816
+ const last = page[page.length - 1];
1817
+ if (last !== undefined)
1818
+ after = { arrivalSeq: last.arrivalSeq, workId: last.workId };
1819
+ }
1820
+ // The delete checks the revision. A record that another path wrote is
1821
+ // read again once.
1822
+ for (let attempt = 0;; attempt++) {
1823
+ if (await completeReceiveWork(this.ctx, record, 'expired')) {
1824
+ this.receiveQueue.forget(record.workId);
1825
+ // A later receive of the conversation can wait behind this one.
1826
+ this.receiveQueue.wake();
1827
+ return this.pendingReceiveOf(record);
1828
+ }
1829
+ if (attempt === 1)
1830
+ return null;
1831
+ const current = await this._storage.getReceiveWork(record.workId);
1832
+ if (current === null || current.stage === 'receipt-due')
1833
+ return null;
1834
+ record = current;
1835
+ }
1836
+ }
1837
+ /**
1838
+ * Run one pass of the receive queue now, and stop between records at the
1839
+ * deadline. A host that wakes for a push calls it after it acknowledged
1840
+ * the pulled envelopes.
1841
+ *
1842
+ * @param options - `deadlineMs` bounds the pass. With no deadline, the
1843
+ * pass runs until each record is handled.
1844
+ * @returns The receives that the pass handled, and the receives that
1845
+ * still wait
1846
+ */
1847
+ async processPendingReceives(options = {}) {
1848
+ const { processed, remaining } = await this.receiveQueue.processPending(options);
1849
+ return { processed, remaining };
1850
+ }
1851
+ /**
1852
+ * Decrypt one envelope with no receive record.
1853
+ *
1854
+ * The decrypt installs a sender key distribution that the content
1855
+ * carries, and checks that a managed group context binds to the group of
1856
+ * the transport. It stores no content, decides no group state, and sends
1857
+ * no receipt.
1858
+ *
1859
+ * Warning: the decrypt spends the ratchet step. When the application
1860
+ * loses the returned plaintext, no later decrypt of the envelope gives it
1861
+ * again. Use `processIncomingEnvelope`, which keeps the content until the
1862
+ * application completes the receive.
1863
+ *
1864
+ * @param envelope - The encrypted message envelope
1865
+ * @returns The plaintext as its sender gave it, and the group context of
1866
+ * managed-group content
1867
+ * @throws EncryptionError when the decrypt fails, and INVALID_CIPHERTEXT
1868
+ * for a `retry_request` envelope, identified or sealed
1869
+ * @throws GroupReceiveRefusedError when the group context is malformed or
1870
+ * names another group than the transport
1871
+ */
1872
+ async decryptEnvelope(envelope) {
1873
+ if (envelope.messageType === 'retry_request') {
1874
+ throw new EncryptionError('A retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
1875
+ }
1876
+ let commit;
1877
+ try {
1878
+ commit = await this.cipher.commitEnvelope(this.relayEnvelopeOf(envelope), {
1879
+ sealedSender: this.config.sealedSender,
1880
+ });
1881
+ }
1882
+ catch (error) {
1883
+ if (error instanceof SealedRetryRequestReceived) {
1884
+ throw new EncryptionError('A sealed retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: 'retry_request', senderId: error.envelope.senderUserId });
1885
+ }
1886
+ throw error;
1887
+ }
1888
+ if (commit.kind === 'denied')
1889
+ throw commit.error;
1890
+ if (commit.kind !== 'committed') {
1891
+ throw new Error('A decrypt with no receive record committed one');
1892
+ }
1893
+ const { content } = commit;
1894
+ const claim = classifyGroupContent(content.messageType === 'sender_key' ? content.transportGroupId : null, content.inspected);
1895
+ let groupContext;
1896
+ if (claim) {
1897
+ const group = groupOfContext(claim);
1898
+ if ('denial' in group)
1899
+ throw new GroupReceiveRefusedError(group.denial);
1900
+ groupContext = group.context;
1901
+ }
1902
+ return {
1903
+ plaintext: this.contentAdapter.withoutGroupContext(content.plaintext),
1904
+ ...(groupContext !== undefined && { groupContext }),
1905
+ };
1906
+ }
1907
+ /** The Relay envelope of an envelope that the application passed. */
1908
+ relayEnvelopeOf(envelope) {
1909
+ return {
1910
+ ...envelope,
1911
+ targetUserId: this.userId,
1912
+ targetDeviceId: this.deviceId,
1913
+ deliveryClass: 'user-visible',
1914
+ messageType: (envelope.messageType ?? 'ciphertext'),
1915
+ };
1916
+ }
1917
+ /**
1918
+ * Receive one envelope that the application passed. The queue skips its
1919
+ * record while the receive runs, and runs a pass after it.
1920
+ *
1921
+ * @param direct - The group and the receive record ID of a framed group
1922
+ * message that `decryptGroupMessage` passed. A decrypt failure then
1923
+ * throws with no retry request and no report.
1924
+ * @returns The outcome, and the error behind a `pending` or `denied`
1925
+ * outcome
1926
+ */
1927
+ async receiveForCaller(envelope, options, direct) {
1351
1928
  if (envelope.messageType === 'retry_request') {
1352
1929
  throw new EncryptionError('A retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
1353
1930
  }
1354
1931
  // The fingerprint covers the envelope as the Relay delivered it, before
1355
1932
  // any unseal, so every receive path stores one value for it.
1356
- const fingerprint = envelope.id
1357
- ? await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope)
1358
- : undefined;
1359
- return receiveInRetryFamily(this._storage, this.logger, envelope, async (family) => {
1360
- if (!(await family.admit())) {
1933
+ const workId = direct?.workId ?? (await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope));
1934
+ const release = this.receiveQueue.hold(workId);
1935
+ try {
1936
+ // The record sorts after the stored records once the resume ends. The
1937
+ // wait comes before the retry family lock, which the resume also takes.
1938
+ await this.receiveQueue.seeded();
1939
+ return await receiveInRetryFamily(this._storage, this.logger, this.hooks, envelope, (family) => this.receiveForCallerLocked(envelope, family, workId, options, direct));
1940
+ }
1941
+ finally {
1942
+ release();
1943
+ this.receiveQueue.wake();
1944
+ }
1945
+ }
1946
+ /** Receive one envelope that the application passed, under its retry family lock. */
1947
+ async receiveForCallerLocked(envelope, family, workId, options, direct) {
1948
+ // The processed record of an envelope with no ID has no key.
1949
+ const receiveId = envelope.id ? workId : undefined;
1950
+ let record = await this._storage.getReceiveWork(workId);
1951
+ if (record) {
1952
+ // The application got the content. Only its receipt can wait.
1953
+ if (record.plaintext === undefined) {
1361
1954
  await this.markMessageDeliveredSilently(envelope.id, options);
1362
- throw new EncryptionError('The application already has the content of this failed envelope', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1955
+ return { outcome: { kind: 'duplicate' } };
1956
+ }
1957
+ if (!record.awaitingEnvelope) {
1958
+ // The receive queue delivers a Relay record to onMessageDecrypted.
1959
+ if (record.origin === 'relay') {
1960
+ return {
1961
+ outcome: { kind: 'pending', messageId: record.messageId ?? workId, reason: 'queued' },
1962
+ };
1963
+ }
1964
+ // A redelivery of content that waits for completeReceive.
1965
+ if (record.stage === 'awaiting-completion') {
1966
+ return { outcome: await this.processedReceive(record, options) };
1967
+ }
1363
1968
  }
1364
- const plaintext = await this.decryptIncomingEnvelope(envelope, family, fingerprint, options);
1365
- // A null message carries no content, so the caller never gets it.
1366
- if (this.contentAdapter.inspectContent(plaintext).nullMessage) {
1367
- await family.consumeNull(fingerprint);
1969
+ else {
1970
+ // A converted legacy record gets its sender from this envelope.
1971
+ const opened = await this.openForCaller(envelope, family, receiveId, options);
1972
+ record = await this.fillAwaitingRecord(record, family, workId, opened);
1973
+ }
1974
+ }
1975
+ else {
1976
+ if (!(await family.admit())) {
1368
1977
  await this.markMessageDeliveredSilently(envelope.id, options);
1369
- throw new EncryptionError('A null message carries no content', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1978
+ return { outcome: { kind: 'duplicate' } };
1370
1979
  }
1371
- await family.fulfill();
1372
- return plaintext;
1980
+ const opened = await this.openForCaller(envelope, family, receiveId, options);
1981
+ const decrypted = await this.decryptForCaller(envelope, opened, family, workId, options, direct);
1982
+ if ('outcome' in decrypted)
1983
+ return decrypted;
1984
+ record = decrypted.record;
1985
+ }
1986
+ const restored = await this.cipher.restoreCommitted(record);
1987
+ // The ratchet step is spent, so a resend cannot repair the content.
1988
+ if (restored.kind === 'denied') {
1989
+ await denyReceiveWork(this.ctx, record, restored, restored.error);
1990
+ await this.markMessageDeliveredSilently(envelope.id, options);
1991
+ return {
1992
+ outcome: { kind: 'denied', reason: receiveDenialReason(restored.error) },
1993
+ error: restored.error,
1994
+ };
1995
+ }
1996
+ const { content } = restored;
1997
+ // A null message carries no content, so the caller never gets it.
1998
+ if (content.inspected.nullMessage) {
1999
+ await family.consumeNull(receiveId);
2000
+ await completeReceiveWork(this.ctx, record);
2001
+ await this.markMessageDeliveredSilently(envelope.id, options);
2002
+ return { outcome: { kind: 'null-message' } };
2003
+ }
2004
+ // Outcome 1 comes before the return. A redelivery after a failed write
2005
+ // finds the committed record and writes it again, as on the Relay path.
2006
+ await family.fulfill({
2007
+ senderKeyDistribution: content.inspected.senderKeyDistribution !== undefined,
2008
+ content: content.inspected.senderKeyDistribution === undefined ||
2009
+ content.inspected.senderKeyDistributionOnly === false,
2010
+ ...RelaySubscriptionOps.groupOfFulfill(content),
1373
2011
  });
2012
+ const decision = await this.cipher.decideGroupContent(content);
2013
+ if (decision.kind === 'denied') {
2014
+ await denyReceiveWork(this.ctx, record, content, decision.error);
2015
+ await this.markMessageDeliveredSilently(envelope.id, options);
2016
+ return { outcome: { kind: 'denied', reason: decision.error.reason }, error: decision.error };
2017
+ }
2018
+ const expiresAt = receiveExpiresAt(record);
2019
+ if (decision.kind === 'unavailable') {
2020
+ await blockReceiveWork(this.ctx, record, content, decision, Date.now(), expiresAt);
2021
+ return {
2022
+ outcome: { kind: 'pending', messageId: content.messageId, reason: decision.error.reason },
2023
+ error: decision.error,
2024
+ };
2025
+ }
2026
+ const awaiting = (await awaitReceiveCompletion(this.ctx, record, decision.groupId, expiresAt)) ??
2027
+ (await this._storage.getReceiveWork(workId)) ??
2028
+ record;
2029
+ return { outcome: await this.processedReceive(awaiting, options) };
1374
2030
  }
1375
2031
  /**
1376
- * Decrypt one envelope that is not a `retry_request`, under its retry family
1377
- * lock. The fingerprint is that of the delivered envelope, also for the
1378
- * inner envelope of a seal.
2032
+ * Open the seal of a sealed envelope that the application passed. A
2033
+ * member whose seal fails to open asks the device of its request for the
2034
+ * next attempt, as a member whose decrypt fails does.
2035
+ *
2036
+ * @returns The envelope inside the seal, or the envelope itself
2037
+ * @throws EncryptionError INVALID_CIPHERTEXT for a sealed retry request
1379
2038
  */
1380
- async decryptIncomingEnvelope(envelope, family, fingerprint, options) {
1381
- // Handle sealed sender envelopes: unseal to reveal sender before decrypting
1382
- if (envelope.messageType === 'unidentified_sender' && this.config.sealedSender) {
1383
- const identityKeyPair = await this._storage.getIdentityKey();
1384
- if (!identityKeyPair) {
1385
- throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
1386
- }
1387
- const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
1388
- let unsealed;
1389
- try {
1390
- unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1391
- }
1392
- catch (error) {
1393
- // A member whose seal fails to open asks the device of its request
1394
- // for the next attempt, as a member whose decrypt fails does.
1395
- if (family.member !== undefined) {
1396
- await this.sendRetryRequestInternal(family.withRequestedSender(envelope), error, family, fingerprint, options);
1397
- }
1398
- throw error;
2039
+ async openForCaller(envelope, family, receiveId, options) {
2040
+ if (envelope.messageType !== 'unidentified_sender' || !this.config.sealedSender) {
2041
+ return { inner: envelope, arrivedSealed: false };
2042
+ }
2043
+ const identityKeyPair = await this._storage.getIdentityKey();
2044
+ if (!identityKeyPair) {
2045
+ throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
2046
+ }
2047
+ let unsealed;
2048
+ try {
2049
+ unsealed = await unsealMessage(envelope.ciphertext, base64ToBytes(identityKeyPair.dhKey.privateKey), this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
2050
+ }
2051
+ catch (error) {
2052
+ if (family.member !== undefined) {
2053
+ await this.sendRetryRequestInternal(family.withRequestedSender(envelope), error, family, receiveId, options);
1399
2054
  }
1400
- // Process the inner envelope with revealed sender identity. The inner
1401
- // type and the content hint travel inside the seal. Nothing outside it
1402
- // distinguishes a group message from a pairwise one. The same mapping
1403
- // serves the other receive path via `reconstructEnvelope`.
1404
- return this.decryptIncomingEnvelope({
2055
+ throw error;
2056
+ }
2057
+ // A sealed retry request holds no plaintext, as an identified one.
2058
+ // It asks for no resend of itself.
2059
+ if (unsealed.contentType === SealedSenderContentType.PLAINTEXT_CONTENT) {
2060
+ throw new EncryptionError('A sealed retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: 'retry_request', senderId: unsealed.senderUserId });
2061
+ }
2062
+ // The inner type and the content hint travel inside the seal. The same
2063
+ // mapping serves the other receive path via `reconstructEnvelope`.
2064
+ return {
2065
+ inner: {
1405
2066
  ...envelope,
1406
2067
  senderUserId: unsealed.senderUserId,
1407
2068
  senderDeviceId: unsealed.senderDeviceId,
1408
2069
  ciphertext: unsealed.innerCiphertextBase64,
1409
2070
  messageType: envelopeTypeForContent(unsealed.contentType),
1410
2071
  contentHint: unsealed.contentHint,
1411
- }, family, fingerprint, options);
1412
- }
1413
- // Route group messages to sender key decryption. `sender_key` says the
1414
- // payload is a framed SenderKeyMessage. It does not say which group, so
1415
- // the group comes from the frame's distribution identifier resolved
1416
- // against the local sender key store.
1417
- if (envelope.messageType === 'sender_key') {
1418
- // Framed SenderKeyMessage: base64 → bytes (Uint8Array)
1419
- const framedBytes = base64ToBytes(envelope.ciphertext);
1420
- const groupId = await this.senderKeyManager.resolveGroupForFramedMessage(framedBytes, envelope.senderUserId, envelope.senderDeviceId);
1421
- if (groupId === null) {
1422
- throw new EncryptionError(`No sender key from ${envelope.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
1423
- }
1424
- return this.decryptGroupMessage(groupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes);
1425
- }
1426
- const senderAddress = ProtocolAddress.create(envelope.senderUserId, envelope.senderDeviceId);
2072
+ },
2073
+ arrivedSealed: true,
2074
+ };
2075
+ }
2076
+ /** The receive commit of an envelope that the application passed. */
2077
+ callerReceiveCommit(family, workId) {
2078
+ return createReceiveCommit({
2079
+ storage: this._storage,
2080
+ policy: this.receiveQueue.policy,
2081
+ logger: this.logger,
2082
+ contentAdapter: this.contentAdapter,
2083
+ family,
2084
+ workId,
2085
+ origin: 'caller',
2086
+ receiptJoin: false,
2087
+ });
2088
+ }
2089
+ /**
2090
+ * Fill the sender fields of a converted legacy record from the envelope
2091
+ * that the application passed. The record keeps its age and its arrival
2092
+ * order, and becomes a helper record.
2093
+ */
2094
+ async fillAwaitingRecord(existing, family, workId, opened) {
2095
+ const { inner, arrivedSealed } = opened;
2096
+ const groupId = existing.groupId ??
2097
+ (inner.messageType === 'sender_key'
2098
+ ? ((await this.senderKeyManager.resolveGroupForFramedMessage(envelopeCiphertextBytes(inner.ciphertext), inner.senderUserId, inner.senderDeviceId)) ?? undefined)
2099
+ : undefined);
2100
+ const seed = this.callerReceiveCommit(family, workId).commit.seed(this.relayEnvelopeOf(inner), arrivedSealed);
2101
+ const filled = sizedReceiveWork({
2102
+ ...seed({ plaintext: existing.plaintext, ...(groupId !== undefined && { groupId }) }),
2103
+ workId: existing.workId,
2104
+ revision: existing.revision + 1,
2105
+ stage: existing.stage,
2106
+ arrivalSeq: existing.arrivalSeq,
2107
+ receivedAt: existing.receivedAt,
2108
+ dueAt: existing.dueAt,
2109
+ plaintext: existing.plaintext,
2110
+ ...(groupId !== undefined && { groupId }),
2111
+ ...(existing.blockedOn !== undefined && { blockedOn: existing.blockedOn }),
2112
+ });
2113
+ if (await this._storage.putReceiveWork(filled, existing.revision))
2114
+ return filled;
2115
+ return (await this._storage.getReceiveWork(workId)) ?? existing;
2116
+ }
2117
+ /**
2118
+ * Decrypt one opened envelope under the receive admission, and commit its
2119
+ * receive record with the ratchet step.
2120
+ *
2121
+ * A decrypt failure that no resend can repair, as `receiveRefusal`
2122
+ * decides on both receive paths, asks for nothing: `onDecryptionError`
2123
+ * runs once, the envelope is stored as processed and acknowledged, and
2124
+ * the outcome is `denied`. A retryable failure (per SESAME spec §4.1)
2125
+ * sends a retry request, which acknowledges the envelope, and throws. A
2126
+ * failure after the decrypt built the record is a store failure: it
2127
+ * throws with no request, and the ratchet step rolled back.
2128
+ *
2129
+ * @returns The committed record, or the outcome when nothing committed
2130
+ */
2131
+ async decryptForCaller(envelope, opened, family, workId, options, direct) {
2132
+ const { inner, arrivedSealed } = opened;
2133
+ const receiveId = envelope.id ? workId : undefined;
2134
+ const handle = this.callerReceiveCommit(family, workId);
2135
+ const failure = { reported: false };
2136
+ let admitted;
1427
2137
  try {
1428
- // Decode ciphertext: base64 → UTF-8 bytes → JSON string
1429
- // Relay stores as base64(UTF-8(JSON)), we need to reverse both encodings
1430
- const ciphertextBytes = base64ToBytes(envelope.ciphertext);
1431
- const ciphertext = utf8Decode(ciphertextBytes);
1432
- // Decrypt message using Double Ratchet
1433
- const plaintext = await this.decryptMessage(senderAddress, ciphertext);
1434
- return plaintext;
2138
+ const seed = handle.commit.seed(this.relayEnvelopeOf(inner), arrivedSealed);
2139
+ if (inner.messageType === 'sender_key') {
2140
+ // `sender_key` says the payload is a framed SenderKeyMessage. It
2141
+ // does not say which group, so the group comes from the frame's
2142
+ // distribution identifier resolved against the local sender key
2143
+ // store.
2144
+ const framed = direct?.framed ?? envelopeCiphertextBytes(inner.ciphertext);
2145
+ const groupId = direct?.groupId ??
2146
+ (await this.senderKeyManager.resolveGroupForFramedMessage(framed, inner.senderUserId, inner.senderDeviceId));
2147
+ if (groupId === null) {
2148
+ throw new EncryptionError(`No sender key from ${inner.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
2149
+ }
2150
+ admitted = await this.groupSenderKeys.run(groupId, (rawGroupId) => handle.commit.admit(rawGroupId, () => GroupOps.decryptGroupMessage(this.ctx, this.senderKeyManager, rawGroupId, inner.senderUserId, inner.senderDeviceId, framed, seed)));
2151
+ }
2152
+ else {
2153
+ // Decode ciphertext: base64 → UTF-8 bytes → JSON string
2154
+ const ciphertext = utf8Decode(envelopeCiphertextBytes(inner.ciphertext));
2155
+ const address = ProtocolAddress.create(inner.senderUserId, inner.senderDeviceId);
2156
+ admitted = await handle.commit.admit(null, async () => {
2157
+ // The failure of the decrypt runs onDecryptionError.
2158
+ try {
2159
+ return await MessageOps.decryptMessage(this.ctx, address, ciphertext, seed);
2160
+ }
2161
+ catch (error) {
2162
+ failure.reported = true;
2163
+ throw error;
2164
+ }
2165
+ });
2166
+ }
1435
2167
  }
1436
2168
  catch (error) {
1437
- // Send retry request if error is retryable (per SESAME spec §4.1)
2169
+ if (handle.seeded() || direct !== undefined)
2170
+ throw error;
2171
+ if (receiveRefusal(error) !== null) {
2172
+ await reportReceiveRefusal(this._storage, this.hooks, inner, error, receiveId, failure.reported);
2173
+ await this.markMessageDeliveredSilently(envelope.id, options);
2174
+ return {
2175
+ outcome: { kind: 'denied', reason: receiveDenialReason(error) },
2176
+ error: error,
2177
+ };
2178
+ }
1438
2179
  if (isRetryableDecryptionError(error)) {
1439
- await this.sendRetryRequestInternal(envelope, error, family, fingerprint, options);
2180
+ await this.sendRetryRequestInternal(inner, error, family, receiveId, options);
1440
2181
  }
1441
- // Re-throw so caller can handle (log, skip message, etc.)
1442
2182
  throw error;
1443
2183
  }
2184
+ if (admitted === null) {
2185
+ return { outcome: { kind: 'refused', persisted: false, reason: 'capacity' } };
2186
+ }
2187
+ const record = await this._storage.getReceiveWork(workId);
2188
+ // The caller acknowledges only content that is stored.
2189
+ if (!record)
2190
+ throw new Error('The store did not commit the receive record');
2191
+ return { record };
2192
+ }
2193
+ /**
2194
+ * The `processed` outcome of a helper record that waits for completion.
2195
+ * With `onPersist`, the record completes when the callback resolves. A
2196
+ * callback that rejects leaves the record for a redelivery or for
2197
+ * `completeReceive`.
2198
+ */
2199
+ async processedReceive(record, options) {
2200
+ const outcome = {
2201
+ kind: 'processed',
2202
+ // The caller gets the content as its sender gave it.
2203
+ plaintext: this.contentAdapter.withoutGroupContext(record.plaintext),
2204
+ messageId: record.messageId ?? record.workId,
2205
+ ...(record.groupId !== undefined && { groupId: extractGroupId(record.groupId) }),
2206
+ };
2207
+ if (options?.onPersist) {
2208
+ try {
2209
+ await options.onPersist(outcome);
2210
+ }
2211
+ catch (error) {
2212
+ this.logger.warn('The application failed to store received content', {
2213
+ category: 'E2EE',
2214
+ data: {
2215
+ messageId: outcome.messageId,
2216
+ behavior: 'RECEIVE_PERSIST_FAILED',
2217
+ error: error.message,
2218
+ },
2219
+ });
2220
+ return outcome;
2221
+ }
2222
+ await this.completeCallerRecord(record.workId);
2223
+ }
2224
+ return outcome;
2225
+ }
2226
+ /**
2227
+ * Complete one helper record that waits for completion. A record whose
2228
+ * revision changed is read again once.
2229
+ */
2230
+ async completeCallerRecord(workId) {
2231
+ for (let attempt = 0; attempt < 2; attempt++) {
2232
+ const record = await this._storage.getReceiveWork(workId);
2233
+ if (record?.origin !== 'caller' || record.stage !== 'awaiting-completion')
2234
+ return;
2235
+ if (await completeReceiveWork(this.ctx, record))
2236
+ return;
2237
+ }
2238
+ }
2239
+ /** The application view of one stored receive. */
2240
+ pendingReceiveOf(record) {
2241
+ const ready = record.stage === 'awaiting-completion';
2242
+ return {
2243
+ // A converted legacy record has no message ID. Its outcomes give the
2244
+ // record ID, as `completeReceive` matches.
2245
+ messageId: record.messageId ?? record.workId,
2246
+ stage: ready ? 'awaiting-completion' : 'decrypted',
2247
+ origin: record.origin,
2248
+ receivedAt: record.receivedAt,
2249
+ ...(record.senderUserId !== undefined && { senderId: record.senderUserId }),
2250
+ ...(record.senderDeviceId !== undefined && { senderDeviceId: record.senderDeviceId }),
2251
+ ...(record.groupId !== undefined && { groupId: extractGroupId(record.groupId) }),
2252
+ ...(ready &&
2253
+ record.plaintext !== undefined && {
2254
+ plaintext: this.contentAdapter.withoutGroupContext(record.plaintext),
2255
+ }),
2256
+ hookAttempts: record.hookAttempts ?? 0,
2257
+ };
1444
2258
  }
1445
2259
  /**
1446
2260
  * Process multiple incoming encrypted message envelopes.
@@ -1455,15 +2269,15 @@ export class DefaultSignalProtocolClient {
1455
2269
  * session convergence requires this when the client promotes archived sessions.
1456
2270
  *
1457
2271
  * @param envelopes - Array of encrypted message envelopes
1458
- * @param options - Transport callbacks for background scenarios
1459
- * @returns Array of results, each either success (plaintext) or failure (error)
2272
+ * @param options - Transport callbacks for background scenarios, and `onPersist`
2273
+ * @returns Array of results, each either the receive outcome or the error
1460
2274
  *
1461
2275
  * @example
1462
2276
  * ```typescript
1463
2277
  * const results = await signal.processIncomingEnvelopes(pendingMessages);
1464
2278
  * for (const result of results) {
1465
- * if ('plaintext' in result) {
1466
- * handleDecryptedMessage(result.envelope, result.plaintext);
2279
+ * if ('outcome' in result) {
2280
+ * handleReceiveOutcome(result.envelope, result.outcome);
1467
2281
  * } else {
1468
2282
  * handleDecryptionError(result.envelope, result.error);
1469
2283
  * }
@@ -1479,8 +2293,8 @@ export class DefaultSignalProtocolClient {
1479
2293
  const results = [];
1480
2294
  for (const envelope of sorted) {
1481
2295
  try {
1482
- const plaintext = await this.processIncomingEnvelope(envelope, options);
1483
- results.push({ envelope, plaintext });
2296
+ const outcome = await this.processIncomingEnvelope(envelope, options);
2297
+ results.push({ envelope, outcome });
1484
2298
  }
1485
2299
  catch (error) {
1486
2300
  results.push({ envelope, error: error });
@@ -1495,30 +2309,54 @@ export class DefaultSignalProtocolClient {
1495
2309
  * each envelope that the client drops as a duplicate, and each null
1496
2310
  * message that the content adapter reports, which the client consumes
1497
2311
  * and never gives to onMessageDecrypted.
2312
+ *
2313
+ * The content reaches onMessageDecrypted in a later pass of the receive
2314
+ * queue, after this call returns. After `stop()`, the content waits for
2315
+ * the next start of the queue from `startRelaySubscription`, or for
2316
+ * `processPendingReceives`.
1498
2317
  */
1499
2318
  async receiveIncomingEnvelopes(envelopes) {
2319
+ const { release, ...results } = await this.commitIncomingEnvelopes(envelopes);
2320
+ release();
2321
+ return results;
2322
+ }
2323
+ /**
2324
+ * @internal Commit a pulled batch as `receiveIncomingEnvelopes` does, and
2325
+ * keep each record held until `release` runs. A queue pass skips a held
2326
+ * record, so the hosted pull releases only after its acknowledgment
2327
+ * settles, and no content reaches the application before it. `release`
2328
+ * then wakes the queue.
2329
+ */
2330
+ async commitIncomingEnvelopes(envelopes) {
1500
2331
  if (!this.hooks?.onMessageDecrypted) {
1501
2332
  throw new Error('Register onMessageDecrypted before receiving Relay messages');
1502
2333
  }
1503
2334
  const processedMessageIds = [];
1504
2335
  const failedMessageIds = [];
1505
- const context = { ...this.ctx, cipher: this.cipher };
1506
- for (const envelope of sortEnvelopesForDecryption(envelopes)) {
1507
- try {
1508
- const processed = await RelaySubscriptionOps.processRelayMessage(context, {
1509
- ...envelope,
1510
- targetUserId: this.userId,
1511
- targetDeviceId: this.deviceId,
1512
- deliveryClass: 'user-visible',
1513
- messageType: (envelope.messageType ?? 'ciphertext'),
1514
- }, this.relaySubscriptionState, this.relaySubscriptionCallbacks(context), { ...this.relaySubscriptionConfig, acknowledgeFailures: false });
1515
- (processed ? processedMessageIds : failedMessageIds).push(envelope.id);
1516
- }
1517
- catch {
1518
- failedMessageIds.push(envelope.id);
2336
+ const releases = [];
2337
+ const release = () => {
2338
+ for (const releaseOne of releases)
2339
+ releaseOne();
2340
+ this.receiveQueue.wake();
2341
+ };
2342
+ const context = { ...this.ctx, cipher: this.cipher, receiveQueue: this.receiveQueue };
2343
+ try {
2344
+ for (const envelope of sortEnvelopesForDecryption(envelopes)) {
2345
+ releases.push(this.receiveQueue.hold(await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope)));
2346
+ try {
2347
+ const processed = await RelaySubscriptionOps.processRelayMessage(context, this.relayEnvelopeOf(envelope), this.relaySubscriptionState, this.relaySubscriptionCallbacks(context), { ...this.relaySubscriptionConfig, acknowledgeFailures: false });
2348
+ (processed ? processedMessageIds : failedMessageIds).push(envelope.id);
2349
+ }
2350
+ catch {
2351
+ failedMessageIds.push(envelope.id);
2352
+ }
1519
2353
  }
1520
2354
  }
1521
- return { processedMessageIds, failedMessageIds };
2355
+ catch (error) {
2356
+ release();
2357
+ throw error;
2358
+ }
2359
+ return { processedMessageIds, failedMessageIds, release };
1522
2360
  }
1523
2361
  /**
1524
2362
  * Internal: Send SESAME retry request for failed decryption.
@@ -1635,6 +2473,18 @@ export class DefaultSignalProtocolClient {
1635
2473
  * The stop signal of relay work ends a wait for the recipient's lock.
1636
2474
  */
1637
2475
  async sendWithContext(recipientId, content, options, context, stopSignal) {
2476
+ // Every send error carries the logical-send identifier, also an error
2477
+ // before the encryption, such as a failed content serialization.
2478
+ const clientMessageId = options?.clientMessageId ?? (await generateUuidV4());
2479
+ try {
2480
+ return await this.sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId);
2481
+ }
2482
+ catch (error) {
2483
+ throw attachClientMessageId(error, clientMessageId);
2484
+ }
2485
+ }
2486
+ /** Send under a logical-send identifier that the caller already chose. */
2487
+ async sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId) {
1638
2488
  // Normalize all inputs to Uint8Array before calling cipher.encrypt()
1639
2489
  let plaintextBytes;
1640
2490
  let clientTimestamp;
@@ -1657,13 +2507,19 @@ export class DefaultSignalProtocolClient {
1657
2507
  await profileKeys?.offer(recipientId);
1658
2508
  plaintextBytes = content; // already Uint8Array
1659
2509
  }
1660
- // A receipt for this send waits until the send resolves.
1661
- const clientMessageId = options?.clientMessageId ?? (await generateUuidV4());
2510
+ const contentHint = isGroupId(recipientId)
2511
+ ? this.groupContentHint(options?.contentHint, clientTimestamp !== undefined)
2512
+ : options?.contentHint;
2513
+ if (isGroupId(recipientId) && contentHint === ContentHint.Resendable) {
2514
+ await this.sweepResendableContentDaily();
2515
+ }
1662
2516
  const encrypt = (sendContext) => this.cipher.encrypt(recipientId, plaintextBytes, {
1663
2517
  ...options,
1664
2518
  clientMessageId,
1665
2519
  ...(clientTimestamp !== undefined && { timestamp: clientTimestamp }),
2520
+ ...(contentHint !== undefined && { contentHint }),
1666
2521
  }, this.sendSessionCallbacks(() => sendContext, stopSignal), stopSignal);
2522
+ // A receipt for this send waits until the send resolves.
1667
2523
  this.deliveries.beginSend(clientMessageId);
1668
2524
  let result;
1669
2525
  try {
@@ -1675,11 +2531,24 @@ export class DefaultSignalProtocolClient {
1675
2531
  finally {
1676
2532
  this.deliveries.endSend(clientMessageId);
1677
2533
  }
2534
+ // A Relay that accepted a declared post without comparing it does not
2535
+ // change the result. The hook reports it once for the completed send.
2536
+ const protocolError = relayProtocolErrorOf(result);
1678
2537
  this.releaseDeliveries(clientMessageId);
1679
2538
  if (profileKey)
1680
2539
  await profileKeys?.delivered(recipientId, profileKey);
2540
+ if (protocolError)
2541
+ await callHook(context.hooks, 'onRelayProtocolError', protocolError);
1681
2542
  return clientTimestamp !== undefined ? { ...result, clientTimestamp } : result;
1682
2543
  }
2544
+ /** @see SignalProtocolClient.forgetSentContent */
2545
+ async forgetSentContent(clientMessageId) {
2546
+ return this.resendableContent.forget(clientMessageId);
2547
+ }
2548
+ /** @see SignalProtocolClient.getPendingRecipients */
2549
+ async getPendingRecipients(clientMessageId) {
2550
+ return this.resendableContent.pendingRecipients(clientMessageId);
2551
+ }
1683
2552
  async uploadAttachment(data, options) {
1684
2553
  return this.cipher.uploadAttachment(data, options);
1685
2554
  }
@@ -1791,6 +2660,9 @@ export class DefaultSignalProtocolClient {
1791
2660
  registerHook(name, callback) {
1792
2661
  assertHookName(name);
1793
2662
  this.hooks[name] = callback;
2663
+ // Received content waits for this hook, or failed in the hook before.
2664
+ if (name === 'onMessageDecrypted')
2665
+ this.receiveQueue.retryFailedHooks();
1794
2666
  this.logger.debug('Hook registered', {
1795
2667
  category: 'E2EE',
1796
2668
  data: { hookName: name },
@@ -1853,7 +2725,12 @@ export class DefaultSignalProtocolClient {
1853
2725
  this.relayUnsubscribe = this.relay.subscribe(this.userId, this.deviceId, (envelope) => {
1854
2726
  const handled = this.state.relayWork.run((work) => {
1855
2727
  const ctx = this.relayWorkContext(work);
1856
- return RelaySubscriptionOps.handleRelayMessage({ ...ctx, cipher: this.cipher, stopSignal: work.stopSignal }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx, work.stopSignal), this.relaySubscriptionConfig);
2728
+ return RelaySubscriptionOps.handleRelayMessage({
2729
+ ...ctx,
2730
+ cipher: this.cipher,
2731
+ receiveQueue: this.receiveQueue,
2732
+ stopSignal: work.stopSignal,
2733
+ }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx, work.stopSignal), this.relaySubscriptionConfig);
1857
2734
  });
1858
2735
  handled.catch((error) => {
1859
2736
  // The relay delivers an envelope that it did not acknowledge again.
@@ -1874,9 +2751,48 @@ export class DefaultSignalProtocolClient {
1874
2751
  onBatchEnd: () => this.contentAdapter.setRelayBatching(false),
1875
2752
  });
1876
2753
  }
1877
- /** Start the retry request scheduler with a pass in the background. */
2754
+ /**
2755
+ * Delete the stale Sesame device records in the background. A removed
2756
+ * device record goes when its removal is older than `maxLatency`. The
2757
+ * receive queue runs it once in each run, after its resume. A failure is
2758
+ * logged, and the next run tries again.
2759
+ */
2760
+ cleanupStaleDeviceRecords() {
2761
+ this.sesameManager.cleanupStaleRecords().catch((error) => {
2762
+ this.logger.warn('Stale device record cleanup failed', {
2763
+ category: 'E2EE',
2764
+ data: { error: error.message },
2765
+ });
2766
+ });
2767
+ }
2768
+ /**
2769
+ * Start the receive queue. After its resume, start the retry request
2770
+ * lifecycle.
2771
+ */
1878
2772
  startRetryRequests() {
2773
+ void this.receiveQueue.start(() => this.startRetryLifecycle());
2774
+ }
2775
+ /**
2776
+ * Start the retry request scheduler and the resend job driver, each with a
2777
+ * pass in the background. Each relay transition to connected runs the
2778
+ * resend jobs again until stop().
2779
+ */
2780
+ startRetryLifecycle() {
1879
2781
  void this.retryRequests.start();
2782
+ this.groupFetcher?.start().catch((error) => {
2783
+ this.logger.warn('The group fetcher failed to start', {
2784
+ category: 'E2EE',
2785
+ data: { behavior: 'GROUP_FETCH_START_FAILED', error: error.message },
2786
+ });
2787
+ });
2788
+ void this.resendJobs.start();
2789
+ const relay = this.relay;
2790
+ if (this.resendJobsOnConnect === undefined && relay) {
2791
+ this.resendJobsOnConnect = relay.subscribeRelayConnectionState((connection) => {
2792
+ if (connection.state === 'connected')
2793
+ void this.resendJobs.start();
2794
+ });
2795
+ }
1880
2796
  }
1881
2797
  /**
1882
2798
  * Stop the relay subscription
@@ -1918,9 +2834,15 @@ export class DefaultSignalProtocolClient {
1918
2834
  * @param timestamps - Array of message timestamps that have been delivered
1919
2835
  * @param ctx - Client context, whose hooks run through the relay work of the send
1920
2836
  *
2837
+ * A failed send rejects and makes no retry of its own: the receive queue
2838
+ * keeps the receive in `receipt-due` and sends again. A send that the
2839
+ * Relay refused rejects with ReceiptSendTerminalError, and the queue
2840
+ * completes the receive with no receipt.
1921
2841
  */
1922
2842
  async sendDeliveryReceipt(recipientUserId, timestamps, ctx = this.receiptContext()) {
1923
- return this.sendReceipt(recipientUserId, timestamps, ReceiptType.DELIVERY, ctx);
2843
+ return MessageOps.sendReceipt(ctx, recipientUserId, timestamps, ReceiptType.DELIVERY, {
2844
+ report: true,
2845
+ });
1924
2846
  }
1925
2847
  /**
1926
2848
  * Send read receipt to original message sender (all devices)
@@ -2139,9 +3061,15 @@ export class DefaultSignalProtocolClient {
2139
3061
  // for this run and does not start a second run. A subscription start
2140
3062
  // from a step is refused
2141
3063
  await Promise.resolve();
2142
- // 0. Stop the retry request scheduler, so no pass starts. Step 4 waits
2143
- // for a pass in progress, as for other relay work
3064
+ // 0. Stop the retry request scheduler, the resend job driver, the group
3065
+ // fetcher, and the receive queue, so no pass starts. Step 4 waits for a
3066
+ // pass in progress, as for other relay work
2144
3067
  this.retryRequests.stop();
3068
+ this.resendJobs.stop();
3069
+ this.groupFetcher?.stop();
3070
+ this.receiveQueue.stop();
3071
+ this.resendJobsOnConnect?.();
3072
+ this.resendJobsOnConnect = undefined;
2145
3073
  // 1. Start the receipt deadline, 5 s from now. Take the receipt sends in
2146
3074
  // progress, except a send that an earlier stop() stopped, and start the
2147
3075
  // send of the batched delivery receipts, once each, as relay work. Until
@@ -2176,11 +3104,12 @@ export class DefaultSignalProtocolClient {
2176
3104
  }
2177
3105
  // 3. Stop all relay work except the delivery receipt sends, then wait
2178
3106
  // for the receipt sends of step 1, with their app hooks, until the
2179
- // receipt deadline. A delivery or retry request whose app hook returns
2180
- // during the wait writes nothing more, and the relay delivers it again
2181
- // after the next start. A receipt send is not stopped here, because the
2182
- // relay has the acknowledgment of its messages and does not deliver
2183
- // them again
3107
+ // receipt deadline. A delivery, a receive queue pass, or a retry request
3108
+ // whose app hook returns during the wait writes nothing more. The relay
3109
+ // delivers an unacknowledged envelope again after the next start, and
3110
+ // the receive queue runs a stored receive record again at the next
3111
+ // start. A receipt send is not stopped here, because the relay has the
3112
+ // acknowledgment of its messages and does not deliver them again
2184
3113
  if (receiptSends.length > 0) {
2185
3114
  this.state.relayWork.stopAllExcept(new Set(this.deliveryReceiptSends.keys()));
2186
3115
  await this.waitForStopReceiptSends(receiptSends, receiptDeadline - Date.now());
@@ -2230,19 +3159,19 @@ export class DefaultSignalProtocolClient {
2230
3159
  data: { error: error.message },
2231
3160
  });
2232
3161
  }
2233
- // 8. Cleanup expired message records (SESAME spec §6.2)
3162
+ // 8. Cleanup expired resendable content (SESAME spec §6.2 and the send log)
2234
3163
  try {
2235
- const deleted = await this._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
2236
- if (deleted > 0) {
2237
- this.logger.debug('Cleaned up expired message records', {
3164
+ const deleted = await this.resendableContent.sweep();
3165
+ if (deleted.messageRecords > 0 || deleted.sendLogEntries > 0) {
3166
+ this.logger.debug('Cleaned up expired resendable content', {
2238
3167
  category: 'E2EE',
2239
- data: { deleted },
3168
+ data: deleted,
2240
3169
  });
2241
3170
  }
2242
3171
  }
2243
3172
  catch (error) {
2244
3173
  // Log but do not fail stop
2245
- this.logger.warn('Error cleaning up message records', {
3174
+ this.logger.warn('Error cleaning up resendable content', {
2246
3175
  category: 'E2EE',
2247
3176
  data: { error: error.message },
2248
3177
  });
@@ -2357,8 +3286,10 @@ export class DefaultSignalProtocolClient {
2357
3286
  * ```
2358
3287
  */
2359
3288
  async processGroupSenderKeyDistribution(groupId, senderId, senderDeviceId, message) {
3289
+ // Signal installs a distribution from an authenticated session with no
3290
+ // group check. The key decrypts nothing until group content that names
3291
+ // it passes the group checks.
2360
3292
  return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
2361
- await this.groupReceiveAuthorizer?.(rawGroupId, senderId, 'distribution');
2362
3293
  return GroupOps.processSenderKeyDistribution(this.ctx, this.senderKeyManager, rawGroupId, senderId, senderDeviceId, message);
2363
3294
  });
2364
3295
  }
@@ -2395,11 +3326,27 @@ export class DefaultSignalProtocolClient {
2395
3326
  * Use this to decrypt messages from other group members.
2396
3327
  * You must process the sender's distribution message first.
2397
3328
  *
3329
+ * The message passes the group decision of `processIncomingEnvelope`.
3330
+ * Content whose group state must update first stays stored, and a later
3331
+ * call with the same message decides it with no second decrypt.
3332
+ *
3333
+ * @deprecated Use `processIncomingEnvelope`, which returns a receive
3334
+ * outcome and keeps the content until the application completes the
3335
+ * receive. This method completes the receive before it returns, so a
3336
+ * plaintext that the application loses is gone.
3337
+ *
2398
3338
  * @param groupId - Group identifier
2399
3339
  * @param senderId - Sender's user ID
2400
3340
  * @param senderDeviceId - Sender's device ID
2401
3341
  * @param framedMessage - Framed SenderKeyMessage bytes
2402
3342
  * @returns Decrypted plaintext
3343
+ * @throws GroupReceiveUnavailableError when the group state of the content
3344
+ * is not current. Its `messageId` names the stored receive. Call again
3345
+ * later with the same message.
3346
+ * @throws GroupReceiveRefusedError when the client refuses the content
3347
+ * @throws EncryptionError MESSAGE_DUPLICATE for a message that this client
3348
+ * processed, or that carries no content, and STORAGE_QUOTA_EXCEEDED when
3349
+ * the receive queue has no room
2403
3350
  *
2404
3351
  * @example
2405
3352
  * ```typescript
@@ -2413,9 +3360,41 @@ export class DefaultSignalProtocolClient {
2413
3360
  * ```
2414
3361
  */
2415
3362
  async decryptGroupMessage(groupId, senderId, senderDeviceId, framedMessage) {
2416
- return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
2417
- await this.groupReceiveAuthorizer?.(rawGroupId, senderId, 'message');
2418
- return GroupOps.decryptGroupMessage(this.ctx, this.senderKeyManager, rawGroupId, senderId, senderDeviceId, framedMessage);
3363
+ // The message has no envelope ID, so its receive record ID binds the
3364
+ // sender and the framed bytes.
3365
+ const ciphertext = bytesToBase64(framedMessage);
3366
+ const workId = await deliveredEnvelopeFingerprint(this.userId, this.deviceId, {
3367
+ senderUserId: senderId,
3368
+ senderDeviceId,
3369
+ messageType: 'sender_key',
3370
+ ciphertext,
3371
+ });
3372
+ // A concurrent call with the same message waits here, and then reads
3373
+ // the record that the first call left, as a later call does.
3374
+ return withKeyedLock(groupMessageReceiveLocks, this._storage, workId, async () => {
3375
+ const { outcome, error } = await this.receiveForCaller({
3376
+ id: '',
3377
+ senderUserId: senderId,
3378
+ senderDeviceId,
3379
+ ciphertext,
3380
+ timestamp: Date.now(),
3381
+ messageType: 'sender_key',
3382
+ }, undefined, { groupId, workId, framed: framedMessage });
3383
+ switch (outcome.kind) {
3384
+ case 'processed':
3385
+ await this.completeCallerRecord(workId);
3386
+ return outcome.plaintext;
3387
+ case 'pending':
3388
+ case 'denied':
3389
+ if (error)
3390
+ throw error;
3391
+ break;
3392
+ case 'refused':
3393
+ throw new EncryptionError('The receive queue has no room for this group message', EncryptionErrorCode.STORAGE_QUOTA_EXCEEDED, { senderId });
3394
+ default:
3395
+ break;
3396
+ }
3397
+ throw new EncryptionError('This group message gives no content', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId });
2419
3398
  });
2420
3399
  }
2421
3400
  /**
@@ -2734,7 +3713,12 @@ export class DefaultSignalProtocolClient {
2734
3713
  * Sync group state from server.
2735
3714
  */
2736
3715
  async syncGroup(groupId) {
2737
- return GroupOps.syncGroup(this.ctx, await this.groups, groupId);
3716
+ // A manual sync joins the receive fetch of the group, as one fetcher
3717
+ // owns each group's server work.
3718
+ const fetcher = this.groupFetcher;
3719
+ return GroupOps.syncGroup(this.ctx, fetcher
3720
+ ? { syncGroup: (id) => fetcher.sync(extractGroupId(id)) }
3721
+ : await this.groups, groupId);
2738
3722
  }
2739
3723
  /**
2740
3724
  * Add a member to a group.