@open-e2ee/signal-protocol-sdk 10.1.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (595) hide show
  1. package/ADAPTERS.md +4 -4
  2. package/ARCHITECTURE.md +6 -8
  3. package/CHANGELOG.md +1413 -0
  4. package/README.md +1 -1
  5. package/SECURITY.md +2 -2
  6. package/TROUBLESHOOTING.md +1 -1
  7. package/client/README.md +84 -37
  8. package/device/README.md +39 -85
  9. package/dist/client/client.d.ts +342 -62
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +1195 -179
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/client/config.d.ts +40 -32
  14. package/dist/client/config.d.ts.map +1 -1
  15. package/dist/client/config.js +1 -1
  16. package/dist/client/config.js.map +1 -1
  17. package/dist/client/constants.d.ts +42 -8
  18. package/dist/client/constants.d.ts.map +1 -1
  19. package/dist/client/constants.js +48 -3
  20. package/dist/client/constants.js.map +1 -1
  21. package/dist/client/content-adapter.d.ts +80 -0
  22. package/dist/client/content-adapter.d.ts.map +1 -1
  23. package/dist/client/content-adapter.js +225 -12
  24. package/dist/client/content-adapter.js.map +1 -1
  25. package/dist/client/delivery-error.d.ts +150 -0
  26. package/dist/client/delivery-error.d.ts.map +1 -0
  27. package/dist/client/delivery-error.js +226 -0
  28. package/dist/client/delivery-error.js.map +1 -0
  29. package/dist/client/delivery-status.d.ts +32 -6
  30. package/dist/client/delivery-status.d.ts.map +1 -1
  31. package/dist/client/delivery-status.js +61 -13
  32. package/dist/client/delivery-status.js.map +1 -1
  33. package/dist/client/device-set-reconciliation.d.ts +196 -0
  34. package/dist/client/device-set-reconciliation.d.ts.map +1 -0
  35. package/dist/client/device-set-reconciliation.js +282 -0
  36. package/dist/client/device-set-reconciliation.js.map +1 -0
  37. package/dist/client/distribution-records.d.ts +29 -0
  38. package/dist/client/distribution-records.d.ts.map +1 -0
  39. package/dist/client/distribution-records.js +33 -0
  40. package/dist/client/distribution-records.js.map +1 -0
  41. package/dist/client/event-hooks.d.ts +308 -6
  42. package/dist/client/event-hooks.d.ts.map +1 -1
  43. package/dist/client/event-hooks.js +9 -0
  44. package/dist/client/event-hooks.js.map +1 -1
  45. package/dist/client/group-device-set.d.ts +47 -0
  46. package/dist/client/group-device-set.d.ts.map +1 -0
  47. package/dist/client/group-device-set.js +65 -0
  48. package/dist/client/group-device-set.js.map +1 -0
  49. package/dist/client/group-fetcher.d.ts +116 -0
  50. package/dist/client/group-fetcher.d.ts.map +1 -0
  51. package/dist/client/group-fetcher.js +598 -0
  52. package/dist/client/group-fetcher.js.map +1 -0
  53. package/dist/client/group-outbox.d.ts +172 -10
  54. package/dist/client/group-outbox.d.ts.map +1 -1
  55. package/dist/client/group-outbox.js +915 -74
  56. package/dist/client/group-outbox.js.map +1 -1
  57. package/dist/client/group-receive-authorization.d.ts +127 -4
  58. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  59. package/dist/client/group-receive-authorization.js +270 -20
  60. package/dist/client/group-receive-authorization.js.map +1 -1
  61. package/dist/client/group-sealed-sender.d.ts +3 -0
  62. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  63. package/dist/client/group-sealed-sender.js +1 -0
  64. package/dist/client/group-sealed-sender.js.map +1 -1
  65. package/dist/client/group-sender-key-operations.d.ts +14 -3
  66. package/dist/client/group-sender-key-operations.d.ts.map +1 -1
  67. package/dist/client/group-sender-key-operations.js +26 -5
  68. package/dist/client/group-sender-key-operations.js.map +1 -1
  69. package/dist/client/groups.d.ts +5 -5
  70. package/dist/client/groups.d.ts.map +1 -1
  71. package/dist/client/groups.js +5 -4
  72. package/dist/client/groups.js.map +1 -1
  73. package/dist/client/hosted-anonymous-delivery.d.ts +61 -9
  74. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  75. package/dist/client/hosted-anonymous-delivery.js +242 -48
  76. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  77. package/dist/client/hosted-assertion-id.d.ts +7 -0
  78. package/dist/client/hosted-assertion-id.d.ts.map +1 -0
  79. package/dist/client/hosted-assertion-id.js +51 -0
  80. package/dist/client/hosted-assertion-id.js.map +1 -0
  81. package/dist/client/hosted-device-standing.d.ts +52 -0
  82. package/dist/client/hosted-device-standing.d.ts.map +1 -0
  83. package/dist/client/hosted-device-standing.js +74 -0
  84. package/dist/client/hosted-device-standing.js.map +1 -0
  85. package/dist/client/hosted-mailbox-subscription.d.ts +48 -3
  86. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  87. package/dist/client/hosted-mailbox-subscription.js +288 -74
  88. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  89. package/dist/client/hosted-push.d.ts +22 -4
  90. package/dist/client/hosted-push.d.ts.map +1 -1
  91. package/dist/client/hosted-push.js +75 -22
  92. package/dist/client/hosted-push.js.map +1 -1
  93. package/dist/client/hosted-transport.d.ts +22 -28
  94. package/dist/client/hosted-transport.d.ts.map +1 -1
  95. package/dist/client/hosted-transport.js +167 -69
  96. package/dist/client/hosted-transport.js.map +1 -1
  97. package/dist/client/hosted.d.ts +22 -5
  98. package/dist/client/hosted.d.ts.map +1 -1
  99. package/dist/client/hosted.js +122 -45
  100. package/dist/client/hosted.js.map +1 -1
  101. package/dist/client/index.d.ts +6 -4
  102. package/dist/client/index.d.ts.map +1 -1
  103. package/dist/client/index.js +3 -1
  104. package/dist/client/index.js.map +1 -1
  105. package/dist/client/messages.d.ts +25 -3
  106. package/dist/client/messages.d.ts.map +1 -1
  107. package/dist/client/messages.js +118 -17
  108. package/dist/client/messages.js.map +1 -1
  109. package/dist/client/one-time-prekey-refill.d.ts +7 -0
  110. package/dist/client/one-time-prekey-refill.d.ts.map +1 -1
  111. package/dist/client/one-time-prekey-refill.js +5 -1
  112. package/dist/client/one-time-prekey-refill.js.map +1 -1
  113. package/dist/client/receive-admission.d.ts +58 -0
  114. package/dist/client/receive-admission.d.ts.map +1 -0
  115. package/dist/client/receive-admission.js +78 -0
  116. package/dist/client/receive-admission.js.map +1 -0
  117. package/dist/client/receive-expiry.d.ts +31 -0
  118. package/dist/client/receive-expiry.d.ts.map +1 -0
  119. package/dist/client/receive-expiry.js +35 -0
  120. package/dist/client/receive-expiry.js.map +1 -0
  121. package/dist/client/receive-hook-bound.d.ts +50 -0
  122. package/dist/client/receive-hook-bound.d.ts.map +1 -0
  123. package/dist/client/receive-hook-bound.js +115 -0
  124. package/dist/client/receive-hook-bound.js.map +1 -0
  125. package/dist/client/receive-queue.d.ts +299 -0
  126. package/dist/client/receive-queue.d.ts.map +1 -0
  127. package/dist/client/receive-queue.js +1420 -0
  128. package/dist/client/receive-queue.js.map +1 -0
  129. package/dist/client/receive-work-seed.d.ts +54 -0
  130. package/dist/client/receive-work-seed.d.ts.map +1 -0
  131. package/dist/client/receive-work-seed.js +116 -0
  132. package/dist/client/receive-work-seed.js.map +1 -0
  133. package/dist/client/recovery-driver.d.ts +25 -0
  134. package/dist/client/recovery-driver.d.ts.map +1 -0
  135. package/dist/client/recovery-driver.js +121 -0
  136. package/dist/client/recovery-driver.js.map +1 -0
  137. package/dist/client/relay-acceptance.d.ts +30 -0
  138. package/dist/client/relay-acceptance.d.ts.map +1 -1
  139. package/dist/client/relay-acceptance.js +55 -0
  140. package/dist/client/relay-acceptance.js.map +1 -1
  141. package/dist/client/relay-device-refusal.d.ts +18 -0
  142. package/dist/client/relay-device-refusal.d.ts.map +1 -1
  143. package/dist/client/relay-device-refusal.js +31 -0
  144. package/dist/client/relay-device-refusal.js.map +1 -1
  145. package/dist/client/relay-sealed-route.d.ts +36 -0
  146. package/dist/client/relay-sealed-route.d.ts.map +1 -0
  147. package/dist/client/relay-sealed-route.js +45 -0
  148. package/dist/client/relay-sealed-route.js.map +1 -0
  149. package/dist/client/relay-subscription.d.ts +56 -13
  150. package/dist/client/relay-subscription.d.ts.map +1 -1
  151. package/dist/client/relay-subscription.js +220 -150
  152. package/dist/client/relay-subscription.js.map +1 -1
  153. package/dist/client/resendable-content.d.ts +98 -0
  154. package/dist/client/resendable-content.d.ts.map +1 -0
  155. package/dist/client/resendable-content.js +136 -0
  156. package/dist/client/resendable-content.js.map +1 -0
  157. package/dist/client/retry-family.d.ts +68 -19
  158. package/dist/client/retry-family.d.ts.map +1 -1
  159. package/dist/client/retry-family.js +59 -17
  160. package/dist/client/retry-family.js.map +1 -1
  161. package/dist/client/retry-request-envelope.d.ts +145 -18
  162. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  163. package/dist/client/retry-request-envelope.js +301 -64
  164. package/dist/client/retry-request-envelope.js.map +1 -1
  165. package/dist/client/retry-request-lifecycle.d.ts +157 -0
  166. package/dist/client/retry-request-lifecycle.d.ts.map +1 -0
  167. package/dist/client/retry-request-lifecycle.js +437 -0
  168. package/dist/client/retry-request-lifecycle.js.map +1 -0
  169. package/dist/client/retry-terminal-recovery.d.ts +100 -0
  170. package/dist/client/retry-terminal-recovery.d.ts.map +1 -0
  171. package/dist/client/retry-terminal-recovery.js +164 -0
  172. package/dist/client/retry-terminal-recovery.js.map +1 -0
  173. package/dist/client/retry-utils.d.ts +27 -0
  174. package/dist/client/retry-utils.d.ts.map +1 -1
  175. package/dist/client/retry-utils.js +46 -0
  176. package/dist/client/retry-utils.js.map +1 -1
  177. package/dist/client/retry.d.ts +106 -18
  178. package/dist/client/retry.d.ts.map +1 -1
  179. package/dist/client/retry.js +687 -139
  180. package/dist/client/retry.js.map +1 -1
  181. package/dist/client/sealed-sender.d.ts +23 -6
  182. package/dist/client/sealed-sender.d.ts.map +1 -1
  183. package/dist/client/sealed-sender.js +30 -6
  184. package/dist/client/sealed-sender.js.map +1 -1
  185. package/dist/client/sessions.d.ts +2 -2
  186. package/dist/client/sessions.js +2 -2
  187. package/dist/client/signal-service-cipher.d.ts +726 -19
  188. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  189. package/dist/client/signal-service-cipher.js +2265 -343
  190. package/dist/client/signal-service-cipher.js.map +1 -1
  191. package/dist/client/state.d.ts +5 -0
  192. package/dist/client/state.d.ts.map +1 -1
  193. package/dist/client/state.js +11 -1
  194. package/dist/client/state.js.map +1 -1
  195. package/dist/client/storage-protection.d.ts +64 -0
  196. package/dist/client/storage-protection.d.ts.map +1 -0
  197. package/dist/client/storage-protection.js +150 -0
  198. package/dist/client/storage-protection.js.map +1 -0
  199. package/dist/client/types.d.ts +149 -15
  200. package/dist/client/types.d.ts.map +1 -1
  201. package/dist/client/types.js +1 -1
  202. package/dist/client/types.js.map +1 -1
  203. package/dist/device/constants.d.ts +0 -5
  204. package/dist/device/constants.d.ts.map +1 -1
  205. package/dist/device/constants.js +0 -5
  206. package/dist/device/constants.js.map +1 -1
  207. package/dist/device/expo/index.d.ts +4 -17
  208. package/dist/device/expo/index.d.ts.map +1 -1
  209. package/dist/device/expo/index.js +4 -23
  210. package/dist/device/expo/index.js.map +1 -1
  211. package/dist/device/index.d.ts +0 -2
  212. package/dist/device/index.d.ts.map +1 -1
  213. package/dist/device/index.js +0 -7
  214. package/dist/device/index.js.map +1 -1
  215. package/dist/device/lifecycle/manager.d.ts +5 -4
  216. package/dist/device/lifecycle/manager.d.ts.map +1 -1
  217. package/dist/device/lifecycle/manager.js +16 -16
  218. package/dist/device/lifecycle/manager.js.map +1 -1
  219. package/dist/device/lifecycle/types.d.ts +2 -2
  220. package/dist/device/lifecycle/types.d.ts.map +1 -1
  221. package/dist/device/react-native/index.d.ts +4 -15
  222. package/dist/device/react-native/index.d.ts.map +1 -1
  223. package/dist/device/react-native/index.js +4 -21
  224. package/dist/device/react-native/index.js.map +1 -1
  225. package/dist/device/types.d.ts +1 -1
  226. package/dist/groups/index.d.ts +1 -1
  227. package/dist/groups/index.d.ts.map +1 -1
  228. package/dist/index.d.ts +8 -6
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +2 -1
  231. package/dist/index.js.map +1 -1
  232. package/dist/internal/crypto/ec/x25519-validation.d.ts +0 -1
  233. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  234. package/dist/internal/crypto/ec/x25519-validation.js +0 -1
  235. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  236. package/dist/internal/crypto/validation.d.ts +2 -2
  237. package/dist/internal/groups/index.d.ts +1 -0
  238. package/dist/internal/groups/index.d.ts.map +1 -1
  239. package/dist/internal/groups/index.js +1 -0
  240. package/dist/internal/groups/index.js.map +1 -1
  241. package/dist/internal/groups/manager.d.ts +37 -16
  242. package/dist/internal/groups/manager.d.ts.map +1 -1
  243. package/dist/internal/groups/manager.js +46 -1
  244. package/dist/internal/groups/manager.js.map +1 -1
  245. package/dist/internal/groups/receive-record.d.ts +78 -0
  246. package/dist/internal/groups/receive-record.d.ts.map +1 -0
  247. package/dist/internal/groups/receive-record.js +43 -0
  248. package/dist/internal/groups/receive-record.js.map +1 -0
  249. package/dist/internal/groups/sdk-store.d.ts +27 -3
  250. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  251. package/dist/internal/groups/sdk-store.js +151 -19
  252. package/dist/internal/groups/sdk-store.js.map +1 -1
  253. package/dist/internal/groups/wire.d.ts +12 -1
  254. package/dist/internal/groups/wire.d.ts.map +1 -1
  255. package/dist/internal/groups/wire.js +36 -0
  256. package/dist/internal/groups/wire.js.map +1 -1
  257. package/dist/internal/manager/index.d.ts +1 -1
  258. package/dist/internal/manager/manager.d.ts +20 -19
  259. package/dist/internal/manager/manager.d.ts.map +1 -1
  260. package/dist/internal/manager/manager.js +56 -39
  261. package/dist/internal/manager/manager.js.map +1 -1
  262. package/dist/internal/protocol/double-ratchet/chains.d.ts +4 -18
  263. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  264. package/dist/internal/protocol/double-ratchet/chains.js +23 -74
  265. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  266. package/dist/internal/protocol/double-ratchet/index.d.ts +1 -1
  267. package/dist/internal/protocol/double-ratchet/index.d.ts.map +1 -1
  268. package/dist/internal/protocol/double-ratchet/index.js +1 -1
  269. package/dist/internal/protocol/double-ratchet/index.js.map +1 -1
  270. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +5 -7
  271. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  272. package/dist/internal/protocol/double-ratchet/ratchet.js +4 -6
  273. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  274. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  275. package/dist/internal/protocol/pqxdh/pqxdh.js +2 -1
  276. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  277. package/dist/internal/protocol/sealed-sender/types.d.ts +6 -8
  278. package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
  279. package/dist/internal/protocol/sealed-sender/types.js +8 -9
  280. package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
  281. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts +110 -0
  282. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts.map +1 -0
  283. package/dist/internal/protocol/sender-keys/handoff-ledger.js +124 -0
  284. package/dist/internal/protocol/sender-keys/handoff-ledger.js.map +1 -0
  285. package/dist/internal/protocol/sender-keys/manager.d.ts +71 -62
  286. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  287. package/dist/internal/protocol/sender-keys/manager.js +228 -175
  288. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  289. package/dist/internal/protocol/spqr/index.d.ts +2 -2
  290. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  291. package/dist/internal/protocol/spqr/index.js +2 -2
  292. package/dist/internal/protocol/spqr/index.js.map +1 -1
  293. package/dist/internal/protocol/spqr/serialize.d.ts +9 -1
  294. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  295. package/dist/internal/protocol/spqr/serialize.js +56 -16
  296. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  297. package/dist/internal/protocol/spqr/spqr.d.ts +1 -14
  298. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  299. package/dist/internal/protocol/spqr/spqr.js +54 -42
  300. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  301. package/dist/internal/protocol/spqr/validate.d.ts +26 -6
  302. package/dist/internal/protocol/spqr/validate.d.ts.map +1 -1
  303. package/dist/internal/protocol/spqr/validate.js +49 -21
  304. package/dist/internal/protocol/spqr/validate.js.map +1 -1
  305. package/dist/internal/sesame/index.d.ts +1 -1
  306. package/dist/internal/sesame/index.d.ts.map +1 -1
  307. package/dist/internal/sesame/index.js.map +1 -1
  308. package/dist/internal/sesame/manager.d.ts +66 -13
  309. package/dist/internal/sesame/manager.d.ts.map +1 -1
  310. package/dist/internal/sesame/manager.js +221 -87
  311. package/dist/internal/sesame/manager.js.map +1 -1
  312. package/dist/internal/sesame/types.d.ts +95 -17
  313. package/dist/internal/sesame/types.d.ts.map +1 -1
  314. package/dist/internal/sesame/types.js +17 -0
  315. package/dist/internal/sesame/types.js.map +1 -1
  316. package/dist/internal/session/builder.d.ts +5 -5
  317. package/dist/internal/session/builder.d.ts.map +1 -1
  318. package/dist/internal/session/builder.js +12 -17
  319. package/dist/internal/session/builder.js.map +1 -1
  320. package/dist/internal/session/cipher.d.ts +13 -11
  321. package/dist/internal/session/cipher.d.ts.map +1 -1
  322. package/dist/internal/session/cipher.js +40 -22
  323. package/dist/internal/session/cipher.js.map +1 -1
  324. package/dist/internal/session/factory.d.ts +5 -5
  325. package/dist/internal/session/factory.d.ts.map +1 -1
  326. package/dist/internal/session/factory.js +4 -4
  327. package/dist/internal/session/factory.js.map +1 -1
  328. package/dist/internal/session/handshake.d.ts +14 -16
  329. package/dist/internal/session/handshake.d.ts.map +1 -1
  330. package/dist/internal/session/handshake.js +18 -75
  331. package/dist/internal/session/handshake.js.map +1 -1
  332. package/dist/internal/session/index.d.ts +1 -1
  333. package/dist/internal/session/index.js +1 -1
  334. package/dist/internal/session/record-locks.d.ts +17 -6
  335. package/dist/internal/session/record-locks.d.ts.map +1 -1
  336. package/dist/internal/session/record-locks.js +43 -7
  337. package/dist/internal/session/record-locks.js.map +1 -1
  338. package/dist/internal/session/session-resolver.d.ts +1 -1
  339. package/dist/internal/session/session-resolver.js +1 -1
  340. package/dist/internal/session/state.d.ts +2 -2
  341. package/dist/internal/session/state.js +1 -1
  342. package/dist/internal/session/types.d.ts +4 -12
  343. package/dist/internal/session/types.d.ts.map +1 -1
  344. package/dist/internal/session/types.js +1 -1
  345. package/dist/keys/generation.d.ts +2 -2
  346. package/dist/keys/generation.js +2 -2
  347. package/dist/keys/types.d.ts +5 -5
  348. package/dist/keys/types.d.ts.map +1 -1
  349. package/dist/keys/types.js +1 -1
  350. package/dist/layers.d.ts +1 -1
  351. package/dist/layers.js +2 -2
  352. package/dist/layers.js.map +1 -1
  353. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  354. package/dist/local/store/expo/adapter.js +12 -8
  355. package/dist/local/store/expo/adapter.js.map +1 -1
  356. package/dist/local/store/key-value/adapter.d.ts +76 -10
  357. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  358. package/dist/local/store/key-value/adapter.js +367 -61
  359. package/dist/local/store/key-value/adapter.js.map +1 -1
  360. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
  361. package/dist/local/store/key-value/backend-conformance.js +74 -0
  362. package/dist/local/store/key-value/backend-conformance.js.map +1 -1
  363. package/dist/local/store/key-value/batch.d.ts +2 -0
  364. package/dist/local/store/key-value/batch.d.ts.map +1 -1
  365. package/dist/local/store/key-value/batch.js +26 -0
  366. package/dist/local/store/key-value/batch.js.map +1 -1
  367. package/dist/local/store/key-value/receive-work.d.ts +55 -0
  368. package/dist/local/store/key-value/receive-work.d.ts.map +1 -0
  369. package/dist/local/store/key-value/receive-work.js +162 -0
  370. package/dist/local/store/key-value/receive-work.js.map +1 -0
  371. package/dist/local/store/key-value/send-log.d.ts +61 -0
  372. package/dist/local/store/key-value/send-log.d.ts.map +1 -0
  373. package/dist/local/store/key-value/send-log.js +430 -0
  374. package/dist/local/store/key-value/send-log.js.map +1 -0
  375. package/dist/local/store/key-value/sender-key-handoff.d.ts +68 -0
  376. package/dist/local/store/key-value/sender-key-handoff.d.ts.map +1 -0
  377. package/dist/local/store/key-value/sender-key-handoff.js +189 -0
  378. package/dist/local/store/key-value/sender-key-handoff.js.map +1 -0
  379. package/dist/local/store/key-value/storage.d.ts +15 -0
  380. package/dist/local/store/key-value/storage.d.ts.map +1 -1
  381. package/dist/local/store/keyed-index.d.ts +23 -0
  382. package/dist/local/store/keyed-index.d.ts.map +1 -0
  383. package/dist/local/store/keyed-index.js +41 -0
  384. package/dist/local/store/keyed-index.js.map +1 -0
  385. package/dist/local/store/memory/adapter.d.ts +44 -12
  386. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  387. package/dist/local/store/memory/adapter.js +197 -46
  388. package/dist/local/store/memory/adapter.js.map +1 -1
  389. package/dist/local/store/memory/send-log.d.ts +42 -0
  390. package/dist/local/store/memory/send-log.d.ts.map +1 -0
  391. package/dist/local/store/memory/send-log.js +190 -0
  392. package/dist/local/store/memory/send-log.js.map +1 -0
  393. package/dist/local/store/node/adapter.d.ts.map +1 -1
  394. package/dist/local/store/node/adapter.js +8 -6
  395. package/dist/local/store/node/adapter.js.map +1 -1
  396. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  397. package/dist/local/store/react-native/adapter.js +12 -8
  398. package/dist/local/store/react-native/adapter.js.map +1 -1
  399. package/dist/local/store/receive-work.d.ts +87 -0
  400. package/dist/local/store/receive-work.d.ts.map +1 -0
  401. package/dist/local/store/receive-work.js +204 -0
  402. package/dist/local/store/receive-work.js.map +1 -0
  403. package/dist/local/store/received-content.d.ts +3 -3
  404. package/dist/local/store/received-content.d.ts.map +1 -1
  405. package/dist/local/store/received-content.js +2 -11
  406. package/dist/local/store/received-content.js.map +1 -1
  407. package/dist/local/store/reliability.d.ts +411 -14
  408. package/dist/local/store/reliability.d.ts.map +1 -1
  409. package/dist/local/store/reliability.js +532 -58
  410. package/dist/local/store/reliability.js.map +1 -1
  411. package/dist/local/store/send-log-order.d.ts +15 -0
  412. package/dist/local/store/send-log-order.d.ts.map +1 -0
  413. package/dist/local/store/send-log-order.js +24 -0
  414. package/dist/local/store/send-log-order.js.map +1 -0
  415. package/dist/local/store/sender-key-handoff-index.d.ts +38 -0
  416. package/dist/local/store/sender-key-handoff-index.d.ts.map +1 -0
  417. package/dist/local/store/sender-key-handoff-index.js +101 -0
  418. package/dist/local/store/sender-key-handoff-index.js.map +1 -0
  419. package/dist/local/store/sender-key-handoff-table.d.ts +29 -0
  420. package/dist/local/store/sender-key-handoff-table.d.ts.map +1 -0
  421. package/dist/local/store/sender-key-handoff-table.js +97 -0
  422. package/dist/local/store/sender-key-handoff-table.js.map +1 -0
  423. package/dist/local/store/sqlite/encryption.d.ts +8 -1
  424. package/dist/local/store/sqlite/encryption.d.ts.map +1 -1
  425. package/dist/local/store/sqlite/encryption.js +9 -0
  426. package/dist/local/store/sqlite/encryption.js.map +1 -1
  427. package/dist/local/store/sqlite/key-storage/index.d.ts +25 -4
  428. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  429. package/dist/local/store/sqlite/key-storage/index.js +68 -7
  430. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  431. package/dist/local/store/sqlite/key-storage/message-records.d.ts +16 -4
  432. package/dist/local/store/sqlite/key-storage/message-records.d.ts.map +1 -1
  433. package/dist/local/store/sqlite/key-storage/message-records.js +49 -6
  434. package/dist/local/store/sqlite/key-storage/message-records.js.map +1 -1
  435. package/dist/local/store/sqlite/key-storage/metadata.d.ts +8 -7
  436. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  437. package/dist/local/store/sqlite/key-storage/metadata.js +17 -15
  438. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  439. package/dist/local/store/sqlite/key-storage/receive-work.d.ts +27 -0
  440. package/dist/local/store/sqlite/key-storage/receive-work.d.ts.map +1 -0
  441. package/dist/local/store/sqlite/key-storage/receive-work.js +98 -0
  442. package/dist/local/store/sqlite/key-storage/receive-work.js.map +1 -0
  443. package/dist/local/store/sqlite/key-storage/send-log.d.ts +27 -0
  444. package/dist/local/store/sqlite/key-storage/send-log.d.ts.map +1 -0
  445. package/dist/local/store/sqlite/key-storage/send-log.js +178 -0
  446. package/dist/local/store/sqlite/key-storage/send-log.js.map +1 -0
  447. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts +27 -0
  448. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts.map +1 -0
  449. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js +75 -0
  450. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js.map +1 -0
  451. package/dist/local/store/sqlite/key-storage/session-trust.d.ts +2 -2
  452. package/dist/local/store/sqlite/key-storage/session-trust.js +5 -5
  453. package/dist/local/store/sqlite/key-storage/session-trust.js.map +1 -1
  454. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  455. package/dist/local/store/sqlite/migrations.js +101 -0
  456. package/dist/local/store/sqlite/migrations.js.map +1 -1
  457. package/dist/local/store/sqlite/models/index.d.ts +2 -1
  458. package/dist/local/store/sqlite/models/index.d.ts.map +1 -1
  459. package/dist/local/store/sqlite/models/index.js +5 -1
  460. package/dist/local/store/sqlite/models/index.js.map +1 -1
  461. package/dist/local/store/sqlite/models/message-record.d.ts +15 -0
  462. package/dist/local/store/sqlite/models/message-record.d.ts.map +1 -1
  463. package/dist/local/store/sqlite/models/message-record.js +24 -0
  464. package/dist/local/store/sqlite/models/message-record.js.map +1 -1
  465. package/dist/local/store/sqlite/models/send-log.d.ts +51 -0
  466. package/dist/local/store/sqlite/models/send-log.d.ts.map +1 -0
  467. package/dist/local/store/sqlite/models/send-log.js +206 -0
  468. package/dist/local/store/sqlite/models/send-log.js.map +1 -0
  469. package/dist/local/store/sqlite/open-store.d.ts +9 -1
  470. package/dist/local/store/sqlite/open-store.d.ts.map +1 -1
  471. package/dist/local/store/sqlite/open-store.js +20 -1
  472. package/dist/local/store/sqlite/open-store.js.map +1 -1
  473. package/dist/local/store/sqlite/schema.d.ts +34 -1
  474. package/dist/local/store/sqlite/schema.d.ts.map +1 -1
  475. package/dist/local/store/sqlite/schema.js +14 -0
  476. package/dist/local/store/sqlite/schema.js.map +1 -1
  477. package/dist/local/store/sqlite/store.d.ts +61 -11
  478. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  479. package/dist/local/store/sqlite/store.js +191 -27
  480. package/dist/local/store/sqlite/store.js.map +1 -1
  481. package/dist/local/store/web/adapter.d.ts +76 -8
  482. package/dist/local/store/web/adapter.d.ts.map +1 -1
  483. package/dist/local/store/web/adapter.js +579 -127
  484. package/dist/local/store/web/adapter.js.map +1 -1
  485. package/dist/local/store/web/receive-work.d.ts +57 -0
  486. package/dist/local/store/web/receive-work.d.ts.map +1 -0
  487. package/dist/local/store/web/receive-work.js +99 -0
  488. package/dist/local/store/web/receive-work.js.map +1 -0
  489. package/dist/local/store/web/send-log.d.ts +92 -0
  490. package/dist/local/store/web/send-log.d.ts.map +1 -0
  491. package/dist/local/store/web/send-log.js +267 -0
  492. package/dist/local/store/web/send-log.js.map +1 -0
  493. package/dist/local/store/web/sender-key-handoff.d.ts +81 -0
  494. package/dist/local/store/web/sender-key-handoff.d.ts.map +1 -0
  495. package/dist/local/store/web/sender-key-handoff.js +156 -0
  496. package/dist/local/store/web/sender-key-handoff.js.map +1 -0
  497. package/dist/local/store/web-sqlite/adapter.d.ts +2 -0
  498. package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -1
  499. package/dist/local/store/web-sqlite/adapter.js +12 -6
  500. package/dist/local/store/web-sqlite/adapter.js.map +1 -1
  501. package/dist/local/vault/custody.d.ts +8 -0
  502. package/dist/local/vault/custody.d.ts.map +1 -0
  503. package/dist/local/vault/custody.js +9 -0
  504. package/dist/local/vault/custody.js.map +1 -0
  505. package/dist/local/vault/electron-safe-storage.d.ts +3 -1
  506. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  507. package/dist/local/vault/electron-safe-storage.js +2 -0
  508. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  509. package/dist/local/vault/expo-secure-store.d.ts +3 -1
  510. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  511. package/dist/local/vault/expo-secure-store.js +2 -0
  512. package/dist/local/vault/expo-secure-store.js.map +1 -1
  513. package/dist/local/vault/indexed-db.d.ts +3 -1
  514. package/dist/local/vault/indexed-db.d.ts.map +1 -1
  515. package/dist/local/vault/indexed-db.js +2 -0
  516. package/dist/local/vault/indexed-db.js.map +1 -1
  517. package/dist/local/vault/react-native-keychain.d.ts +3 -1
  518. package/dist/local/vault/react-native-keychain.d.ts.map +1 -1
  519. package/dist/local/vault/react-native-keychain.js +2 -0
  520. package/dist/local/vault/react-native-keychain.js.map +1 -1
  521. package/dist/remote/relay/device-set.d.ts +94 -0
  522. package/dist/remote/relay/device-set.d.ts.map +1 -0
  523. package/dist/remote/relay/device-set.js +156 -0
  524. package/dist/remote/relay/device-set.js.map +1 -0
  525. package/dist/remote/relay/types.d.ts +104 -110
  526. package/dist/remote/relay/types.d.ts.map +1 -1
  527. package/dist/safety/core.d.ts +15 -6
  528. package/dist/safety/core.d.ts.map +1 -1
  529. package/dist/safety/core.js +41 -27
  530. package/dist/safety/core.js.map +1 -1
  531. package/dist/safety/index.d.ts +2 -1
  532. package/dist/safety/index.d.ts.map +1 -1
  533. package/dist/safety/index.js +12 -18
  534. package/dist/safety/index.js.map +1 -1
  535. package/dist/types/api.d.ts +707 -62
  536. package/dist/types/api.d.ts.map +1 -1
  537. package/dist/types/errors.d.ts +14 -33
  538. package/dist/types/errors.d.ts.map +1 -1
  539. package/dist/types/errors.js +14 -24
  540. package/dist/types/errors.js.map +1 -1
  541. package/dist/types/messages.d.ts +2 -2
  542. package/dist/types/messages.js +1 -1
  543. package/dist/types/protocol-config.d.ts +175 -42
  544. package/dist/types/protocol-config.d.ts.map +1 -1
  545. package/dist/types/protocol-config.js +19 -38
  546. package/dist/types/protocol-config.js.map +1 -1
  547. package/dist/types/protocol-constants.d.ts +6 -6
  548. package/dist/types/protocol-constants.js +6 -6
  549. package/dist/types/session.d.ts +7 -7
  550. package/dist/types/session.d.ts.map +1 -1
  551. package/dist/types/session.js +39 -21
  552. package/dist/types/session.js.map +1 -1
  553. package/dist/username/link.d.ts +2 -2
  554. package/dist/username/link.js +2 -2
  555. package/dist/utils/origin-lock.d.ts +45 -0
  556. package/dist/utils/origin-lock.d.ts.map +1 -0
  557. package/dist/utils/origin-lock.js +80 -0
  558. package/dist/utils/origin-lock.js.map +1 -0
  559. package/dist/utils/retry.d.ts +2 -0
  560. package/dist/utils/retry.d.ts.map +1 -1
  561. package/dist/utils/retry.js +7 -0
  562. package/dist/utils/retry.js.map +1 -1
  563. package/docs/ASSURANCE.md +6 -6
  564. package/docs/CLIENT_COMPOSITION.md +2 -2
  565. package/docs/DEVIATIONS.md +677 -182
  566. package/docs/E2EE.md +1 -1
  567. package/docs/ERROR_HANDLING.md +235 -2
  568. package/docs/GETTING_STARTED.md +7 -4
  569. package/docs/INTERFACES.md +1 -1
  570. package/docs/PACKAGE_SURFACE.md +6 -5
  571. package/docs/PROTOCOL_POLICY.md +102 -22
  572. package/docs/RECIPES.md +3 -15
  573. package/docs/SECURITY.md +90 -5
  574. package/keys/README.md +3 -3
  575. package/local/store/README.md +78 -14
  576. package/local/store/key-value/README.md +14 -3
  577. package/local/store/node/README.md +8 -3
  578. package/local/store/web/README.md +9 -0
  579. package/local/store/web-sqlite/README.md +14 -2
  580. package/local/vault/README.md +21 -0
  581. package/package.json +1 -6
  582. package/remote/README.md +0 -1
  583. package/remote/relay/README.md +2 -2
  584. package/dist/device/provisioning.d.ts +0 -242
  585. package/dist/device/provisioning.d.ts.map +0 -1
  586. package/dist/device/provisioning.js +0 -421
  587. package/dist/device/provisioning.js.map +0 -1
  588. package/dist/internal/protocol/x3dh/index.d.ts +0 -15
  589. package/dist/internal/protocol/x3dh/index.d.ts.map +0 -1
  590. package/dist/internal/protocol/x3dh/index.js +0 -13
  591. package/dist/internal/protocol/x3dh/index.js.map +0 -1
  592. package/dist/internal/protocol/x3dh/x3dh.d.ts +0 -131
  593. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +0 -1
  594. package/dist/internal/protocol/x3dh/x3dh.js +0 -261
  595. package/dist/internal/protocol/x3dh/x3dh.js.map +0 -1
@@ -0,0 +1,1420 @@
1
+ /**
2
+ * The receive queue: the processor of the stored receive records.
3
+ *
4
+ * A Relay receive commits its decrypted content as a receive record, and
5
+ * holds the record while it runs. The Relay subscription and the hosted
6
+ * pull hold the record until the acknowledgment of its envelope settles.
7
+ * `receiveIncomingEnvelopes` and `processIncomingEnvelope` hold it until the
8
+ * commit ends, because the application acknowledges after the call returns.
9
+ * After the release, the queue decides on the group of the content, gives it
10
+ * to the application, sends the E2EE delivery receipt, and completes the
11
+ * record. A record that waits for its group state stays on the device, not
12
+ * at the Relay.
13
+ *
14
+ * The queue processes the records of one conversation in arrival order. A
15
+ * record that waits, for its group or after a failed hook below the attempt
16
+ * cap, holds back each later record of its conversation. See "Order key".
17
+ * Each pass runs these steps on each record, in arrival order:
18
+ *
19
+ * - A record that has expired (`MAX_RECEIVE_WORK_AGE_MS`, 30 days) and owes
20
+ * no receipt runs `onReceiveExpired`, then completes with the `expired`
21
+ * outcome. A `receipt-due` record that has expired, or whose receipt
22
+ * lifespan of 1 day after its `dueAt` has ended, completes with no
23
+ * receipt and no report: the application has its content.
24
+ * - A `decrypted` record gets its group decision. Authorized content goes
25
+ * to the application, and the record then completes or moves to
26
+ * `receipt-due`. Denied content runs `onDecryptionError` and completes
27
+ * with the `denied` outcome. Content whose group state must update first
28
+ * waits until its retry time or until a fetch of its group completes.
29
+ * - A `receipt-due` record waits for the receipt decision of the Relay for
30
+ * no longer than the reply window, then sends its receipt and completes.
31
+ * - An `awaiting-completion` record waits for `completeReceive` or expiry.
32
+ *
33
+ * A pass runs after the release of each held record, when a fetch of a group
34
+ * completes, at start, at the earliest due time of the records, and from
35
+ * `processPendingReceives`. Each pass is relay work, so a client stop stops
36
+ * it, and its hooks run through that work. At start, before the retry
37
+ * request lifecycle starts, the queue writes outcome 1 again for each
38
+ * stored resend, so the retry deadline never resets a session whose resend
39
+ * content the device holds.
40
+ *
41
+ * Signal equivalence. The order is Signal's. Signal commits the ratchet
42
+ * step and the decrypted content in one transaction, acknowledges after
43
+ * that commit, and sends no acknowledgment when the commit fails. Content
44
+ * that waits for its group stays on the device after the acknowledgment.
45
+ * One Signal client keeps it in a job with a 30-day life. The E2EE delivery
46
+ * receipt goes out only after the group checks, as in another Signal
47
+ * client. It is the only proof that the
48
+ * application processed the content. A Relay delivery receipt that the
49
+ * acknowledgment produces means only that the device holds the content.
50
+ * A resend clears its pending retry only after its processing, as in one
51
+ * Signal client, so `onDeliveryRecovered` waits for the completed record.
52
+ *
53
+ * Order key. A waiting record holds back the later records of its
54
+ * conversation, as one Signal client queues its message jobs per
55
+ * conversation. Group
56
+ * content keys by its group, a sent transcript of this account keys by its
57
+ * destination, and other content keys by its sender account, not by its
58
+ * sender device. So a blocked group holds back the later records of that
59
+ * group from every sender, and direct chats and other groups make
60
+ * progress. The pass learns the conversation of pairwise content only when
61
+ * it restores the content, before the group decision. A record that the
62
+ * pass has not restored keys by the group that it stores, otherwise by its
63
+ * sender account. The queue keeps the key of each restored record in
64
+ * memory, so a record in backoff holds back its conversation and not only
65
+ * its sender account. A record of a group that waits behind an earlier
66
+ * record of that group is written as a record that waits for an update of
67
+ * the group, so the group share of the admission counts it. The commit
68
+ * order stays per sender device by `(arrivalSeq, workId)`. Tests:
69
+ * "processes the records of each sender account in arrival order", "a
70
+ * direct message delivers while an earlier group message of its sender
71
+ * waits for its group", "a message in another group makes progress while a
72
+ * blocked group record of its sender waits", "a blocked head that expires
73
+ * lets the later records of its conversation through", "direct messages
74
+ * progress while global room exists with pairwise group overshoot", and
75
+ * the conversation tests: "a sent transcript waits only behind an earlier
76
+ * transcript to its destination", "a direct message from a second device
77
+ * of a sender waits behind a refused record of its first device", "a
78
+ * record that fails before its restore holds back only its sender
79
+ * account", "a group record that blocks after its decrypt holds back its
80
+ * group from every sender", "pairwise content of a blocked group waits
81
+ * behind the group and delivers after the fetch", "a second sender in a
82
+ * blocked group waits in the group and delivers its direct message".
83
+ *
84
+ * The deviations, each with its constraint and its tests:
85
+ *
86
+ * - Failed hook. One Signal client retries cached content every 2 minutes
87
+ * and deletes it after 10 attempts or 45 days. Another retries a job only
88
+ * on a network error, a missing redemption credential, or a busy group
89
+ * change, and drops the content on other errors. The queue keeps the content
90
+ * until it expires, because the hook is application code: the SDK cannot
91
+ * tell a lasting failure from a passing one, and a drop loses content
92
+ * whose ratchet step is spent. A timer retries the hook after
93
+ * `RECEIVE_RETRY_BACKOFF_MS`. The record keeps a durable `hookAttempts`
94
+ * count, written with the revision check before the hook runs. The first
95
+ * client also counts an attempt of an entry before it processes it. So a
96
+ * hook that ends the process counts as an attempt, and a pass that loses
97
+ * the revision check skips the record. Only the hook stage counts an
98
+ * attempt, so a throw in `restoreCommitted` or in the group decision adds
99
+ * no count and reaches no cap. After `RECEIVE_HOOK_ATTEMPT_CAP` attempts,
100
+ * the cap of 10 of the first client, the record no longer holds
101
+ * back the later records of its conversation, so one failing message
102
+ * never stalls its conversation, as on Signal. Each start then offers it
103
+ * to the hook once: in the start pass, or at the registration of
104
+ * `onMessageDecrypted` when the start pass had no hook. After that offer,
105
+ * or after the attempt that reaches the cap, only `processPendingReceives`
106
+ * runs it again before the next start, and `discardPendingReceive`
107
+ * removes it. In that pass, the record at the cap runs after the other
108
+ * records of the pass, so a hook that ends the process on it still lets
109
+ * the later records of its conversation deliver first. Only an earlier
110
+ * record of its conversation holds it back in that pass. A later record that
111
+ * waits, such as for its group, does not. A pass that ends before the
112
+ * records at the cap run, at its deadline or at any failed page read,
113
+ * leaves them to the next pass. The process then ends at each start until the
114
+ * record expires or the application discards it. The first client deletes
115
+ * the entry at the cap at startup, before it processes any entry, and loses the
116
+ * message. The SDK keeps the record because an application update can
117
+ * repair the hook. Tests: "keeps the content of a rejected application
118
+ * write across its replay", "a hook that always fails stops
119
+ * holding back its conversation after the attempt cap", "the hook attempt count
120
+ * survives a restart", "a hook that ends the process counts toward the
121
+ * attempt cap", "a hook that ends the process on a record at the cap lets
122
+ * the later records of its conversation deliver", "a record at the cap
123
+ * runs while a later record of its conversation waits for its group", "a
124
+ * record at the cap waits behind an earlier record of its conversation
125
+ * that waits for its group", "a record at the cap that holds back its
126
+ * conversation holds back the later records at the cap", "a start pass that fails at its first page
127
+ * read leaves the records at the cap to the next pass", "a capped-retry
128
+ * pass that fails at a page read leaves the records at the cap to the
129
+ * next pass", "a capped-retry pass that reaches its deadline before the
130
+ * records at the cap leaves them to the next pass", "a record that
131
+ * reaches the cap in a pass that reaches its deadline waits for a
132
+ * capped-retry trigger", "a call to processPendingReceives after a failed
133
+ * start pass retries the records at the cap once", "an ordinary pass
134
+ * that fails at a page read leaves no capped retry due", "a record at
135
+ * the cap is offered once at start and not again at the hook
136
+ * registration", "a record that reaches the cap is not offered again
137
+ * before the next start", "discardPendingReceive removes a record at the
138
+ * cap with no receipt, no hook call, and no expiry report".
139
+ * - Missing hook. Signal always has its processor. `create()` resumes the
140
+ * stored records before the application can register
141
+ * `onMessageDecrypted`, so a stored record waits with no backoff, as a job
142
+ * of one Signal client waits for its network constraint, and the hook
143
+ * registration wakes it. The Relay subscription and `receiveIncomingEnvelopes` refuse
144
+ * to start without the hook. Test: "keeps a stored
145
+ * receive with no hook and no backoff, and the hook registration delivers
146
+ * it".
147
+ * - Hook bound. One Signal client bounds its receive pipeline at 2 minutes
148
+ * and its application handlers at 30 minutes. The SDK waits for each
149
+ * application hook of a pass for at most `receiveHookTimeoutMs`, 2 minutes by default, as the founder ruling on the hook bound sets. A timeout counts
150
+ * as a hook failure of that call, and a late settle writes nothing.
151
+ * Tests: "onMessageDecrypted: a hung hook counts one attempt per pass and
152
+ * holds back its conversation until the cap", "onMessageDecrypted: a settle
153
+ * after the bound writes nothing, and the next attempt delivers", and one
154
+ * timeout test for each other await site.
155
+ * - Expiry hook. One Signal client drops an expired job with no report,
156
+ * and another deletes the expired row. The queue
157
+ * runs `onReceiveExpired` first, because the application, not the SDK,
158
+ * shows the user that a message is lost. Before the hook, the queue reads
159
+ * the record again. A record that another path completed after the list
160
+ * of the pass and before this read, such as at the redelivery of its
161
+ * envelope, gets no report. A record that another path wrote in that time
162
+ * expires in a later pass, from its new revision. Expiry is by age only,
163
+ * never by the hook attempt count, because a pass also runs on events,
164
+ * such as an arrival or a group fetch, and a count would measure the
165
+ * events and not the wait (design v5 deviation 5). Tests: the expiry
166
+ * suite, and in it "a record that another path completes after the pass
167
+ * lists it expires with no report", "a record that another path writes
168
+ * after the pass lists it expires in a later pass".
169
+ * - Helper completion. One Signal client confirms a receive after its own
170
+ * save. An SDK customer owns its message store,
171
+ * so a helper record waits in `awaiting-completion` for `completeReceive`
172
+ * (design v5 deviation 6). Tests: V11, V12, and the helper completion
173
+ * suite.
174
+ * - Durable receipt. One Signal client batches the receipt in memory, so a
175
+ * crash can lose it. Another keeps it in a stored job with a 1-day life
176
+ * and no attempt limit. The queue keeps it durable, as that stored job
177
+ * does, in a `receipt-due` record. The Relay can own the receipt, and its decision
178
+ * comes in the reply to the acknowledgment, so the record keeps the
179
+ * receipt and the decision across a restart, and stays in flight until its
180
+ * completion is written. Tests: V7, V8,
181
+ * "a ReceiptSendTerminalError completes with no receipt", "keeps a Relay
182
+ * receipt decision that arrives while the record waits, across a restart".
183
+ * - Receipt lifetime. The Signal client with the stored job stops its receipt
184
+ * retries 1 day after it creates the job, after the message is processed.
185
+ * The queue sends a receipt only until `RECEIPT_LIFESPAN_MS`, 1 day,
186
+ * after the `dueAt` that the move to `receipt-due` writes. That `dueAt` is
187
+ * when the receipt becomes owed, so the lifespan of that job starts there.
188
+ * It includes the receipt-join wait, and the in-memory receipt backoff
189
+ * does not change it. At the end of the lifespan, the record completes
190
+ * with no receipt, no `onMessageDecrypted` call, and no
191
+ * `onReceiveExpired` report. A
192
+ * `receipt-due` record past its 30-day age before then completes in the
193
+ * same way (ruling Q6). The completion of a resend record still reports
194
+ * `onDeliveryRecovered` through its gate. Two other
195
+ * limits of the queue have their own notes: two processes that share one
196
+ * store can overshoot a bound (Q16, see `receive-admission.ts`), and the
197
+ * memory store loses the queue at a restart (T-36). In Q16, each process
198
+ * also keeps its own arrival counter, so a record of one process can sort
199
+ * before a record that another process admitted earlier (see
200
+ * `receive-work-seed.ts`). Tests: "Q6 deletes a receipt-due record past
201
+ * its 30-day age with no receipt, no onMessageDecrypted call, and no
202
+ * onReceiveExpired report", "sends a receipt 1 ms before the end of its
203
+ * 1-day lifespan", "completes a receipt-due record at the end of its
204
+ * 1-day lifespan with no receipt and no report", "a resend record at the
205
+ * end of its receipt lifespan still reports onDeliveryRecovered", "a
206
+ * running client stops its receipt retries at the end of the lifespan".
207
+ * - Bounds. Signal has no device bound on deferred content. The SDK shares a
208
+ * storage budget with the application in a browser and on mobile, so
209
+ * admission checks `maxItems`, `maxBytes`, and `blockedGroupShare` before
210
+ * decrypt, and a refusal is not acknowledged. A refused envelope stays at
211
+ * the Relay and expires there at the project TTL with no local hook. While
212
+ * the mailbox of the device is full, the Relay refuses a new message to it
213
+ * with `MAILBOX_FULL` to its sender. A refusal does not stall the messages
214
+ * behind it: the socket acknowledges each page, and an HTTP pull sends
215
+ * the Relay cursor of the page before it. Tests: the bounds suite.
216
+ * - Outcome 1 before the acknowledgment. The SDK retry lifecycle can reset a
217
+ * session at its deadline, and Signal has no such reset. So the commit of
218
+ * a resend writes the failed envelope as fulfilled before the
219
+ * acknowledgment, and the start writes it again before the lifecycle
220
+ * starts. Tests: both V9 tests, "the retry deadline never deletes a
221
+ * committed receive record".
222
+ * - The separate sender key install and its replay: see `restoreCommitted`.
223
+ * - Converted SDK 11 rows have no Signal form. The data-preserving migration
224
+ * rule keeps them, and the redelivered envelope fills them. Tests: the
225
+ * legacy conversion suite and the converted row tests.
226
+ */
227
+ import { extractGroupId } from '../internal/groups/index.js';
228
+ import { completeReceiveRecord, getProcessedEnvelope, storeProcessedEnvelope, withProcessedEnvelopeLock, writeProcessedEnvelopes, } from '../local/store/reliability.js';
229
+ import { RECEIVE_WORK_DEFAULT_LIMIT, sizedReceiveWork } from '../local/store/receive-work.js';
230
+ import { reportDeliveryRecovered, reportReceiveDenial } from './delivery-error.js';
231
+ import { callHook, } from './event-hooks.js';
232
+ import { classifyGroupContent, groupOfContext } from './group-receive-authorization.js';
233
+ import { ReceiptSendTerminalError } from './messages.js';
234
+ import { isReceiveExpired, receiveExpiresAt } from './receive-expiry.js';
235
+ import { ReceiveHookTimeout } from './receive-hook-bound.js';
236
+ import { RELAY_RECEIPT_REPLY_MS } from './relay-receipt-join.js';
237
+ import { raiseArrivalSeq } from './receive-work-seed.js';
238
+ import { accumulateDeliveryReceipt, } from './relay-subscription.js';
239
+ import { RelayWorkStopped, rethrowRelayWorkStopped, } from './relay-work.js';
240
+ /**
241
+ * A failed hook or receipt send of one record runs again after this time.
242
+ * Signal drops or counts such failures. See "Failed hook" in the module
243
+ * comment for the reason the queue retries until expiry.
244
+ */
245
+ export const RECEIVE_RETRY_BACKOFF_MS = 30_000;
246
+ /**
247
+ * After this many `onMessageDecrypted` attempts, a record no longer
248
+ * holds back the later records of its conversation. One Signal client
249
+ * has the same cap. See "Failed hook" in the module comment.
250
+ */
251
+ export const RECEIVE_HOOK_ATTEMPT_CAP = 10;
252
+ /**
253
+ * A `receipt-due` record sends its receipt only for this time after the
254
+ * `dueAt` of its receipt-due stage: 1 day, the lifespan of the stored
255
+ * receipt job of one Signal client. See "Receipt lifetime" in the module comment.
256
+ */
257
+ export const RECEIPT_LIFESPAN_MS = 24 * 60 * 60 * 1000;
258
+ /** The longest delay that one timer can hold. */
259
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
260
+ const WAIT = (next) => ({ next, processed: false });
261
+ const DONE = { next: Infinity, processed: true };
262
+ /** The time at which a `receipt-due` record stops sending its receipt. */
263
+ const receiptEndsAt = (record) => record.dueAt + RECEIPT_LIFESPAN_MS;
264
+ /** The application has not registered onMessageDecrypted yet. */
265
+ class ReceiveHookMissing extends Error {
266
+ constructor() {
267
+ super('Register onMessageDecrypted before receiving Relay messages');
268
+ this.name = 'ReceiveHookMissing';
269
+ }
270
+ }
271
+ /** The conversation key of a group, from its raw or prefixed ID. */
272
+ const groupConversation = (groupId) => `group:${extractGroupId(groupId)}`;
273
+ /**
274
+ * The conversation key of a record before the pass restores its content:
275
+ * the group that the record stores, otherwise the sender account. A
276
+ * converted legacy record has no sender, so it keys by itself. See "Order
277
+ * key" in the module comment.
278
+ */
279
+ function storedConversationOf(record) {
280
+ if (record.groupId !== undefined)
281
+ return groupConversation(record.groupId);
282
+ return record.senderUserId === undefined
283
+ ? `work:${record.workId}`
284
+ : `account:${record.senderUserId}`;
285
+ }
286
+ /**
287
+ * The raw managed group of restored content before its group decision:
288
+ * the group that the decision checks. Null for content of no managed group.
289
+ */
290
+ function managedGroupOf(content) {
291
+ const claim = classifyGroupContent(content.messageType === 'sender_key' ? content.transportGroupId : null, content.inspected);
292
+ if (!claim)
293
+ return null;
294
+ const group = groupOfContext(claim);
295
+ // The decision denies content whose context names no valid group.
296
+ return 'groupId' in group ? group.groupId : (claim.groupId ?? null);
297
+ }
298
+ /**
299
+ * The group of restored content before its group decision: its managed
300
+ * group, or for content of no managed group the group that the
301
+ * application gets. Null for content of no group.
302
+ */
303
+ function groupOfContent(content) {
304
+ const managed = managedGroupOf(content);
305
+ if (managed !== null)
306
+ return managed;
307
+ return (content.transportGroupId ??
308
+ (content.inspected.senderKeyDistributionOnly === false ? content.distributionGroupId : null));
309
+ }
310
+ /**
311
+ * The conversation key of restored content: the group of the record or of
312
+ * the content, the destination of a sent transcript of this account,
313
+ * otherwise the sender account. See "Order key" in the module comment.
314
+ *
315
+ * @param userId - The account of this client
316
+ */
317
+ function conversationOf(record, content, userId) {
318
+ if (record.groupId !== undefined)
319
+ return groupConversation(record.groupId);
320
+ const groupId = groupOfContent(content);
321
+ if (groupId !== null)
322
+ return groupConversation(groupId);
323
+ const sync = content.inspected.sync;
324
+ if (content.senderUserId === userId && sync?.type === 'sent') {
325
+ // A direct transcript names its recipient. A group transcript names
326
+ // its group as its conversation.
327
+ if (sync.recipientUserId !== undefined)
328
+ return `account:${sync.recipientUserId}`;
329
+ if (sync.conversationId !== undefined)
330
+ return groupConversation(sync.conversationId);
331
+ }
332
+ return `account:${content.senderUserId}`;
333
+ }
334
+ /**
335
+ * Write a record of a group that waits behind an earlier record of its
336
+ * group as a record that waits for an update of that group. The group
337
+ * share of the admission then counts it, as it counts a record whose own
338
+ * decision waits. The record keeps its `dueAt`, so it waits only for its
339
+ * conversation. A record that waits already, or whose stored revision
340
+ * changed, is not written.
341
+ */
342
+ async function waitForGroupUpdate(ctx, record, groupId) {
343
+ if (record.blockedOn !== undefined)
344
+ return;
345
+ await ctx.storage.putReceiveWork(sizedReceiveWork({
346
+ ...record,
347
+ revision: record.revision + 1,
348
+ blockedOn: 'group-update',
349
+ groupId,
350
+ }), record.revision);
351
+ }
352
+ /**
353
+ * Tell whether a pass runs a record at the hook attempt cap.
354
+ *
355
+ * @param offered - The records at the cap that the hook got since the last
356
+ * start
357
+ */
358
+ function retriesCap(record, cappedRetry, offered) {
359
+ if ((record.hookAttempts ?? 0) < RECEIVE_HOOK_ATTEMPT_CAP)
360
+ return false;
361
+ return cappedRetry === 'all' || (cappedRetry === 'unoffered' && !offered.has(record.workId));
362
+ }
363
+ /** Tell whether one record sorts before another in the store order. */
364
+ function sortsBefore(a, b) {
365
+ return a.arrivalSeq < b.arrivalSeq || (a.arrivalSeq === b.arrivalSeq && a.workId < b.workId);
366
+ }
367
+ /** Hold back a conversation for the later records of the pass. */
368
+ function block(blocked, record, conversation) {
369
+ const earliest = blocked.get(conversation);
370
+ if (earliest === undefined || sortsBefore(record, earliest)) {
371
+ blocked.set(conversation, { arrivalSeq: record.arrivalSeq, workId: record.workId });
372
+ }
373
+ }
374
+ /**
375
+ * Tell whether an earlier record of the same conversation holds back a
376
+ * record. A record at the hook attempt cap runs after the page loop, so a
377
+ * later record can hold back its conversation first. That later record
378
+ * does not hold back the earlier record.
379
+ */
380
+ function isBlocked(blocked, record, conversation) {
381
+ const earliest = blocked.get(conversation);
382
+ return earliest !== undefined && sortsBefore(earliest, record);
383
+ }
384
+ /** The record without its plaintext, its wait, and its hook attempts. */
385
+ function withoutContent(record) {
386
+ const { plaintext: _plaintext, blockedOn: _blockedOn, hookAttempts: _hookAttempts, ...rest } = record;
387
+ return rest;
388
+ }
389
+ /**
390
+ * Complete one receive record (outcome 2, or a terminal outcome): delete it
391
+ * and write the processed record of its envelope in one store step. A
392
+ * completed resend also marks its failed envelope fulfilled and completed in
393
+ * the same step, then runs `onDeliveryRecovered` through the completion gate. An
394
+ * expired or denied resend never marks its failed envelope completed.
395
+ *
396
+ * @returns False, with nothing written, when the stored revision changed.
397
+ */
398
+ export async function completeReceiveWork(ctx, record, outcome) {
399
+ const writes = [];
400
+ if (record.envelopeId !== undefined) {
401
+ writes.push({
402
+ envelopeId: record.envelopeId,
403
+ fingerprint: record.workId,
404
+ ...(outcome !== undefined && { outcome }),
405
+ });
406
+ }
407
+ const recovered = outcome === undefined ? record.failedEnvelopeId : undefined;
408
+ // The application has the content, so outcome 1 holds too. A pass that
409
+ // completes the record before a failed outcome-1 write runs again still
410
+ // stops the retry scheduler and drops each later member.
411
+ if (recovered !== undefined) {
412
+ writes.push({ envelopeId: recovered, fulfilled: true, completed: true });
413
+ }
414
+ const done = await completeReceiveRecord(ctx.storage, record.workId, record.revision, writes);
415
+ if (!done || recovered === undefined)
416
+ return done;
417
+ await reportResendRecovered(ctx, recovered);
418
+ return true;
419
+ }
420
+ /**
421
+ * Run `onDeliveryRecovered` through the completion gate for the failed
422
+ * envelope of a completed resend. A failure is logged, and the retry request
423
+ * lifecycle runs the hook again through the gate.
424
+ *
425
+ * @param markCompleted - Write the fulfilled and completed facts of the
426
+ * failed envelope first. A record that moves to `receipt-due` uses it:
427
+ * the application has the content, and the record completes after its
428
+ * receipt.
429
+ */
430
+ async function reportResendRecovered(ctx, failedEnvelopeId, markCompleted = false) {
431
+ try {
432
+ if (markCompleted) {
433
+ await writeProcessedEnvelopes(ctx.storage, [
434
+ { envelopeId: failedEnvelopeId, fulfilled: true, completed: true },
435
+ ]);
436
+ }
437
+ await withProcessedEnvelopeLock(ctx.storage, failedEnvelopeId, () => reportDeliveryRecovered(ctx.storage, ctx.hooks, failedEnvelopeId));
438
+ }
439
+ catch (error) {
440
+ rethrowRelayWorkStopped(error);
441
+ // The receive hook bound logged its timeout.
442
+ if (error instanceof ReceiveHookTimeout)
443
+ return;
444
+ ctx.logger.warn('The onDeliveryRecovered hook failed', {
445
+ category: 'E2EE',
446
+ data: {
447
+ failedEnvelopeId,
448
+ behavior: 'DELIVERY_RECOVERED_HOOK_FAILED',
449
+ error: error.message,
450
+ },
451
+ });
452
+ }
453
+ }
454
+ /**
455
+ * Deny committed content: run `onDecryptionError`, then write the
456
+ * processed `denied` record. With a receive record, the write is the
457
+ * completion of the record. No receipt and no retry request go out.
458
+ */
459
+ export async function denyReceiveWork(ctx, record, sender, error) {
460
+ ctx.logger.warn('Refusing received content', {
461
+ category: 'E2EE',
462
+ data: {
463
+ messageId: sender.messageId,
464
+ senderId: sender.senderUserId,
465
+ behavior: 'RECEIVE_DENIED',
466
+ error: error.message,
467
+ },
468
+ });
469
+ await reportReceiveDenial(ctx.hooks, sender, error);
470
+ if (record !== null) {
471
+ await completeReceiveWork(ctx, record, 'denied');
472
+ }
473
+ else if (sender.envelopeId !== undefined) {
474
+ await writeProcessedEnvelopes(ctx.storage, [
475
+ {
476
+ envelopeId: sender.envelopeId,
477
+ ...(sender.workId !== undefined && { fingerprint: sender.workId }),
478
+ outcome: 'denied',
479
+ },
480
+ ]);
481
+ }
482
+ }
483
+ /**
484
+ * Write a record whose group state must update first. The record waits
485
+ * until its retry time, or until a fetch of its group completes.
486
+ *
487
+ * @returns The time of the next attempt. It is never after the expiry.
488
+ */
489
+ export async function blockReceiveWork(ctx, record, sender, decision, now, expiresAt) {
490
+ const dueAt = Math.min(now + Math.max(0, decision.error.retryAfterMs), expiresAt);
491
+ ctx.logger.info('Group content waits for its group state', {
492
+ category: 'E2EE',
493
+ data: {
494
+ messageId: sender.messageId,
495
+ senderId: sender.senderUserId,
496
+ behavior: 'GROUP_RECEIVE_UNAVAILABLE',
497
+ reason: decision.error.reason,
498
+ },
499
+ });
500
+ await ctx.storage.putReceiveWork(sizedReceiveWork({
501
+ ...record,
502
+ revision: record.revision + 1,
503
+ blockedOn: 'group-update',
504
+ groupId: decision.groupId,
505
+ dueAt,
506
+ }), record.revision);
507
+ return dueAt;
508
+ }
509
+ /**
510
+ * Move a helper record with authorized content to `awaiting-completion`.
511
+ * The record then waits for `completeReceive` or for its expiry.
512
+ *
513
+ * @param groupId - The group of the authorized content, or null
514
+ * @returns The written record, or null when the stored revision changed
515
+ */
516
+ export async function awaitReceiveCompletion(ctx, record, groupId, expiresAt) {
517
+ if (record.stage === 'awaiting-completion')
518
+ return record;
519
+ const { blockedOn: _blockedOn, ...rest } = record;
520
+ const awaiting = sizedReceiveWork({
521
+ ...rest,
522
+ revision: record.revision + 1,
523
+ stage: 'awaiting-completion',
524
+ dueAt: expiresAt,
525
+ ...(groupId !== null && rest.groupId === undefined && { groupId }),
526
+ });
527
+ return (await ctx.storage.putReceiveWork(awaiting, record.revision)) ? awaiting : null;
528
+ }
529
+ /**
530
+ * Expire one record: read it again, run `onReceiveExpired`, then write
531
+ * `expired` and delete it. When another path completed the record or wrote
532
+ * a new revision after the list of the pass and before this read, there is
533
+ * no report and no write.
534
+ * Signal drops expired content with no report. See "Expiry hook" in the
535
+ * module comment.
536
+ */
537
+ async function expireReceiveWork(ctx, record) {
538
+ const current = await ctx.storage.getReceiveWork(record.workId);
539
+ if (current === null || current.revision !== record.revision)
540
+ return;
541
+ const event = {
542
+ workId: record.workId,
543
+ reason: 'max-age',
544
+ receivedAt: record.receivedAt,
545
+ stage: record.stage === 'awaiting-completion' ? 'awaiting-completion' : 'decrypted',
546
+ origin: record.origin,
547
+ ...(record.messageId !== undefined && { messageId: record.messageId }),
548
+ ...(record.senderUserId !== undefined && { senderId: record.senderUserId }),
549
+ ...(record.senderDeviceId !== undefined && { senderDeviceId: record.senderDeviceId }),
550
+ ...(record.groupId !== undefined && { groupId: record.groupId }),
551
+ ...(record.failedEnvelopeId !== undefined && { failedEnvelopeId: record.failedEnvelopeId }),
552
+ };
553
+ await callHook(ctx.hooks, 'onReceiveExpired', event);
554
+ await completeReceiveWork(ctx, record, 'expired');
555
+ }
556
+ /**
557
+ * The processor of the stored receive records. One instance serves one
558
+ * client.
559
+ *
560
+ * @internal
561
+ */
562
+ export class ReceiveQueue {
563
+ relayWork;
564
+ policy;
565
+ pass;
566
+ onResumed;
567
+ timer;
568
+ armedAt = Infinity;
569
+ resumeTimer;
570
+ tail = Promise.resolve();
571
+ queued = false;
572
+ stopped = true;
573
+ /** The start time of this run. A join window that began earlier has passed. */
574
+ startedAt = Infinity;
575
+ afterResume;
576
+ /** True once the resume of this run succeeded. */
577
+ resumed = false;
578
+ starting = Promise.resolve();
579
+ /** Settles when the first resume of this run ends, or at stop(). */
580
+ seeding = Promise.resolve();
581
+ endSeeding;
582
+ /** Records that a receive path holds. A pass skips them. */
583
+ held = new Map();
584
+ /** The next attempt time of a record whose hook or receipt send failed. */
585
+ backoff = new Map();
586
+ /**
587
+ * The conversation key of each record that a pass restored and that is
588
+ * still in the queue, so a record in backoff holds back its conversation
589
+ * and not only its sender account. See "Order key" in the module comment.
590
+ */
591
+ conversations = new Map();
592
+ /**
593
+ * Records whose receipt waits in the receipt batch, or whose completion
594
+ * after the send is not written yet. stop() keeps them, so
595
+ * a pass during stop() does not batch a receipt that stop() sends. start()
596
+ * clears them, because stop() drops a batch that it does not send.
597
+ */
598
+ receiptsInFlight = new Set();
599
+ /** The receipt decisions of the Relay that are not written yet. */
600
+ decisions = new Map();
601
+ /**
602
+ * The receipt batch of each record that waits for the receipt decision of
603
+ * the Relay. stop() keeps them: its release of the join decides each one,
604
+ * and a record that the Relay does not receipt then puts its receipt in
605
+ * the batch that stop() sends.
606
+ */
607
+ joinWaits = new Map();
608
+ /** Groups whose fetch completed since the last pass. */
609
+ wokenGroups = new Set();
610
+ /**
611
+ * The next background pass also retries the records at the hook attempt
612
+ * cap that the hook did not get since the last start.
613
+ */
614
+ cappedRetryDue = false;
615
+ /**
616
+ * The records at the hook attempt cap that the hook got since the last
617
+ * start. Only `processPending` runs them again before the next start.
618
+ */
619
+ offeredAtCap = new Set();
620
+ constructor(relayWork,
621
+ /** The resolved `protocol.receiveQueue` policy. */
622
+ policy, pass,
623
+ /**
624
+ * Runs once in each run of the queue, after its resume and before its
625
+ * first pass, which expires the records past their age. The client
626
+ * starts the stale device record cleanup from it.
627
+ */
628
+ onResumed) {
629
+ this.relayWork = relayWork;
630
+ this.policy = policy;
631
+ this.pass = pass;
632
+ this.onResumed = onResumed;
633
+ }
634
+ /**
635
+ * Start the queue. It writes outcome 1 again for each stored resend (the
636
+ * V9 resume) and raises the arrival counter to the stored records, then
637
+ * calls `afterResume`, then runs a pass. A resume that
638
+ * fails is logged and runs again after the backoff, and `afterResume`
639
+ * waits for it. The promise never rejects.
640
+ *
641
+ * @param afterResume - Starts the retry request lifecycle.
642
+ */
643
+ start(afterResume) {
644
+ if (!this.stopped) {
645
+ // A start of a running queue waits for its resume.
646
+ if (afterResume !== undefined) {
647
+ if (this.resumed)
648
+ afterResume();
649
+ else {
650
+ const earlier = this.afterResume;
651
+ this.afterResume = () => {
652
+ earlier?.();
653
+ afterResume();
654
+ };
655
+ }
656
+ }
657
+ return this.starting;
658
+ }
659
+ this.stopped = false;
660
+ this.resumed = false;
661
+ this.startedAt = Date.now();
662
+ // The join window of a waiting record began before this start, so it
663
+ // has passed. A receipt batch of the earlier run is sent or dropped.
664
+ this.joinWaits.clear();
665
+ this.receiptsInFlight.clear();
666
+ this.afterResume = afterResume;
667
+ let endSeeding;
668
+ this.seeding = new Promise((resolve) => {
669
+ endSeeding = resolve;
670
+ });
671
+ this.endSeeding = endSeeding;
672
+ this.starting = this.resumeThenRun(endSeeding);
673
+ return this.starting;
674
+ }
675
+ /**
676
+ * Wait until the first resume of this run ends. The resume raises the
677
+ * arrival counter to the stored records, so a record that a receive path
678
+ * admits after this wait sorts after them, even when the clock stepped
679
+ * back across a restart. A receive path waits before it takes a lock,
680
+ * because the resume takes the processed envelope locks. After a failed
681
+ * resume, the counter covers only the records that the resume paged.
682
+ * A `stop()` during the first resume settles the promise, and the counter
683
+ * then covers only the records that the resume paged before the stop.
684
+ * The promise never rejects.
685
+ */
686
+ seeded() {
687
+ return this.seeding;
688
+ }
689
+ /** Clear the timers. No pass starts until the next start(). */
690
+ stop() {
691
+ this.stopped = true;
692
+ this.clear();
693
+ if (this.resumeTimer !== undefined)
694
+ clearTimeout(this.resumeTimer);
695
+ this.resumeTimer = undefined;
696
+ this.afterResume = undefined;
697
+ this.endSeeding?.();
698
+ this.endSeeding = undefined;
699
+ this.decisions.clear();
700
+ this.backoff.clear();
701
+ this.conversations.clear();
702
+ this.wokenGroups.clear();
703
+ this.cappedRetryDue = false;
704
+ this.offeredAtCap.clear();
705
+ }
706
+ /**
707
+ * Hold one record while a receive path commits it. The Relay subscription
708
+ * and the hosted pull keep the hold until the acknowledgment of the
709
+ * envelope settles. A pass skips a held record and each later record of
710
+ * its conversation.
711
+ *
712
+ * @returns The release of the hold. The release does not wake the queue,
713
+ * so the caller wakes it after the release.
714
+ */
715
+ hold(workId) {
716
+ this.held.set(workId, (this.held.get(workId) ?? 0) + 1);
717
+ let released = false;
718
+ return () => {
719
+ if (released)
720
+ return;
721
+ released = true;
722
+ const count = (this.held.get(workId) ?? 1) - 1;
723
+ if (count > 0)
724
+ this.held.set(workId, count);
725
+ else
726
+ this.held.delete(workId);
727
+ };
728
+ }
729
+ /**
730
+ * Run a pass soon. With a group, the records that wait for that group get
731
+ * their group decision again in that pass.
732
+ */
733
+ wake(groupId) {
734
+ if (groupId !== undefined)
735
+ this.wokenGroups.add(groupId);
736
+ this.schedule(Date.now());
737
+ }
738
+ /**
739
+ * Run a pass soon that also retries each record at the hook attempt cap
740
+ * that the hook did not get since the last start. The registration of
741
+ * `onMessageDecrypted` calls it.
742
+ */
743
+ retryFailedHooks() {
744
+ this.cappedRetryDue = true;
745
+ this.schedule(Date.now());
746
+ }
747
+ /**
748
+ * Take the receipt decision of the Relay for one record. Each stored
749
+ * record keeps it, so a restart in any stage before the completion does
750
+ * not send a receipt that the Relay owns.
751
+ *
752
+ * @param owned - True when the Relay sends the receipt.
753
+ */
754
+ joinDecided(workId, owned) {
755
+ const batchReceipt = this.joinWaits.get(workId);
756
+ this.joinWaits.delete(workId);
757
+ if (this.stopped) {
758
+ // stop() releases the join, and then sends the receipt batches. The
759
+ // record stays receipt-due until a pass after the next start completes
760
+ // it, so a stop that ends the send loses no receipt.
761
+ if (!owned)
762
+ batchReceipt?.();
763
+ return;
764
+ }
765
+ this.decisions.set(workId, owned);
766
+ // The write runs between passes, so a pass never acts on a revision that
767
+ // this write replaced.
768
+ void this.exclusive(() => this.relayWork.run(async (work) => {
769
+ const { storage } = this.pass(work).ctx;
770
+ const record = await storage.getReceiveWork(workId);
771
+ work.proceed();
772
+ // The record keeps the decision once it is durable, or it completed.
773
+ if (!record || record.relayOwnsReceipt !== undefined) {
774
+ this.decisions.delete(workId);
775
+ return;
776
+ }
777
+ const written = await storage.putReceiveWork(sizedReceiveWork({ ...record, revision: record.revision + 1, relayOwnsReceipt: owned }), record.revision);
778
+ if (written)
779
+ this.decisions.delete(workId);
780
+ }))
781
+ .catch(() => undefined)
782
+ .finally(() => this.schedule(Date.now()));
783
+ }
784
+ /**
785
+ * Run one pass now, in the caller's turn, and stop between records at the
786
+ * deadline. A pass that runs waits first.
787
+ */
788
+ processPending(options = {}) {
789
+ const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + Math.max(0, options.deadlineMs);
790
+ return this.exclusive(async () => {
791
+ // This pass retries the records at the cap. A pass that ends before
792
+ // them arms the capped retry again.
793
+ this.cappedRetryDue = false;
794
+ let result = { processed: 0, remaining: 0 };
795
+ await this.relayWork.run(async (work) => {
796
+ result = await this.runPass(work, deadline, 'all');
797
+ });
798
+ return result;
799
+ });
800
+ }
801
+ /** @param endSeeding - Settles `seeded()` of the run after the first attempt. */
802
+ async resumeThenRun(endSeeding) {
803
+ let resumed = false;
804
+ await this.relayWork
805
+ .run(async (work) => {
806
+ resumed = await this.resume(work);
807
+ })
808
+ .catch(() => undefined);
809
+ endSeeding?.();
810
+ if (this.stopped)
811
+ return;
812
+ if (!resumed) {
813
+ if (this.resumeTimer !== undefined)
814
+ clearTimeout(this.resumeTimer);
815
+ const timer = setTimeout(() => {
816
+ if (this.resumeTimer !== timer)
817
+ return;
818
+ this.resumeTimer = undefined;
819
+ void this.resumeThenRun();
820
+ }, RECEIVE_RETRY_BACKOFF_MS);
821
+ timer.unref?.();
822
+ this.resumeTimer = timer;
823
+ return;
824
+ }
825
+ this.resumed = true;
826
+ this.onResumed?.();
827
+ const afterResume = this.afterResume;
828
+ this.afterResume = undefined;
829
+ afterResume?.();
830
+ this.cappedRetryDue = true;
831
+ await this.run();
832
+ }
833
+ /**
834
+ * The V9 resume: write outcome 1 for each stored record of a resend whose
835
+ * failed envelope has no fulfilled record. A crash between the receive
836
+ * commit and the outcome-1 write leaves such a record. The resume also
837
+ * raises the arrival counter to the largest stored `arrivalSeq`.
838
+ *
839
+ * @returns False when a store step failed. The failure is logged.
840
+ */
841
+ async resume(work) {
842
+ const { storage, logger } = this.pass(work).ctx;
843
+ try {
844
+ let after;
845
+ for (;;) {
846
+ const page = await storage.listReceiveWork({
847
+ ...(after !== undefined && { after }),
848
+ limit: RECEIVE_WORK_DEFAULT_LIMIT,
849
+ });
850
+ for (const record of page) {
851
+ work.proceed();
852
+ after = { arrivalSeq: record.arrivalSeq, workId: record.workId };
853
+ // The pages run in arrival order, so the counter ends at the
854
+ // largest stored value.
855
+ raiseArrivalSeq(storage, record.arrivalSeq);
856
+ const failed = record.failedEnvelopeId;
857
+ if (failed === undefined)
858
+ continue;
859
+ await withProcessedEnvelopeLock(storage, failed, async () => {
860
+ if ((await getProcessedEnvelope(storage, failed))?.fulfilled)
861
+ return;
862
+ await storeProcessedEnvelope(storage, failed, Date.now(), undefined, true);
863
+ });
864
+ }
865
+ if (page.length < RECEIVE_WORK_DEFAULT_LIMIT)
866
+ return true;
867
+ }
868
+ }
869
+ catch (error) {
870
+ rethrowRelayWorkStopped(error);
871
+ logger.warn('The receive queue failed to resume the stored resends', {
872
+ category: 'E2EE',
873
+ data: { behavior: 'RECEIVE_RESUME_FAILED', error: error.message },
874
+ });
875
+ return false;
876
+ }
877
+ }
878
+ /**
879
+ * Arm the timer for the given time when it is earlier than the armed time.
880
+ * A pass that is due now holds the process open, so the work that woke
881
+ * the queue completes. A later pass, such as a backoff or an expiry, does
882
+ * not hold it.
883
+ */
884
+ schedule(at) {
885
+ if (this.stopped || at >= this.armedAt)
886
+ return;
887
+ this.clear();
888
+ this.armedAt = at;
889
+ const delay = Math.min(MAX_TIMER_DELAY_MS, Math.max(0, at - Date.now()));
890
+ const timer = setTimeout(() => {
891
+ if (this.timer !== timer)
892
+ return;
893
+ this.timer = undefined;
894
+ this.armedAt = Infinity;
895
+ void this.run();
896
+ }, delay);
897
+ if (delay > 0)
898
+ timer.unref?.();
899
+ this.timer = timer;
900
+ }
901
+ clear() {
902
+ if (this.timer !== undefined)
903
+ clearTimeout(this.timer);
904
+ this.timer = undefined;
905
+ this.armedAt = Infinity;
906
+ }
907
+ /** Run tasks one at a time. */
908
+ exclusive(task) {
909
+ const result = this.tail.then(task);
910
+ this.tail = result.then(() => undefined, () => undefined);
911
+ return result;
912
+ }
913
+ /** Run a background pass. A call while a pass waits to start adds no pass. */
914
+ run() {
915
+ if (this.queued)
916
+ return this.tail;
917
+ this.queued = true;
918
+ return this.exclusive(async () => {
919
+ this.queued = false;
920
+ if (this.stopped)
921
+ return;
922
+ const retryCapped = this.cappedRetryDue;
923
+ this.cappedRetryDue = false;
924
+ // A pass logs its own failures. RelayWorkStopped ends the pass.
925
+ await this.relayWork
926
+ .run((work) => this.runPass(work, Infinity, retryCapped ? 'unoffered' : 'none').then(() => undefined))
927
+ .catch(() => undefined);
928
+ });
929
+ }
930
+ /**
931
+ * @param cappedRetry - The records at the hook attempt cap that the pass
932
+ * also retries.
933
+ */
934
+ async runPass(work, deadline, cappedRetry) {
935
+ const pass = this.pass(work);
936
+ const { storage, logger } = pass.ctx;
937
+ const woken = this.wokenGroups;
938
+ this.wokenGroups = new Set();
939
+ const blocked = new Map();
940
+ let next = Infinity;
941
+ let processed = 0;
942
+ let remaining = 0;
943
+ let after;
944
+ let timedOut = false;
945
+ // In a capped-retry pass, a record at the hook attempt cap runs after
946
+ // every other record of the pass. See "Failed hook" in the module comment.
947
+ const capped = [];
948
+ const visit = async (record) => {
949
+ if (!timedOut && Date.now() >= deadline) {
950
+ timedOut = true;
951
+ // The records that this pass skips get their group decision again
952
+ // in the next pass.
953
+ for (const groupId of woken)
954
+ this.wokenGroups.add(groupId);
955
+ }
956
+ if (timedOut) {
957
+ if (record.stage !== 'awaiting-completion')
958
+ remaining++;
959
+ return;
960
+ }
961
+ work.proceed();
962
+ let step;
963
+ try {
964
+ step = await this.step(pass, work, record, blocked, woken, cappedRetry);
965
+ }
966
+ catch (error) {
967
+ rethrowRelayWorkStopped(error);
968
+ logger.warn('A receive record failed in the receive queue', {
969
+ category: 'E2EE',
970
+ data: {
971
+ workId: record.workId,
972
+ behavior: 'RECEIVE_QUEUE_RECORD_FAILED',
973
+ error: error.message,
974
+ },
975
+ });
976
+ block(blocked, record, this.conversationOf(record));
977
+ const retryAt = Date.now() + RECEIVE_RETRY_BACKOFF_MS;
978
+ this.backoff.set(record.workId, retryAt);
979
+ step = WAIT(retryAt);
980
+ }
981
+ if (step.processed)
982
+ processed++;
983
+ else if (record.stage !== 'awaiting-completion')
984
+ remaining++;
985
+ next = Math.min(next, step.next);
986
+ };
987
+ let finished = false;
988
+ try {
989
+ for (;;) {
990
+ const page = await storage.listReceiveWork({
991
+ ...(after !== undefined && { after }),
992
+ limit: RECEIVE_WORK_DEFAULT_LIMIT,
993
+ });
994
+ for (const record of page) {
995
+ after = { arrivalSeq: record.arrivalSeq, workId: record.workId };
996
+ if (retriesCap(record, cappedRetry, this.offeredAtCap)) {
997
+ capped.push(record);
998
+ continue;
999
+ }
1000
+ await visit(record);
1001
+ }
1002
+ if (page.length < RECEIVE_WORK_DEFAULT_LIMIT)
1003
+ break;
1004
+ }
1005
+ for (const record of capped)
1006
+ await visit(record);
1007
+ finished = true;
1008
+ }
1009
+ finally {
1010
+ // A capped-retry pass that ends early, such as at a failed page read,
1011
+ // did not run the records at the cap, or did not reach them. The next
1012
+ // pass retries them.
1013
+ if (cappedRetry !== 'none' && !finished)
1014
+ this.cappedRetryDue = true;
1015
+ }
1016
+ // The next pass retries the records at the cap that this pass skipped.
1017
+ if (timedOut && capped.length > 0)
1018
+ this.cappedRetryDue = true;
1019
+ if (timedOut)
1020
+ next = Date.now();
1021
+ if (next !== Infinity)
1022
+ this.schedule(next);
1023
+ return { processed, remaining };
1024
+ }
1025
+ /**
1026
+ * Drop the in-memory state of a record that left the queue: it completed,
1027
+ * it waits for `completeReceive`, or the application discarded it.
1028
+ */
1029
+ forget(workId) {
1030
+ this.decisions.delete(workId);
1031
+ this.backoff.delete(workId);
1032
+ this.conversations.delete(workId);
1033
+ this.offeredAtCap.delete(workId);
1034
+ }
1035
+ /**
1036
+ * The conversation key of a record: the key of its content when a pass
1037
+ * restored it, otherwise its stored key.
1038
+ */
1039
+ conversationOf(record) {
1040
+ return this.conversations.get(record.workId) ?? storedConversationOf(record);
1041
+ }
1042
+ /** Handle one record. */
1043
+ async step(pass, work, record, blocked, woken, cappedRetry) {
1044
+ const { ctx } = pass;
1045
+ const now = Date.now();
1046
+ const conversation = this.conversationOf(record);
1047
+ // The receive path of a held record runs. It wakes the queue after the release.
1048
+ if (this.held.has(record.workId)) {
1049
+ block(blocked, record, conversation);
1050
+ return WAIT(Infinity);
1051
+ }
1052
+ const expiresAt = receiveExpiresAt(record);
1053
+ if (isReceiveExpired(record, now)) {
1054
+ // The application has the content of a receipt-due record.
1055
+ if (record.stage === 'receipt-due')
1056
+ await completeReceiveWork(ctx, record);
1057
+ else
1058
+ await expireReceiveWork(ctx, record);
1059
+ this.forget(record.workId);
1060
+ return DONE;
1061
+ }
1062
+ if (record.stage === 'receipt-due' && now >= receiptEndsAt(record)) {
1063
+ // The receipt lifespan ended. The application has the content.
1064
+ await completeReceiveWork(ctx, record);
1065
+ this.forget(record.workId);
1066
+ return DONE;
1067
+ }
1068
+ if (record.stage === 'awaiting-completion')
1069
+ return WAIT(expiresAt);
1070
+ if (record.stage === 'receipt-due')
1071
+ return this.receiptStep(pass, record, now);
1072
+ // A converted legacy record waits for its redelivery.
1073
+ if (record.awaitingEnvelope)
1074
+ return WAIT(expiresAt);
1075
+ // An earlier record of the conversation holds back this record. See
1076
+ // "Order key" in the module comment.
1077
+ if (isBlocked(blocked, record, conversation)) {
1078
+ // The next pass after the blocker clears decides on the woken group.
1079
+ if (record.groupId !== undefined && woken.has(record.groupId)) {
1080
+ this.wokenGroups.add(record.groupId);
1081
+ }
1082
+ if (record.groupId !== undefined && conversation === groupConversation(record.groupId)) {
1083
+ await waitForGroupUpdate(ctx, record, record.groupId);
1084
+ }
1085
+ return WAIT(expiresAt);
1086
+ }
1087
+ // A record at the hook attempt cap holds back no record. See "Failed
1088
+ // hook" in the module comment.
1089
+ if ((record.hookAttempts ?? 0) >= RECEIVE_HOOK_ATTEMPT_CAP &&
1090
+ !retriesCap(record, cappedRetry, this.offeredAtCap)) {
1091
+ return WAIT(expiresAt);
1092
+ }
1093
+ const retryAt = this.backoff.get(record.workId);
1094
+ if (retryAt !== undefined && retryAt > now) {
1095
+ block(blocked, record, conversation);
1096
+ return WAIT(Math.min(retryAt, expiresAt));
1097
+ }
1098
+ if (record.blockedOn !== undefined &&
1099
+ record.dueAt > now &&
1100
+ !(record.groupId !== undefined && woken.has(record.groupId))) {
1101
+ block(blocked, record, conversation);
1102
+ return WAIT(Math.min(record.dueAt, expiresAt));
1103
+ }
1104
+ return this.processRecord(pass, work, record, blocked, now, expiresAt);
1105
+ }
1106
+ /** Decide on the group of one decrypted record and deliver its content. */
1107
+ async processRecord(pass, work, record, blocked, now, expiresAt) {
1108
+ const { ctx } = pass;
1109
+ const restored = await ctx.cipher.restoreCommitted(record, work.stopSignal);
1110
+ if (restored.kind === 'denied') {
1111
+ await denyReceiveWork(ctx, record, restored, restored.error);
1112
+ this.forget(record.workId);
1113
+ return DONE;
1114
+ }
1115
+ const { content } = restored;
1116
+ // A null message carries no content. Its receive consumed it.
1117
+ if (content.inspected.nullMessage) {
1118
+ await completeReceiveWork(ctx, record);
1119
+ this.forget(record.workId);
1120
+ return DONE;
1121
+ }
1122
+ // The pass knows the conversation of the content only now. An earlier
1123
+ // record of that conversation holds back this record before its group
1124
+ // decision, so a later record never applies a group change first. See
1125
+ // "Order key" in the module comment.
1126
+ const conversation = conversationOf(record, content, ctx.userId);
1127
+ this.conversations.set(record.workId, conversation);
1128
+ if (isBlocked(blocked, record, conversation)) {
1129
+ const groupId = record.groupId ?? managedGroupOf(content);
1130
+ if (groupId !== null && conversation === groupConversation(groupId)) {
1131
+ await waitForGroupUpdate(ctx, record, groupId);
1132
+ }
1133
+ return WAIT(expiresAt);
1134
+ }
1135
+ const decision = await ctx.cipher.decideGroupContent(content);
1136
+ work.proceed();
1137
+ if (decision.kind === 'denied') {
1138
+ await denyReceiveWork(ctx, record, content, decision.error);
1139
+ this.forget(record.workId);
1140
+ return DONE;
1141
+ }
1142
+ if (decision.kind === 'unavailable') {
1143
+ const dueAt = await blockReceiveWork(ctx, record, content, decision, now, expiresAt);
1144
+ block(blocked, record, conversation);
1145
+ return WAIT(dueAt);
1146
+ }
1147
+ if (record.origin === 'caller') {
1148
+ // The application completes a helper receive.
1149
+ await awaitReceiveCompletion(ctx, record, decision.groupId, expiresAt);
1150
+ this.forget(record.workId);
1151
+ return DONE;
1152
+ }
1153
+ // The attempt count is durable before the hook runs, so a hook that
1154
+ // ends the process counts as an attempt. A pass with no registered hook
1155
+ // makes no attempt. See "Failed hook" in the module comment.
1156
+ const receive = ctx.hooks?.onMessageDecrypted;
1157
+ let attempted = record;
1158
+ if (receive) {
1159
+ attempted = sizedReceiveWork({
1160
+ ...record,
1161
+ revision: record.revision + 1,
1162
+ hookAttempts: (record.hookAttempts ?? 0) + 1,
1163
+ });
1164
+ // Another writer changed the record. A later pass reads it again.
1165
+ if (!(await ctx.storage.putReceiveWork(attempted, record.revision))) {
1166
+ block(blocked, record, conversation);
1167
+ return WAIT(Math.min(Date.now() + RECEIVE_RETRY_BACKOFF_MS, expiresAt));
1168
+ }
1169
+ // The hook gets a record at the cap once per start.
1170
+ if ((attempted.hookAttempts ?? 0) >= RECEIVE_HOOK_ATTEMPT_CAP) {
1171
+ this.offeredAtCap.add(record.workId);
1172
+ }
1173
+ }
1174
+ const retryAt = Date.now() + RECEIVE_RETRY_BACKOFF_MS;
1175
+ let owesReceipt;
1176
+ try {
1177
+ owesReceipt = await this.deliver(pass, attempted, content, decision.groupId, receive);
1178
+ }
1179
+ catch (error) {
1180
+ rethrowRelayWorkStopped(error);
1181
+ // The registration of onMessageDecrypted wakes the queue. See
1182
+ // "Missing hook" in the module comment.
1183
+ if (error instanceof ReceiveHookMissing) {
1184
+ block(blocked, record, conversation);
1185
+ return WAIT(expiresAt);
1186
+ }
1187
+ // The count of this attempt is already stored. A timeout counts as a
1188
+ // failure, and the receive hook bound logged it.
1189
+ const hookAttempts = attempted.hookAttempts ?? 0;
1190
+ if (!(error instanceof ReceiveHookTimeout)) {
1191
+ ctx.logger.warn('The application failed to take received content', {
1192
+ category: 'E2EE',
1193
+ data: {
1194
+ messageId: content.messageId,
1195
+ behavior: 'RECEIVE_HOOK_FAILED',
1196
+ hookAttempts,
1197
+ error: error.message,
1198
+ },
1199
+ });
1200
+ }
1201
+ if (hookAttempts >= RECEIVE_HOOK_ATTEMPT_CAP) {
1202
+ this.backoff.delete(record.workId);
1203
+ return WAIT(expiresAt);
1204
+ }
1205
+ this.backoff.set(record.workId, retryAt);
1206
+ block(blocked, record, conversation);
1207
+ return WAIT(Math.min(retryAt, expiresAt));
1208
+ }
1209
+ work.proceed();
1210
+ this.backoff.delete(record.workId);
1211
+ if (!owesReceipt) {
1212
+ await completeReceiveWork(ctx, attempted);
1213
+ this.forget(record.workId);
1214
+ return DONE;
1215
+ }
1216
+ const at = Date.now();
1217
+ const contentTimestamp = content.inspected.timestamp;
1218
+ const { senderTimestamp: _envelopeTimestamp, ...withoutTimestamp } = withoutContent(attempted);
1219
+ const decided = this.decisions.get(record.workId);
1220
+ const due = sizedReceiveWork({
1221
+ ...withoutTimestamp,
1222
+ revision: attempted.revision + 1,
1223
+ stage: 'receipt-due',
1224
+ // The receipt names the content timestamp, or receivedAt.
1225
+ ...(typeof contentTimestamp === 'number' &&
1226
+ Number.isSafeInteger(contentTimestamp) && { senderTimestamp: contentTimestamp }),
1227
+ dueAt: record.ackIntent?.hasReceiptJoin ? record.ackIntent.at + RELAY_RECEIPT_REPLY_MS : at,
1228
+ ...(decided !== undefined && { relayOwnsReceipt: decided }),
1229
+ });
1230
+ if (!(await ctx.storage.putReceiveWork(due, attempted.revision)))
1231
+ return DONE;
1232
+ // The record keeps the decision.
1233
+ if (decided !== undefined)
1234
+ this.decisions.delete(record.workId);
1235
+ // Outcome 2: the application has the content, and the receipt follows.
1236
+ if (due.failedEnvelopeId !== undefined) {
1237
+ await reportResendRecovered(ctx, due.failedEnvelopeId, true);
1238
+ }
1239
+ await this.receiptStep(pass, due, at);
1240
+ return DONE;
1241
+ }
1242
+ /**
1243
+ * Give authorized content to the application.
1244
+ *
1245
+ * @param receive - The `onMessageDecrypted` hook that the attempt count
1246
+ * covers, or undefined when the application has not registered it.
1247
+ * @returns True when the content owes a delivery receipt.
1248
+ */
1249
+ async deliver(pass, record, content, groupId, receive) {
1250
+ const { ctx, callbacks } = pass;
1251
+ const { inspected } = content;
1252
+ let decrypted = ctx.cipher.decryptedEnvelopeOf(content, groupId);
1253
+ // A resend with group content gives the content of its failed group
1254
+ // message, so the application gets it under the ID of that message.
1255
+ if (record.failedEnvelopeId !== undefined && decrypted.isGroup) {
1256
+ decrypted = { ...decrypted, messageId: record.failedEnvelopeId };
1257
+ }
1258
+ // A peer's profile key in authenticated 1:1 content. The exchange never throws.
1259
+ if (inspected.profileKey !== undefined &&
1260
+ !decrypted.isGroup &&
1261
+ decrypted.senderId !== ctx.userId) {
1262
+ await ctx.profileKeys?.incoming(decrypted.senderId, inspected.profileKey);
1263
+ }
1264
+ // The commit installed the distribution. Content beside it continues.
1265
+ if (inspected.senderKeyDistribution && inspected.senderKeyDistributionOnly !== false) {
1266
+ return false;
1267
+ }
1268
+ // A key-update DataMessage carries only the profile key, kept above.
1269
+ if (inspected.profileKeyUpdate)
1270
+ return false;
1271
+ const authenticated = {
1272
+ targetUserId: ctx.userId,
1273
+ targetDeviceId: ctx.deviceId,
1274
+ senderUserId: content.senderUserId,
1275
+ senderDeviceId: content.senderDeviceId,
1276
+ ciphertext: '',
1277
+ messageType: record.messageType ?? 'ciphertext',
1278
+ deliveryClass: 'ephemeral',
1279
+ timestamp: decrypted.timestamp,
1280
+ ...(record.envelopeId !== undefined && { id: record.envelopeId }),
1281
+ ...(content.serverTimestamp !== undefined && { serverTimestamp: content.serverTimestamp }),
1282
+ };
1283
+ if (inspected.receipt) {
1284
+ await callbacks.handleDeliveryReceipt(authenticated, inspected.receipt);
1285
+ return false;
1286
+ }
1287
+ if (inspected.typing) {
1288
+ // Typing indicators are transient: no storage, no delivery receipt.
1289
+ await callbacks.handleTypingIndicator(authenticated, inspected.typing);
1290
+ return false;
1291
+ }
1292
+ if (!receive)
1293
+ throw new ReceiveHookMissing();
1294
+ // The application gets the content as its sender gave it.
1295
+ await receive({
1296
+ ...decrypted,
1297
+ content: ctx.contentAdapter.withoutGroupContext(decrypted.content),
1298
+ });
1299
+ const receipts = ctx.config.deliveryReceipts ?? 'auto';
1300
+ return (inspected.shouldSendDeliveryReceipt &&
1301
+ ctx.relay !== undefined &&
1302
+ receipts !== 'off' &&
1303
+ Boolean(decrypted.timestamp));
1304
+ }
1305
+ /**
1306
+ * Send the receipt of one `receipt-due` record, or complete the record
1307
+ * when the Relay owns the receipt or no receipt can go out. The record
1308
+ * keeps the receipt durable. See "Durable receipt" in the module comment.
1309
+ */
1310
+ async receiptStep(pass, record, now) {
1311
+ const { ctx, state, callbacks } = pass;
1312
+ const owned = record.relayOwnsReceipt ?? this.decisions.get(record.workId);
1313
+ if (owned === true) {
1314
+ await completeReceiveWork(ctx, record);
1315
+ this.forget(record.workId);
1316
+ return DONE;
1317
+ }
1318
+ const { workId, senderUserId } = record;
1319
+ const receipts = ctx.config.deliveryReceipts ?? 'auto';
1320
+ const batchReceipt = ctx.relay !== undefined && receipts !== 'off' && senderUserId !== undefined
1321
+ ? () => {
1322
+ accumulateDeliveryReceipt(state.receiptAccumulator, senderUserId, record.senderTimestamp ?? record.receivedAt, callbacks.sendDeliveryReceipt, ctx.logger).then(() => this.receiptSettled(workId, undefined), (error) => this.receiptSettled(workId, error ?? new Error('Receipt send failed')));
1323
+ }
1324
+ : undefined;
1325
+ const intent = record.ackIntent;
1326
+ // After a restart, an intent with no decision means the window passed.
1327
+ if (owned === undefined &&
1328
+ intent?.hasReceiptJoin === true &&
1329
+ intent.at >= this.startedAt &&
1330
+ now < intent.at + RELAY_RECEIPT_REPLY_MS) {
1331
+ if (batchReceipt !== undefined)
1332
+ this.joinWaits.set(workId, batchReceipt);
1333
+ return WAIT(intent.at + RELAY_RECEIPT_REPLY_MS);
1334
+ }
1335
+ this.joinWaits.delete(workId);
1336
+ if (this.receiptsInFlight.has(workId))
1337
+ return WAIT(Infinity);
1338
+ const retryAt = this.backoff.get(workId);
1339
+ if (retryAt !== undefined && retryAt > now)
1340
+ return WAIT(retryAt);
1341
+ if (batchReceipt === undefined) {
1342
+ await completeReceiveWork(ctx, record);
1343
+ this.forget(workId);
1344
+ return DONE;
1345
+ }
1346
+ this.receiptsInFlight.add(workId);
1347
+ batchReceipt();
1348
+ return WAIT(Infinity);
1349
+ }
1350
+ /** Complete a record whose receipt went out, or retry its send later. */
1351
+ receiptSettled(workId, error) {
1352
+ // A stopped send sends again after the next start.
1353
+ if (error instanceof RelayWorkStopped) {
1354
+ this.receiptsInFlight.delete(workId);
1355
+ return;
1356
+ }
1357
+ if (error !== undefined && !(error instanceof ReceiptSendTerminalError)) {
1358
+ if (this.stopped) {
1359
+ this.receiptsInFlight.delete(workId);
1360
+ return;
1361
+ }
1362
+ // A pass can expire the record while its send runs. Only a record that
1363
+ // still owes its receipt gets a backoff, so an expired record leaves no
1364
+ // in-memory state. The read and the backoff write run between passes,
1365
+ // so no pass expires the record between them. The record stays in
1366
+ // flight until the read ends, so a pass before then does not send its
1367
+ // receipt again. A failed read keeps the backoff, and a later pass
1368
+ // reads the record again.
1369
+ void this.exclusive(async () => {
1370
+ let owesReceipt = true;
1371
+ await this.relayWork
1372
+ .run(async (work) => {
1373
+ const { ctx } = this.pass(work);
1374
+ const record = await ctx.storage.getReceiveWork(workId);
1375
+ work.proceed();
1376
+ owesReceipt = record?.stage === 'receipt-due';
1377
+ })
1378
+ .catch(() => undefined);
1379
+ this.receiptsInFlight.delete(workId);
1380
+ if (this.stopped)
1381
+ return;
1382
+ if (!owesReceipt) {
1383
+ this.forget(workId);
1384
+ return;
1385
+ }
1386
+ const retryAt = Date.now() + RECEIVE_RETRY_BACKOFF_MS;
1387
+ this.backoff.set(workId, retryAt);
1388
+ this.schedule(retryAt);
1389
+ });
1390
+ return;
1391
+ }
1392
+ // The receipt went out, or the Relay refused it for good. The record
1393
+ // stays in flight until its completion is written, so a pass before that
1394
+ // write does not send its receipt again. A completion that a client stop
1395
+ // stops leaves the record, and its receipt goes out again after the next
1396
+ // start.
1397
+ let retryAt;
1398
+ void this.relayWork
1399
+ .run(async (work) => {
1400
+ const { ctx } = this.pass(work);
1401
+ const record = await ctx.storage.getReceiveWork(workId);
1402
+ work.proceed();
1403
+ if (record?.stage !== 'receipt-due')
1404
+ return;
1405
+ if (await completeReceiveWork(ctx, record))
1406
+ this.forget(workId);
1407
+ else
1408
+ retryAt = Date.now();
1409
+ })
1410
+ .catch(() => {
1411
+ retryAt = Date.now() + RECEIVE_RETRY_BACKOFF_MS;
1412
+ })
1413
+ .then(() => {
1414
+ this.receiptsInFlight.delete(workId);
1415
+ if (retryAt !== undefined)
1416
+ this.schedule(retryAt);
1417
+ });
1418
+ }
1419
+ }
1420
+ //# sourceMappingURL=receive-queue.js.map