@open-e2ee/signal-protocol-sdk 10.1.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 (595) hide show
  1. package/ADAPTERS.md +4 -4
  2. package/ARCHITECTURE.md +6 -8
  3. package/CHANGELOG.md +1413 -0
  4. package/README.md +1 -1
  5. package/SECURITY.md +2 -2
  6. package/TROUBLESHOOTING.md +1 -1
  7. package/client/README.md +84 -37
  8. package/device/README.md +39 -85
  9. package/dist/client/client.d.ts +342 -62
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +1195 -179
  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 +308 -6
  42. package/dist/client/event-hooks.d.ts.map +1 -1
  43. package/dist/client/event-hooks.js +9 -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-device-standing.d.ts +52 -0
  82. package/dist/client/hosted-device-standing.d.ts.map +1 -0
  83. package/dist/client/hosted-device-standing.js +74 -0
  84. package/dist/client/hosted-device-standing.js.map +1 -0
  85. package/dist/client/hosted-mailbox-subscription.d.ts +48 -3
  86. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  87. package/dist/client/hosted-mailbox-subscription.js +288 -74
  88. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  89. package/dist/client/hosted-push.d.ts +22 -4
  90. package/dist/client/hosted-push.d.ts.map +1 -1
  91. package/dist/client/hosted-push.js +75 -22
  92. package/dist/client/hosted-push.js.map +1 -1
  93. package/dist/client/hosted-transport.d.ts +22 -28
  94. package/dist/client/hosted-transport.d.ts.map +1 -1
  95. package/dist/client/hosted-transport.js +167 -69
  96. package/dist/client/hosted-transport.js.map +1 -1
  97. package/dist/client/hosted.d.ts +22 -5
  98. package/dist/client/hosted.d.ts.map +1 -1
  99. package/dist/client/hosted.js +122 -45
  100. package/dist/client/hosted.js.map +1 -1
  101. package/dist/client/index.d.ts +6 -4
  102. package/dist/client/index.d.ts.map +1 -1
  103. package/dist/client/index.js +3 -1
  104. package/dist/client/index.js.map +1 -1
  105. package/dist/client/messages.d.ts +25 -3
  106. package/dist/client/messages.d.ts.map +1 -1
  107. package/dist/client/messages.js +118 -17
  108. package/dist/client/messages.js.map +1 -1
  109. package/dist/client/one-time-prekey-refill.d.ts +7 -0
  110. package/dist/client/one-time-prekey-refill.d.ts.map +1 -1
  111. package/dist/client/one-time-prekey-refill.js +5 -1
  112. package/dist/client/one-time-prekey-refill.js.map +1 -1
  113. package/dist/client/receive-admission.d.ts +58 -0
  114. package/dist/client/receive-admission.d.ts.map +1 -0
  115. package/dist/client/receive-admission.js +78 -0
  116. package/dist/client/receive-admission.js.map +1 -0
  117. package/dist/client/receive-expiry.d.ts +31 -0
  118. package/dist/client/receive-expiry.d.ts.map +1 -0
  119. package/dist/client/receive-expiry.js +35 -0
  120. package/dist/client/receive-expiry.js.map +1 -0
  121. package/dist/client/receive-hook-bound.d.ts +50 -0
  122. package/dist/client/receive-hook-bound.d.ts.map +1 -0
  123. package/dist/client/receive-hook-bound.js +115 -0
  124. package/dist/client/receive-hook-bound.js.map +1 -0
  125. package/dist/client/receive-queue.d.ts +299 -0
  126. package/dist/client/receive-queue.d.ts.map +1 -0
  127. package/dist/client/receive-queue.js +1420 -0
  128. package/dist/client/receive-queue.js.map +1 -0
  129. package/dist/client/receive-work-seed.d.ts +54 -0
  130. package/dist/client/receive-work-seed.d.ts.map +1 -0
  131. package/dist/client/receive-work-seed.js +116 -0
  132. package/dist/client/receive-work-seed.js.map +1 -0
  133. package/dist/client/recovery-driver.d.ts +25 -0
  134. package/dist/client/recovery-driver.d.ts.map +1 -0
  135. package/dist/client/recovery-driver.js +121 -0
  136. package/dist/client/recovery-driver.js.map +1 -0
  137. package/dist/client/relay-acceptance.d.ts +30 -0
  138. package/dist/client/relay-acceptance.d.ts.map +1 -1
  139. package/dist/client/relay-acceptance.js +55 -0
  140. package/dist/client/relay-acceptance.js.map +1 -1
  141. package/dist/client/relay-device-refusal.d.ts +18 -0
  142. package/dist/client/relay-device-refusal.d.ts.map +1 -1
  143. package/dist/client/relay-device-refusal.js +31 -0
  144. package/dist/client/relay-device-refusal.js.map +1 -1
  145. package/dist/client/relay-sealed-route.d.ts +36 -0
  146. package/dist/client/relay-sealed-route.d.ts.map +1 -0
  147. package/dist/client/relay-sealed-route.js +45 -0
  148. package/dist/client/relay-sealed-route.js.map +1 -0
  149. package/dist/client/relay-subscription.d.ts +56 -13
  150. package/dist/client/relay-subscription.d.ts.map +1 -1
  151. package/dist/client/relay-subscription.js +220 -150
  152. package/dist/client/relay-subscription.js.map +1 -1
  153. package/dist/client/resendable-content.d.ts +98 -0
  154. package/dist/client/resendable-content.d.ts.map +1 -0
  155. package/dist/client/resendable-content.js +136 -0
  156. package/dist/client/resendable-content.js.map +1 -0
  157. package/dist/client/retry-family.d.ts +68 -19
  158. package/dist/client/retry-family.d.ts.map +1 -1
  159. package/dist/client/retry-family.js +59 -17
  160. package/dist/client/retry-family.js.map +1 -1
  161. package/dist/client/retry-request-envelope.d.ts +145 -18
  162. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  163. package/dist/client/retry-request-envelope.js +301 -64
  164. package/dist/client/retry-request-envelope.js.map +1 -1
  165. package/dist/client/retry-request-lifecycle.d.ts +157 -0
  166. package/dist/client/retry-request-lifecycle.d.ts.map +1 -0
  167. package/dist/client/retry-request-lifecycle.js +437 -0
  168. package/dist/client/retry-request-lifecycle.js.map +1 -0
  169. package/dist/client/retry-terminal-recovery.d.ts +100 -0
  170. package/dist/client/retry-terminal-recovery.d.ts.map +1 -0
  171. package/dist/client/retry-terminal-recovery.js +164 -0
  172. package/dist/client/retry-terminal-recovery.js.map +1 -0
  173. package/dist/client/retry-utils.d.ts +27 -0
  174. package/dist/client/retry-utils.d.ts.map +1 -1
  175. package/dist/client/retry-utils.js +46 -0
  176. package/dist/client/retry-utils.js.map +1 -1
  177. package/dist/client/retry.d.ts +106 -18
  178. package/dist/client/retry.d.ts.map +1 -1
  179. package/dist/client/retry.js +687 -139
  180. package/dist/client/retry.js.map +1 -1
  181. package/dist/client/sealed-sender.d.ts +23 -6
  182. package/dist/client/sealed-sender.d.ts.map +1 -1
  183. package/dist/client/sealed-sender.js +30 -6
  184. package/dist/client/sealed-sender.js.map +1 -1
  185. package/dist/client/sessions.d.ts +2 -2
  186. package/dist/client/sessions.js +2 -2
  187. package/dist/client/signal-service-cipher.d.ts +726 -19
  188. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  189. package/dist/client/signal-service-cipher.js +2265 -343
  190. package/dist/client/signal-service-cipher.js.map +1 -1
  191. package/dist/client/state.d.ts +5 -0
  192. package/dist/client/state.d.ts.map +1 -1
  193. package/dist/client/state.js +11 -1
  194. package/dist/client/state.js.map +1 -1
  195. package/dist/client/storage-protection.d.ts +64 -0
  196. package/dist/client/storage-protection.d.ts.map +1 -0
  197. package/dist/client/storage-protection.js +150 -0
  198. package/dist/client/storage-protection.js.map +1 -0
  199. package/dist/client/types.d.ts +149 -15
  200. package/dist/client/types.d.ts.map +1 -1
  201. package/dist/client/types.js +1 -1
  202. package/dist/client/types.js.map +1 -1
  203. package/dist/device/constants.d.ts +0 -5
  204. package/dist/device/constants.d.ts.map +1 -1
  205. package/dist/device/constants.js +0 -5
  206. package/dist/device/constants.js.map +1 -1
  207. package/dist/device/expo/index.d.ts +4 -17
  208. package/dist/device/expo/index.d.ts.map +1 -1
  209. package/dist/device/expo/index.js +4 -23
  210. package/dist/device/expo/index.js.map +1 -1
  211. package/dist/device/index.d.ts +0 -2
  212. package/dist/device/index.d.ts.map +1 -1
  213. package/dist/device/index.js +0 -7
  214. package/dist/device/index.js.map +1 -1
  215. package/dist/device/lifecycle/manager.d.ts +5 -4
  216. package/dist/device/lifecycle/manager.d.ts.map +1 -1
  217. package/dist/device/lifecycle/manager.js +16 -16
  218. package/dist/device/lifecycle/manager.js.map +1 -1
  219. package/dist/device/lifecycle/types.d.ts +2 -2
  220. package/dist/device/lifecycle/types.d.ts.map +1 -1
  221. package/dist/device/react-native/index.d.ts +4 -15
  222. package/dist/device/react-native/index.d.ts.map +1 -1
  223. package/dist/device/react-native/index.js +4 -21
  224. package/dist/device/react-native/index.js.map +1 -1
  225. package/dist/device/types.d.ts +1 -1
  226. package/dist/groups/index.d.ts +1 -1
  227. package/dist/groups/index.d.ts.map +1 -1
  228. package/dist/index.d.ts +8 -6
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +2 -1
  231. package/dist/index.js.map +1 -1
  232. package/dist/internal/crypto/ec/x25519-validation.d.ts +0 -1
  233. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  234. package/dist/internal/crypto/ec/x25519-validation.js +0 -1
  235. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  236. package/dist/internal/crypto/validation.d.ts +2 -2
  237. package/dist/internal/groups/index.d.ts +1 -0
  238. package/dist/internal/groups/index.d.ts.map +1 -1
  239. package/dist/internal/groups/index.js +1 -0
  240. package/dist/internal/groups/index.js.map +1 -1
  241. package/dist/internal/groups/manager.d.ts +37 -16
  242. package/dist/internal/groups/manager.d.ts.map +1 -1
  243. package/dist/internal/groups/manager.js +46 -1
  244. package/dist/internal/groups/manager.js.map +1 -1
  245. package/dist/internal/groups/receive-record.d.ts +78 -0
  246. package/dist/internal/groups/receive-record.d.ts.map +1 -0
  247. package/dist/internal/groups/receive-record.js +43 -0
  248. package/dist/internal/groups/receive-record.js.map +1 -0
  249. package/dist/internal/groups/sdk-store.d.ts +27 -3
  250. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  251. package/dist/internal/groups/sdk-store.js +151 -19
  252. package/dist/internal/groups/sdk-store.js.map +1 -1
  253. package/dist/internal/groups/wire.d.ts +12 -1
  254. package/dist/internal/groups/wire.d.ts.map +1 -1
  255. package/dist/internal/groups/wire.js +36 -0
  256. package/dist/internal/groups/wire.js.map +1 -1
  257. package/dist/internal/manager/index.d.ts +1 -1
  258. package/dist/internal/manager/manager.d.ts +20 -19
  259. package/dist/internal/manager/manager.d.ts.map +1 -1
  260. package/dist/internal/manager/manager.js +56 -39
  261. package/dist/internal/manager/manager.js.map +1 -1
  262. package/dist/internal/protocol/double-ratchet/chains.d.ts +4 -18
  263. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  264. package/dist/internal/protocol/double-ratchet/chains.js +23 -74
  265. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  266. package/dist/internal/protocol/double-ratchet/index.d.ts +1 -1
  267. package/dist/internal/protocol/double-ratchet/index.d.ts.map +1 -1
  268. package/dist/internal/protocol/double-ratchet/index.js +1 -1
  269. package/dist/internal/protocol/double-ratchet/index.js.map +1 -1
  270. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +5 -7
  271. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  272. package/dist/internal/protocol/double-ratchet/ratchet.js +4 -6
  273. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  274. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  275. package/dist/internal/protocol/pqxdh/pqxdh.js +2 -1
  276. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  277. package/dist/internal/protocol/sealed-sender/types.d.ts +6 -8
  278. package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
  279. package/dist/internal/protocol/sealed-sender/types.js +8 -9
  280. package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
  281. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts +110 -0
  282. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts.map +1 -0
  283. package/dist/internal/protocol/sender-keys/handoff-ledger.js +124 -0
  284. package/dist/internal/protocol/sender-keys/handoff-ledger.js.map +1 -0
  285. package/dist/internal/protocol/sender-keys/manager.d.ts +71 -62
  286. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  287. package/dist/internal/protocol/sender-keys/manager.js +228 -175
  288. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  289. package/dist/internal/protocol/spqr/index.d.ts +2 -2
  290. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  291. package/dist/internal/protocol/spqr/index.js +2 -2
  292. package/dist/internal/protocol/spqr/index.js.map +1 -1
  293. package/dist/internal/protocol/spqr/serialize.d.ts +9 -1
  294. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  295. package/dist/internal/protocol/spqr/serialize.js +56 -16
  296. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  297. package/dist/internal/protocol/spqr/spqr.d.ts +1 -14
  298. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  299. package/dist/internal/protocol/spqr/spqr.js +54 -42
  300. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  301. package/dist/internal/protocol/spqr/validate.d.ts +26 -6
  302. package/dist/internal/protocol/spqr/validate.d.ts.map +1 -1
  303. package/dist/internal/protocol/spqr/validate.js +49 -21
  304. package/dist/internal/protocol/spqr/validate.js.map +1 -1
  305. package/dist/internal/sesame/index.d.ts +1 -1
  306. package/dist/internal/sesame/index.d.ts.map +1 -1
  307. package/dist/internal/sesame/index.js.map +1 -1
  308. package/dist/internal/sesame/manager.d.ts +66 -13
  309. package/dist/internal/sesame/manager.d.ts.map +1 -1
  310. package/dist/internal/sesame/manager.js +221 -87
  311. package/dist/internal/sesame/manager.js.map +1 -1
  312. package/dist/internal/sesame/types.d.ts +95 -17
  313. package/dist/internal/sesame/types.d.ts.map +1 -1
  314. package/dist/internal/sesame/types.js +17 -0
  315. package/dist/internal/sesame/types.js.map +1 -1
  316. package/dist/internal/session/builder.d.ts +5 -5
  317. package/dist/internal/session/builder.d.ts.map +1 -1
  318. package/dist/internal/session/builder.js +12 -17
  319. package/dist/internal/session/builder.js.map +1 -1
  320. package/dist/internal/session/cipher.d.ts +13 -11
  321. package/dist/internal/session/cipher.d.ts.map +1 -1
  322. package/dist/internal/session/cipher.js +40 -22
  323. package/dist/internal/session/cipher.js.map +1 -1
  324. package/dist/internal/session/factory.d.ts +5 -5
  325. package/dist/internal/session/factory.d.ts.map +1 -1
  326. package/dist/internal/session/factory.js +4 -4
  327. package/dist/internal/session/factory.js.map +1 -1
  328. package/dist/internal/session/handshake.d.ts +14 -16
  329. package/dist/internal/session/handshake.d.ts.map +1 -1
  330. package/dist/internal/session/handshake.js +18 -75
  331. package/dist/internal/session/handshake.js.map +1 -1
  332. package/dist/internal/session/index.d.ts +1 -1
  333. package/dist/internal/session/index.js +1 -1
  334. package/dist/internal/session/record-locks.d.ts +17 -6
  335. package/dist/internal/session/record-locks.d.ts.map +1 -1
  336. package/dist/internal/session/record-locks.js +43 -7
  337. package/dist/internal/session/record-locks.js.map +1 -1
  338. package/dist/internal/session/session-resolver.d.ts +1 -1
  339. package/dist/internal/session/session-resolver.js +1 -1
  340. package/dist/internal/session/state.d.ts +2 -2
  341. package/dist/internal/session/state.js +1 -1
  342. package/dist/internal/session/types.d.ts +4 -12
  343. package/dist/internal/session/types.d.ts.map +1 -1
  344. package/dist/internal/session/types.js +1 -1
  345. package/dist/keys/generation.d.ts +2 -2
  346. package/dist/keys/generation.js +2 -2
  347. package/dist/keys/types.d.ts +5 -5
  348. package/dist/keys/types.d.ts.map +1 -1
  349. package/dist/keys/types.js +1 -1
  350. package/dist/layers.d.ts +1 -1
  351. package/dist/layers.js +2 -2
  352. package/dist/layers.js.map +1 -1
  353. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  354. package/dist/local/store/expo/adapter.js +12 -8
  355. package/dist/local/store/expo/adapter.js.map +1 -1
  356. package/dist/local/store/key-value/adapter.d.ts +76 -10
  357. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  358. package/dist/local/store/key-value/adapter.js +367 -61
  359. package/dist/local/store/key-value/adapter.js.map +1 -1
  360. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
  361. package/dist/local/store/key-value/backend-conformance.js +74 -0
  362. package/dist/local/store/key-value/backend-conformance.js.map +1 -1
  363. package/dist/local/store/key-value/batch.d.ts +2 -0
  364. package/dist/local/store/key-value/batch.d.ts.map +1 -1
  365. package/dist/local/store/key-value/batch.js +26 -0
  366. package/dist/local/store/key-value/batch.js.map +1 -1
  367. package/dist/local/store/key-value/receive-work.d.ts +55 -0
  368. package/dist/local/store/key-value/receive-work.d.ts.map +1 -0
  369. package/dist/local/store/key-value/receive-work.js +162 -0
  370. package/dist/local/store/key-value/receive-work.js.map +1 -0
  371. package/dist/local/store/key-value/send-log.d.ts +61 -0
  372. package/dist/local/store/key-value/send-log.d.ts.map +1 -0
  373. package/dist/local/store/key-value/send-log.js +430 -0
  374. package/dist/local/store/key-value/send-log.js.map +1 -0
  375. package/dist/local/store/key-value/sender-key-handoff.d.ts +68 -0
  376. package/dist/local/store/key-value/sender-key-handoff.d.ts.map +1 -0
  377. package/dist/local/store/key-value/sender-key-handoff.js +189 -0
  378. package/dist/local/store/key-value/sender-key-handoff.js.map +1 -0
  379. package/dist/local/store/key-value/storage.d.ts +15 -0
  380. package/dist/local/store/key-value/storage.d.ts.map +1 -1
  381. package/dist/local/store/keyed-index.d.ts +23 -0
  382. package/dist/local/store/keyed-index.d.ts.map +1 -0
  383. package/dist/local/store/keyed-index.js +41 -0
  384. package/dist/local/store/keyed-index.js.map +1 -0
  385. package/dist/local/store/memory/adapter.d.ts +44 -12
  386. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  387. package/dist/local/store/memory/adapter.js +197 -46
  388. package/dist/local/store/memory/adapter.js.map +1 -1
  389. package/dist/local/store/memory/send-log.d.ts +42 -0
  390. package/dist/local/store/memory/send-log.d.ts.map +1 -0
  391. package/dist/local/store/memory/send-log.js +190 -0
  392. package/dist/local/store/memory/send-log.js.map +1 -0
  393. package/dist/local/store/node/adapter.d.ts.map +1 -1
  394. package/dist/local/store/node/adapter.js +8 -6
  395. package/dist/local/store/node/adapter.js.map +1 -1
  396. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  397. package/dist/local/store/react-native/adapter.js +12 -8
  398. package/dist/local/store/react-native/adapter.js.map +1 -1
  399. package/dist/local/store/receive-work.d.ts +87 -0
  400. package/dist/local/store/receive-work.d.ts.map +1 -0
  401. package/dist/local/store/receive-work.js +204 -0
  402. package/dist/local/store/receive-work.js.map +1 -0
  403. package/dist/local/store/received-content.d.ts +3 -3
  404. package/dist/local/store/received-content.d.ts.map +1 -1
  405. package/dist/local/store/received-content.js +2 -11
  406. package/dist/local/store/received-content.js.map +1 -1
  407. package/dist/local/store/reliability.d.ts +411 -14
  408. package/dist/local/store/reliability.d.ts.map +1 -1
  409. package/dist/local/store/reliability.js +532 -58
  410. package/dist/local/store/reliability.js.map +1 -1
  411. package/dist/local/store/send-log-order.d.ts +15 -0
  412. package/dist/local/store/send-log-order.d.ts.map +1 -0
  413. package/dist/local/store/send-log-order.js +24 -0
  414. package/dist/local/store/send-log-order.js.map +1 -0
  415. package/dist/local/store/sender-key-handoff-index.d.ts +38 -0
  416. package/dist/local/store/sender-key-handoff-index.d.ts.map +1 -0
  417. package/dist/local/store/sender-key-handoff-index.js +101 -0
  418. package/dist/local/store/sender-key-handoff-index.js.map +1 -0
  419. package/dist/local/store/sender-key-handoff-table.d.ts +29 -0
  420. package/dist/local/store/sender-key-handoff-table.d.ts.map +1 -0
  421. package/dist/local/store/sender-key-handoff-table.js +97 -0
  422. package/dist/local/store/sender-key-handoff-table.js.map +1 -0
  423. package/dist/local/store/sqlite/encryption.d.ts +8 -1
  424. package/dist/local/store/sqlite/encryption.d.ts.map +1 -1
  425. package/dist/local/store/sqlite/encryption.js +9 -0
  426. package/dist/local/store/sqlite/encryption.js.map +1 -1
  427. package/dist/local/store/sqlite/key-storage/index.d.ts +25 -4
  428. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  429. package/dist/local/store/sqlite/key-storage/index.js +68 -7
  430. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  431. package/dist/local/store/sqlite/key-storage/message-records.d.ts +16 -4
  432. package/dist/local/store/sqlite/key-storage/message-records.d.ts.map +1 -1
  433. package/dist/local/store/sqlite/key-storage/message-records.js +49 -6
  434. package/dist/local/store/sqlite/key-storage/message-records.js.map +1 -1
  435. package/dist/local/store/sqlite/key-storage/metadata.d.ts +8 -7
  436. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  437. package/dist/local/store/sqlite/key-storage/metadata.js +17 -15
  438. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  439. package/dist/local/store/sqlite/key-storage/receive-work.d.ts +27 -0
  440. package/dist/local/store/sqlite/key-storage/receive-work.d.ts.map +1 -0
  441. package/dist/local/store/sqlite/key-storage/receive-work.js +98 -0
  442. package/dist/local/store/sqlite/key-storage/receive-work.js.map +1 -0
  443. package/dist/local/store/sqlite/key-storage/send-log.d.ts +27 -0
  444. package/dist/local/store/sqlite/key-storage/send-log.d.ts.map +1 -0
  445. package/dist/local/store/sqlite/key-storage/send-log.js +178 -0
  446. package/dist/local/store/sqlite/key-storage/send-log.js.map +1 -0
  447. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts +27 -0
  448. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts.map +1 -0
  449. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js +75 -0
  450. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js.map +1 -0
  451. package/dist/local/store/sqlite/key-storage/session-trust.d.ts +2 -2
  452. package/dist/local/store/sqlite/key-storage/session-trust.js +5 -5
  453. package/dist/local/store/sqlite/key-storage/session-trust.js.map +1 -1
  454. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  455. package/dist/local/store/sqlite/migrations.js +101 -0
  456. package/dist/local/store/sqlite/migrations.js.map +1 -1
  457. package/dist/local/store/sqlite/models/index.d.ts +2 -1
  458. package/dist/local/store/sqlite/models/index.d.ts.map +1 -1
  459. package/dist/local/store/sqlite/models/index.js +5 -1
  460. package/dist/local/store/sqlite/models/index.js.map +1 -1
  461. package/dist/local/store/sqlite/models/message-record.d.ts +15 -0
  462. package/dist/local/store/sqlite/models/message-record.d.ts.map +1 -1
  463. package/dist/local/store/sqlite/models/message-record.js +24 -0
  464. package/dist/local/store/sqlite/models/message-record.js.map +1 -1
  465. package/dist/local/store/sqlite/models/send-log.d.ts +51 -0
  466. package/dist/local/store/sqlite/models/send-log.d.ts.map +1 -0
  467. package/dist/local/store/sqlite/models/send-log.js +206 -0
  468. package/dist/local/store/sqlite/models/send-log.js.map +1 -0
  469. package/dist/local/store/sqlite/open-store.d.ts +9 -1
  470. package/dist/local/store/sqlite/open-store.d.ts.map +1 -1
  471. package/dist/local/store/sqlite/open-store.js +20 -1
  472. package/dist/local/store/sqlite/open-store.js.map +1 -1
  473. package/dist/local/store/sqlite/schema.d.ts +34 -1
  474. package/dist/local/store/sqlite/schema.d.ts.map +1 -1
  475. package/dist/local/store/sqlite/schema.js +14 -0
  476. package/dist/local/store/sqlite/schema.js.map +1 -1
  477. package/dist/local/store/sqlite/store.d.ts +61 -11
  478. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  479. package/dist/local/store/sqlite/store.js +191 -27
  480. package/dist/local/store/sqlite/store.js.map +1 -1
  481. package/dist/local/store/web/adapter.d.ts +76 -8
  482. package/dist/local/store/web/adapter.d.ts.map +1 -1
  483. package/dist/local/store/web/adapter.js +579 -127
  484. package/dist/local/store/web/adapter.js.map +1 -1
  485. package/dist/local/store/web/receive-work.d.ts +57 -0
  486. package/dist/local/store/web/receive-work.d.ts.map +1 -0
  487. package/dist/local/store/web/receive-work.js +99 -0
  488. package/dist/local/store/web/receive-work.js.map +1 -0
  489. package/dist/local/store/web/send-log.d.ts +92 -0
  490. package/dist/local/store/web/send-log.d.ts.map +1 -0
  491. package/dist/local/store/web/send-log.js +267 -0
  492. package/dist/local/store/web/send-log.js.map +1 -0
  493. package/dist/local/store/web/sender-key-handoff.d.ts +81 -0
  494. package/dist/local/store/web/sender-key-handoff.d.ts.map +1 -0
  495. package/dist/local/store/web/sender-key-handoff.js +156 -0
  496. package/dist/local/store/web/sender-key-handoff.js.map +1 -0
  497. package/dist/local/store/web-sqlite/adapter.d.ts +2 -0
  498. package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -1
  499. package/dist/local/store/web-sqlite/adapter.js +12 -6
  500. package/dist/local/store/web-sqlite/adapter.js.map +1 -1
  501. package/dist/local/vault/custody.d.ts +8 -0
  502. package/dist/local/vault/custody.d.ts.map +1 -0
  503. package/dist/local/vault/custody.js +9 -0
  504. package/dist/local/vault/custody.js.map +1 -0
  505. package/dist/local/vault/electron-safe-storage.d.ts +3 -1
  506. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  507. package/dist/local/vault/electron-safe-storage.js +2 -0
  508. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  509. package/dist/local/vault/expo-secure-store.d.ts +3 -1
  510. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  511. package/dist/local/vault/expo-secure-store.js +2 -0
  512. package/dist/local/vault/expo-secure-store.js.map +1 -1
  513. package/dist/local/vault/indexed-db.d.ts +3 -1
  514. package/dist/local/vault/indexed-db.d.ts.map +1 -1
  515. package/dist/local/vault/indexed-db.js +2 -0
  516. package/dist/local/vault/indexed-db.js.map +1 -1
  517. package/dist/local/vault/react-native-keychain.d.ts +3 -1
  518. package/dist/local/vault/react-native-keychain.d.ts.map +1 -1
  519. package/dist/local/vault/react-native-keychain.js +2 -0
  520. package/dist/local/vault/react-native-keychain.js.map +1 -1
  521. package/dist/remote/relay/device-set.d.ts +94 -0
  522. package/dist/remote/relay/device-set.d.ts.map +1 -0
  523. package/dist/remote/relay/device-set.js +156 -0
  524. package/dist/remote/relay/device-set.js.map +1 -0
  525. package/dist/remote/relay/types.d.ts +104 -110
  526. package/dist/remote/relay/types.d.ts.map +1 -1
  527. package/dist/safety/core.d.ts +15 -6
  528. package/dist/safety/core.d.ts.map +1 -1
  529. package/dist/safety/core.js +41 -27
  530. package/dist/safety/core.js.map +1 -1
  531. package/dist/safety/index.d.ts +2 -1
  532. package/dist/safety/index.d.ts.map +1 -1
  533. package/dist/safety/index.js +12 -18
  534. package/dist/safety/index.js.map +1 -1
  535. package/dist/types/api.d.ts +707 -62
  536. package/dist/types/api.d.ts.map +1 -1
  537. package/dist/types/errors.d.ts +14 -33
  538. package/dist/types/errors.d.ts.map +1 -1
  539. package/dist/types/errors.js +14 -24
  540. package/dist/types/errors.js.map +1 -1
  541. package/dist/types/messages.d.ts +2 -2
  542. package/dist/types/messages.js +1 -1
  543. package/dist/types/protocol-config.d.ts +175 -42
  544. package/dist/types/protocol-config.d.ts.map +1 -1
  545. package/dist/types/protocol-config.js +19 -38
  546. package/dist/types/protocol-config.js.map +1 -1
  547. package/dist/types/protocol-constants.d.ts +6 -6
  548. package/dist/types/protocol-constants.js +6 -6
  549. package/dist/types/session.d.ts +7 -7
  550. package/dist/types/session.d.ts.map +1 -1
  551. package/dist/types/session.js +39 -21
  552. package/dist/types/session.js.map +1 -1
  553. package/dist/username/link.d.ts +2 -2
  554. package/dist/username/link.js +2 -2
  555. package/dist/utils/origin-lock.d.ts +45 -0
  556. package/dist/utils/origin-lock.d.ts.map +1 -0
  557. package/dist/utils/origin-lock.js +80 -0
  558. package/dist/utils/origin-lock.js.map +1 -0
  559. package/dist/utils/retry.d.ts +2 -0
  560. package/dist/utils/retry.d.ts.map +1 -1
  561. package/dist/utils/retry.js +7 -0
  562. package/dist/utils/retry.js.map +1 -1
  563. package/docs/ASSURANCE.md +6 -6
  564. package/docs/CLIENT_COMPOSITION.md +2 -2
  565. package/docs/DEVIATIONS.md +677 -182
  566. package/docs/E2EE.md +1 -1
  567. package/docs/ERROR_HANDLING.md +235 -2
  568. package/docs/GETTING_STARTED.md +7 -4
  569. package/docs/INTERFACES.md +1 -1
  570. package/docs/PACKAGE_SURFACE.md +6 -5
  571. package/docs/PROTOCOL_POLICY.md +102 -22
  572. package/docs/RECIPES.md +3 -15
  573. package/docs/SECURITY.md +90 -5
  574. package/keys/README.md +3 -3
  575. package/local/store/README.md +78 -14
  576. package/local/store/key-value/README.md +14 -3
  577. package/local/store/node/README.md +8 -3
  578. package/local/store/web/README.md +9 -0
  579. package/local/store/web-sqlite/README.md +14 -2
  580. package/local/vault/README.md +21 -0
  581. package/package.json +1 -6
  582. package/remote/README.md +0 -1
  583. package/remote/relay/README.md +2 -2
  584. package/dist/device/provisioning.d.ts +0 -242
  585. package/dist/device/provisioning.d.ts.map +0 -1
  586. package/dist/device/provisioning.js +0 -421
  587. package/dist/device/provisioning.js.map +0 -1
  588. package/dist/internal/protocol/x3dh/index.d.ts +0 -15
  589. package/dist/internal/protocol/x3dh/index.d.ts.map +0 -1
  590. package/dist/internal/protocol/x3dh/index.js +0 -13
  591. package/dist/internal/protocol/x3dh/index.js.map +0 -1
  592. package/dist/internal/protocol/x3dh/x3dh.d.ts +0 -131
  593. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +0 -1
  594. package/dist/internal/protocol/x3dh/x3dh.js +0 -261
  595. 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';
@@ -77,17 +83,29 @@ import * as GroupOps from './groups.js';
77
83
  import * as PreKeyOps from './prekeys.js';
78
84
  import * as RetryOps from './retry.js';
79
85
  import { receiveInRetryFamily } from './retry-family.js';
86
+ import { RetryRequestScheduler } from './retry-request-lifecycle.js';
87
+ import { ResendJobDriver } from './recovery-driver.js';
88
+ import { retryRequestPost } from './retry-request-envelope.js';
89
+ import { migrateRetryRequestRecords } from '../local/store/reliability.js';
80
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';
81
96
  import * as RelaySubscriptionOps from './relay-subscription.js';
82
97
  import { relayReceiptJoinOf } from './relay-receipt-join.js';
83
98
  import { SignalProtocolClientState, SIGNAL_PROTOCOL_CLIENT_CONSTANTS } from './state.js';
84
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';
85
102
  import { deleteMediaAttachment, resolveMediaAttachment, } from '../media/index.js';
86
103
  import { StorageBackedSignalProtocolClientMedia } from './media.js';
87
104
  // Group state (Signal Private Group System)
88
105
  import { GroupManager, decodeGroupTrustRoot } from '../internal/groups/index.js';
89
106
  import { SignalProtocolGroupStateStore } from '../internal/groups/sdk-store.js';
90
107
  import { deriveAccessKey } from '../internal/protocol/sealed-sender/delivery-token.js';
108
+ import { SealedSenderContentType } from '../internal/protocol/sealed-sender/types.js';
91
109
  /**
92
110
  * Module-level lock for storage initialization.
93
111
  * Prevents multiple concurrent DefaultSignalProtocolClient.create() calls from creating
@@ -97,6 +115,20 @@ const storageLock = new AsyncLock({
97
115
  timeout: 30000, // 30 second timeout for storage initialization
98
116
  maxPending: 100, // Limit pending operations
99
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
+ }
100
132
  /**
101
133
  * Type guard: DataMessage is a plain object (not string or Uint8Array).
102
134
  * TypeScript enforces correct content types at compile time. This routes at runtime.
@@ -153,7 +185,14 @@ export class DefaultSignalProtocolClient {
153
185
  groupManager;
154
186
  groupSessionFor;
155
187
  groupStore;
156
- 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;
157
196
  // Cipher coordination (encrypts/decrypts, routes to appropriate cipher)
158
197
  cipher;
159
198
  // The relay request bound that every fan-out of this client shares
@@ -173,6 +212,21 @@ export class DefaultSignalProtocolClient {
173
212
  get syncStatus() {
174
213
  return this._syncStatus;
175
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
+ }
176
230
  stoppedRelayConnection = {
177
231
  state: 'stopped',
178
232
  since: Date.now(),
@@ -217,6 +271,42 @@ export class DefaultSignalProtocolClient {
217
271
  * starts. It does not stop them before then.
218
272
  */
219
273
  deliveryReceiptSends = new Map();
274
+ /**
275
+ * Posts the stored retry requests at their next attempt times, ends them
276
+ * at their deadlines, and calls `onRetryTerminal`. create() and
277
+ * startRelaySubscription() start it when a relay is configured, and stop()
278
+ * stops it. Each pass is relay work, so its hooks run through that work.
279
+ */
280
+ retryRequests = new RetryRequestScheduler(this.state.relayWork, (work) => {
281
+ const relay = this.relay;
282
+ const context = { ...this.relayWorkContext(work), stopSignal: work.stopSignal };
283
+ return {
284
+ storage: this._storage,
285
+ logger: this.logger,
286
+ hooks: work.wrapHooks(this.hooks),
287
+ local: { userId: this.userId, deviceId: this.deviceId },
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),
292
+ };
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;
220
310
  /**
221
311
  * The stop() in progress. It is set before a step of stop() runs, so a
222
312
  * stop() call that overlaps it, also from a step, waits for it, and a
@@ -262,6 +352,30 @@ export class DefaultSignalProtocolClient {
262
352
  throw new Error('Storage must be provided by DefaultSignalProtocolClient.create() callers');
263
353
  }
264
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);
265
379
  this.deliveries = new DeliveryStatusTracker(this._storage);
266
380
  this._storage.setLogger?.(this.logger);
267
381
  this.media = new StorageBackedSignalProtocolClientMedia({
@@ -280,8 +394,13 @@ export class DefaultSignalProtocolClient {
280
394
  // Initialize Sesame manager for multi-device support
281
395
  this.sesameManager = new DefaultSesameManager(this._storage, {}, // Use default Sesame config
282
396
  this.manager, undefined, this.logger);
283
- // Wire up MessageRecord storage for retry request support (SESAME spec §6.2)
284
- 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
+ }
285
404
  // Initialize Sender Key manager for group messaging
286
405
  this.senderKeyManager = new SenderKeyManager(this._storage, config?.senderKeys, this.logger);
287
406
  this.groupSenderKeys = new GroupSenderKeyOperations(this._storage, userId, deviceId);
@@ -335,7 +454,7 @@ export class DefaultSignalProtocolClient {
335
454
  profileKeyCredentialPublicKey: trustRoot.profileKeyCredentialPublicKey,
336
455
  profileKey: groupConfig.profileKey,
337
456
  onSenderKeyRotation: async (groupId) => {
338
- 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));
339
458
  },
340
459
  onEndorsementsInvalidated: endorsementManager
341
460
  ? async (groupId) => {
@@ -363,6 +482,8 @@ export class DefaultSignalProtocolClient {
363
482
  const sessions = this.sendSessionCallbacks(() => this.ctx);
364
483
  if (sessions)
365
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));
366
487
  if (config?.sealedSender) {
367
488
  this.cipher.setSealedSenderDeliveryMode(config.sealedSender.deliveryMode ?? 'preferred');
368
489
  if (config.sealedSender.onIdentifiedFallback) {
@@ -395,15 +516,49 @@ export class DefaultSignalProtocolClient {
395
516
  // Set up group secret params provider. Derives params from master key in store
396
517
  if (this.groupStore) {
397
518
  const store = this.groupStore;
398
- this.groupReceiveAuthorizer = createGroupReceiveAuthorizer(store, config.aci?.uuid, config.groups?.resolveAciBytesByUserIds);
399
- 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);
400
545
  this.cipher.setGroupSecretParamsProvider(async (groupId) => {
401
546
  const masterKey = await store.getMasterKey(groupId);
402
547
  if (!masterKey)
403
548
  return null;
404
549
  return deriveGroupSecretParams(masterKey);
405
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
+ });
406
560
  }
561
+ this.groupMembership = createGroupMembershipChecker(this.groupStore, config.groups?.resolveAciBytesByUserIds, this.contentRecoveryPolicy.isCurrentMember, this.groupFetcher);
407
562
  // Set up endorsement refresher for pre-send V2 sealed sender refresh.
408
563
  // Fetches fresh endorsements from server when cache is empty, expiring, or
409
564
  // missing members.
@@ -497,39 +652,44 @@ export class DefaultSignalProtocolClient {
497
652
  contentAdapter: this.contentAdapter,
498
653
  profileKeys: profileKeyExchange(this),
499
654
  deliveries: this.deliveries,
655
+ resendableContent: this.resendableContent,
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),
500
660
  sealReceipt: (recipientUserId, recipientDeviceId, ciphertextBase64) => this.cipher.sealReceipt(recipientUserId, recipientDeviceId, ciphertextBase64),
661
+ sealRetryRequest: (recipientUserId, recipientDeviceId, payloadBase64) => this.cipher.sealRetryRequest(recipientUserId, recipientDeviceId, payloadBase64),
501
662
  };
502
663
  }
503
664
  /**
504
665
  * Apply one Relay delivery receipt, then announce its deliveries. A
505
- * 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.
506
670
  */
507
671
  async receiveRelayReceipt(receipt) {
508
- let applied = false;
672
+ let announced = false;
509
673
  await this.state.relayWork.run(async (work) => {
510
674
  work.proceed();
511
675
  const events = await this.deliveries.applyRelayReceipt(receipt);
512
- applied = true;
513
- await this.announceDeliveries(work.wrapHooks(this.hooks), events);
676
+ await this.deliveries.announce(work.wrapHooks(this.hooks), events);
677
+ announced = true;
514
678
  });
515
- if (!applied)
679
+ if (!announced)
516
680
  throw new RelayWorkStopped();
517
681
  }
518
- /** Run the onDelivered hook once for each event, in order. */
519
- async announceDeliveries(hooks, events) {
520
- for (const event of events)
521
- await callHook(hooks, 'onDelivered', event);
522
- }
523
682
  /**
524
683
  * Announce the deliveries that waited for a send of this client message ID
525
- * 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.
526
686
  */
527
687
  releaseDeliveries(clientMessageId) {
528
688
  void this.state.relayWork
529
689
  .run(async (work) => {
530
690
  work.proceed();
531
691
  const events = await this.deliveries.release(clientMessageId);
532
- await this.announceDeliveries(work.wrapHooks(this.hooks), events);
692
+ await this.deliveries.announce(work.wrapHooks(this.hooks), events);
533
693
  })
534
694
  .catch((error) => {
535
695
  this.logger.warn('Failed to announce deliveries', {
@@ -645,6 +805,10 @@ export class DefaultSignalProtocolClient {
645
805
  establishSession: (address, bundle) => SessionOps.establishSession(ctx, this.sesameManager, address, bundle),
646
806
  resend: (userId, deviceId, content, options) => this.cipher.resendToDevice(userId, deviceId, content, options, stopSignal),
647
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),
648
812
  };
649
813
  }
650
814
  /**
@@ -674,9 +838,14 @@ export class DefaultSignalProtocolClient {
674
838
  * carries the stop signal of the tracker, which also aborts at a stop
675
839
  * after the work ends, so a retry timer of the send sees that stop. The
676
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
677
845
  */
678
- sendDeliveryReceiptAsRelayWork(userId, timestamps) {
679
- return this.state.relayWork.run(async (work) => {
846
+ async sendDeliveryReceiptAsRelayWork(userId, timestamps) {
847
+ let sent = false;
848
+ await this.state.relayWork.run(async (work) => {
680
849
  const send = this.sendDeliveryReceipt(userId, timestamps, {
681
850
  ...this.relayWorkContext(work),
682
851
  stopSignal: this.state.relayWork.stopSignal,
@@ -684,11 +853,14 @@ export class DefaultSignalProtocolClient {
684
853
  this.deliveryReceiptSends.set(work, send);
685
854
  try {
686
855
  await send;
856
+ sent = true;
687
857
  }
688
858
  finally {
689
859
  this.deliveryReceiptSends.delete(work);
690
860
  }
691
861
  });
862
+ if (!sent)
863
+ throw new RelayWorkStopped();
692
864
  }
693
865
  /**
694
866
  * Start the send of every batched delivery receipt, once each. The batches
@@ -714,10 +886,112 @@ export class DefaultSignalProtocolClient {
714
886
  clearTimeout(timer);
715
887
  }
716
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
+ }
717
982
  /** Client context whose hooks call the app through the given relay work. */
718
983
  relayWorkContext(work) {
719
984
  return { ...this.ctx, hooks: work.wrapHooks(this.hooks) };
720
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
+ }
721
995
  /**
722
996
  * Session callbacks of a send. Their session hooks run through the given
723
997
  * context, so a send in relay work calls the app through that work. Session
@@ -835,10 +1109,10 @@ export class DefaultSignalProtocolClient {
835
1109
  * storage,
836
1110
  * });
837
1111
  *
838
- * // Linked device; storage must already contain provisioned identity material.
1112
+ * // Linked device; storage must already contain the account identity.
839
1113
  * const signal = await DefaultSignalProtocolClient.create('user-123', {
840
1114
  * deviceId: 2,
841
- * storage: provisionedLinkedDeviceStorage
1115
+ * storage: linkedDeviceStorage
842
1116
  * });
843
1117
  *
844
1118
  * // With an application-owned authenticated relay transport.
@@ -896,19 +1170,36 @@ export class DefaultSignalProtocolClient {
896
1170
  const hasIdentityKey = await finalConfig.storage.hasIdentityKey(identityType);
897
1171
  if (!hasIdentityKey) {
898
1172
  throw new Error(`Linked device ${deviceId} requires a provisioned ${identityType.toUpperCase()} identity key in storage. ` +
899
- '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.');
900
1175
  }
901
1176
  }
902
1177
  }
903
1178
  const client = new DefaultSignalProtocolClient(userId, deviceId, finalConfig);
904
1179
  await client.initialize();
905
1180
  await client.hydratePersistedState();
906
- // Cleanup expired sessions and message records on startup.
1181
+ await migrateRetryRequestRecords(client._storage);
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.
907
1198
  // The reference implementation relies on event-driven cleanup (identity change, retry, end-session).
908
1199
  // We also enforce our maxRecv TTL here to prevent unbounded session growth.
909
1200
  try {
910
1201
  await client.sesameManager.cleanupExpiredSessions();
911
- await client._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
1202
+ await client.resendableContent.sweep();
912
1203
  }
913
1204
  catch (cleanupError) {
914
1205
  // Non-fatal: cleanup failures should not prevent client creation
@@ -937,6 +1228,15 @@ export class DefaultSignalProtocolClient {
937
1228
  if (!syncFailed && finalConfig?.relay && finalConfig?.hooks?.onMessageDecrypted) {
938
1229
  client.startRelaySubscription();
939
1230
  }
1231
+ // Post the stored retry requests whose next attempt time has come, and
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.
1236
+ if (finalConfig?.relay)
1237
+ client.startRetryRequests();
1238
+ else
1239
+ void client.receiveQueue.start();
940
1240
  // Validate sender keys config and warn on extreme values
941
1241
  if (finalConfig?.senderKeys) {
942
1242
  const sk = finalConfig.senderKeys;
@@ -996,7 +1296,7 @@ export class DefaultSignalProtocolClient {
996
1296
  /**
997
1297
  * Explicitly rotate this account's relay identity using a caller-authenticated
998
1298
  * compare-and-swap commitment, then publish fresh prekeys for that namespace.
999
- * Normal sync and linked-device provisioning never call this operation.
1299
+ * Normal sync and the managed device link never call this operation.
1000
1300
  */
1001
1301
  async rotateAccountIdentity(expectedCurrentCommitment, identityType = 'aci') {
1002
1302
  if (!this.config.relay) {
@@ -1044,6 +1344,96 @@ export class DefaultSignalProtocolClient {
1044
1344
  /**
1045
1345
  * Hydrate state from persistent storage.
1046
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
+ }
1047
1437
  async hydratePersistedState() {
1048
1438
  try {
1049
1439
  const stored = await this._storage.getMetadata('lastForcedPreKeyRotation');
@@ -1273,150 +1663,598 @@ export class DefaultSignalProtocolClient {
1273
1663
  /**
1274
1664
  * Process an incoming encrypted message envelope.
1275
1665
  *
1276
- * Unified entry point for both foreground (relay) and background (HTTP) message processing.
1277
- * Handles decryption and automatically sends SESAME retry requests on retryable failures.
1278
- *
1279
- * This method:
1280
- * 1. Decodes base64 ciphertext from the envelope
1281
- * 2. Decrypts message using Double Ratchet
1282
- * 3. On retryable error: sends retry request via relay or options callback
1283
- * 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.
1284
1697
  *
1285
1698
  * A `retry_request` envelope holds no plaintext. This method rejects it
1286
1699
  * before decryption and sends no retry request. Give it to
1287
1700
  * `receiveIncomingEnvelopes`, which handles it.
1288
1701
  *
1289
- * A failed envelope that this client asked a resend for, and each resend
1290
- * or null message for it, gives plaintext at most once on both receive
1291
- * paths. When this client processed the envelope, or the application
1292
- * already has that content, this method acknowledges the envelope and
1293
- * throws MESSAGE_DUPLICATE with no decrypt.
1294
- *
1295
- * A null message carries no content. The client consumes a null message
1296
- * when the content adapter reports `nullMessage: true`, and a custom
1297
- * adapter must report it for its own null encoding. This method never
1298
- * returns a null message. It marks the null message processed,
1299
- * acknowledges it and throws MESSAGE_DUPLICATE. A null message for a
1300
- * failed envelope marks that envelope processed, so a redelivery of it
1301
- * is dropped, but a content resend for it that comes later still gives
1302
- * its plaintext.
1303
- *
1304
- * A resend or null message that fails to decrypt, or whose seal fails to
1305
- * open, asks again for its failed envelope under the same retry ID. When
1306
- * the processed record of the failed envelope fails to store after a
1307
- * decrypt, the client writes a warning with the behavior
1308
- * RETRY_FULFILL_WRITE_FAILED, as on every receive path, and this method
1309
- * returns the plaintext. A redelivery of the failed envelope or of
1310
- * another family member can then give the content again. When a
1311
- * processed record of a null message or of its failed envelope fails to
1312
- * store, the client writes a warning with the behavior
1313
- * RETRY_NULL_WRITE_FAILED, as on every receive path, and this method
1314
- * still throws MESSAGE_DUPLICATE. A redelivery of the failed envelope
1315
- * 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.
1316
1705
  *
1317
1706
  * @param envelope - The encrypted message envelope
1318
- * @param options - Transport callbacks for background (no relay) scenarios
1319
- * @returns Decrypted plaintext
1707
+ * @param options - Transport callbacks for background (no relay)
1708
+ * scenarios, and `onPersist`
1709
+ * @returns The receive outcome
1320
1710
  * @throws EncryptionError after sending retry request if decryption fails
1321
- * @throws EncryptionError INVALID_CIPHERTEXT for a `retry_request` envelope
1322
- * @throws EncryptionError MESSAGE_DUPLICATE when this client processed the
1323
- * envelope, the application already has the content of the failed
1324
- * 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
1325
1713
  */
1326
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) {
1327
1928
  if (envelope.messageType === 'retry_request') {
1328
1929
  throw new EncryptionError('A retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
1329
1930
  }
1330
1931
  // The fingerprint covers the envelope as the Relay delivered it, before
1331
1932
  // any unseal, so every receive path stores one value for it.
1332
- const fingerprint = envelope.id
1333
- ? await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope)
1334
- : undefined;
1335
- return receiveInRetryFamily(this._storage, this.logger, envelope, async (family) => {
1336
- 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) {
1337
1954
  await this.markMessageDeliveredSilently(envelope.id, options);
1338
- throw new EncryptionError('The application already has the content of this failed envelope', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1955
+ return { outcome: { kind: 'duplicate' } };
1339
1956
  }
1340
- const plaintext = await this.decryptIncomingEnvelope(envelope, family, fingerprint, options);
1341
- // A null message carries no content, so the caller never gets it.
1342
- if (this.contentAdapter.inspectContent(plaintext).nullMessage) {
1343
- await family.consumeNull(fingerprint);
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
+ }
1968
+ }
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())) {
1344
1977
  await this.markMessageDeliveredSilently(envelope.id, options);
1345
- throw new EncryptionError('A null message carries no content', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1978
+ return { outcome: { kind: 'duplicate' } };
1346
1979
  }
1347
- await family.fulfill();
1348
- 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),
1349
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) };
1350
2030
  }
1351
2031
  /**
1352
- * Decrypt one envelope that is not a `retry_request`, under its retry family
1353
- * lock. The fingerprint is that of the delivered envelope, also for the
1354
- * 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
1355
2038
  */
1356
- async decryptIncomingEnvelope(envelope, family, fingerprint, options) {
1357
- // Handle sealed sender envelopes: unseal to reveal sender before decrypting
1358
- if (envelope.messageType === 'unidentified_sender' && this.config.sealedSender) {
1359
- const identityKeyPair = await this._storage.getIdentityKey();
1360
- if (!identityKeyPair) {
1361
- throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
1362
- }
1363
- const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
1364
- let unsealed;
1365
- try {
1366
- unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1367
- }
1368
- catch (error) {
1369
- // A member whose seal fails to open asks the device of its request
1370
- // for the next attempt, as a member whose decrypt fails does.
1371
- if (family.member !== undefined) {
1372
- await this.sendRetryRequestInternal(family.withRequestedSender(envelope), error, family, fingerprint, options);
1373
- }
1374
- 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);
1375
2054
  }
1376
- // Process the inner envelope with revealed sender identity. The inner
1377
- // type and the content hint travel inside the seal. Nothing outside it
1378
- // distinguishes a group message from a pairwise one. The same mapping
1379
- // serves the other receive path via `reconstructEnvelope`.
1380
- 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: {
1381
2066
  ...envelope,
1382
2067
  senderUserId: unsealed.senderUserId,
1383
2068
  senderDeviceId: unsealed.senderDeviceId,
1384
2069
  ciphertext: unsealed.innerCiphertextBase64,
1385
2070
  messageType: envelopeTypeForContent(unsealed.contentType),
1386
2071
  contentHint: unsealed.contentHint,
1387
- }, family, fingerprint, options);
1388
- }
1389
- // Route group messages to sender key decryption. `sender_key` says the
1390
- // payload is a framed SenderKeyMessage. It does not say which group, so
1391
- // the group comes from the frame's distribution identifier resolved
1392
- // against the local sender key store.
1393
- if (envelope.messageType === 'sender_key') {
1394
- // Framed SenderKeyMessage: base64 → bytes (Uint8Array)
1395
- const framedBytes = base64ToBytes(envelope.ciphertext);
1396
- const groupId = await this.senderKeyManager.resolveGroupForFramedMessage(framedBytes, envelope.senderUserId, envelope.senderDeviceId);
1397
- if (groupId === null) {
1398
- throw new EncryptionError(`No sender key from ${envelope.senderUserId} matches this group message - request key distribution`, EncryptionErrorCode.SESSION_NOT_FOUND);
1399
- }
1400
- return this.decryptGroupMessage(groupId, envelope.senderUserId, envelope.senderDeviceId, framedBytes);
1401
- }
1402
- 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;
1403
2137
  try {
1404
- // Decode ciphertext: base64 → UTF-8 bytes → JSON string
1405
- // Relay stores as base64(UTF-8(JSON)), we need to reverse both encodings
1406
- const ciphertextBytes = base64ToBytes(envelope.ciphertext);
1407
- const ciphertext = utf8Decode(ciphertextBytes);
1408
- // Decrypt message using Double Ratchet
1409
- const plaintext = await this.decryptMessage(senderAddress, ciphertext);
1410
- 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
+ }
1411
2167
  }
1412
2168
  catch (error) {
1413
- // 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
+ }
1414
2179
  if (isRetryableDecryptionError(error)) {
1415
- await this.sendRetryRequestInternal(envelope, error, family, fingerprint, options);
2180
+ await this.sendRetryRequestInternal(inner, error, family, receiveId, options);
1416
2181
  }
1417
- // Re-throw so caller can handle (log, skip message, etc.)
1418
2182
  throw error;
1419
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
+ };
1420
2258
  }
1421
2259
  /**
1422
2260
  * Process multiple incoming encrypted message envelopes.
@@ -1431,15 +2269,15 @@ export class DefaultSignalProtocolClient {
1431
2269
  * session convergence requires this when the client promotes archived sessions.
1432
2270
  *
1433
2271
  * @param envelopes - Array of encrypted message envelopes
1434
- * @param options - Transport callbacks for background scenarios
1435
- * @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
1436
2274
  *
1437
2275
  * @example
1438
2276
  * ```typescript
1439
2277
  * const results = await signal.processIncomingEnvelopes(pendingMessages);
1440
2278
  * for (const result of results) {
1441
- * if ('plaintext' in result) {
1442
- * handleDecryptedMessage(result.envelope, result.plaintext);
2279
+ * if ('outcome' in result) {
2280
+ * handleReceiveOutcome(result.envelope, result.outcome);
1443
2281
  * } else {
1444
2282
  * handleDecryptionError(result.envelope, result.error);
1445
2283
  * }
@@ -1455,8 +2293,8 @@ export class DefaultSignalProtocolClient {
1455
2293
  const results = [];
1456
2294
  for (const envelope of sorted) {
1457
2295
  try {
1458
- const plaintext = await this.processIncomingEnvelope(envelope, options);
1459
- results.push({ envelope, plaintext });
2296
+ const outcome = await this.processIncomingEnvelope(envelope, options);
2297
+ results.push({ envelope, outcome });
1460
2298
  }
1461
2299
  catch (error) {
1462
2300
  results.push({ envelope, error: error });
@@ -1471,30 +2309,54 @@ export class DefaultSignalProtocolClient {
1471
2309
  * each envelope that the client drops as a duplicate, and each null
1472
2310
  * message that the content adapter reports, which the client consumes
1473
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`.
1474
2317
  */
1475
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) {
1476
2331
  if (!this.hooks?.onMessageDecrypted) {
1477
2332
  throw new Error('Register onMessageDecrypted before receiving Relay messages');
1478
2333
  }
1479
2334
  const processedMessageIds = [];
1480
2335
  const failedMessageIds = [];
1481
- const context = { ...this.ctx, cipher: this.cipher };
1482
- for (const envelope of sortEnvelopesForDecryption(envelopes)) {
1483
- try {
1484
- const processed = await RelaySubscriptionOps.processRelayMessage(context, {
1485
- ...envelope,
1486
- targetUserId: this.userId,
1487
- targetDeviceId: this.deviceId,
1488
- deliveryClass: 'user-visible',
1489
- messageType: (envelope.messageType ?? 'ciphertext'),
1490
- }, this.relaySubscriptionState, this.relaySubscriptionCallbacks(context), { ...this.relaySubscriptionConfig, acknowledgeFailures: false });
1491
- (processed ? processedMessageIds : failedMessageIds).push(envelope.id);
1492
- }
1493
- catch {
1494
- 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
+ }
1495
2353
  }
1496
2354
  }
1497
- return { processedMessageIds, failedMessageIds };
2355
+ catch (error) {
2356
+ release();
2357
+ throw error;
2358
+ }
2359
+ return { processedMessageIds, failedMessageIds, release };
1498
2360
  }
1499
2361
  /**
1500
2362
  * Internal: Send SESAME retry request for failed decryption.
@@ -1611,6 +2473,18 @@ export class DefaultSignalProtocolClient {
1611
2473
  * The stop signal of relay work ends a wait for the recipient's lock.
1612
2474
  */
1613
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) {
1614
2488
  // Normalize all inputs to Uint8Array before calling cipher.encrypt()
1615
2489
  let plaintextBytes;
1616
2490
  let clientTimestamp;
@@ -1633,13 +2507,19 @@ export class DefaultSignalProtocolClient {
1633
2507
  await profileKeys?.offer(recipientId);
1634
2508
  plaintextBytes = content; // already Uint8Array
1635
2509
  }
1636
- // A receipt for this send waits until the send resolves.
1637
- 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
+ }
1638
2516
  const encrypt = (sendContext) => this.cipher.encrypt(recipientId, plaintextBytes, {
1639
2517
  ...options,
1640
2518
  clientMessageId,
1641
2519
  ...(clientTimestamp !== undefined && { timestamp: clientTimestamp }),
2520
+ ...(contentHint !== undefined && { contentHint }),
1642
2521
  }, this.sendSessionCallbacks(() => sendContext, stopSignal), stopSignal);
2522
+ // A receipt for this send waits until the send resolves.
1643
2523
  this.deliveries.beginSend(clientMessageId);
1644
2524
  let result;
1645
2525
  try {
@@ -1651,11 +2531,24 @@ export class DefaultSignalProtocolClient {
1651
2531
  finally {
1652
2532
  this.deliveries.endSend(clientMessageId);
1653
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);
1654
2537
  this.releaseDeliveries(clientMessageId);
1655
2538
  if (profileKey)
1656
2539
  await profileKeys?.delivered(recipientId, profileKey);
2540
+ if (protocolError)
2541
+ await callHook(context.hooks, 'onRelayProtocolError', protocolError);
1657
2542
  return clientTimestamp !== undefined ? { ...result, clientTimestamp } : result;
1658
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
+ }
1659
2552
  async uploadAttachment(data, options) {
1660
2553
  return this.cipher.uploadAttachment(data, options);
1661
2554
  }
@@ -1767,6 +2660,9 @@ export class DefaultSignalProtocolClient {
1767
2660
  registerHook(name, callback) {
1768
2661
  assertHookName(name);
1769
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();
1770
2666
  this.logger.debug('Hook registered', {
1771
2667
  category: 'E2EE',
1772
2668
  data: { hookName: name },
@@ -1825,10 +2721,16 @@ export class DefaultSignalProtocolClient {
1825
2721
  category: 'E2EE',
1826
2722
  data: { userId: this.userId, deviceId: this.deviceId },
1827
2723
  });
2724
+ this.startRetryRequests();
1828
2725
  this.relayUnsubscribe = this.relay.subscribe(this.userId, this.deviceId, (envelope) => {
1829
2726
  const handled = this.state.relayWork.run((work) => {
1830
2727
  const ctx = this.relayWorkContext(work);
1831
- 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);
1832
2734
  });
1833
2735
  handled.catch((error) => {
1834
2736
  // The relay delivers an envelope that it did not acknowledge again.
@@ -1849,6 +2751,49 @@ export class DefaultSignalProtocolClient {
1849
2751
  onBatchEnd: () => this.contentAdapter.setRelayBatching(false),
1850
2752
  });
1851
2753
  }
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
+ */
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() {
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
+ }
2796
+ }
1852
2797
  /**
1853
2798
  * Stop the relay subscription
1854
2799
  *
@@ -1889,9 +2834,15 @@ export class DefaultSignalProtocolClient {
1889
2834
  * @param timestamps - Array of message timestamps that have been delivered
1890
2835
  * @param ctx - Client context, whose hooks run through the relay work of the send
1891
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.
1892
2841
  */
1893
2842
  async sendDeliveryReceipt(recipientUserId, timestamps, ctx = this.receiptContext()) {
1894
- return this.sendReceipt(recipientUserId, timestamps, ReceiptType.DELIVERY, ctx);
2843
+ return MessageOps.sendReceipt(ctx, recipientUserId, timestamps, ReceiptType.DELIVERY, {
2844
+ report: true,
2845
+ });
1895
2846
  }
1896
2847
  /**
1897
2848
  * Send read receipt to original message sender (all devices)
@@ -2110,6 +3061,15 @@ export class DefaultSignalProtocolClient {
2110
3061
  // for this run and does not start a second run. A subscription start
2111
3062
  // from a step is refused
2112
3063
  await Promise.resolve();
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
3067
+ this.retryRequests.stop();
3068
+ this.resendJobs.stop();
3069
+ this.groupFetcher?.stop();
3070
+ this.receiveQueue.stop();
3071
+ this.resendJobsOnConnect?.();
3072
+ this.resendJobsOnConnect = undefined;
2113
3073
  // 1. Start the receipt deadline, 5 s from now. Take the receipt sends in
2114
3074
  // progress, except a send that an earlier stop() stopped, and start the
2115
3075
  // send of the batched delivery receipts, once each, as relay work. Until
@@ -2144,11 +3104,12 @@ export class DefaultSignalProtocolClient {
2144
3104
  }
2145
3105
  // 3. Stop all relay work except the delivery receipt sends, then wait
2146
3106
  // for the receipt sends of step 1, with their app hooks, until the
2147
- // receipt deadline. A delivery or retry request whose app hook returns
2148
- // during the wait writes nothing more, and the relay delivers it again
2149
- // after the next start. A receipt send is not stopped here, because the
2150
- // relay has the acknowledgment of its messages and does not deliver
2151
- // 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
2152
3113
  if (receiptSends.length > 0) {
2153
3114
  this.state.relayWork.stopAllExcept(new Set(this.deliveryReceiptSends.keys()));
2154
3115
  await this.waitForStopReceiptSends(receiptSends, receiptDeadline - Date.now());
@@ -2198,19 +3159,19 @@ export class DefaultSignalProtocolClient {
2198
3159
  data: { error: error.message },
2199
3160
  });
2200
3161
  }
2201
- // 8. Cleanup expired message records (SESAME spec §6.2)
3162
+ // 8. Cleanup expired resendable content (SESAME spec §6.2 and the send log)
2202
3163
  try {
2203
- const deleted = await this._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
2204
- if (deleted > 0) {
2205
- 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', {
2206
3167
  category: 'E2EE',
2207
- data: { deleted },
3168
+ data: deleted,
2208
3169
  });
2209
3170
  }
2210
3171
  }
2211
3172
  catch (error) {
2212
3173
  // Log but do not fail stop
2213
- this.logger.warn('Error cleaning up message records', {
3174
+ this.logger.warn('Error cleaning up resendable content', {
2214
3175
  category: 'E2EE',
2215
3176
  data: { error: error.message },
2216
3177
  });
@@ -2325,8 +3286,10 @@ export class DefaultSignalProtocolClient {
2325
3286
  * ```
2326
3287
  */
2327
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.
2328
3292
  return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
2329
- await this.groupReceiveAuthorizer?.(rawGroupId, senderId, 'distribution');
2330
3293
  return GroupOps.processSenderKeyDistribution(this.ctx, this.senderKeyManager, rawGroupId, senderId, senderDeviceId, message);
2331
3294
  });
2332
3295
  }
@@ -2363,11 +3326,27 @@ export class DefaultSignalProtocolClient {
2363
3326
  * Use this to decrypt messages from other group members.
2364
3327
  * You must process the sender's distribution message first.
2365
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
+ *
2366
3338
  * @param groupId - Group identifier
2367
3339
  * @param senderId - Sender's user ID
2368
3340
  * @param senderDeviceId - Sender's device ID
2369
3341
  * @param framedMessage - Framed SenderKeyMessage bytes
2370
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
2371
3350
  *
2372
3351
  * @example
2373
3352
  * ```typescript
@@ -2381,9 +3360,41 @@ export class DefaultSignalProtocolClient {
2381
3360
  * ```
2382
3361
  */
2383
3362
  async decryptGroupMessage(groupId, senderId, senderDeviceId, framedMessage) {
2384
- return this.groupSenderKeys.run(groupId, async (rawGroupId) => {
2385
- await this.groupReceiveAuthorizer?.(rawGroupId, senderId, 'message');
2386
- 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 });
2387
3398
  });
2388
3399
  }
2389
3400
  /**
@@ -2702,7 +3713,12 @@ export class DefaultSignalProtocolClient {
2702
3713
  * Sync group state from server.
2703
3714
  */
2704
3715
  async syncGroup(groupId) {
2705
- 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);
2706
3722
  }
2707
3723
  /**
2708
3724
  * Add a member to a group.