@open-e2ee/signal-protocol-sdk 11.0.0 → 12.0.1

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