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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (583) hide show
  1. package/ADAPTERS.md +4 -4
  2. package/ARCHITECTURE.md +6 -8
  3. package/CHANGELOG.md +1315 -0
  4. package/README.md +1 -1
  5. package/SECURITY.md +2 -2
  6. package/TROUBLESHOOTING.md +1 -1
  7. package/client/README.md +70 -37
  8. package/device/README.md +39 -85
  9. package/dist/client/client.d.ts +334 -63
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +1168 -184
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/client/config.d.ts +40 -32
  14. package/dist/client/config.d.ts.map +1 -1
  15. package/dist/client/config.js +1 -1
  16. package/dist/client/config.js.map +1 -1
  17. package/dist/client/constants.d.ts +42 -8
  18. package/dist/client/constants.d.ts.map +1 -1
  19. package/dist/client/constants.js +48 -3
  20. package/dist/client/constants.js.map +1 -1
  21. package/dist/client/content-adapter.d.ts +80 -0
  22. package/dist/client/content-adapter.d.ts.map +1 -1
  23. package/dist/client/content-adapter.js +225 -12
  24. package/dist/client/content-adapter.js.map +1 -1
  25. package/dist/client/delivery-error.d.ts +150 -0
  26. package/dist/client/delivery-error.d.ts.map +1 -0
  27. package/dist/client/delivery-error.js +226 -0
  28. package/dist/client/delivery-error.js.map +1 -0
  29. package/dist/client/delivery-status.d.ts +32 -6
  30. package/dist/client/delivery-status.d.ts.map +1 -1
  31. package/dist/client/delivery-status.js +61 -13
  32. package/dist/client/delivery-status.js.map +1 -1
  33. package/dist/client/device-set-reconciliation.d.ts +196 -0
  34. package/dist/client/device-set-reconciliation.d.ts.map +1 -0
  35. package/dist/client/device-set-reconciliation.js +282 -0
  36. package/dist/client/device-set-reconciliation.js.map +1 -0
  37. package/dist/client/distribution-records.d.ts +29 -0
  38. package/dist/client/distribution-records.d.ts.map +1 -0
  39. package/dist/client/distribution-records.js +33 -0
  40. package/dist/client/distribution-records.js.map +1 -0
  41. package/dist/client/event-hooks.d.ts +280 -14
  42. package/dist/client/event-hooks.d.ts.map +1 -1
  43. package/dist/client/event-hooks.js +8 -0
  44. package/dist/client/event-hooks.js.map +1 -1
  45. package/dist/client/group-device-set.d.ts +47 -0
  46. package/dist/client/group-device-set.d.ts.map +1 -0
  47. package/dist/client/group-device-set.js +65 -0
  48. package/dist/client/group-device-set.js.map +1 -0
  49. package/dist/client/group-fetcher.d.ts +116 -0
  50. package/dist/client/group-fetcher.d.ts.map +1 -0
  51. package/dist/client/group-fetcher.js +598 -0
  52. package/dist/client/group-fetcher.js.map +1 -0
  53. package/dist/client/group-outbox.d.ts +172 -10
  54. package/dist/client/group-outbox.d.ts.map +1 -1
  55. package/dist/client/group-outbox.js +915 -74
  56. package/dist/client/group-outbox.js.map +1 -1
  57. package/dist/client/group-receive-authorization.d.ts +127 -4
  58. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  59. package/dist/client/group-receive-authorization.js +270 -20
  60. package/dist/client/group-receive-authorization.js.map +1 -1
  61. package/dist/client/group-sealed-sender.d.ts +3 -0
  62. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  63. package/dist/client/group-sealed-sender.js +1 -0
  64. package/dist/client/group-sealed-sender.js.map +1 -1
  65. package/dist/client/group-sender-key-operations.d.ts +14 -3
  66. package/dist/client/group-sender-key-operations.d.ts.map +1 -1
  67. package/dist/client/group-sender-key-operations.js +26 -5
  68. package/dist/client/group-sender-key-operations.js.map +1 -1
  69. package/dist/client/groups.d.ts +5 -5
  70. package/dist/client/groups.d.ts.map +1 -1
  71. package/dist/client/groups.js +5 -4
  72. package/dist/client/groups.js.map +1 -1
  73. package/dist/client/hosted-anonymous-delivery.d.ts +61 -9
  74. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  75. package/dist/client/hosted-anonymous-delivery.js +242 -48
  76. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  77. package/dist/client/hosted-assertion-id.d.ts +7 -0
  78. package/dist/client/hosted-assertion-id.d.ts.map +1 -0
  79. package/dist/client/hosted-assertion-id.js +51 -0
  80. package/dist/client/hosted-assertion-id.js.map +1 -0
  81. package/dist/client/hosted-mailbox-subscription.d.ts +34 -2
  82. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  83. package/dist/client/hosted-mailbox-subscription.js +87 -17
  84. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  85. package/dist/client/hosted-push.d.ts +22 -4
  86. package/dist/client/hosted-push.d.ts.map +1 -1
  87. package/dist/client/hosted-push.js +75 -22
  88. package/dist/client/hosted-push.js.map +1 -1
  89. package/dist/client/hosted-transport.d.ts +22 -28
  90. package/dist/client/hosted-transport.d.ts.map +1 -1
  91. package/dist/client/hosted-transport.js +115 -55
  92. package/dist/client/hosted-transport.js.map +1 -1
  93. package/dist/client/hosted.d.ts +10 -4
  94. package/dist/client/hosted.d.ts.map +1 -1
  95. package/dist/client/hosted.js +10 -4
  96. package/dist/client/hosted.js.map +1 -1
  97. package/dist/client/index.d.ts +5 -3
  98. package/dist/client/index.d.ts.map +1 -1
  99. package/dist/client/index.js +2 -0
  100. package/dist/client/index.js.map +1 -1
  101. package/dist/client/messages.d.ts +25 -3
  102. package/dist/client/messages.d.ts.map +1 -1
  103. package/dist/client/messages.js +111 -20
  104. package/dist/client/messages.js.map +1 -1
  105. package/dist/client/receive-admission.d.ts +58 -0
  106. package/dist/client/receive-admission.d.ts.map +1 -0
  107. package/dist/client/receive-admission.js +78 -0
  108. package/dist/client/receive-admission.js.map +1 -0
  109. package/dist/client/receive-expiry.d.ts +31 -0
  110. package/dist/client/receive-expiry.d.ts.map +1 -0
  111. package/dist/client/receive-expiry.js +35 -0
  112. package/dist/client/receive-expiry.js.map +1 -0
  113. package/dist/client/receive-hook-bound.d.ts +50 -0
  114. package/dist/client/receive-hook-bound.d.ts.map +1 -0
  115. package/dist/client/receive-hook-bound.js +115 -0
  116. package/dist/client/receive-hook-bound.js.map +1 -0
  117. package/dist/client/receive-queue.d.ts +299 -0
  118. package/dist/client/receive-queue.d.ts.map +1 -0
  119. package/dist/client/receive-queue.js +1420 -0
  120. package/dist/client/receive-queue.js.map +1 -0
  121. package/dist/client/receive-work-seed.d.ts +54 -0
  122. package/dist/client/receive-work-seed.d.ts.map +1 -0
  123. package/dist/client/receive-work-seed.js +116 -0
  124. package/dist/client/receive-work-seed.js.map +1 -0
  125. package/dist/client/recovery-driver.d.ts +25 -0
  126. package/dist/client/recovery-driver.d.ts.map +1 -0
  127. package/dist/client/recovery-driver.js +121 -0
  128. package/dist/client/recovery-driver.js.map +1 -0
  129. package/dist/client/relay-acceptance.d.ts +20 -7
  130. package/dist/client/relay-acceptance.d.ts.map +1 -1
  131. package/dist/client/relay-acceptance.js +30 -12
  132. package/dist/client/relay-acceptance.js.map +1 -1
  133. package/dist/client/relay-device-refusal.d.ts +18 -0
  134. package/dist/client/relay-device-refusal.d.ts.map +1 -1
  135. package/dist/client/relay-device-refusal.js +31 -0
  136. package/dist/client/relay-device-refusal.js.map +1 -1
  137. package/dist/client/relay-sealed-route.d.ts +36 -0
  138. package/dist/client/relay-sealed-route.d.ts.map +1 -0
  139. package/dist/client/relay-sealed-route.js +45 -0
  140. package/dist/client/relay-sealed-route.js.map +1 -0
  141. package/dist/client/relay-subscription.d.ts +56 -13
  142. package/dist/client/relay-subscription.d.ts.map +1 -1
  143. package/dist/client/relay-subscription.js +193 -123
  144. package/dist/client/relay-subscription.js.map +1 -1
  145. package/dist/client/resendable-content.d.ts +98 -0
  146. package/dist/client/resendable-content.d.ts.map +1 -0
  147. package/dist/client/resendable-content.js +136 -0
  148. package/dist/client/resendable-content.js.map +1 -0
  149. package/dist/client/retry-family.d.ts +57 -10
  150. package/dist/client/retry-family.d.ts.map +1 -1
  151. package/dist/client/retry-family.js +54 -12
  152. package/dist/client/retry-family.js.map +1 -1
  153. package/dist/client/retry-request-envelope.d.ts +107 -8
  154. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  155. package/dist/client/retry-request-envelope.js +172 -23
  156. package/dist/client/retry-request-envelope.js.map +1 -1
  157. package/dist/client/retry-request-lifecycle.d.ts +70 -14
  158. package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
  159. package/dist/client/retry-request-lifecycle.js +162 -32
  160. package/dist/client/retry-request-lifecycle.js.map +1 -1
  161. package/dist/client/retry-terminal-recovery.d.ts +100 -0
  162. package/dist/client/retry-terminal-recovery.d.ts.map +1 -0
  163. package/dist/client/retry-terminal-recovery.js +164 -0
  164. package/dist/client/retry-terminal-recovery.js.map +1 -0
  165. package/dist/client/retry-utils.d.ts +27 -0
  166. package/dist/client/retry-utils.d.ts.map +1 -1
  167. package/dist/client/retry-utils.js +46 -0
  168. package/dist/client/retry-utils.js.map +1 -1
  169. package/dist/client/retry.d.ts +100 -12
  170. package/dist/client/retry.d.ts.map +1 -1
  171. package/dist/client/retry.js +619 -116
  172. package/dist/client/retry.js.map +1 -1
  173. package/dist/client/sealed-sender.d.ts +23 -6
  174. package/dist/client/sealed-sender.d.ts.map +1 -1
  175. package/dist/client/sealed-sender.js +30 -6
  176. package/dist/client/sealed-sender.js.map +1 -1
  177. package/dist/client/sessions.d.ts +2 -2
  178. package/dist/client/sessions.js +2 -2
  179. package/dist/client/signal-service-cipher.d.ts +726 -19
  180. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  181. package/dist/client/signal-service-cipher.js +2260 -342
  182. package/dist/client/signal-service-cipher.js.map +1 -1
  183. package/dist/client/state.d.ts +5 -0
  184. package/dist/client/state.d.ts.map +1 -1
  185. package/dist/client/state.js +11 -1
  186. package/dist/client/state.js.map +1 -1
  187. package/dist/client/storage-protection.d.ts +64 -0
  188. package/dist/client/storage-protection.d.ts.map +1 -0
  189. package/dist/client/storage-protection.js +150 -0
  190. package/dist/client/storage-protection.js.map +1 -0
  191. package/dist/client/types.d.ts +149 -15
  192. package/dist/client/types.d.ts.map +1 -1
  193. package/dist/client/types.js +1 -1
  194. package/dist/client/types.js.map +1 -1
  195. package/dist/device/constants.d.ts +0 -5
  196. package/dist/device/constants.d.ts.map +1 -1
  197. package/dist/device/constants.js +0 -5
  198. package/dist/device/constants.js.map +1 -1
  199. package/dist/device/expo/index.d.ts +4 -17
  200. package/dist/device/expo/index.d.ts.map +1 -1
  201. package/dist/device/expo/index.js +4 -23
  202. package/dist/device/expo/index.js.map +1 -1
  203. package/dist/device/index.d.ts +0 -2
  204. package/dist/device/index.d.ts.map +1 -1
  205. package/dist/device/index.js +0 -7
  206. package/dist/device/index.js.map +1 -1
  207. package/dist/device/lifecycle/manager.d.ts +5 -4
  208. package/dist/device/lifecycle/manager.d.ts.map +1 -1
  209. package/dist/device/lifecycle/manager.js +16 -16
  210. package/dist/device/lifecycle/manager.js.map +1 -1
  211. package/dist/device/lifecycle/types.d.ts +2 -2
  212. package/dist/device/lifecycle/types.d.ts.map +1 -1
  213. package/dist/device/react-native/index.d.ts +4 -15
  214. package/dist/device/react-native/index.d.ts.map +1 -1
  215. package/dist/device/react-native/index.js +4 -21
  216. package/dist/device/react-native/index.js.map +1 -1
  217. package/dist/device/types.d.ts +1 -1
  218. package/dist/groups/index.d.ts +1 -1
  219. package/dist/groups/index.d.ts.map +1 -1
  220. package/dist/index.d.ts +8 -6
  221. package/dist/index.d.ts.map +1 -1
  222. package/dist/index.js +2 -1
  223. package/dist/index.js.map +1 -1
  224. package/dist/internal/crypto/ec/x25519-validation.d.ts +0 -1
  225. package/dist/internal/crypto/ec/x25519-validation.d.ts.map +1 -1
  226. package/dist/internal/crypto/ec/x25519-validation.js +0 -1
  227. package/dist/internal/crypto/ec/x25519-validation.js.map +1 -1
  228. package/dist/internal/crypto/validation.d.ts +2 -2
  229. package/dist/internal/groups/index.d.ts +1 -0
  230. package/dist/internal/groups/index.d.ts.map +1 -1
  231. package/dist/internal/groups/index.js +1 -0
  232. package/dist/internal/groups/index.js.map +1 -1
  233. package/dist/internal/groups/manager.d.ts +37 -16
  234. package/dist/internal/groups/manager.d.ts.map +1 -1
  235. package/dist/internal/groups/manager.js +46 -1
  236. package/dist/internal/groups/manager.js.map +1 -1
  237. package/dist/internal/groups/receive-record.d.ts +78 -0
  238. package/dist/internal/groups/receive-record.d.ts.map +1 -0
  239. package/dist/internal/groups/receive-record.js +43 -0
  240. package/dist/internal/groups/receive-record.js.map +1 -0
  241. package/dist/internal/groups/sdk-store.d.ts +27 -3
  242. package/dist/internal/groups/sdk-store.d.ts.map +1 -1
  243. package/dist/internal/groups/sdk-store.js +151 -19
  244. package/dist/internal/groups/sdk-store.js.map +1 -1
  245. package/dist/internal/groups/wire.d.ts +12 -1
  246. package/dist/internal/groups/wire.d.ts.map +1 -1
  247. package/dist/internal/groups/wire.js +36 -0
  248. package/dist/internal/groups/wire.js.map +1 -1
  249. package/dist/internal/manager/index.d.ts +1 -1
  250. package/dist/internal/manager/manager.d.ts +20 -19
  251. package/dist/internal/manager/manager.d.ts.map +1 -1
  252. package/dist/internal/manager/manager.js +56 -39
  253. package/dist/internal/manager/manager.js.map +1 -1
  254. package/dist/internal/protocol/double-ratchet/chains.d.ts +4 -18
  255. package/dist/internal/protocol/double-ratchet/chains.d.ts.map +1 -1
  256. package/dist/internal/protocol/double-ratchet/chains.js +23 -74
  257. package/dist/internal/protocol/double-ratchet/chains.js.map +1 -1
  258. package/dist/internal/protocol/double-ratchet/index.d.ts +1 -1
  259. package/dist/internal/protocol/double-ratchet/index.d.ts.map +1 -1
  260. package/dist/internal/protocol/double-ratchet/index.js +1 -1
  261. package/dist/internal/protocol/double-ratchet/index.js.map +1 -1
  262. package/dist/internal/protocol/double-ratchet/ratchet.d.ts +5 -7
  263. package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
  264. package/dist/internal/protocol/double-ratchet/ratchet.js +4 -6
  265. package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
  266. package/dist/internal/protocol/pqxdh/pqxdh.d.ts.map +1 -1
  267. package/dist/internal/protocol/pqxdh/pqxdh.js +2 -1
  268. package/dist/internal/protocol/pqxdh/pqxdh.js.map +1 -1
  269. package/dist/internal/protocol/sealed-sender/types.d.ts +6 -8
  270. package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
  271. package/dist/internal/protocol/sealed-sender/types.js +8 -9
  272. package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
  273. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts +110 -0
  274. package/dist/internal/protocol/sender-keys/handoff-ledger.d.ts.map +1 -0
  275. package/dist/internal/protocol/sender-keys/handoff-ledger.js +124 -0
  276. package/dist/internal/protocol/sender-keys/handoff-ledger.js.map +1 -0
  277. package/dist/internal/protocol/sender-keys/manager.d.ts +71 -62
  278. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  279. package/dist/internal/protocol/sender-keys/manager.js +228 -175
  280. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  281. package/dist/internal/protocol/spqr/index.d.ts +2 -2
  282. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  283. package/dist/internal/protocol/spqr/index.js +2 -2
  284. package/dist/internal/protocol/spqr/index.js.map +1 -1
  285. package/dist/internal/protocol/spqr/serialize.d.ts +9 -1
  286. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  287. package/dist/internal/protocol/spqr/serialize.js +56 -16
  288. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  289. package/dist/internal/protocol/spqr/spqr.d.ts +1 -14
  290. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  291. package/dist/internal/protocol/spqr/spqr.js +54 -42
  292. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  293. package/dist/internal/protocol/spqr/validate.d.ts +26 -6
  294. package/dist/internal/protocol/spqr/validate.d.ts.map +1 -1
  295. package/dist/internal/protocol/spqr/validate.js +49 -21
  296. package/dist/internal/protocol/spqr/validate.js.map +1 -1
  297. package/dist/internal/sesame/index.d.ts +1 -1
  298. package/dist/internal/sesame/index.d.ts.map +1 -1
  299. package/dist/internal/sesame/index.js.map +1 -1
  300. package/dist/internal/sesame/manager.d.ts +66 -13
  301. package/dist/internal/sesame/manager.d.ts.map +1 -1
  302. package/dist/internal/sesame/manager.js +221 -87
  303. package/dist/internal/sesame/manager.js.map +1 -1
  304. package/dist/internal/sesame/types.d.ts +95 -17
  305. package/dist/internal/sesame/types.d.ts.map +1 -1
  306. package/dist/internal/sesame/types.js +17 -0
  307. package/dist/internal/sesame/types.js.map +1 -1
  308. package/dist/internal/session/builder.d.ts +5 -5
  309. package/dist/internal/session/builder.d.ts.map +1 -1
  310. package/dist/internal/session/builder.js +12 -17
  311. package/dist/internal/session/builder.js.map +1 -1
  312. package/dist/internal/session/cipher.d.ts +13 -11
  313. package/dist/internal/session/cipher.d.ts.map +1 -1
  314. package/dist/internal/session/cipher.js +40 -22
  315. package/dist/internal/session/cipher.js.map +1 -1
  316. package/dist/internal/session/factory.d.ts +5 -5
  317. package/dist/internal/session/factory.d.ts.map +1 -1
  318. package/dist/internal/session/factory.js +4 -4
  319. package/dist/internal/session/factory.js.map +1 -1
  320. package/dist/internal/session/handshake.d.ts +14 -16
  321. package/dist/internal/session/handshake.d.ts.map +1 -1
  322. package/dist/internal/session/handshake.js +18 -75
  323. package/dist/internal/session/handshake.js.map +1 -1
  324. package/dist/internal/session/index.d.ts +1 -1
  325. package/dist/internal/session/index.js +1 -1
  326. package/dist/internal/session/record-locks.d.ts +17 -6
  327. package/dist/internal/session/record-locks.d.ts.map +1 -1
  328. package/dist/internal/session/record-locks.js +43 -7
  329. package/dist/internal/session/record-locks.js.map +1 -1
  330. package/dist/internal/session/session-resolver.d.ts +1 -1
  331. package/dist/internal/session/session-resolver.js +1 -1
  332. package/dist/internal/session/state.d.ts +2 -2
  333. package/dist/internal/session/state.js +1 -1
  334. package/dist/internal/session/types.d.ts +4 -12
  335. package/dist/internal/session/types.d.ts.map +1 -1
  336. package/dist/internal/session/types.js +1 -1
  337. package/dist/keys/generation.d.ts +2 -2
  338. package/dist/keys/generation.js +2 -2
  339. package/dist/keys/types.d.ts +5 -5
  340. package/dist/keys/types.d.ts.map +1 -1
  341. package/dist/keys/types.js +1 -1
  342. package/dist/layers.d.ts +1 -1
  343. package/dist/layers.js +2 -2
  344. package/dist/layers.js.map +1 -1
  345. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  346. package/dist/local/store/expo/adapter.js +12 -8
  347. package/dist/local/store/expo/adapter.js.map +1 -1
  348. package/dist/local/store/key-value/adapter.d.ts +76 -10
  349. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  350. package/dist/local/store/key-value/adapter.js +367 -61
  351. package/dist/local/store/key-value/adapter.js.map +1 -1
  352. package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
  353. package/dist/local/store/key-value/backend-conformance.js +74 -0
  354. package/dist/local/store/key-value/backend-conformance.js.map +1 -1
  355. package/dist/local/store/key-value/batch.d.ts +2 -0
  356. package/dist/local/store/key-value/batch.d.ts.map +1 -1
  357. package/dist/local/store/key-value/batch.js +26 -0
  358. package/dist/local/store/key-value/batch.js.map +1 -1
  359. package/dist/local/store/key-value/receive-work.d.ts +55 -0
  360. package/dist/local/store/key-value/receive-work.d.ts.map +1 -0
  361. package/dist/local/store/key-value/receive-work.js +162 -0
  362. package/dist/local/store/key-value/receive-work.js.map +1 -0
  363. package/dist/local/store/key-value/send-log.d.ts +61 -0
  364. package/dist/local/store/key-value/send-log.d.ts.map +1 -0
  365. package/dist/local/store/key-value/send-log.js +430 -0
  366. package/dist/local/store/key-value/send-log.js.map +1 -0
  367. package/dist/local/store/key-value/sender-key-handoff.d.ts +68 -0
  368. package/dist/local/store/key-value/sender-key-handoff.d.ts.map +1 -0
  369. package/dist/local/store/key-value/sender-key-handoff.js +189 -0
  370. package/dist/local/store/key-value/sender-key-handoff.js.map +1 -0
  371. package/dist/local/store/key-value/storage.d.ts +15 -0
  372. package/dist/local/store/key-value/storage.d.ts.map +1 -1
  373. package/dist/local/store/keyed-index.d.ts +23 -0
  374. package/dist/local/store/keyed-index.d.ts.map +1 -0
  375. package/dist/local/store/keyed-index.js +41 -0
  376. package/dist/local/store/keyed-index.js.map +1 -0
  377. package/dist/local/store/memory/adapter.d.ts +44 -12
  378. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  379. package/dist/local/store/memory/adapter.js +197 -46
  380. package/dist/local/store/memory/adapter.js.map +1 -1
  381. package/dist/local/store/memory/send-log.d.ts +42 -0
  382. package/dist/local/store/memory/send-log.d.ts.map +1 -0
  383. package/dist/local/store/memory/send-log.js +190 -0
  384. package/dist/local/store/memory/send-log.js.map +1 -0
  385. package/dist/local/store/node/adapter.d.ts.map +1 -1
  386. package/dist/local/store/node/adapter.js +8 -6
  387. package/dist/local/store/node/adapter.js.map +1 -1
  388. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  389. package/dist/local/store/react-native/adapter.js +12 -8
  390. package/dist/local/store/react-native/adapter.js.map +1 -1
  391. package/dist/local/store/receive-work.d.ts +87 -0
  392. package/dist/local/store/receive-work.d.ts.map +1 -0
  393. package/dist/local/store/receive-work.js +204 -0
  394. package/dist/local/store/receive-work.js.map +1 -0
  395. package/dist/local/store/received-content.d.ts +3 -3
  396. package/dist/local/store/received-content.d.ts.map +1 -1
  397. package/dist/local/store/received-content.js +2 -11
  398. package/dist/local/store/received-content.js.map +1 -1
  399. package/dist/local/store/reliability.d.ts +317 -18
  400. package/dist/local/store/reliability.d.ts.map +1 -1
  401. package/dist/local/store/reliability.js +371 -46
  402. package/dist/local/store/reliability.js.map +1 -1
  403. package/dist/local/store/send-log-order.d.ts +15 -0
  404. package/dist/local/store/send-log-order.d.ts.map +1 -0
  405. package/dist/local/store/send-log-order.js +24 -0
  406. package/dist/local/store/send-log-order.js.map +1 -0
  407. package/dist/local/store/sender-key-handoff-index.d.ts +38 -0
  408. package/dist/local/store/sender-key-handoff-index.d.ts.map +1 -0
  409. package/dist/local/store/sender-key-handoff-index.js +101 -0
  410. package/dist/local/store/sender-key-handoff-index.js.map +1 -0
  411. package/dist/local/store/sender-key-handoff-table.d.ts +29 -0
  412. package/dist/local/store/sender-key-handoff-table.d.ts.map +1 -0
  413. package/dist/local/store/sender-key-handoff-table.js +97 -0
  414. package/dist/local/store/sender-key-handoff-table.js.map +1 -0
  415. package/dist/local/store/sqlite/encryption.d.ts +8 -1
  416. package/dist/local/store/sqlite/encryption.d.ts.map +1 -1
  417. package/dist/local/store/sqlite/encryption.js +9 -0
  418. package/dist/local/store/sqlite/encryption.js.map +1 -1
  419. package/dist/local/store/sqlite/key-storage/index.d.ts +25 -4
  420. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  421. package/dist/local/store/sqlite/key-storage/index.js +68 -7
  422. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  423. package/dist/local/store/sqlite/key-storage/message-records.d.ts +16 -4
  424. package/dist/local/store/sqlite/key-storage/message-records.d.ts.map +1 -1
  425. package/dist/local/store/sqlite/key-storage/message-records.js +49 -6
  426. package/dist/local/store/sqlite/key-storage/message-records.js.map +1 -1
  427. package/dist/local/store/sqlite/key-storage/metadata.d.ts +8 -7
  428. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  429. package/dist/local/store/sqlite/key-storage/metadata.js +17 -15
  430. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  431. package/dist/local/store/sqlite/key-storage/receive-work.d.ts +27 -0
  432. package/dist/local/store/sqlite/key-storage/receive-work.d.ts.map +1 -0
  433. package/dist/local/store/sqlite/key-storage/receive-work.js +98 -0
  434. package/dist/local/store/sqlite/key-storage/receive-work.js.map +1 -0
  435. package/dist/local/store/sqlite/key-storage/send-log.d.ts +27 -0
  436. package/dist/local/store/sqlite/key-storage/send-log.d.ts.map +1 -0
  437. package/dist/local/store/sqlite/key-storage/send-log.js +178 -0
  438. package/dist/local/store/sqlite/key-storage/send-log.js.map +1 -0
  439. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts +27 -0
  440. package/dist/local/store/sqlite/key-storage/sender-key-handoff.d.ts.map +1 -0
  441. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js +75 -0
  442. package/dist/local/store/sqlite/key-storage/sender-key-handoff.js.map +1 -0
  443. package/dist/local/store/sqlite/key-storage/session-trust.d.ts +2 -2
  444. package/dist/local/store/sqlite/key-storage/session-trust.js +5 -5
  445. package/dist/local/store/sqlite/key-storage/session-trust.js.map +1 -1
  446. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  447. package/dist/local/store/sqlite/migrations.js +101 -0
  448. package/dist/local/store/sqlite/migrations.js.map +1 -1
  449. package/dist/local/store/sqlite/models/index.d.ts +2 -1
  450. package/dist/local/store/sqlite/models/index.d.ts.map +1 -1
  451. package/dist/local/store/sqlite/models/index.js +5 -1
  452. package/dist/local/store/sqlite/models/index.js.map +1 -1
  453. package/dist/local/store/sqlite/models/message-record.d.ts +15 -0
  454. package/dist/local/store/sqlite/models/message-record.d.ts.map +1 -1
  455. package/dist/local/store/sqlite/models/message-record.js +24 -0
  456. package/dist/local/store/sqlite/models/message-record.js.map +1 -1
  457. package/dist/local/store/sqlite/models/send-log.d.ts +51 -0
  458. package/dist/local/store/sqlite/models/send-log.d.ts.map +1 -0
  459. package/dist/local/store/sqlite/models/send-log.js +206 -0
  460. package/dist/local/store/sqlite/models/send-log.js.map +1 -0
  461. package/dist/local/store/sqlite/open-store.d.ts +9 -1
  462. package/dist/local/store/sqlite/open-store.d.ts.map +1 -1
  463. package/dist/local/store/sqlite/open-store.js +20 -1
  464. package/dist/local/store/sqlite/open-store.js.map +1 -1
  465. package/dist/local/store/sqlite/schema.d.ts +34 -1
  466. package/dist/local/store/sqlite/schema.d.ts.map +1 -1
  467. package/dist/local/store/sqlite/schema.js +14 -0
  468. package/dist/local/store/sqlite/schema.js.map +1 -1
  469. package/dist/local/store/sqlite/store.d.ts +61 -11
  470. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  471. package/dist/local/store/sqlite/store.js +191 -27
  472. package/dist/local/store/sqlite/store.js.map +1 -1
  473. package/dist/local/store/web/adapter.d.ts +76 -8
  474. package/dist/local/store/web/adapter.d.ts.map +1 -1
  475. package/dist/local/store/web/adapter.js +579 -127
  476. package/dist/local/store/web/adapter.js.map +1 -1
  477. package/dist/local/store/web/receive-work.d.ts +57 -0
  478. package/dist/local/store/web/receive-work.d.ts.map +1 -0
  479. package/dist/local/store/web/receive-work.js +99 -0
  480. package/dist/local/store/web/receive-work.js.map +1 -0
  481. package/dist/local/store/web/send-log.d.ts +92 -0
  482. package/dist/local/store/web/send-log.d.ts.map +1 -0
  483. package/dist/local/store/web/send-log.js +267 -0
  484. package/dist/local/store/web/send-log.js.map +1 -0
  485. package/dist/local/store/web/sender-key-handoff.d.ts +81 -0
  486. package/dist/local/store/web/sender-key-handoff.d.ts.map +1 -0
  487. package/dist/local/store/web/sender-key-handoff.js +156 -0
  488. package/dist/local/store/web/sender-key-handoff.js.map +1 -0
  489. package/dist/local/store/web-sqlite/adapter.d.ts +2 -0
  490. package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -1
  491. package/dist/local/store/web-sqlite/adapter.js +12 -6
  492. package/dist/local/store/web-sqlite/adapter.js.map +1 -1
  493. package/dist/local/vault/custody.d.ts +8 -0
  494. package/dist/local/vault/custody.d.ts.map +1 -0
  495. package/dist/local/vault/custody.js +9 -0
  496. package/dist/local/vault/custody.js.map +1 -0
  497. package/dist/local/vault/electron-safe-storage.d.ts +3 -1
  498. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  499. package/dist/local/vault/electron-safe-storage.js +2 -0
  500. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  501. package/dist/local/vault/expo-secure-store.d.ts +3 -1
  502. package/dist/local/vault/expo-secure-store.d.ts.map +1 -1
  503. package/dist/local/vault/expo-secure-store.js +2 -0
  504. package/dist/local/vault/expo-secure-store.js.map +1 -1
  505. package/dist/local/vault/indexed-db.d.ts +3 -1
  506. package/dist/local/vault/indexed-db.d.ts.map +1 -1
  507. package/dist/local/vault/indexed-db.js +2 -0
  508. package/dist/local/vault/indexed-db.js.map +1 -1
  509. package/dist/local/vault/react-native-keychain.d.ts +3 -1
  510. package/dist/local/vault/react-native-keychain.d.ts.map +1 -1
  511. package/dist/local/vault/react-native-keychain.js +2 -0
  512. package/dist/local/vault/react-native-keychain.js.map +1 -1
  513. package/dist/remote/relay/device-set.d.ts +94 -0
  514. package/dist/remote/relay/device-set.d.ts.map +1 -0
  515. package/dist/remote/relay/device-set.js +156 -0
  516. package/dist/remote/relay/device-set.js.map +1 -0
  517. package/dist/remote/relay/types.d.ts +92 -107
  518. package/dist/remote/relay/types.d.ts.map +1 -1
  519. package/dist/safety/core.d.ts +15 -6
  520. package/dist/safety/core.d.ts.map +1 -1
  521. package/dist/safety/core.js +41 -27
  522. package/dist/safety/core.js.map +1 -1
  523. package/dist/safety/index.d.ts +2 -1
  524. package/dist/safety/index.d.ts.map +1 -1
  525. package/dist/safety/index.js +12 -18
  526. package/dist/safety/index.js.map +1 -1
  527. package/dist/types/api.d.ts +707 -62
  528. package/dist/types/api.d.ts.map +1 -1
  529. package/dist/types/errors.d.ts +14 -33
  530. package/dist/types/errors.d.ts.map +1 -1
  531. package/dist/types/errors.js +14 -24
  532. package/dist/types/errors.js.map +1 -1
  533. package/dist/types/messages.d.ts +2 -2
  534. package/dist/types/messages.js +1 -1
  535. package/dist/types/protocol-config.d.ts +175 -42
  536. package/dist/types/protocol-config.d.ts.map +1 -1
  537. package/dist/types/protocol-config.js +19 -38
  538. package/dist/types/protocol-config.js.map +1 -1
  539. package/dist/types/protocol-constants.d.ts +6 -6
  540. package/dist/types/protocol-constants.js +6 -6
  541. package/dist/types/session.d.ts +7 -7
  542. package/dist/types/session.d.ts.map +1 -1
  543. package/dist/types/session.js +39 -21
  544. package/dist/types/session.js.map +1 -1
  545. package/dist/username/link.d.ts +2 -2
  546. package/dist/username/link.js +2 -2
  547. package/dist/utils/origin-lock.d.ts +45 -0
  548. package/dist/utils/origin-lock.d.ts.map +1 -0
  549. package/dist/utils/origin-lock.js +80 -0
  550. package/dist/utils/origin-lock.js.map +1 -0
  551. package/docs/ASSURANCE.md +6 -6
  552. package/docs/CLIENT_COMPOSITION.md +2 -2
  553. package/docs/DEVIATIONS.md +677 -182
  554. package/docs/E2EE.md +1 -1
  555. package/docs/ERROR_HANDLING.md +165 -2
  556. package/docs/GETTING_STARTED.md +7 -4
  557. package/docs/INTERFACES.md +1 -1
  558. package/docs/PACKAGE_SURFACE.md +6 -5
  559. package/docs/PROTOCOL_POLICY.md +102 -22
  560. package/docs/RECIPES.md +3 -15
  561. package/docs/SECURITY.md +90 -5
  562. package/keys/README.md +3 -3
  563. package/local/store/README.md +78 -14
  564. package/local/store/key-value/README.md +14 -3
  565. package/local/store/node/README.md +8 -3
  566. package/local/store/web/README.md +9 -0
  567. package/local/store/web-sqlite/README.md +14 -2
  568. package/local/vault/README.md +21 -0
  569. package/package.json +1 -6
  570. package/remote/README.md +0 -1
  571. package/remote/relay/README.md +2 -2
  572. package/dist/device/provisioning.d.ts +0 -242
  573. package/dist/device/provisioning.d.ts.map +0 -1
  574. package/dist/device/provisioning.js +0 -421
  575. package/dist/device/provisioning.js.map +0 -1
  576. package/dist/internal/protocol/x3dh/index.d.ts +0 -15
  577. package/dist/internal/protocol/x3dh/index.d.ts.map +0 -1
  578. package/dist/internal/protocol/x3dh/index.js +0 -13
  579. package/dist/internal/protocol/x3dh/index.js.map +0 -1
  580. package/dist/internal/protocol/x3dh/x3dh.d.ts +0 -131
  581. package/dist/internal/protocol/x3dh/x3dh.d.ts.map +0 -1
  582. package/dist/internal/protocol/x3dh/x3dh.js +0 -261
  583. package/dist/internal/protocol/x3dh/x3dh.js.map +0 -1
@@ -7,14 +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';
10
+ import { determineRetryReason, retryFailedEnvelope } from './retry-utils.js';
11
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 { base64ToBytes, bytesToString } from '../internal/crypto/utils.js';
17
+ import { extractGroupId } from '../internal/groups/group-id.js';
18
+ import { GroupResendDeferredError } from './group-receive-authorization.js';
16
19
  import { getRetryResend, RELIABILITY_RECORD_TTL_MS, retryRequestAttempt, storeRetryResend, } from '../local/store/reliability.js';
17
- import { callHook } from './event-hooks.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
+ }
18
30
  // Max 10 retry requests per sender per 3-hour window
19
31
  export const MAX_RETRY_REQUESTS_PER_SENDER = 10;
20
32
  export const RETRY_REQUEST_WINDOW_MS = 3 * 60 * 60 * 1000; // 3 hours
@@ -97,9 +109,8 @@ async function sendNullMessageForRetryReset(callbacks, retryRequest, ctx, retry)
97
109
  }
98
110
  /**
99
111
  * Store the terminal state of the answer to a request attempt, call the
100
- * `onRetryTerminal` hook, and then store the state as emitted. A
101
- * RelayWorkStopped from the hook propagates and leaves the state not
102
- * emitted, so a redelivery of the request calls the hook again.
112
+ * `onRetryTerminal` hook, and then store the state as emitted, as
113
+ * `emitRetryResendTerminal` tells.
103
114
  */
104
115
  async function endRetryResend(ctx, retryRequest, retry, terminalClass) {
105
116
  const ended = {
@@ -113,14 +124,21 @@ async function endRetryResend(ctx, retryRequest, retry, terminalClass) {
113
124
  await storeRetryResend(ctx.storage, ended);
114
125
  await emitRetryResendTerminal(ctx, ended);
115
126
  }
116
- /** Call the hook for a terminal answer that is not emitted, and store it as emitted. */
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
+ */
117
135
  async function emitRetryResendTerminal(ctx, ended) {
118
136
  if (ended.terminal.emitted)
119
137
  return;
120
- await callHook(ctx.hooks, 'onRetryTerminal', {
121
- class: ended.terminal.class,
122
- failedEnvelopeId: ended.failedEnvelopeId,
123
- });
138
+ const hook = ctx.hooks?.onRetryTerminal;
139
+ if (hook) {
140
+ await hook({ class: ended.terminal.class, failedEnvelopeId: ended.failedEnvelopeId });
141
+ }
124
142
  await storeRetryResend(ctx.storage, {
125
143
  ...ended,
126
144
  terminal: { ...ended.terminal, emitted: true },
@@ -150,13 +168,39 @@ async function replayStoredResend(ctx, retryRequest, record, callbacks, retry) {
150
168
  });
151
169
  return posted;
152
170
  }
153
- // 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.
154
172
  const plaintext = record?.recipientUserId === requesterUserId ? record.plaintext : null;
155
173
  return await callbacks.resend(requesterUserId, requesterDeviceId, plaintext, {
156
174
  timestamp: record?.timestamp ?? retryRequest.failedTimestamp,
157
175
  retry: { ...retry, kind: 'resend' },
158
176
  });
159
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
+ }
160
204
  /**
161
205
  * Get session key string from userId and deviceId
162
206
  */
@@ -232,8 +276,15 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
232
276
  const retryReason = determineRetryReason(error);
233
277
  // Send via relay (foreground) or callback (background)
234
278
  const relay = ctx.relay;
235
- const send = relay ? (request) => relay.send(request) : options?.sendRetryRequest;
236
- 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) => {
237
288
  // Rotate before sending a retry request for a stale-prekey failure.
238
289
  const isStalePreKeyIndicator = error instanceof EncryptionError &&
239
290
  (error.code === EncryptionErrorCode.PREKEY_NOT_FOUND ||
@@ -309,7 +360,7 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
309
360
  timestamp: envelope.timestamp,
310
361
  };
311
362
  // Create retry request via SesameManager
312
- return ctx.sesameManager.createRetryRequest(failedMessage, retryReason);
363
+ return ctx.sesameManager.createRetryRequest(failedMessage, retryReason, { senderKey });
313
364
  };
314
365
  const outcome = await requestRetryInFamily(family, fingerprint, {
315
366
  storage: ctx.storage,
@@ -317,13 +368,16 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
317
368
  hooks: ctx.hooks,
318
369
  local: { userId: ctx.userId, deviceId: ctx.deviceId },
319
370
  senderUserId: envelope.senderUserId,
371
+ senderDeviceId: envelope.senderDeviceId,
320
372
  // Receiver-side rate limiting. A failed envelope with a request record
321
373
  // spends nothing, as `requestRetryInFamily` tells.
322
374
  allow: () => checkRetryRateLimit(rateLimitState, envelope.senderUserId),
323
375
  windowMs: RETRY_REQUEST_WINDOW_MS,
324
376
  send,
377
+ failedEnvelope: await retryFailedEnvelope(ctx.storage, envelope),
325
378
  createRequest,
326
379
  schedule: ctx.scheduleRetryRequest,
380
+ reset: ctx.retryTerminalReset?.(ctx),
327
381
  });
328
382
  if (outcome === 'posted' || outcome === 'pending') {
329
383
  ctx.logger.info('Sent retry request for failed decryption', {
@@ -371,20 +425,43 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
371
425
  * Handle incoming retry request and resend the original message
372
426
  *
373
427
  * Per SESAME spec §4.1, this method:
374
- * 1. Looks up the MessageRecord for the failed sequence number. When the
375
- * sender already stored a resend or a null message for this request
376
- * envelope, it posts the stored bytes again and does no session work
377
- * 2. Verifies the requester is the intended recipient
378
- * 3. Checks retry limits and TTL
379
- * 4. Creates new session if orphaned, or uses existing different session
380
- * 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
381
452
  * MessageRecord with the record of the new encryption. Only a delivery
382
- * 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.
383
455
  *
384
- * It refuses a request for a message sent more than
456
+ * It refuses a request for a message stored more than
385
457
  * `RELIABILITY_RECORD_TTL_MS` ago, before it reads a stored resend. The
386
- * Relay can keep the last resend post for that time again, and the
387
- * 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.
388
465
  *
389
466
  * It returns normally when it resends the message or refuses the request.
390
467
  * It throws every other error, so the caller keeps the request envelope and
@@ -404,33 +481,22 @@ export async function sendRetryRequestInternal(ctx, envelope, error, rateLimitSt
404
481
  */
405
482
  export async function handleRetryRequestAndResend(ctx, retryRequest, responseState, callbacks, config, retry) {
406
483
  const sessionId = `${retryRequest.requesterUserId}:${retryRequest.requesterDeviceId}`;
407
- if (Date.now() - retryRequest.failedTimestamp > RELIABILITY_RECORD_TTL_MS) {
408
- 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', {
409
489
  category: 'E2EE',
410
490
  data: {
411
491
  sessionId,
412
492
  failedTimestamp: retryRequest.failedTimestamp,
413
- behavior: 'RETRY_REQUEST_EXPIRED',
493
+ behavior: 'RETRY_REQUEST_OTHER_DEVICE',
414
494
  },
415
495
  });
416
496
  return;
417
497
  }
418
498
  // The response count of one message is keyed by its session and timestamp.
419
499
  const dedupKey = `${sessionId}:${retryRequest.failedTimestamp}`;
420
- // Enforce retry response limit
421
- // Prevents infinite retry loops when decryption consistently fails
422
- const responseCount = responseState.retryResponseCounts.get(dedupKey) ?? 0;
423
- if (responseCount >= MAX_RETRY_RESPONSES_PER_MESSAGE) {
424
- ctx.logger.warn('Retry response limit reached, ignoring further retry requests', {
425
- category: 'E2EE',
426
- data: {
427
- dedupKey,
428
- responseCount,
429
- limit: MAX_RETRY_RESPONSES_PER_MESSAGE,
430
- },
431
- });
432
- return;
433
- }
434
500
  ctx.logger.info('Processing retry request', {
435
501
  category: 'E2EE',
436
502
  data: {
@@ -440,10 +506,25 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
440
506
  },
441
507
  });
442
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);
443
511
  // Look up the original outbound record by peer session and timestamp.
444
- 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
+ }
445
526
  // The answer to this failed envelope ended. A redelivery of a request
446
- // only calls the hook when the client stopped before it stored the call.
527
+ // only calls the hook when no earlier call returned.
447
528
  if (retry !== undefined) {
448
529
  const stored = await getRetryResend(ctx.storage, retryRequest.requesterUserId, retryRequest.requesterDeviceId, retry.failedEnvelopeId);
449
530
  if (stored?.terminal !== undefined) {
@@ -452,16 +533,70 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
452
533
  }
453
534
  }
454
535
  // The sender already answered this request envelope, and the post did
455
- // 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.
456
539
  if (retry !== undefined &&
457
- (await replayStoredResend(ctx, retryRequest, record, callbacks, retry))) {
458
- 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
+ }
459
544
  ctx.logger.info('Posted the stored resend of this request attempt again', {
460
545
  category: 'E2EE',
461
546
  data: { sessionId, failedTimestamp: retryRequest.failedTimestamp },
462
547
  });
463
548
  return;
464
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
+ }
465
600
  if (!record) {
466
601
  ctx.logger.warn('MessageRecord not found for retry request', {
467
602
  category: 'E2EE',
@@ -471,8 +606,10 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
471
606
  },
472
607
  });
473
608
  // A null message completes the reset when the original resend payload is
474
- // no longer present in the send log.
475
- 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;
476
613
  if (!shouldAttemptNullFallback) {
477
614
  return;
478
615
  }
@@ -487,6 +624,13 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
487
624
  skipMessageRecordValidation: true,
488
625
  });
489
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
+ }
490
634
  await sendNullMessageForRetryReset(callbacks, retryRequest, ctx, retry);
491
635
  // Null-message fallbacks are not retryable payloads. Delete the
492
636
  // synthetic record created by the generic send pipeline.
@@ -527,8 +671,8 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
527
671
  plaintextLength: record.plaintext.length,
528
672
  },
529
673
  });
530
- // 2. Check message TTL
531
- if (Date.now() - record.createdAt > MESSAGE_RECORD_TTL_MS) {
674
+ // 2. Check the content retention
675
+ if (ctx.resendableContent.isExpired(record.createdAt)) {
532
676
  ctx.logger.warn('Message expired, cannot resend', {
533
677
  category: 'E2EE',
534
678
  data: {
@@ -540,69 +684,17 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
540
684
  await ctx.storage.deleteMessageRecord(sessionId, record.timestamp);
541
685
  return;
542
686
  }
543
- // 3. Get current session to check for orphaned session
544
- const currentSession = await ctx.sesameManager.getActiveSession(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
545
- const address = ProtocolAddress.create(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
546
- // Compare our current ratchet key (DHs) against the DHs stored at send time (sessionStateId).
547
- // If DHs advanced (DH ratchet occurred), session is healthy. Reuse it.
548
- // If DHs matches or is missing, session has not advanced. Needs fresh bundle.
549
- // The send record captures the local ratchet key because the retry request
550
- // does not carry a peer-authenticated copy.
551
- const senderRatchetKey = currentSession?.DHs?.publicKey;
552
- const isOrphanedSession = !currentSession || !senderRatchetKey || senderRatchetKey === record.sessionStateId;
553
- const needsFreshBundle = isOrphanedSession;
554
- if (needsFreshBundle) {
555
- // 4a. Need fresh bundle: Archive old session and create new session
556
- const result = await ctx.sesameManager.handleRetryRequest(retryRequest);
557
- if (!result.requiresNewSession) {
558
- ctx.logger.debug('Retry request handled without resend', {
559
- category: 'E2EE',
560
- data: { action: result.action },
561
- });
562
- return;
563
- }
564
- // Fetch prekey bundle and create new initiating session
565
- if (!ctx.relay) {
566
- throw new Error('Relay not configured - cannot fetch prekey bundle');
567
- }
568
- const bundle = await ctx.relay.fetchPreKeyBundle(retryRequest.requesterUserId, retryRequest.requesterDeviceId);
569
- if (!bundle) {
570
- ctx.logger.warn('Failed to fetch prekey bundle for retry', {
571
- category: 'E2EE',
572
- data: {
573
- userId: retryRequest.requesterUserId,
574
- deviceId: retryRequest.requesterDeviceId,
575
- },
576
- });
577
- // The requester has no prekey bundle, so no resend can reach it.
578
- // The answer ends, and the request envelope is acknowledged.
579
- if (retry !== undefined) {
580
- await endRetryResend(ctx, retryRequest, retry, 'missing-prekey');
581
- }
582
- return;
583
- }
584
- await callbacks.establishSession(address, bundle);
585
- const sessionReason = !currentSession ? 'no_session' : 'orphaned';
586
- ctx.logger.debug('Created new session for retry', {
587
- category: 'E2EE',
588
- data: {
589
- address: ProtocolAddress.toString(address),
590
- reason: sessionReason,
591
- retryReason: retryRequest.reason,
592
- },
593
- });
594
- }
595
- else {
596
- // 4b. Different active session exists AND not MAC failure - use it directly
597
- ctx.logger.debug('Using existing different session for retry (no prekey fetch)', {
598
- category: 'E2EE',
599
- data: {
600
- address: ProtocolAddress.toString(address),
601
- activeRatchetKey: currentSession.DHs?.publicKey?.substring(0, 12) + '...',
602
- storedRatchetKey: record.sessionStateId.substring(0, 12) + '...',
603
- },
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',
604
695
  });
605
- }
696
+ if (!sessionReady)
697
+ return;
606
698
  // 5. SESAME Step 4-5: Re-encrypt the original message and send it only
607
699
  // to the device that asked. Reuse the original timestamp for envelope
608
700
  // alignment. The post has a fresh operation epoch.
@@ -614,7 +706,9 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
614
706
  responseState.retryResponseCounts.set(dedupKey, responseCount + 1);
615
707
  // 6. The resend replaced the MessageRecord at the same timestamp with the
616
708
  // record of the new encryption. A delivery receipt from the device or the
617
- // 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.
618
712
  ctx.logger.info('Message resent successfully after retry request', {
619
713
  category: 'E2EE',
620
714
  data: {
@@ -638,6 +732,415 @@ export async function handleRetryRequestAndResend(ctx, retryRequest, responseSta
638
732
  throw error;
639
733
  }
640
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
+ }
641
1144
  /** A SesameError that refuses the retry request. A later attempt gets the same refusal. */
642
1145
  function isRetryRefusal(error) {
643
1146
  return (error instanceof SesameError &&