@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
@@ -7,13 +7,26 @@
7
7
  import { EncryptionError, EncryptionErrorCode } from '../types/index.js';
8
8
  import { ContentHint } from '../types/messages.js';
9
9
  import { ProtocolAddress } from '../types/address.js';
10
- import { determineRetryReason } from './retry-utils.js';
11
- import { postRetryRequest } from './retry-request-envelope.js';
10
+ import { determineRetryReason, retryFailedEnvelope } from './retry-utils.js';
11
+ import { acknowledgesRetryRequest, requestRetryInFamily } from './retry-request-lifecycle.js';
12
+ import { retryRequestPost } from './retry-request-envelope.js';
12
13
  import { RetryReason, SesameError, } from '../internal/sesame/types.js';
13
- import { isImplicitContentType, MESSAGE_RECORD_TTL_MS, MAX_RETRY_RESPONSES_PER_MESSAGE, } from './constants.js';
14
+ import { isImplicitContentType, MAX_RETRY_RESPONSES_PER_MESSAGE, SEND_LOG_RESEND_JOB_TTL_MS, } from './constants.js';
14
15
  import { SIGNAL_PROTOCOL_CLIENT_CONSTANTS } from './state.js';
15
- import { base64ToBytes } from '../internal/crypto/utils.js';
16
- import { getRetryResend, RELIABILITY_RECORD_TTL_MS, } from '../local/store/reliability.js';
16
+ import { base64ToBytes, bytesToString } from '../internal/crypto/utils.js';
17
+ import { extractGroupId } from '../internal/groups/group-id.js';
18
+ import { GroupResendDeferredError } from './group-receive-authorization.js';
19
+ import { getRetryResend, RELIABILITY_RECORD_TTL_MS, retryRequestAttempt, storeRetryResend, } from '../local/store/reliability.js';
20
+ import { createKeyedLocks, withKeyedLock } from '../utils/keyed-lock.js';
21
+ /** One resend job of a store runs at a time in this process. */
22
+ const resendJobLocks = createKeyedLocks();
23
+ /**
24
+ * The ID of the resend job of one logged send for one request envelope. A
25
+ * redelivery of the request envelope names the same job.
26
+ */
27
+ export function resendJobId(requestEnvelopeId, clientMessageId) {
28
+ return `${requestEnvelopeId}:${clientMessageId}`;
29
+ }
17
30
  // Max 10 retry requests per sender per 3-hour window
18
31
  export const MAX_RETRY_REQUESTS_PER_SENDER = 10;
19
32
  export const RETRY_REQUEST_WINDOW_MS = 3 * 60 * 60 * 1000; // 3 hours
@@ -94,6 +107,43 @@ async function sendNullMessageForRetryReset(callbacks, retryRequest, ctx, retry)
94
107
  ...(retry && { retry: { ...retry, kind: 'null' } }),
95
108
  });
96
109
  }
110
+ /**
111
+ * Store the terminal state of the answer to a request attempt, call the
112
+ * `onRetryTerminal` hook, and then store the state as emitted, as
113
+ * `emitRetryResendTerminal` tells.
114
+ */
115
+ async function endRetryResend(ctx, retryRequest, retry, terminalClass) {
116
+ const ended = {
117
+ ...retry,
118
+ kind: 'resend',
119
+ attempt: retryRequestAttempt(retry),
120
+ recipientUserId: retryRequest.requesterUserId,
121
+ recipientDeviceId: retryRequest.requesterDeviceId,
122
+ terminal: { class: terminalClass, at: Date.now(), emitted: false },
123
+ };
124
+ await storeRetryResend(ctx.storage, ended);
125
+ await emitRetryResendTerminal(ctx, ended);
126
+ }
127
+ /**
128
+ * Call the hook for a terminal answer that is not emitted, and then store it
129
+ * as emitted. The hook is called directly, not through `callHook`, so a hook
130
+ * that throws, and the RelayWorkStopped of a stop, propagate and leave the
131
+ * answer not emitted. The rule is: mark only after the hook returns. The
132
+ * error fails the handling of the request envelope, so the relay delivers it
133
+ * again, and the redelivery calls the hook again.
134
+ */
135
+ async function emitRetryResendTerminal(ctx, ended) {
136
+ if (ended.terminal.emitted)
137
+ return;
138
+ const hook = ctx.hooks?.onRetryTerminal;
139
+ if (hook) {
140
+ await hook({ class: ended.terminal.class, failedEnvelopeId: ended.failedEnvelopeId });
141
+ }
142
+ await storeRetryResend(ctx.storage, {
143
+ ...ended,
144
+ terminal: { ...ended.terminal, emitted: true },
145
+ });
146
+ }
97
147
  /**
98
148
  * Post the stored resend or null message that answered this request
99
149
  * envelope again: the post of that answer did not complete. It does no
@@ -118,13 +168,39 @@ async function replayStoredResend(ctx, retryRequest, record, callbacks, retry) {
118
168
  });
119
169
  return posted;
120
170
  }
121
- // The plaintext is gone after a delivery receipt or the record TTL.
171
+ // The plaintext is gone after a delivery receipt or the content retention.
122
172
  const plaintext = record?.recipientUserId === requesterUserId ? record.plaintext : null;
123
173
  return await callbacks.resend(requesterUserId, requesterDeviceId, plaintext, {
124
174
  timestamp: record?.timestamp ?? retryRequest.failedTimestamp,
125
175
  retry: { ...retry, kind: 'resend' },
126
176
  });
127
177
  }
178
+ /**
179
+ * The message record of a peer session and client timestamp, without a
180
+ * sender key distribution. A distribution holds a chain key, which rests
181
+ * only in the sender key store: the lookup stores the record without it,
182
+ * or deletes a record that holds only a distribution and returns null, so
183
+ * the request is answered as for a missing record.
184
+ */
185
+ async function getResendableMessageRecord(ctx, sessionId, timestamp) {
186
+ const record = await ctx.storage.getMessageRecord(sessionId, timestamp);
187
+ if (record === null)
188
+ return null;
189
+ const plaintext = ctx.contentAdapter.withoutSenderKeyDistribution(record.plaintext);
190
+ if (plaintext === record.plaintext)
191
+ return record;
192
+ ctx.logger.info('Removed a sender key distribution from a message record', {
193
+ category: 'E2EE',
194
+ data: { sessionId, timestamp, deleted: plaintext === null },
195
+ });
196
+ if (plaintext === null) {
197
+ await ctx.storage.deleteMessageRecord(sessionId, timestamp);
198
+ return null;
199
+ }
200
+ // A replace keeps the stored createdAt, so the retention does not move.
201
+ await ctx.storage.storeMessageRecord({ ...record, plaintext });
202
+ return { ...record, plaintext };
203
+ }
128
204
  /**
129
205
  * Get session key string from userId and deviceId
130
206
  */
@@ -139,12 +215,12 @@ export function getSessionKey(userId, deviceId) {
139
215
  * Handles IMPLICIT content type discarding, rate limiting, and stale prekey rotation.
140
216
  * An envelope without an identified sender, or from the local device, gets
141
217
  * one warn line and no request. The request is stored under the failed
142
- * envelope ID before its post, and a later failure of the same envelope posts
143
- * the stored request again. The rate limit counts each post. A failed resend
144
- * or null message asks again for its failed envelope through the retry
145
- * family, whatever its content hint. A member that fails with an error that
146
- * is not retryable posts nothing here, and its redelivery on the pull path
147
- * asks again.
218
+ * envelope ID before its post, and the request record then owns it, as
219
+ * `requestRetryInFamily` tells. A redelivery of the failed envelope posts
220
+ * nothing. A failed resend or null message asks again for its failed
221
+ * envelope through the retry family, whatever its content hint. A member
222
+ * that fails with an error that is not retryable posts nothing here, and its
223
+ * redelivery on the pull path asks again.
148
224
  *
149
225
  * @param ctx - Retry context with dependencies
150
226
  * @param envelope - The failed message envelope
@@ -200,8 +276,15 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
200
276
  const retryReason = determineRetryReason(error);
201
277
  // Send via relay (foreground) or callback (background)
202
278
  const relay = ctx.relay;
203
- const send = relay ? (request) => relay.send(request) : options?.sendRetryRequest;
204
- const createRequest = async () => {
279
+ // The seal also applies to the background callback. With no relay it
280
+ // has no anonymous delivery, so the request goes identified only when
281
+ // the sealed sender delivery mode permits it.
282
+ const sendIdentified = relay
283
+ ? (request) => relay.send(request)
284
+ : options?.sendRetryRequest;
285
+ const send = sendIdentified &&
286
+ retryRequestPost(ctx.sealRetryRequest, relay, sendIdentified, ctx.recipientRegistrationId, (userId, deviceId) => ctx.refreshStaleSession?.(ctx, userId, deviceId) ?? Promise.resolve(false));
287
+ const createRequest = async (senderKey) => {
205
288
  // Rotate before sending a retry request for a stale-prekey failure.
206
289
  const isStalePreKeyIndicator = error instanceof EncryptionError &&
207
290
  (error.code === EncryptionErrorCode.PREKEY_NOT_FOUND ||
@@ -277,40 +360,42 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
277
360
  timestamp: envelope.timestamp,
278
361
  };
279
362
  // Create retry request via SesameManager
280
- return ctx.sesameManager.createRetryRequest(failedMessage, retryReason);
363
+ return ctx.sesameManager.createRetryRequest(failedMessage, retryReason, { senderKey });
281
364
  };
282
- const posted = await family.requestRetry(fingerprint, async (failed) => {
283
- // Receiver-side rate limiting. A post of a stored request counts too.
284
- if (!checkRetryRateLimit(rateLimitState, envelope.senderUserId)) {
285
- ctx.logger.warn('Retry rate limit exceeded for sender', {
286
- category: 'E2EE',
287
- data: { senderId: envelope.senderUserId, windowMs: RETRY_REQUEST_WINDOW_MS },
288
- });
289
- // A member stays unacknowledged, so its redelivery after the
290
- // window asks again.
291
- if (family.member === undefined) {
292
- await markMessageDeliveredSilently(envelope.id, ctx.relay, ctx.logger, options);
293
- }
294
- return false;
295
- }
296
- if (!send) {
297
- ctx.logger.warn('Cannot send retry request: no relay or callback', { category: 'E2EE' });
298
- return false;
299
- }
300
- await postRetryRequest(ctx.storage, failed, createRequest, { userId: ctx.userId, deviceId: ctx.deviceId }, send);
301
- return true;
365
+ const outcome = await requestRetryInFamily(family, fingerprint, {
366
+ storage: ctx.storage,
367
+ logger: ctx.logger,
368
+ hooks: ctx.hooks,
369
+ local: { userId: ctx.userId, deviceId: ctx.deviceId },
370
+ senderUserId: envelope.senderUserId,
371
+ senderDeviceId: envelope.senderDeviceId,
372
+ // Receiver-side rate limiting. A failed envelope with a request record
373
+ // spends nothing, as `requestRetryInFamily` tells.
374
+ allow: () => checkRetryRateLimit(rateLimitState, envelope.senderUserId),
375
+ windowMs: RETRY_REQUEST_WINDOW_MS,
376
+ send,
377
+ failedEnvelope: await retryFailedEnvelope(ctx.storage, envelope),
378
+ createRequest,
379
+ schedule: ctx.scheduleRetryRequest,
380
+ reset: ctx.retryTerminalReset?.(ctx),
302
381
  });
303
- // An envelope with no post stays unacknowledged.
304
- if (!posted)
382
+ if (outcome === 'posted' || outcome === 'pending') {
383
+ ctx.logger.info('Sent retry request for failed decryption', {
384
+ category: 'E2EE',
385
+ data: {
386
+ sender: `${envelope.senderUserId}:${envelope.senderDeviceId}`,
387
+ timestamp: envelope.timestamp,
388
+ reason: retryReason,
389
+ outcome,
390
+ },
391
+ });
392
+ }
393
+ // The record of the failed envelope owns its request, so the envelope
394
+ // is acknowledged. A member is acknowledged only when its request
395
+ // attempt is posted or ended: a deferred member asks again on its
396
+ // redelivery after the rate limit window.
397
+ if (!acknowledgesRetryRequest(outcome, family.member !== undefined))
305
398
  return;
306
- ctx.logger.info('Sent retry request for failed decryption', {
307
- category: 'E2EE',
308
- data: {
309
- sender: `${envelope.senderUserId}:${envelope.senderDeviceId}`,
310
- timestamp: envelope.timestamp,
311
- reason: retryReason,
312
- },
313
- });
314
399
  // Mark failed message as delivered so it does not reappear
315
400
  if (ctx.relay?.markDelivered) {
316
401
  await ctx.relay.markDelivered(envelope.id).catch((err) => {
@@ -340,20 +425,43 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
340
425
  * Handle incoming retry request and resend the original message
341
426
  *
342
427
  * Per SESAME spec §4.1, this method:
343
- * 1. Looks up the MessageRecord for the failed sequence number. When the
344
- * sender already stored a resend or a null message for this request
345
- * envelope, it posts the stored bytes again and does no session work
346
- * 2. Verifies the requester is the intended recipient
347
- * 3. Checks retry limits and TTL
348
- * 4. Creates new session if orphaned, or uses existing different session
349
- * 5. Re-encrypts and sends the original message, which replaces the old
428
+ * 1. Drops a request for another device of this user. Then it looks up the
429
+ * content that the requesting device can get again: the rows of that
430
+ * exact device in the send log, by the failed client message ID, then by
431
+ * the failed envelope ID, then by the failed timestamp, and else the
432
+ * MessageRecord of the device at the failed timestamp. When the sender
433
+ * already stored a resend or a null message for this request envelope,
434
+ * it posts the stored bytes again and does no session work
435
+ * 2. Sends logged group content only to a current member of its group.
436
+ * A requester that is not a current member, or a group with no source
437
+ * of current membership, gets no content, and the answer to the failed
438
+ * envelope ends with `membership-refused`. Each row counts its resends,
439
+ * and the count survives a restart. A row with
440
+ * `MAX_RETRY_RESPONSES_PER_MESSAGE` resends gets no more
441
+ * 3. For a request without a ratchet key, a sender-key failure, with no
442
+ * row: when this client sent a group to the requester at the failed
443
+ * timestamp, only a current member of that group gets an answer. With no
444
+ * record of the device at that timestamp, the answer is the current
445
+ * sender-key distribution alone. A sender-key failure never resets the
446
+ * pairwise session
447
+ * 4. For a pairwise MessageRecord: verifies that the requester is its
448
+ * recipient and checks the content retention. With the ratchet key of
449
+ * the failed message, it creates a new session if the session is
450
+ * orphaned, or uses the existing different session
451
+ * 5. Re-encrypts and sends the content, which replaces the old
350
452
  * MessageRecord with the record of the new encryption. Only a delivery
351
- * receipt from the device or the TTL deletes that record.
453
+ * receipt from the device or the content retention deletes that record
454
+ * or the row.
352
455
  *
353
- * It refuses a request for a message sent more than
456
+ * It refuses a request for a message stored more than
354
457
  * `RELIABILITY_RECORD_TTL_MS` ago, before it reads a stored resend. The
355
- * Relay can keep the last resend post for that time again, and the
356
- * requester keeps its retry records for both periods.
458
+ * store clock at local persistence (`createdAt` of the MessageRecord or of
459
+ * the send log entry) sets that age, so the message timestamp never moves
460
+ * it. With no stored content, the failed timestamp sets it. The Relay can
461
+ * keep the last resend post for that time again, and the requester keeps
462
+ * its retry records for both periods. The content
463
+ * retention (`protocol.contentRecovery.retentionMs`, 14 days by default) is
464
+ * shorter. A request after it gets no content.
357
465
  *
358
466
  * It returns normally when it resends the message or refuses the request.
359
467
  * It throws every other error, so the caller keeps the request envelope and
@@ -373,33 +481,22 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
373
481
  */
374
482
  export async function handleRetryRequestAndResend(ctx, retryRequest, responseState, callbacks, config, retry) {
375
483
  const sessionId = `${retryRequest.requesterUserId}:${retryRequest.requesterDeviceId}`;
376
- if (Date.now() - retryRequest.failedTimestamp > RELIABILITY_RECORD_TTL_MS) {
377
- ctx.logger.warn('Refusing a retry request for a message older than the retry TTL', {
484
+ // Another device of this user sent the failed message. Only that device
485
+ // can answer.
486
+ if (retryRequest.originalSenderUserId !== ctx.userId ||
487
+ retryRequest.originalSenderDeviceId !== ctx.deviceId) {
488
+ ctx.logger.warn('Dropping a retry request for another device', {
378
489
  category: 'E2EE',
379
490
  data: {
380
491
  sessionId,
381
492
  failedTimestamp: retryRequest.failedTimestamp,
382
- behavior: 'RETRY_REQUEST_EXPIRED',
493
+ behavior: 'RETRY_REQUEST_OTHER_DEVICE',
383
494
  },
384
495
  });
385
496
  return;
386
497
  }
387
498
  // The response count of one message is keyed by its session and timestamp.
388
499
  const dedupKey = `${sessionId}:${retryRequest.failedTimestamp}`;
389
- // Enforce retry response limit
390
- // Prevents infinite retry loops when decryption consistently fails
391
- const responseCount = responseState.retryResponseCounts.get(dedupKey) ?? 0;
392
- if (responseCount >= MAX_RETRY_RESPONSES_PER_MESSAGE) {
393
- ctx.logger.warn('Retry response limit reached, ignoring further retry requests', {
394
- category: 'E2EE',
395
- data: {
396
- dedupKey,
397
- responseCount,
398
- limit: MAX_RETRY_RESPONSES_PER_MESSAGE,
399
- },
400
- });
401
- return;
402
- }
403
500
  ctx.logger.info('Processing retry request', {
404
501
  category: 'E2EE',
405
502
  data: {
@@ -409,19 +506,97 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
409
506
  },
410
507
  });
411
508
  try {
509
+ // The rows of this exact device name the logged group content.
510
+ const entries = await ctx.resendableContent.lookup({ userId: retryRequest.requesterUserId, deviceId: retryRequest.requesterDeviceId }, [retryRequest.failedClientMessageId, retry?.failedEnvelopeId], retryRequest.failedTimestamp);
412
511
  // Look up the original outbound record by peer session and timestamp.
413
- const record = await ctx.storage.getMessageRecord(sessionId, retryRequest.failedTimestamp);
512
+ const record = await getResendableMessageRecord(ctx, sessionId, retryRequest.failedTimestamp);
513
+ // The age of the request runs from the local persistence of the content.
514
+ const storedAt = record?.createdAt ?? entries[0]?.payload.createdAt ?? retryRequest.failedTimestamp;
515
+ if (Date.now() - storedAt > RELIABILITY_RECORD_TTL_MS) {
516
+ ctx.logger.warn('Refusing a retry request for a message older than the retry TTL', {
517
+ category: 'E2EE',
518
+ data: {
519
+ sessionId,
520
+ failedTimestamp: retryRequest.failedTimestamp,
521
+ behavior: 'RETRY_REQUEST_EXPIRED',
522
+ },
523
+ });
524
+ return;
525
+ }
526
+ // The answer to this failed envelope ended. A redelivery of a request
527
+ // only calls the hook when no earlier call returned.
528
+ if (retry !== undefined) {
529
+ const stored = await getRetryResend(ctx.storage, retryRequest.requesterUserId, retryRequest.requesterDeviceId, retry.failedEnvelopeId);
530
+ if (stored?.terminal !== undefined) {
531
+ await emitRetryResendTerminal(ctx, stored);
532
+ return;
533
+ }
534
+ }
414
535
  // The sender already answered this request envelope, and the post did
415
- // not complete. Post the stored bytes again, with no session work.
536
+ // not complete. Post the stored bytes again, with no session work. A
537
+ // group answer posts only stored bytes here. When they expired, the
538
+ // answer below encrypts again after the membership check.
416
539
  if (retry !== undefined &&
417
- (await replayStoredResend(ctx, retryRequest, record, callbacks, retry))) {
418
- responseState.retryResponseCounts.set(dedupKey, responseCount + 1);
540
+ (await replayStoredResend(ctx, retryRequest, entries.length > 0 ? null : record, callbacks, retry))) {
541
+ if (entries.length === 0) {
542
+ responseState.retryResponseCounts.set(dedupKey, (responseState.retryResponseCounts.get(dedupKey) ?? 0) + 1);
543
+ }
419
544
  ctx.logger.info('Posted the stored resend of this request attempt again', {
420
545
  category: 'E2EE',
421
546
  data: { sessionId, failedTimestamp: retryRequest.failedTimestamp },
422
547
  });
423
548
  return;
424
549
  }
550
+ if (entries.length > 0) {
551
+ await resendLoggedGroupContent(ctx, retryRequest, entries, responseState, callbacks, retry);
552
+ return;
553
+ }
554
+ // Enforce retry response limit
555
+ // Prevents infinite retry loops when decryption consistently fails
556
+ const responseCount = responseState.retryResponseCounts.get(dedupKey) ?? 0;
557
+ if (responseCount >= MAX_RETRY_RESPONSES_PER_MESSAGE) {
558
+ ctx.logger.warn('Retry response limit reached, ignoring further retry requests', {
559
+ category: 'E2EE',
560
+ data: {
561
+ dedupKey,
562
+ responseCount,
563
+ limit: MAX_RETRY_RESPONSES_PER_MESSAGE,
564
+ },
565
+ });
566
+ return;
567
+ }
568
+ // A sender-key failure with no row: the sender did not log the content,
569
+ // or the device was no recipient of it. Only a current member of the
570
+ // group of the failed timestamp gets an answer. With no record, the
571
+ // current distribution answers alone, so the later group messages of
572
+ // this device decrypt. No record holds a distribution: the lookup
573
+ // deleted a distribution-only record above, and a record with content
574
+ // answers below with that content alone.
575
+ if (retryRequest.ratchetKey === undefined) {
576
+ const groupId = await callbacks.findSentGroupId(retryRequest.requesterUserId, retryRequest.failedTimestamp);
577
+ if (groupId !== undefined) {
578
+ if (!(await admitsGroupResend(ctx, retryRequest, groupId, responseState, callbacks))) {
579
+ if (retry !== undefined) {
580
+ await endRetryResend(ctx, retryRequest, retry, 'membership-refused');
581
+ }
582
+ return;
583
+ }
584
+ if (!record) {
585
+ // The device reports that it cannot decrypt a message of the group,
586
+ // so it can lack the current key. Its rows in the group go first,
587
+ // and the accepted distribution records a new row. The scope is the
588
+ // group only, as in the sender-key retry receipt of one Signal client.
589
+ await callbacks.invalidateSenderKeyHandoff(groupId, {
590
+ userId: retryRequest.requesterUserId,
591
+ deviceId: retryRequest.requesterDeviceId,
592
+ });
593
+ const sent = await resendCurrentDistribution(ctx, retryRequest, groupId, callbacks, retry);
594
+ if (sent)
595
+ responseState.retryResponseCounts.set(dedupKey, responseCount + 1);
596
+ return;
597
+ }
598
+ }
599
+ }
425
600
  if (!record) {
426
601
  ctx.logger.warn('MessageRecord not found for retry request', {
427
602
  category: 'E2EE',
@@ -431,8 +606,10 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
431
606
  },
432
607
  });
433
608
  // A null message completes the reset when the original resend payload is
434
- // no longer present in the send log.
435
- const shouldAttemptNullFallback = retryRequest.reason === RetryReason.DECRYPTION_FAILED;
609
+ // no longer present in the send log. A sender-key failure resets no
610
+ // pairwise session.
611
+ const shouldAttemptNullFallback = retryRequest.reason === RetryReason.DECRYPTION_FAILED &&
612
+ retryRequest.ratchetKey !== undefined;
436
613
  if (!shouldAttemptNullFallback) {
437
614
  return;
438
615
  }
@@ -447,6 +624,13 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
447
624
  skipMessageRecordValidation: true,
448
625
  });
449
626
  if (lifecycle.action === 'SESSION_ARCHIVED' && lifecycle.requiresNewSession) {
627
+ // The reset archived the session, so the null message starts a new
628
+ // one from a fresh prekey bundle.
629
+ const sessionAfterReset = await ctx.sesameManager.getActiveSession(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
630
+ if (!sessionAfterReset &&
631
+ !(await startAnswerSession(ctx, retryRequest, callbacks, retry, true))) {
632
+ return;
633
+ }
450
634
  await sendNullMessageForRetryReset(callbacks, retryRequest, ctx, retry);
451
635
  // Null-message fallbacks are not retryable payloads. Delete the
452
636
  // synthetic record created by the generic send pipeline.
@@ -487,8 +671,8 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
487
671
  plaintextLength: record.plaintext.length,
488
672
  },
489
673
  });
490
- // 2. Check message TTL
491
- if (Date.now() - record.createdAt > MESSAGE_RECORD_TTL_MS) {
674
+ // 2. Check the content retention
675
+ if (ctx.resendableContent.isExpired(record.createdAt)) {
492
676
  ctx.logger.warn('Message expired, cannot resend', {
493
677
  category: 'E2EE',
494
678
  data: {
@@ -500,64 +684,17 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
500
684
  await ctx.storage.deleteMessageRecord(sessionId, record.timestamp);
501
685
  return;
502
686
  }
503
- // 3. Get current session to check for orphaned session
504
- const currentSession = await ctx.sesameManager.getActiveSession(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
505
- const address = ProtocolAddress.create(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
506
- // Compare our current ratchet key (DHs) against the DHs stored at send time (sessionStateId).
507
- // If DHs advanced (DH ratchet occurred), session is healthy. Reuse it.
508
- // If DHs matches or is missing, session has not advanced. Needs fresh bundle.
509
- // The send record captures the local ratchet key because the retry request
510
- // does not carry a peer-authenticated copy.
511
- const senderRatchetKey = currentSession?.DHs?.publicKey;
512
- const isOrphanedSession = !currentSession || !senderRatchetKey || senderRatchetKey === record.sessionStateId;
513
- const needsFreshBundle = isOrphanedSession;
514
- if (needsFreshBundle) {
515
- // 4a. Need fresh bundle: Archive old session and create new session
516
- const result = await ctx.sesameManager.handleRetryRequest(retryRequest);
517
- if (!result.requiresNewSession) {
518
- ctx.logger.debug('Retry request handled without resend', {
519
- category: 'E2EE',
520
- data: { action: result.action },
521
- });
522
- return;
523
- }
524
- // Fetch prekey bundle and create new initiating session
525
- if (!ctx.relay) {
526
- throw new Error('Relay not configured - cannot fetch prekey bundle');
527
- }
528
- const bundle = await ctx.relay.fetchPreKeyBundle(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
529
- if (!bundle) {
530
- ctx.logger.warn('Failed to fetch prekey bundle for retry', {
531
- category: 'E2EE',
532
- data: {
533
- userId: retryRequest.requesterUserId,
534
- deviceId: retryRequest.requesterDeviceId,
535
- },
536
- });
537
- return;
538
- }
539
- await callbacks.establishSession(address, bundle);
540
- const sessionReason = !currentSession ? 'no_session' : 'orphaned';
541
- ctx.logger.debug('Created new session for retry', {
542
- category: 'E2EE',
543
- data: {
544
- address: ProtocolAddress.toString(address),
545
- reason: sessionReason,
546
- retryReason: retryRequest.reason,
547
- },
548
- });
549
- }
550
- else {
551
- // 4b. Different active session exists AND not MAC failure - use it directly
552
- ctx.logger.debug('Using existing different session for retry (no prekey fetch)', {
553
- category: 'E2EE',
554
- data: {
555
- address: ProtocolAddress.toString(address),
556
- activeRatchetKey: currentSession.DHs?.publicKey?.substring(0, 12) + '...',
557
- storedRatchetKey: record.sessionStateId.substring(0, 12) + '...',
558
- },
687
+ // 3-4. A request with a ratchet key resets an orphaned session. The send
688
+ // record captures the local ratchet key at send time.
689
+ const sessionReady = await prepareAnswerSession(ctx, retryRequest, callbacks, retry, retryRequest.ratchetKey === undefined
690
+ ? null
691
+ : {
692
+ request: retryRequest,
693
+ sentRatchetKey: record.sessionStateId,
694
+ validated: 'message-record',
559
695
  });
560
- }
696
+ if (!sessionReady)
697
+ return;
561
698
  // 5. SESAME Step 4-5: Re-encrypt the original message and send it only
562
699
  // to the device that asked. Reuse the original timestamp for envelope
563
700
  // alignment. The post has a fresh operation epoch.
@@ -569,7 +706,9 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
569
706
  responseState.retryResponseCounts.set(dedupKey, responseCount + 1);
570
707
  // 6. The resend replaced the MessageRecord at the same timestamp with the
571
708
  // record of the new encryption. A delivery receipt from the device or the
572
- // TTL deletes it, so a failed resend can be requested again.
709
+ // content retention deletes it, so a failed resend can be requested again.
710
+ // The store keeps the createdAt of the first write on the replace, so the
711
+ // resend does not extend the retention.
573
712
  ctx.logger.info('Message resent successfully after retry request', {
574
713
  category: 'E2EE',
575
714
  data: {
@@ -593,6 +732,415 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
593
732
  throw error;
594
733
  }
595
734
  }
735
+ /**
736
+ * Answer a request with the logged group content that the rows of the
737
+ * requesting device name. With a request attempt, each entry first gets a
738
+ * pending resend job, before the membership check, so the resend job driver
739
+ * finishes the answer after a restart or a failed post. Each entry is
740
+ * checked and counted on its own row: the requester must be a current
741
+ * member of the group of the entry, and the row must have fewer than
742
+ * `MAX_RETRY_RESPONSES_PER_MESSAGE` resends. The job of an entry that is
743
+ * not admitted is abandoned. When no entry is admitted and the membership
744
+ * refused one, the answer ends with `membership-refused`. A group state that
745
+ * waits for an update throws `GroupResendDeferredError` and leaves the
746
+ * stored jobs pending. The first
747
+ * answered entry carries the retry target, so a redelivery of the request
748
+ * posts its stored bytes again. A later entry at the same timestamp posts
749
+ * under a new ID, because one request attempt has one resend ID.
750
+ */
751
+ async function resendLoggedGroupContent(ctx, retryRequest, entries, responseState, callbacks, retry) {
752
+ const device = { userId: retryRequest.requesterUserId, deviceId: retryRequest.requesterDeviceId };
753
+ const jobs = new Map();
754
+ if (retry !== undefined) {
755
+ for (const [index, { payload }] of entries.entries()) {
756
+ const job = await storePendingResendJob(ctx, device, payload, retry, index === 0);
757
+ jobs.set(payload.clientMessageId, job);
758
+ }
759
+ }
760
+ const abandon = async (entry) => {
761
+ const job = jobs.get(entry.payload.clientMessageId);
762
+ if (job)
763
+ await ctx.storage.completeResendJob(job.jobId, 'abandoned');
764
+ };
765
+ const admittedGroups = new Map();
766
+ const admitted = [];
767
+ let refused = false;
768
+ for (const entry of entries) {
769
+ const { groupId } = entry.payload;
770
+ let member = admittedGroups.get(groupId);
771
+ if (member === undefined) {
772
+ member = await admitsGroupResend(ctx, retryRequest, groupId, responseState, callbacks);
773
+ admittedGroups.set(groupId, member);
774
+ }
775
+ if (!member) {
776
+ refused = true;
777
+ await abandon(entry);
778
+ continue;
779
+ }
780
+ if (reachedResendCap(ctx, entry)) {
781
+ await abandon(entry);
782
+ continue;
783
+ }
784
+ admitted.push(entry);
785
+ }
786
+ if (admitted.length === 0) {
787
+ // A refused membership ends the answer. No later request for the
788
+ // failed envelope from this device gets content.
789
+ if (refused && retry !== undefined) {
790
+ await endRetryResend(ctx, retryRequest, retry, 'membership-refused');
791
+ }
792
+ return;
793
+ }
794
+ const sessionReady = await prepareAnswerSession(ctx, retryRequest, callbacks, retry, retryRequest.ratchetKey === undefined
795
+ ? null
796
+ : { request: retryRequest, sentRatchetKey: retryRequest.ratchetKey, validated: 'send-log' });
797
+ if (!sessionReady) {
798
+ for (const entry of admitted)
799
+ await abandon(entry);
800
+ return;
801
+ }
802
+ let target = retry && { ...retry, kind: 'resend' };
803
+ for (const entry of admitted) {
804
+ const job = jobs.get(entry.payload.clientMessageId);
805
+ if (job === undefined) {
806
+ await postLoggedGroupContent(ctx, device, entry.payload, callbacks, target);
807
+ }
808
+ else {
809
+ await withResendJob(ctx, job.jobId, (pending) => postLoggedGroupContent(ctx, device, entry.payload, callbacks, target, pending));
810
+ }
811
+ target = undefined;
812
+ }
813
+ }
814
+ /**
815
+ * Write the pending resend job of one logged entry for a request attempt.
816
+ * The job of the first entry that the request names holds the failed
817
+ * envelope. A redelivered request envelope writes the same job again and
818
+ * keeps its attempts.
819
+ */
820
+ async function storePendingResendJob(ctx, device, payload, retry, answersFailedEnvelope) {
821
+ const jobId = resendJobId(retry.requestEnvelopeId, payload.clientMessageId);
822
+ const existing = await ctx.storage.getResendJob(jobId);
823
+ const job = {
824
+ jobId,
825
+ clientMessageId: payload.clientMessageId,
826
+ requesterUserId: device.userId,
827
+ requesterDeviceId: device.deviceId,
828
+ retryId: retry.retryId,
829
+ requestEnvelopeId: retry.requestEnvelopeId,
830
+ ...(answersFailedEnvelope && { failedEnvelopeId: retry.failedEnvelopeId }),
831
+ createdAt: Date.now(),
832
+ attempts: existing?.attempts ?? 0,
833
+ state: 'pending',
834
+ };
835
+ await ctx.storage.storeResendJob(job);
836
+ return job;
837
+ }
838
+ /**
839
+ * Run an operation on one pending resend job, under the lock of the job.
840
+ * The job is read again under the lock: a job that another run finished
841
+ * meanwhile does not run again.
842
+ */
843
+ async function withResendJob(ctx, jobId, operation) {
844
+ await withKeyedLock(resendJobLocks, ctx.storage, jobId, async () => {
845
+ const job = await ctx.storage.getResendJob(jobId);
846
+ if (job?.state === 'pending')
847
+ await operation(job);
848
+ });
849
+ }
850
+ /** True, with a warning, when the row of the entry has its maximum count of resends. */
851
+ function reachedResendCap(ctx, entry) {
852
+ if (entry.recipient.responses < MAX_RETRY_RESPONSES_PER_MESSAGE)
853
+ return false;
854
+ ctx.logger.warn('Retry response limit reached, ignoring further retry requests', {
855
+ category: 'E2EE',
856
+ data: {
857
+ clientMessageId: entry.payload.clientMessageId,
858
+ responseCount: entry.recipient.responses,
859
+ limit: MAX_RETRY_RESPONSES_PER_MESSAGE,
860
+ },
861
+ });
862
+ return true;
863
+ }
864
+ /**
865
+ * Post the logged content of one group send again to the requesting device,
866
+ * with the current sender-key distribution of the group beside it, at the
867
+ * original timestamp. The distribution is read in the group operation at
868
+ * the current chain index, so the device also decrypts the later group
869
+ * messages of this sender. With no sender key for the group, the content
870
+ * goes alone. A job counts the attempt and holds the failed envelope of the
871
+ * target before the post, and is posted after it. The caller checked the
872
+ * membership of the requester and prepared the session.
873
+ */
874
+ async function postLoggedGroupContent(ctx, device, payload, callbacks, target, job) {
875
+ const text = bytesToString(payload.plaintext);
876
+ // The device reports that it cannot decrypt a message of the group, so it
877
+ // can lack the current key. Its rows in the group go first, and an
878
+ // accepted resend that carries the distribution records a new row. The
879
+ // scope is the group only, as in the sender-key retry receipt of one
880
+ // Signal client.
881
+ await callbacks.invalidateSenderKeyHandoff(payload.groupId, device);
882
+ const current = await callbacks.currentGroupDistribution(payload.groupId);
883
+ const content = current === null
884
+ ? text
885
+ : ctx.contentAdapter.serializeContentBesideSenderKeyDistribution(text, current.groupId, current.distribution);
886
+ if (job !== undefined) {
887
+ const { failedEnvelopeId: _previous, ...rest } = job;
888
+ await ctx.storage.storeResendJob({
889
+ ...rest,
890
+ ...(target && { failedEnvelopeId: target.failedEnvelopeId }),
891
+ attempts: job.attempts + 1,
892
+ });
893
+ }
894
+ await callbacks.resend(device.userId, device.deviceId, content, {
895
+ timestamp: payload.clientTimestamp,
896
+ contentHint: payload.contentHint,
897
+ ...(target && { retry: target }),
898
+ ...(current && { senderKeyHandoff: handoffOf(current) }),
899
+ });
900
+ const responses = await ctx.resendableContent.countResend(payload.clientMessageId, device);
901
+ if (job !== undefined)
902
+ await ctx.storage.completeResendJob(job.jobId, 'posted');
903
+ ctx.logger.info('Resent logged group content after a retry request', {
904
+ category: 'E2EE',
905
+ data: {
906
+ recipient: `${device.userId}:${device.deviceId}`,
907
+ clientMessageId: payload.clientMessageId,
908
+ responses,
909
+ distribution: current !== null,
910
+ },
911
+ });
912
+ }
913
+ /**
914
+ * Run one pending resend job, as the resend job driver does after a restart,
915
+ * a reconnect or a failed post. The job ends as abandoned when it is older
916
+ * than `SEND_LOG_RESEND_JOB_TTL_MS`, when its logged entry or the row of
917
+ * the device is gone or expired, when the answer to its failed envelope
918
+ * ended, when the row has its maximum count of resends, when the requester
919
+ * is not a current member of the group, or when no session to the device
920
+ * can be made. A membership refusal of the job that holds the failed
921
+ * envelope also ends the answer with `membership-refused`. The membership
922
+ * is checked again here. A group state that waits for an update defers the
923
+ * job with `GroupResendDeferredError`. The job never resets a session: a
924
+ * session is made only when there is none. A deferral and any other error
925
+ * leave the job pending and propagate, so the driver runs it again later.
926
+ */
927
+ export async function runResendJob(ctx, jobId, responseState, callbacks) {
928
+ await withResendJob(ctx, jobId, async (job) => {
929
+ const abandon = async (reason) => {
930
+ ctx.logger.info('Abandoned a resend job', {
931
+ category: 'E2EE',
932
+ data: { jobId: job.jobId, clientMessageId: job.clientMessageId, reason },
933
+ });
934
+ await ctx.storage.completeResendJob(job.jobId, 'abandoned');
935
+ };
936
+ if (Date.now() - job.createdAt > SEND_LOG_RESEND_JOB_TTL_MS)
937
+ return abandon('expired');
938
+ const device = { userId: job.requesterUserId, deviceId: job.requesterDeviceId };
939
+ const entry = await ctx.resendableContent.entry(job.clientMessageId, device);
940
+ if (entry === null)
941
+ return abandon('no-content');
942
+ const retry = job.failedEnvelopeId === undefined
943
+ ? undefined
944
+ : {
945
+ failedEnvelopeId: job.failedEnvelopeId,
946
+ retryId: job.retryId,
947
+ requestEnvelopeId: job.requestEnvelopeId,
948
+ };
949
+ if (retry !== undefined) {
950
+ const stored = await getRetryResend(ctx.storage, device.userId, device.deviceId, retry.failedEnvelopeId);
951
+ if (stored?.terminal !== undefined) {
952
+ await emitRetryResendTerminal(ctx, stored);
953
+ return abandon('answer-ended');
954
+ }
955
+ }
956
+ const requester = {
957
+ requesterUserId: device.userId,
958
+ requesterDeviceId: device.deviceId,
959
+ failedTimestamp: entry.payload.clientTimestamp,
960
+ };
961
+ if (!(await admitsGroupResend(ctx, requester, entry.payload.groupId, responseState, callbacks))) {
962
+ if (retry !== undefined)
963
+ await endRetryResend(ctx, requester, retry, 'membership-refused');
964
+ return abandon('membership-refused');
965
+ }
966
+ if (reachedResendCap(ctx, entry))
967
+ return abandon('resend-limit');
968
+ if (!(await prepareAnswerSession(ctx, requester, callbacks, retry, null))) {
969
+ return abandon('no-session');
970
+ }
971
+ await postLoggedGroupContent(ctx, device, entry.payload, callbacks, retry && { ...retry, kind: 'resend' }, job);
972
+ });
973
+ }
974
+ /** The handoff that a resend with this distribution records on acceptance. */
975
+ function handoffOf(current) {
976
+ return {
977
+ groupId: current.groupId,
978
+ senderKeyId: current.distribution.senderKeyId,
979
+ generation: current.distribution.generation,
980
+ };
981
+ }
982
+ /**
983
+ * Answer a sender-key failure with no row and no record with the current
984
+ * sender-key distribution of the group alone. The caller checked the
985
+ * membership of the requester. The requester then decrypts the later group
986
+ * messages of this device, but not the failed one. It returns true when it
987
+ * posted the distribution.
988
+ */
989
+ async function resendCurrentDistribution(ctx, retryRequest, groupId, callbacks, retry) {
990
+ const current = await callbacks.currentGroupDistribution(groupId);
991
+ if (current === null) {
992
+ ctx.logger.info('No sender key to distribute for a group retry request', {
993
+ category: 'E2EE',
994
+ data: { groupId, failedTimestamp: retryRequest.failedTimestamp },
995
+ });
996
+ return false;
997
+ }
998
+ if (!(await prepareAnswerSession(ctx, retryRequest, callbacks, retry, null)))
999
+ return false;
1000
+ await callbacks.resend(retryRequest.requesterUserId, retryRequest.requesterDeviceId, ctx.contentAdapter.serializeSenderKeyDistributionText(current.groupId, current.distribution), {
1001
+ timestamp: retryRequest.failedTimestamp,
1002
+ ...(retry && { retry: { ...retry, kind: 'resend' } }),
1003
+ senderKeyHandoff: handoffOf(current),
1004
+ });
1005
+ ctx.logger.info('Sent the current sender-key distribution after a group retry request', {
1006
+ category: 'E2EE',
1007
+ data: {
1008
+ recipient: `${retryRequest.requesterUserId}:${retryRequest.requesterDeviceId}`,
1009
+ groupId: current.groupId,
1010
+ failedTimestamp: retryRequest.failedTimestamp,
1011
+ },
1012
+ });
1013
+ return true;
1014
+ }
1015
+ /**
1016
+ * True when the requester is a current member of the group. A group with no
1017
+ * source of current membership refuses every resend, and the refusal is
1018
+ * logged once for the group. A group whose state waits for an update throws
1019
+ * `GroupResendDeferredError`: the resend is deferred, not refused, so a
1020
+ * stored job stays pending and the retry request stays unacknowledged.
1021
+ */
1022
+ async function admitsGroupResend(ctx, retryRequest, groupId, responseState, callbacks) {
1023
+ const membership = await callbacks.groupMembership(groupId, retryRequest.requesterUserId);
1024
+ if (membership === 'member')
1025
+ return true;
1026
+ if (membership === 'unavailable') {
1027
+ ctx.logger.info('Deferring a group resend until the group state is current', {
1028
+ category: 'E2EE',
1029
+ data: {
1030
+ groupId,
1031
+ requester: `${retryRequest.requesterUserId}:${retryRequest.requesterDeviceId}`,
1032
+ failedTimestamp: retryRequest.failedTimestamp,
1033
+ behavior: 'RETRY_GROUP_RESEND_DEFERRED',
1034
+ },
1035
+ });
1036
+ throw new GroupResendDeferredError(groupId);
1037
+ }
1038
+ if (membership === 'no-source') {
1039
+ const rawGroupId = extractGroupId(groupId);
1040
+ if (!responseState.refusedGroupResends.has(rawGroupId)) {
1041
+ responseState.refusedGroupResends.add(rawGroupId);
1042
+ ctx.logger.warn('Refusing group resends: no source of current group membership', {
1043
+ category: 'E2EE',
1044
+ data: { groupId: rawGroupId, behavior: 'RETRY_GROUP_RESEND_REFUSED' },
1045
+ });
1046
+ }
1047
+ return false;
1048
+ }
1049
+ ctx.logger.warn('Refusing a group resend to a user who is not a current member', {
1050
+ category: 'E2EE',
1051
+ data: {
1052
+ groupId,
1053
+ requester: `${retryRequest.requesterUserId}:${retryRequest.requesterDeviceId}`,
1054
+ failedTimestamp: retryRequest.failedTimestamp,
1055
+ },
1056
+ });
1057
+ return false;
1058
+ }
1059
+ /**
1060
+ * Make the pairwise session to the requesting device ready for an answer.
1061
+ * With `reset`, the request carries the ratchet key of the failed message:
1062
+ * a session that did not advance since the sent message is archived and
1063
+ * replaced, as `sesameManager.handleRetryRequest` decides. A send log row
1064
+ * validates the request in place of a MessageRecord. Without `reset`, the
1065
+ * request names a sender-key failure: an existing session is used as it is,
1066
+ * and a new session is made only when there is none. It returns false when
1067
+ * the answer ends here.
1068
+ */
1069
+ async function prepareAnswerSession(ctx, retryRequest, callbacks, retry, reset) {
1070
+ const currentSession = await ctx.sesameManager.getActiveSession(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
1071
+ const address = ProtocolAddress.create(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
1072
+ // Compare our current ratchet key (DHs) against the DHs at send time.
1073
+ // If DHs advanced (DH ratchet occurred), session is healthy. Reuse it.
1074
+ // If DHs matches or is missing, session has not advanced. Needs fresh bundle.
1075
+ const currentRatchetKey = currentSession?.DHs?.publicKey;
1076
+ const usable = reset === null
1077
+ ? currentSession !== null && currentSession !== undefined
1078
+ : currentSession !== null &&
1079
+ currentSession !== undefined &&
1080
+ currentRatchetKey !== undefined &&
1081
+ currentRatchetKey !== reset.sentRatchetKey;
1082
+ if (usable) {
1083
+ ctx.logger.debug('Using existing different session for retry (no prekey fetch)', {
1084
+ category: 'E2EE',
1085
+ data: {
1086
+ address: ProtocolAddress.toString(address),
1087
+ activeRatchetKey: currentRatchetKey?.substring(0, 12) + '...',
1088
+ ...(reset && { storedRatchetKey: reset.sentRatchetKey.substring(0, 12) + '...' }),
1089
+ },
1090
+ });
1091
+ return true;
1092
+ }
1093
+ if (reset !== null) {
1094
+ // Archive old session and create new session
1095
+ const result = await ctx.sesameManager.handleRetryRequest(reset.request, reset.validated === 'send-log' ? { skipMessageRecordValidation: true } : undefined);
1096
+ if (!result.requiresNewSession) {
1097
+ ctx.logger.debug('Retry request handled without resend', {
1098
+ category: 'E2EE',
1099
+ data: { action: result.action },
1100
+ });
1101
+ return false;
1102
+ }
1103
+ }
1104
+ return await startAnswerSession(ctx, retryRequest, callbacks, retry, !currentSession);
1105
+ }
1106
+ /**
1107
+ * Start a new initiating session to the requesting device from a fresh
1108
+ * prekey bundle. When the requester has no bundle, the answer ends with
1109
+ * `missing-prekey`, and it returns false.
1110
+ */
1111
+ async function startAnswerSession(ctx, retryRequest, callbacks, retry, hadNoSession = false) {
1112
+ const address = ProtocolAddress.create(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
1113
+ // Fetch prekey bundle and create new initiating session
1114
+ if (!ctx.relay) {
1115
+ throw new Error('Relay not configured - cannot fetch prekey bundle');
1116
+ }
1117
+ const bundle = await ctx.relay.fetchPreKeyBundle(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
1118
+ if (!bundle) {
1119
+ ctx.logger.warn('Failed to fetch prekey bundle for retry', {
1120
+ category: 'E2EE',
1121
+ data: {
1122
+ userId: retryRequest.requesterUserId,
1123
+ deviceId: retryRequest.requesterDeviceId,
1124
+ },
1125
+ });
1126
+ // The requester has no prekey bundle, so no resend can reach it.
1127
+ // The answer ends, and the request envelope is acknowledged.
1128
+ if (retry !== undefined) {
1129
+ await endRetryResend(ctx, retryRequest, retry, 'missing-prekey');
1130
+ }
1131
+ return false;
1132
+ }
1133
+ await callbacks.establishSession(address, bundle);
1134
+ ctx.logger.debug('Created new session for retry', {
1135
+ category: 'E2EE',
1136
+ data: {
1137
+ address: ProtocolAddress.toString(address),
1138
+ reason: hadNoSession ? 'no_session' : 'orphaned',
1139
+ retryReason: retryRequest.reason,
1140
+ },
1141
+ });
1142
+ return true;
1143
+ }
596
1144
  /** A SesameError that refuses the retry request. A later attempt gets the same refusal. */
597
1145
  function isRetryRefusal(error) {
598
1146
  return (error instanceof SesameError &&