@open-e2ee/signal-protocol-sdk 0.4.0 → 2.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 (255) hide show
  1. package/CHANGELOG.md +126 -5
  2. package/COMMERCIAL.md +1 -1
  3. package/README.md +10 -7
  4. package/SECURITY.md +2 -2
  5. package/THIRD_PARTY_NOTICES.md +1 -1
  6. package/device/README.md +7 -5
  7. package/dist/client/client.d.ts +3 -2
  8. package/dist/client/client.d.ts.map +1 -1
  9. package/dist/client/client.js +58 -25
  10. package/dist/client/client.js.map +1 -1
  11. package/dist/client/config.d.ts +46 -7
  12. package/dist/client/config.d.ts.map +1 -1
  13. package/dist/client/config.js +2 -2
  14. package/dist/client/config.js.map +1 -1
  15. package/dist/client/constants.d.ts +4 -2
  16. package/dist/client/constants.d.ts.map +1 -1
  17. package/dist/client/constants.js +4 -2
  18. package/dist/client/constants.js.map +1 -1
  19. package/dist/client/group-outbox.d.ts +38 -0
  20. package/dist/client/group-outbox.d.ts.map +1 -0
  21. package/dist/client/group-outbox.js +224 -0
  22. package/dist/client/group-outbox.js.map +1 -0
  23. package/dist/client/group-sealed-sender.d.ts +28 -0
  24. package/dist/client/group-sealed-sender.d.ts.map +1 -0
  25. package/dist/client/group-sealed-sender.js +74 -0
  26. package/dist/client/group-sealed-sender.js.map +1 -0
  27. package/dist/client/hosted-connection.d.ts +16 -0
  28. package/dist/client/hosted-connection.d.ts.map +1 -0
  29. package/dist/client/hosted-connection.js +255 -0
  30. package/dist/client/hosted-connection.js.map +1 -0
  31. package/dist/client/hosted-push.d.ts +57 -0
  32. package/dist/client/hosted-push.d.ts.map +1 -0
  33. package/dist/client/hosted-push.js +115 -0
  34. package/dist/client/hosted-push.js.map +1 -0
  35. package/dist/client/hosted-transport.d.ts +158 -0
  36. package/dist/client/hosted-transport.d.ts.map +1 -0
  37. package/dist/client/hosted-transport.js +926 -0
  38. package/dist/client/hosted-transport.js.map +1 -0
  39. package/dist/client/hosted.d.ts +223 -0
  40. package/dist/client/hosted.d.ts.map +1 -0
  41. package/dist/client/hosted.js +541 -0
  42. package/dist/client/hosted.js.map +1 -0
  43. package/dist/client/index.d.ts +5 -3
  44. package/dist/client/index.d.ts.map +1 -1
  45. package/dist/client/index.js +2 -0
  46. package/dist/client/index.js.map +1 -1
  47. package/dist/client/messages.d.ts.map +1 -1
  48. package/dist/client/messages.js +4 -5
  49. package/dist/client/messages.js.map +1 -1
  50. package/dist/client/relay-subscription.d.ts.map +1 -1
  51. package/dist/client/relay-subscription.js +37 -7
  52. package/dist/client/relay-subscription.js.map +1 -1
  53. package/dist/client/{sealed-sender-ops.d.ts → sealed-sender.d.ts} +39 -22
  54. package/dist/client/sealed-sender.d.ts.map +1 -0
  55. package/dist/client/sealed-sender.js +296 -0
  56. package/dist/client/sealed-sender.js.map +1 -0
  57. package/dist/client/signal-service-cipher.d.ts +23 -26
  58. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  59. package/dist/client/signal-service-cipher.js +468 -706
  60. package/dist/client/signal-service-cipher.js.map +1 -1
  61. package/dist/client/types.d.ts +18 -3
  62. package/dist/client/types.d.ts.map +1 -1
  63. package/dist/client/types.js +6 -0
  64. package/dist/client/types.js.map +1 -1
  65. package/dist/device/index.d.ts +2 -2
  66. package/dist/device/index.d.ts.map +1 -1
  67. package/dist/device/index.js +1 -1
  68. package/dist/device/index.js.map +1 -1
  69. package/dist/device/transfer.d.ts +7 -43
  70. package/dist/device/transfer.d.ts.map +1 -1
  71. package/dist/device/transfer.js +31 -150
  72. package/dist/device/transfer.js.map +1 -1
  73. package/dist/device/types.d.ts +6 -47
  74. package/dist/device/types.d.ts.map +1 -1
  75. package/dist/device/types.js +1 -1
  76. package/dist/device/types.js.map +1 -1
  77. package/dist/index.d.ts +6 -5
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +2 -1
  80. package/dist/index.js.map +1 -1
  81. package/dist/internal/encoding/proto/pq-ratchet-serialize.js +1 -1
  82. package/dist/internal/encoding/proto/pq-ratchet-serialize.js.map +1 -1
  83. package/dist/internal/encoding/proto/primitives.js +1 -1
  84. package/dist/internal/encoding/proto/primitives.js.map +1 -1
  85. package/dist/internal/groups/manager.d.ts +3 -3
  86. package/dist/internal/groups/manager.d.ts.map +1 -1
  87. package/dist/internal/groups/manager.js +5 -4
  88. package/dist/internal/groups/manager.js.map +1 -1
  89. package/dist/internal/protocol/sealed-sender/certificate.d.ts +10 -4
  90. package/dist/internal/protocol/sealed-sender/certificate.d.ts.map +1 -1
  91. package/dist/internal/protocol/sealed-sender/certificate.js +64 -7
  92. package/dist/internal/protocol/sealed-sender/certificate.js.map +1 -1
  93. package/dist/internal/protocol/sealed-sender/decryption.d.ts +34 -47
  94. package/dist/internal/protocol/sealed-sender/decryption.d.ts.map +1 -1
  95. package/dist/internal/protocol/sealed-sender/decryption.js +95 -182
  96. package/dist/internal/protocol/sealed-sender/decryption.js.map +1 -1
  97. package/dist/internal/protocol/sealed-sender/encryption.d.ts +49 -64
  98. package/dist/internal/protocol/sealed-sender/encryption.d.ts.map +1 -1
  99. package/dist/internal/protocol/sealed-sender/encryption.js +120 -123
  100. package/dist/internal/protocol/sealed-sender/encryption.js.map +1 -1
  101. package/dist/internal/protocol/sealed-sender/index.d.ts +5 -7
  102. package/dist/internal/protocol/sealed-sender/index.d.ts.map +1 -1
  103. package/dist/internal/protocol/sealed-sender/index.js +4 -12
  104. package/dist/internal/protocol/sealed-sender/index.js.map +1 -1
  105. package/dist/internal/protocol/sealed-sender/{v2-helpers.d.ts → multi-recipient-crypto.d.ts} +1 -1
  106. package/dist/internal/protocol/sealed-sender/multi-recipient-crypto.d.ts.map +1 -0
  107. package/dist/internal/protocol/sealed-sender/{v2-helpers.js → multi-recipient-crypto.js} +1 -1
  108. package/dist/internal/protocol/sealed-sender/multi-recipient-crypto.js.map +1 -0
  109. package/dist/internal/protocol/sealed-sender/{v2-binary.d.ts → multi-recipient-message.d.ts} +3 -2
  110. package/dist/internal/protocol/sealed-sender/multi-recipient-message.d.ts.map +1 -0
  111. package/dist/internal/protocol/sealed-sender/{v2-binary.js → multi-recipient-message.js} +16 -8
  112. package/dist/internal/protocol/sealed-sender/multi-recipient-message.js.map +1 -0
  113. package/dist/internal/protocol/sealed-sender/proto/index.d.ts +3 -0
  114. package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
  115. package/dist/internal/protocol/sealed-sender/proto/index.js +25 -2
  116. package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
  117. package/dist/internal/protocol/sealed-sender/trust-root.d.ts +11 -1
  118. package/dist/internal/protocol/sealed-sender/trust-root.d.ts.map +1 -1
  119. package/dist/internal/protocol/sealed-sender/trust-root.js +13 -1
  120. package/dist/internal/protocol/sealed-sender/trust-root.js.map +1 -1
  121. package/dist/internal/protocol/sealed-sender/types.d.ts +20 -135
  122. package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
  123. package/dist/internal/protocol/sealed-sender/types.js +15 -6
  124. package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
  125. package/dist/internal/protocol/sender-keys/manager.d.ts +22 -1
  126. package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
  127. package/dist/internal/protocol/sender-keys/manager.js +39 -4
  128. package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
  129. package/dist/internal/protocol/spqr/braid-serialize.js +1 -1
  130. package/dist/internal/protocol/spqr/braid-serialize.js.map +1 -1
  131. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js +4 -4
  132. package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js.map +1 -1
  133. package/dist/internal/protocol/zk/groups/index.d.ts +1 -1
  134. package/dist/internal/protocol/zk/groups/index.d.ts.map +1 -1
  135. package/dist/internal/protocol/zk/groups/index.js +1 -1
  136. package/dist/internal/protocol/zk/groups/index.js.map +1 -1
  137. package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts +37 -12
  138. package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts.map +1 -1
  139. package/dist/internal/protocol/zk/groups/profile-key-credential.js +104 -31
  140. package/dist/internal/protocol/zk/groups/profile-key-credential.js.map +1 -1
  141. package/dist/local/store/expo/adapter.d.ts +1 -0
  142. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  143. package/dist/local/store/expo/adapter.js +3 -0
  144. package/dist/local/store/expo/adapter.js.map +1 -1
  145. package/dist/local/store/expo/key-storage.d.ts +1 -0
  146. package/dist/local/store/expo/key-storage.d.ts.map +1 -1
  147. package/dist/local/store/expo/key-storage.js +4 -0
  148. package/dist/local/store/expo/key-storage.js.map +1 -1
  149. package/dist/local/store/memory/adapter.d.ts +1 -0
  150. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  151. package/dist/local/store/memory/adapter.js +4 -0
  152. package/dist/local/store/memory/adapter.js.map +1 -1
  153. package/dist/local/store/node/adapter.d.ts +1 -0
  154. package/dist/local/store/node/adapter.d.ts.map +1 -1
  155. package/dist/local/store/node/adapter.js +3 -0
  156. package/dist/local/store/node/adapter.js.map +1 -1
  157. package/dist/local/store/node/database.d.ts +1 -0
  158. package/dist/local/store/node/database.d.ts.map +1 -1
  159. package/dist/local/store/node/database.js +5 -0
  160. package/dist/local/store/node/database.js.map +1 -1
  161. package/dist/local/store/react-native/adapter.d.ts +1 -0
  162. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  163. package/dist/local/store/react-native/adapter.js +4 -0
  164. package/dist/local/store/react-native/adapter.js.map +1 -1
  165. package/dist/local/store/react-native/reference-backend.js +1 -1
  166. package/dist/local/store/react-native/reference-backend.js.map +1 -1
  167. package/dist/local/store/reliability.d.ts +63 -0
  168. package/dist/local/store/reliability.d.ts.map +1 -0
  169. package/dist/local/store/reliability.js +219 -0
  170. package/dist/local/store/reliability.js.map +1 -0
  171. package/dist/local/store/web/adapter.d.ts +1 -0
  172. package/dist/local/store/web/adapter.d.ts.map +1 -1
  173. package/dist/local/store/web/adapter.js +5 -0
  174. package/dist/local/store/web/adapter.js.map +1 -1
  175. package/dist/media/index.d.ts.map +1 -1
  176. package/dist/media/index.js +7 -4
  177. package/dist/media/index.js.map +1 -1
  178. package/dist/remote/object-store/convex-r2/server.d.ts +4 -2
  179. package/dist/remote/object-store/convex-r2/server.d.ts.map +1 -1
  180. package/dist/remote/object-store/convex-r2/server.js +8 -0
  181. package/dist/remote/object-store/convex-r2/server.js.map +1 -1
  182. package/dist/remote/object-store/convex-r2/storage.d.ts +5 -1
  183. package/dist/remote/object-store/convex-r2/storage.d.ts.map +1 -1
  184. package/dist/remote/object-store/convex-r2/storage.js +1 -0
  185. package/dist/remote/object-store/convex-r2/storage.js.map +1 -1
  186. package/dist/remote/object-store/types.d.ts +2 -0
  187. package/dist/remote/object-store/types.d.ts.map +1 -1
  188. package/dist/remote/object-store/validation.d.ts.map +1 -1
  189. package/dist/remote/object-store/validation.js +3 -0
  190. package/dist/remote/object-store/validation.js.map +1 -1
  191. package/dist/remote/relay/convex/backend.d.ts +7 -18
  192. package/dist/remote/relay/convex/backend.d.ts.map +1 -1
  193. package/dist/remote/relay/convex/backend.js +15 -24
  194. package/dist/remote/relay/convex/backend.js.map +1 -1
  195. package/dist/remote/relay/convex/component/_generated/component.d.ts +10 -18
  196. package/dist/remote/relay/convex/component/_generated/component.d.ts.map +1 -1
  197. package/dist/remote/relay/convex/component/certificates.d.ts.map +1 -1
  198. package/dist/remote/relay/convex/component/certificates.js +14 -5
  199. package/dist/remote/relay/convex/component/certificates.js.map +1 -1
  200. package/dist/remote/relay/convex/component/messages.d.ts +3 -17
  201. package/dist/remote/relay/convex/component/messages.d.ts.map +1 -1
  202. package/dist/remote/relay/convex/component/messages.js +28 -56
  203. package/dist/remote/relay/convex/component/messages.js.map +1 -1
  204. package/dist/remote/relay/convex/component/schema.d.ts +6 -6
  205. package/dist/remote/relay/convex/component/schema.js +2 -2
  206. package/dist/remote/relay/convex/component/schema.js.map +1 -1
  207. package/dist/remote/relay/convex/component/zkAuth.d.ts +7 -1
  208. package/dist/remote/relay/convex/component/zkAuth.d.ts.map +1 -1
  209. package/dist/remote/relay/convex/component/zkAuth.js +29 -14
  210. package/dist/remote/relay/convex/component/zkAuth.js.map +1 -1
  211. package/dist/remote/relay/convex/relay.d.ts +3 -6
  212. package/dist/remote/relay/convex/relay.d.ts.map +1 -1
  213. package/dist/remote/relay/convex/relay.js +23 -50
  214. package/dist/remote/relay/convex/relay.js.map +1 -1
  215. package/dist/remote/relay/index.d.ts +1 -1
  216. package/dist/remote/relay/index.d.ts.map +1 -1
  217. package/dist/remote/relay/index.js.map +1 -1
  218. package/dist/remote/relay/memory/adapter.d.ts +5 -11
  219. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  220. package/dist/remote/relay/memory/adapter.js +41 -34
  221. package/dist/remote/relay/memory/adapter.js.map +1 -1
  222. package/dist/remote/relay/types.d.ts +19 -29
  223. package/dist/remote/relay/types.d.ts.map +1 -1
  224. package/dist/types/api.d.ts +2 -0
  225. package/dist/types/api.d.ts.map +1 -1
  226. package/dist/types/errors.d.ts +8 -1
  227. package/dist/types/errors.d.ts.map +1 -1
  228. package/dist/types/errors.js +9 -2
  229. package/dist/types/errors.js.map +1 -1
  230. package/dist/types/protocol-config.d.ts +1 -1
  231. package/dist/username/link.d.ts.map +1 -1
  232. package/dist/username/link.js +1 -1
  233. package/dist/username/link.js.map +1 -1
  234. package/docs/ASSURANCE.md +5 -5
  235. package/docs/DEVIATIONS.md +32 -61
  236. package/docs/GETTING_STARTED.md +7 -0
  237. package/docs/SECURITY.md +6 -0
  238. package/package.json +2 -2
  239. package/remote/relay/convex/component/README.md +28 -24
  240. package/scripts/oe-groups.mjs +5 -1
  241. package/dist/client/sealed-sender-ops.d.ts.map +0 -1
  242. package/dist/client/sealed-sender-ops.js +0 -203
  243. package/dist/client/sealed-sender-ops.js.map +0 -1
  244. package/dist/internal/protocol/sealed-sender/decryption-v2.d.ts +0 -46
  245. package/dist/internal/protocol/sealed-sender/decryption-v2.d.ts.map +0 -1
  246. package/dist/internal/protocol/sealed-sender/decryption-v2.js +0 -198
  247. package/dist/internal/protocol/sealed-sender/decryption-v2.js.map +0 -1
  248. package/dist/internal/protocol/sealed-sender/encryption-v2.d.ts +0 -56
  249. package/dist/internal/protocol/sealed-sender/encryption-v2.d.ts.map +0 -1
  250. package/dist/internal/protocol/sealed-sender/encryption-v2.js +0 -163
  251. package/dist/internal/protocol/sealed-sender/encryption-v2.js.map +0 -1
  252. package/dist/internal/protocol/sealed-sender/v2-binary.d.ts.map +0 -1
  253. package/dist/internal/protocol/sealed-sender/v2-binary.js.map +0 -1
  254. package/dist/internal/protocol/sealed-sender/v2-helpers.d.ts.map +0 -1
  255. package/dist/internal/protocol/sealed-sender/v2-helpers.js.map +0 -1
@@ -20,10 +20,13 @@ import { recordServerClockSample } from '../server-clock.js';
20
20
  import { ProtocolAddress } from '../types/address.js';
21
21
  import { defaultSignalProtocolLogger } from '../logger.js';
22
22
  import { isGroupId, extractGroupId } from '../internal/groups/index.js';
23
- import { SealedSenderContentType } from '../internal/protocol/sealed-sender/types.js';
24
23
  import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
25
24
  import * as CryptoUtils from '../internal/crypto/index.js';
25
+ import { completeOutgoingMessageIntent, getOutgoingMessageIntent, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
26
26
  import { withRetry } from '../utils/retry.js';
27
+ import { prepareGroupSharedMessage } from './group-sealed-sender.js';
28
+ import { sendGroupWithExactOutbox } from './group-outbox.js';
29
+ import { resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, } from './sealed-sender.js';
27
30
  import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
28
31
  import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
29
32
  export function sortEnvelopesForDecryption(envelopes) {
@@ -61,6 +64,26 @@ function getEnvelopeMessageType(ciphertext) {
61
64
  }
62
65
  return 'ciphertext';
63
66
  }
67
+ function attachClientMessageId(error, clientMessageId) {
68
+ const normalized = error instanceof Error ? error : new Error(String(error));
69
+ try {
70
+ Object.defineProperty(normalized, 'clientMessageId', {
71
+ configurable: true,
72
+ enumerable: true,
73
+ value: clientMessageId,
74
+ });
75
+ return normalized;
76
+ }
77
+ catch {
78
+ const wrapped = new Error(normalized.message);
79
+ wrapped.name = normalized.name;
80
+ Object.defineProperty(wrapped, 'clientMessageId', {
81
+ enumerable: true,
82
+ value: clientMessageId,
83
+ });
84
+ return wrapped;
85
+ }
86
+ }
64
87
  /**
65
88
  * Detect if an error is a stale session error from the server
66
89
  *
@@ -83,27 +106,14 @@ function isStaleSessionError(error) {
83
106
  }
84
107
  return false;
85
108
  }
86
- /**
87
- * Detect 409 mismatched devices error from V2 multi-recipient send.
88
- *
89
- * The Convex component does not throw this: it reports skipped recipients
90
- * via `uuids404` on a success response (handled in `tryMultiRecipientSend`).
91
- * The matcher remains for relay implementations that reject the whole send
92
- * with a mismatched-device error instead.
93
- */
94
- function isMismatchedDevicesError(message) {
95
- return message.includes('MISMATCHED_DEVICES');
109
+ class SealedSenderRecipientRejectedError extends Error {
110
+ constructor() {
111
+ super('Sealed sender recipient was not accepted');
112
+ this.name = 'SealedSenderRecipientRejectedError';
113
+ }
96
114
  }
97
- /**
98
- * Detect 410 stale sessions error from V2 multi-recipient send.
99
- *
100
- * The Convex component throws STALE_DEVICE only on the single-recipient
101
- * `send` path (structured `data.code`, see `isStaleSessionError`). Its
102
- * multi-recipient path reports mismatches via `uuids404` instead. The
103
- * matcher remains for relay implementations that reject the whole send.
104
- */
105
- function isStaleSessionV2Error(message) {
106
- return message.includes('STALE_DEVICE');
115
+ function isConclusiveDeviceRejection(error) {
116
+ return isStaleSessionError(error) || error instanceof SealedSenderRecipientRejectedError;
107
117
  }
108
118
  /**
109
119
  * SignalProtocolServiceCipher - Routes encryption and decryption to appropriate ciphers
@@ -139,6 +149,8 @@ export class SignalProtocolServiceCipher {
139
149
  sessionEstablisher;
140
150
  staleSessionRefresher;
141
151
  sealedSenderProvider;
152
+ sealedSenderDeliveryMode = 'preferred';
153
+ sealedSenderIdentifiedFallback;
142
154
  contactProfileStateStore;
143
155
  endorsementManager;
144
156
  endorsementRefresher;
@@ -193,14 +205,11 @@ export class SignalProtocolServiceCipher {
193
205
  ? syncMsg.ciphertext
194
206
  : CryptoUtils.bytesToBase64(syncMsg.ciphertext),
195
207
  messageType: getEnvelopeMessageType(syncMsg.ciphertext),
208
+ deliveryClass: 'background-sync',
196
209
  timestamp: syncMsg.timestamp,
197
210
  });
198
211
  }
199
212
  }
200
- async sendSyncTranscriptToLocalOtherDevices(conversationId, plaintextBytes, timestamp, recipientUserId) {
201
- const transcriptBytes = this.buildSentSyncTranscript(conversationId, plaintextBytes, timestamp, recipientUserId);
202
- await this.sendSyncPayloadToLocalOtherDevices(transcriptBytes, timestamp);
203
- }
204
213
  async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp) {
205
214
  if (!this.relay) {
206
215
  return;
@@ -279,6 +288,35 @@ export class SignalProtocolServiceCipher {
279
288
  setSealedSenderProvider(provider) {
280
289
  this.sealedSenderProvider = provider;
281
290
  }
291
+ setSealedSenderDeliveryMode(mode) {
292
+ this.sealedSenderDeliveryMode = mode;
293
+ }
294
+ setSealedSenderIdentifiedFallback(callback) {
295
+ this.sealedSenderIdentifiedFallback = callback;
296
+ }
297
+ async reportIdentifiedFallback(recipientUserId) {
298
+ try {
299
+ await this.sealedSenderIdentifiedFallback?.({
300
+ recipientUserId,
301
+ reason: 'authorization-rejected',
302
+ });
303
+ }
304
+ catch (fallbackHookError) {
305
+ this.logger.warn('Sealed sender identified-fallback hook failed', {
306
+ category: 'E2EE',
307
+ data: {
308
+ recipientUserId,
309
+ error: fallbackHookError.message,
310
+ },
311
+ });
312
+ }
313
+ }
314
+ useIdentifiedDeliveryOrThrow(recipientUserId, reason) {
315
+ if (this.sealedSenderDeliveryMode === 'required') {
316
+ throw new EncryptionError(`Sealed sender is required but unavailable: ${reason}`, EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId, operation: 'resolveSealedSenderContext', reason });
317
+ }
318
+ return null;
319
+ }
282
320
  setContactProfileStateStore(store) {
283
321
  this.contactProfileStateStore = store;
284
322
  }
@@ -341,7 +379,7 @@ export class SignalProtocolServiceCipher {
341
379
  if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
342
380
  throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
343
381
  }
344
- const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender-ops.js');
382
+ const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender.js');
345
383
  // Get recipient's X25519 identity private key for unsealing
346
384
  const identityKeyPair = await this.storage.getIdentityKey();
347
385
  if (!identityKeyPair) {
@@ -352,7 +390,7 @@ export class SignalProtocolServiceCipher {
352
390
  const ciphertextStr = typeof envelope.ciphertext === 'string'
353
391
  ? envelope.ciphertext
354
392
  : CryptoUtils.bytesToBase64(envelope.ciphertext);
355
- const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, this.logger);
393
+ const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, envelope.serverTimestamp, this.logger);
356
394
  // Reconstruct envelope with revealed sender identity
357
395
  const innerEnvelope = reconstructEnvelope(envelope, unsealed);
358
396
  // Recursively decrypt the inner message (now a standard ciphertext)
@@ -458,19 +496,26 @@ export class SignalProtocolServiceCipher {
458
496
  * @see https://signal.org/docs/specifications/sesame/
459
497
  */
460
498
  async encrypt(recipientId, content, options) {
499
+ const clientMessageId = options?.clientMessageId ?? (await CryptoUtils.generateUuidV4());
500
+ const durableOptions = { ...options, clientMessageId };
461
501
  const lockKey = `encrypt:${recipientId}`;
462
- return this.lock.acquire(lockKey, async () => {
463
- // 1. Route binary file data (Uint8Array with isBinary flag) to blob encryption
464
- if (options?.isBinary) {
465
- return this.encryptBinaryAttachment(recipientId, content, options);
466
- }
467
- // 2. Detect recipient type (group vs user)
468
- if (isGroupId(recipientId)) {
469
- return this.encryptToGroup(recipientId, content, options);
470
- }
471
- // 3. Send to user (existing SESAME path)
472
- return this.encryptToUser(recipientId, content, options);
473
- });
502
+ try {
503
+ return await this.lock.acquire(lockKey, async () => {
504
+ // 1. Route binary file data (Uint8Array with isBinary flag) to blob encryption
505
+ if (durableOptions.isBinary) {
506
+ return this.encryptBinaryAttachment(recipientId, content, durableOptions);
507
+ }
508
+ // 2. Detect recipient type (group vs user)
509
+ if (isGroupId(recipientId)) {
510
+ return this.encryptToGroup(recipientId, content, durableOptions);
511
+ }
512
+ // 3. Send to user (existing SESAME path)
513
+ return this.encryptToUser(recipientId, content, durableOptions);
514
+ });
515
+ }
516
+ catch (error) {
517
+ throw attachClientMessageId(error, clientMessageId);
518
+ }
474
519
  }
475
520
  /**
476
521
  * Encrypt and upload attachment data without sending a standalone message.
@@ -624,8 +669,7 @@ export class SignalProtocolServiceCipher {
624
669
  // Use retry logic for transient network failures
625
670
  result = await withRetry(async () => {
626
671
  const attempt = await this.sessionEstablisher(recipientUserId);
627
- if (attempt.establishedDevices.length === 0 &&
628
- attempt.failedDeviceErrors.length > 0) {
672
+ if (attempt.establishedDevices.length === 0 && attempt.failedDeviceErrors.length > 0) {
629
673
  throw attempt.failedDeviceErrors[0].error;
630
674
  }
631
675
  return attempt;
@@ -663,23 +707,49 @@ export class SignalProtocolServiceCipher {
663
707
  * Encrypt to a single user (all their devices) via SESAME
664
708
  */
665
709
  async encryptToUser(recipientUserId, plaintextBytes, options) {
666
- // Auto-establish sessions if needed (lazy session creation)
710
+ return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options);
711
+ }
712
+ async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options) {
713
+ return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options));
714
+ }
715
+ async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options) {
716
+ const plaintextDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(plaintextBytes));
717
+ const existing = await getOutgoingMessageIntent(this.storage, options.clientMessageId);
718
+ if (existing) {
719
+ if (existing.recipientId !== recipientUserId ||
720
+ existing.plaintextDigest !== plaintextDigest ||
721
+ (options.timestamp !== undefined && existing.clientTimestamp !== options.timestamp) ||
722
+ existing.contentHint !== options.contentHint) {
723
+ throw new Error('A clientMessageId cannot identify two different logical sends');
724
+ }
725
+ if (existing.result)
726
+ return existing.result;
727
+ return this.sendStoredDirectIntent(existing, plaintextBytes);
728
+ }
667
729
  await this.ensureSessionsForUser(recipientUserId);
668
- // SESAME multi-device encryption: encrypt for all recipient devices
730
+ const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
731
+ const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
732
+ const transportMode = directSealedSender
733
+ ? directSealedSender.config.deliveryMode === 'required'
734
+ ? 'sealed_sender_required'
735
+ : 'sealed_sender_preferred'
736
+ : 'identified';
737
+ if (directSealedSender && directSealedSender.auth.type !== 'accessKey') {
738
+ throw new Error('Direct sealed-sender delivery requires access-key authorization');
739
+ }
740
+ const sealedSenderAuth = directSealedSender?.auth.type === 'accessKey' ? { ...directSealedSender.auth } : undefined;
741
+ const clientTimestamp = options.timestamp ?? Date.now();
742
+ const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
669
743
  let batch;
670
744
  try {
671
- const clientTimestamp = options?.timestamp ?? Date.now();
672
- const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
673
745
  batch = await this.sesameManager.send(recipientUserId, plaintextBytes, {
674
746
  clientTimestamp,
675
747
  syncPlaintext,
676
748
  });
677
749
  }
678
750
  catch (error) {
679
- // Preserve EncryptionError codes
680
- if (error instanceof EncryptionError) {
751
+ if (error instanceof EncryptionError)
681
752
  throw error;
682
- }
683
753
  throw new EncryptionError('Failed to encrypt message for user', EncryptionErrorCode.ENCRYPTION_FAILED, { originalError: error, recipientUserId });
684
754
  }
685
755
  this.logger.debug('Message encrypted for user devices', {
@@ -690,97 +760,261 @@ export class SignalProtocolServiceCipher {
690
760
  syncCount: batch.syncMessages.length,
691
761
  },
692
762
  });
693
- // Upload messages to relay server if configured
694
- let messageId = `local-${Date.now()}`;
695
- let timestamp = Date.now(); // Fallback if no relay
696
- if (this.relay) {
697
- // Resolve sealed sender context once per send (avoid re-fetching per device)
698
- const sealedSender = await this.resolveSealedSenderContext(recipientUserId);
699
- // Send to each recipient device with stale session handling
700
- for (const msg of batch.deviceMessages) {
701
- const messageType = getEnvelopeMessageType(msg.ciphertext);
702
- const ciphertextBase64 = typeof msg.ciphertext === 'string'
703
- ? msg.ciphertext
704
- : CryptoUtils.bytesToBase64(msg.ciphertext);
705
- // For PreKeyMessages, get session metadata for server-side validation.
706
- // The reference implementation only validates registrationId
707
- // server-side, for device reinstall detection.
708
- // Stale prekey detection is handled client-side via MAC failure + retry.
709
- let recipientRegistrationId;
710
- if (messageType === 'prekey_bundle') {
711
- const session = await this.sesameManager.getSession(msg.recipientUserId, msg.recipientDeviceId);
712
- if (session?.currentSession) {
713
- recipientRegistrationId = session.currentSession.remoteRegistrationId;
714
- }
715
- }
716
- try {
717
- const result = await this.sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, options?.contentHint, options?.clientMessageId);
718
- // Use first envelope ID and serverTimestamp as the canonical values
719
- if (messageId.startsWith('local-')) {
720
- messageId = result.messageId;
721
- timestamp = result.serverTimestamp;
722
- }
723
- }
724
- catch (error) {
725
- // Recover from a relay stale-device response.
726
- if (isStaleSessionError(error) && this.staleSessionRefresher) {
727
- const staleData = error.data;
728
- this.logger.info('Server detected stale session, refreshing', {
729
- category: 'E2EE',
730
- data: {
731
- code: staleData.code,
732
- reason: staleData.reason,
733
- recipientUserId: msg.recipientUserId,
734
- recipientDeviceId: msg.recipientDeviceId,
735
- },
736
- });
737
- // Refresh the stale session (archive + fetch fresh bundle + re-establish)
738
- const refreshed = await this.staleSessionRefresher(msg.recipientUserId, msg.recipientDeviceId);
739
- if (refreshed) {
740
- // Re-encrypt and retry with fresh session
741
- const freshBatch = await this.sesameManager.send(recipientUserId, plaintextBytes, {
742
- clientTimestamp: options?.timestamp,
743
- });
744
- const freshMsg = freshBatch.deviceMessages.find((m) => m.recipientUserId === msg.recipientUserId &&
745
- m.recipientDeviceId === msg.recipientDeviceId);
746
- if (freshMsg) {
747
- const freshCiphertext = typeof freshMsg.ciphertext === 'string'
748
- ? freshMsg.ciphertext
749
- : CryptoUtils.bytesToBase64(freshMsg.ciphertext);
750
- // Get fresh session metadata
751
- const freshSession = await this.sesameManager.getSession(msg.recipientUserId, msg.recipientDeviceId);
752
- const retryResult = await this.sendToDevice(freshMsg, freshCiphertext, getEnvelopeMessageType(freshMsg.ciphertext), freshSession?.currentSession?.remoteRegistrationId, sealedSender, options?.contentHint, options?.clientMessageId);
753
- if (messageId.startsWith('local-')) {
754
- messageId = retryResult.messageId;
755
- timestamp = retryResult.serverTimestamp;
756
- }
757
- this.logger.info('Successfully sent after stale session refresh', {
758
- category: 'E2EE',
759
- data: {
760
- recipientUserId: msg.recipientUserId,
761
- recipientDeviceId: msg.recipientDeviceId,
762
- },
763
- });
764
- continue; // Successfully sent after refresh
765
- }
766
- }
767
- // If refresh failed or no message for device, throw original error
768
- throw new EncryptionError(`Failed to refresh stale session: ${staleData.reason}`, EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, {
769
- originalError: error,
770
- recipientUserId: msg.recipientUserId,
771
- });
772
- }
773
- // Re-throw non-stale errors
763
+ const deviceMessages = await Promise.all(batch.deviceMessages.map((message) => this.prepareStoredDirectDeviceMessage(message, directSealedSender)));
764
+ const syncMessages = batch.syncMessages.map((msg, index) => ({
765
+ recipientUserId: msg.recipientUserId,
766
+ recipientDeviceId: msg.recipientDeviceId,
767
+ timestamp: msg.timestamp,
768
+ clientMessageId: `${options.clientMessageId}:sync:${index}`,
769
+ ciphertext: typeof msg.ciphertext === 'string'
770
+ ? msg.ciphertext
771
+ : CryptoUtils.bytesToBase64(msg.ciphertext),
772
+ messageType: getEnvelopeMessageType(msg.ciphertext),
773
+ }));
774
+ const intent = {
775
+ kind: 'direct',
776
+ clientMessageId: options.clientMessageId,
777
+ recipientId: recipientUserId,
778
+ plaintextDigest,
779
+ clientTimestamp,
780
+ createdAt: Date.now(),
781
+ transportMode,
782
+ ...(sealedSenderAuth && { sealedSenderAuth }),
783
+ ...(options.contentHint !== undefined && {
784
+ contentHint: options.contentHint,
785
+ }),
786
+ deviceMessages,
787
+ syncMessages,
788
+ };
789
+ await storeOutgoingMessageIntent(this.storage, intent);
790
+ return this.sendStoredDirectIntent(intent, plaintextBytes);
791
+ }
792
+ async prepareStoredDirectDeviceMessage(message, sealedSender) {
793
+ const messageType = getEnvelopeMessageType(message.ciphertext);
794
+ const session = messageType === 'prekey_bundle'
795
+ ? await this.sesameManager.getSession(message.recipientUserId, message.recipientDeviceId)
796
+ : null;
797
+ const storedMessage = {
798
+ recipientUserId: message.recipientUserId,
799
+ recipientDeviceId: message.recipientDeviceId,
800
+ timestamp: message.timestamp,
801
+ ciphertext: typeof message.ciphertext === 'string'
802
+ ? message.ciphertext
803
+ : CryptoUtils.bytesToBase64(message.ciphertext),
804
+ messageType,
805
+ ...(session?.currentSession?.remoteRegistrationId !== undefined && {
806
+ recipientRegistrationId: session.currentSession.remoteRegistrationId,
807
+ }),
808
+ };
809
+ if (sealedSender) {
810
+ storedMessage.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(storedMessage, storedMessage.ciphertext, storedMessage.messageType, storedMessage.recipientRegistrationId, sealedSender);
811
+ }
812
+ return storedMessage;
813
+ }
814
+ async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes) {
815
+ if (!this.staleSessionRefresher)
816
+ throw new Error('Stale-session refresh is not configured');
817
+ const refreshed = await this.staleSessionRefresher(rejected.recipientUserId, rejected.recipientDeviceId);
818
+ if (!refreshed) {
819
+ throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: rejected.recipientUserId });
820
+ }
821
+ const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
822
+ let sealedSender = null;
823
+ if (intent.transportMode !== 'identified') {
824
+ sealedSender = await this.resolveSealedSenderContext(rejected.recipientUserId);
825
+ if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
826
+ throw new Error('Cannot rebuild a sealed-sender transmission after session refresh');
827
+ }
828
+ }
829
+ const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, sealedSender);
830
+ await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
831
+ return replacement;
832
+ }
833
+ async sendStoredDirectDeviceMessage(intent, message) {
834
+ if (intent.transportMode !== 'identified' &&
835
+ (!message.sealedSenderMessage || !intent.sealedSenderAuth)) {
836
+ throw new Error('Corrupt sealed-sender outbox intent');
837
+ }
838
+ return intent.transportMode === 'identified'
839
+ ? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId)
840
+ : this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, {
841
+ sentMessageBase64: message.sealedSenderMessage,
842
+ auth: intent.sealedSenderAuth,
843
+ deliveryMode: intent.transportMode === 'sealed_sender_required' ? 'required' : 'preferred',
844
+ });
845
+ }
846
+ async sendStoredDirectIntent(intent, plaintextBytes) {
847
+ if (intent.kind !== 'direct')
848
+ throw new Error('Expected a direct outbox intent');
849
+ if (!this.relay) {
850
+ const result = {
851
+ clientMessageId: intent.clientMessageId,
852
+ messageId: `local-${intent.clientTimestamp}`,
853
+ timestamp: intent.clientTimestamp,
854
+ recipientDeviceCount: intent.deviceMessages.length,
855
+ };
856
+ await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
857
+ return result;
858
+ }
859
+ let messageId = `local-${intent.clientTimestamp}`;
860
+ let timestamp = intent.clientTimestamp;
861
+ for (const msg of intent.deviceMessages) {
862
+ let result;
863
+ try {
864
+ result = await this.sendStoredDirectDeviceMessage(intent, msg);
865
+ }
866
+ catch (error) {
867
+ if (!isConclusiveDeviceRejection(error))
774
868
  throw error;
775
- }
869
+ const replacement = await this.repairRejectedDirectDeviceMessage(intent, msg, plaintextBytes);
870
+ result = await this.sendStoredDirectDeviceMessage(intent, replacement);
871
+ }
872
+ if (messageId.startsWith('local-')) {
873
+ messageId = result.messageId;
874
+ timestamp = result.serverTimestamp;
776
875
  }
777
- await this.uploadSyncMessages(batch.syncMessages);
778
876
  }
779
- return {
877
+ for (const msg of intent.syncMessages) {
878
+ await this.relay.send({
879
+ targetUserId: msg.recipientUserId,
880
+ targetDeviceId: msg.recipientDeviceId,
881
+ senderUserId: this.userId,
882
+ senderDeviceId: this.deviceId,
883
+ ciphertext: msg.ciphertext,
884
+ messageType: msg.messageType,
885
+ deliveryClass: 'background-sync',
886
+ timestamp: msg.timestamp,
887
+ clientMessageId: msg.clientMessageId,
888
+ });
889
+ }
890
+ const result = {
891
+ clientMessageId: intent.clientMessageId,
780
892
  messageId,
781
893
  timestamp,
782
- recipientDeviceCount: batch.deviceMessages.length,
894
+ recipientDeviceCount: intent.deviceMessages.length,
783
895
  };
896
+ await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
897
+ return result;
898
+ }
899
+ async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options) {
900
+ return sendGroupWithExactOutbox({
901
+ storage: this.storage,
902
+ ...(this.relay && { relay: this.relay }),
903
+ senderUserId: this.userId,
904
+ senderDeviceId: this.deviceId,
905
+ deliveryMode: this.sealedSenderDeliveryMode,
906
+ preparePayload: async (groupId, bytes, sendOptions) => {
907
+ const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions);
908
+ return {
909
+ ciphertext: CryptoUtils.bytesToBase64(prepared.ciphertext),
910
+ preMessages: prepared.preMessages,
911
+ ...(prepared.senderKeyDistributionId && {
912
+ senderKeyDistributionId: prepared.senderKeyDistributionId,
913
+ }),
914
+ };
915
+ },
916
+ confirmSenderKeyDistributionSent: (groupId, senderKeyId) => this.senderKeyManager.confirmSenderKeyDistributionSent(groupId, this.userId, this.deviceId, senderKeyId),
917
+ resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions),
918
+ prepareSharedMessage: async (groupId, members, ciphertext) => {
919
+ if (members.length === 0 ||
920
+ this.sealedSenderDeliveryMode === 'disabled' ||
921
+ !this.sealedSenderProvider ||
922
+ !this.endorsementManager ||
923
+ !this.relay?.sendMultiRecipientUnidentified) {
924
+ return undefined;
925
+ }
926
+ const prepared = await prepareGroupSharedMessage({
927
+ storage: this.storage,
928
+ senderKeys: await this.sealedSenderProvider(),
929
+ members,
930
+ encryptedMessageBase64: ciphertext,
931
+ });
932
+ return prepared
933
+ ? {
934
+ groupId,
935
+ sentMessageBase64: prepared.sentMessageBase64,
936
+ recipientUserIds: prepared.recipientUserIds,
937
+ deliveryMode: this.sealedSenderDeliveryMode === 'required' ? 'required' : 'preferred',
938
+ }
939
+ : undefined;
940
+ },
941
+ prepareDeviceMessage: (member, groupId, ciphertext, timestamp) => this.prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp),
942
+ prepareSyncMessages: async (groupId, bytes, timestamp, clientMessageId) => {
943
+ if (!this.relay)
944
+ return [];
945
+ const syncPayload = this.buildSentSyncTranscript(groupId, bytes, timestamp);
946
+ const prepared = await this.sesameManager.sendToLocalOtherDevices(syncPayload, {
947
+ clientTimestamp: timestamp,
948
+ includeSyncMessages: false,
949
+ });
950
+ return prepared.map((message, index) => ({
951
+ recipientUserId: message.recipientUserId,
952
+ recipientDeviceId: message.recipientDeviceId,
953
+ timestamp: message.timestamp,
954
+ clientMessageId: `${clientMessageId}:sync:${index}`,
955
+ ciphertext: typeof message.ciphertext === 'string'
956
+ ? message.ciphertext
957
+ : CryptoUtils.bytesToBase64(message.ciphertext),
958
+ messageType: getEnvelopeMessageType(message.ciphertext),
959
+ }));
960
+ },
961
+ resolveGroupAuthorization: (groupId, recipients) => this.resolveGroupSendAuthorization(groupId, recipients),
962
+ reportIdentifiedFallback: (recipientUserId) => this.reportIdentifiedFallback(recipientUserId),
963
+ sendPreparedSealedDevice: (intent, message, auth) => this.sendToDevice(message, message.ciphertext, message.messageType, undefined, null, undefined, intent.clientMessageId, {
964
+ sentMessageBase64: message.sealedSenderMessage,
965
+ auth,
966
+ deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
967
+ }),
968
+ }, actualGroupId, plaintextBytes, options);
969
+ }
970
+ async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp) {
971
+ const stored = {
972
+ recipientUserId: member.userId,
973
+ recipientDeviceId: member.deviceId,
974
+ timestamp,
975
+ ciphertext,
976
+ messageType: 'sender_key',
977
+ };
978
+ const sealedSender = await this.resolveSealedSenderContext(member.userId, groupId);
979
+ if (!sealedSender || !this.relay?.sendMultiRecipientUnidentified)
980
+ return stored;
981
+ stored.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(stored, ciphertext, 'sender_key', undefined, sealedSender);
982
+ stored.sealedSenderDeliveryMode =
983
+ sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred';
984
+ if (sealedSender.auth.type === 'accessKey') {
985
+ stored.sealedSenderAuthorization = 'access_key';
986
+ stored.sealedSenderAccessKey = sealedSender.auth.unidentifiedAccessKey;
987
+ }
988
+ else {
989
+ stored.sealedSenderAuthorization = 'group_send_token';
990
+ }
991
+ return stored;
992
+ }
993
+ async resolveGroupSendAuthorization(groupId, recipientUserIds) {
994
+ if (!this.endorsementManager || recipientUserIds.length === 0)
995
+ return null;
996
+ const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, recipientUserIds);
997
+ if (needsRefresh && this.endorsementRefresher) {
998
+ await this.endorsementRefresher(groupId, recipientUserIds);
999
+ this.logger.debug('Refreshed endorsements before durable group send', {
1000
+ category: 'E2EE',
1001
+ data: { groupId, reason },
1002
+ });
1003
+ }
1004
+ const groupSecretParams = this.groupSecretParamsProvider
1005
+ ? await this.groupSecretParamsProvider(groupId)
1006
+ : null;
1007
+ const combined = await this.endorsementManager.getCombinedToken(groupId, recipientUserIds, groupSecretParams ?? undefined);
1008
+ return combined
1009
+ ? {
1010
+ type: 'groupSendToken',
1011
+ groupSendToken: combined.token,
1012
+ recipientAciBytes: combined.aciBytesByUserId,
1013
+ }
1014
+ : null;
1015
+ }
1016
+ async serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender) {
1017
+ return serializeDirectSealedSenderTransport(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender);
784
1018
  }
785
1019
  /**
786
1020
  * Resolve sealed sender context for a recipient.
@@ -807,162 +1041,32 @@ export class SignalProtocolServiceCipher {
807
1041
  *
808
1042
  */
809
1043
  async resolveSealedSenderContext(recipientUserId, groupId) {
810
- if (!this.sealedSenderProvider || !this.relay?.sendUnidentified) {
811
- return null;
812
- }
813
- try {
814
- // Priority 1: GroupSend endorsement (preferred for groups)
815
- // No profile key needed. Endorsement tokens prove group membership via ZK credential
816
- if (groupId && this.endorsementManager) {
817
- try {
818
- // Resolve group secret params for endorsement token generation
819
- const groupSecretParams = this.groupSecretParamsProvider
820
- ? await this.groupSecretParamsProvider(groupId)
821
- : null;
822
- const endorsementToken = await this.endorsementManager.getTokenForRecipient(groupId, recipientUserId, groupSecretParams ?? undefined);
823
- if (endorsementToken) {
824
- const { senderCertificateBase64, senderIdentityPrivate, config } = await this.sealedSenderProvider();
825
- const recipientAddress = ProtocolAddress.create(recipientUserId, 1);
826
- const recipientIdentityRecord = await this.storage.getContactIdentity(recipientAddress);
827
- if (recipientIdentityRecord) {
828
- const recipientIdentityPublic = base64ToBytes(recipientIdentityRecord.identity.x25519PublicKey);
829
- return {
830
- senderCertificateBase64,
831
- senderIdentityPrivate,
832
- recipientIdentityPublic,
833
- config,
834
- auth: {
835
- type: 'groupSendToken',
836
- groupSendToken: endorsementToken.token,
837
- // The identity the token endorses. The relay verifies the
838
- // token against this claim before reading any account.
839
- recipientAciBytes: new Map([
840
- [recipientUserId, endorsementToken.aciBytes],
841
- ]),
842
- },
843
- };
844
- }
845
- }
846
- }
847
- catch (endorsementError) {
848
- // Endorsement lookup failed. Fall through to UAK path
849
- this.logger.debug('Endorsement lookup failed, trying UAK', {
850
- category: 'E2EE',
851
- data: {
852
- recipientUserId,
853
- groupId,
854
- error: endorsementError.message,
855
- },
856
- });
857
- }
858
- }
859
- // Priority 2: Per-contact mode-based UAK (existing path)
860
- // Check mode first. DISABLED skips sealed sender entirely
861
- const contactStateStore = this.contactProfileStateStore;
862
- if (!contactStateStore) {
863
- this.logger.debug('No contact profile state store configured, using identified delivery', {
864
- category: 'E2EE',
865
- data: { recipientUserId, groupId },
866
- });
867
- return null;
868
- }
869
- const mode = await contactStateStore.getUnidentifiedAccessMode(recipientUserId);
870
- if (mode === UnidentifiedAccessMode.DISABLED) {
871
- this.logger.debug('Sealed sender disabled for recipient, using identified delivery', {
872
- category: 'E2EE',
873
- data: { recipientUserId, mode },
874
- });
875
- return null;
876
- }
877
- // Resolve access key based on mode
878
- const { deriveAccessKey } = await import('../internal/protocol/sealed-sender/delivery-token.js');
879
- const { bytesToBase64 } = await import('../internal/crypto/index.js');
880
- let auth;
881
- switch (mode) {
882
- case UnidentifiedAccessMode.UNRESTRICTED: {
883
- // Anyone can send sealed sender. Use zeroed 16-byte key
884
- const zeroedKey = new Uint8Array(16);
885
- auth = {
886
- type: 'accessKey',
887
- unidentifiedAccessKey: bytesToBase64(zeroedKey),
888
- };
889
- break;
890
- }
891
- case UnidentifiedAccessMode.ENABLED: {
892
- // Must derive from profile key. Fail if unavailable
893
- const recipientProfileKey = await contactStateStore.getContactProfileKey(recipientUserId);
894
- if (!recipientProfileKey) {
895
- this.logger.debug('No profile key for ENABLED recipient, using identified delivery', {
896
- category: 'E2EE',
897
- data: { recipientUserId },
898
- });
899
- return null;
900
- }
901
- const accessKey = await deriveAccessKey(recipientProfileKey);
902
- auth = {
903
- type: 'accessKey',
904
- unidentifiedAccessKey: bytesToBase64(accessKey),
905
- };
906
- break;
907
- }
908
- case UnidentifiedAccessMode.UNKNOWN:
909
- default: {
910
- // Best effort: use derived key if available, else zeroed key
911
- const recipientProfileKey = await contactStateStore.getContactProfileKey(recipientUserId);
912
- if (recipientProfileKey) {
913
- const accessKey = await deriveAccessKey(recipientProfileKey);
914
- auth = {
915
- type: 'accessKey',
916
- unidentifiedAccessKey: bytesToBase64(accessKey),
917
- };
918
- }
919
- else {
920
- const zeroedKey = new Uint8Array(16);
921
- auth = {
922
- type: 'accessKey',
923
- unidentifiedAccessKey: bytesToBase64(zeroedKey),
924
- };
925
- }
926
- break;
927
- }
928
- }
929
- // Get sender certificate and identity keys
930
- const { senderCertificateBase64, senderIdentityPrivate, config } = await this.sealedSenderProvider();
931
- // Get recipient's identity public key (needed for sealed sender DH)
932
- const recipientAddress = ProtocolAddress.create(recipientUserId, 1);
933
- const recipientIdentityRecord = await this.storage.getContactIdentity(recipientAddress);
934
- if (!recipientIdentityRecord) {
935
- // No identity key on file - fall back to identified delivery
936
- this.logger.debug('No identity key for recipient, using identified delivery', {
937
- category: 'E2EE',
938
- data: { recipientUserId },
939
- });
940
- return null;
941
- }
942
- const recipientIdentityPublic = base64ToBytes(recipientIdentityRecord.identity.x25519PublicKey);
943
- return {
944
- senderCertificateBase64,
945
- senderIdentityPrivate,
946
- recipientIdentityPublic,
947
- config,
948
- auth,
949
- };
950
- }
951
- catch (error) {
952
- // Sealed sender is best-effort. Fall back to identified delivery on failure
953
- this.logger.warn('Failed to resolve sealed sender context, using identified delivery', {
954
- category: 'E2EE',
955
- data: { recipientUserId, error: error.message },
956
- });
957
- return null;
958
- }
1044
+ return resolveSealedSenderSendContext({
1045
+ storage: this.storage,
1046
+ deliveryMode: this.sealedSenderDeliveryMode,
1047
+ relaySupportsUnidentified: Boolean(this.relay?.sendMultiRecipientUnidentified),
1048
+ ...(this.sealedSenderProvider && {
1049
+ provider: this.sealedSenderProvider,
1050
+ }),
1051
+ ...(this.contactProfileStateStore && {
1052
+ contactProfileStateStore: this.contactProfileStateStore,
1053
+ }),
1054
+ ...(this.endorsementManager && {
1055
+ endorsementManager: this.endorsementManager,
1056
+ }),
1057
+ ...(this.groupSecretParamsProvider && {
1058
+ groupSecretParamsProvider: this.groupSecretParamsProvider,
1059
+ }),
1060
+ logger: this.logger,
1061
+ useIdentifiedDeliveryOrThrow: (userId, reason) => this.useIdentifiedDeliveryOrThrow(userId, reason),
1062
+ }, recipientUserId, groupId);
959
1063
  }
960
1064
  /**
961
1065
  * Send a single ciphertext to a device, optionally wrapping with sealed sender.
962
1066
  *
963
1067
  * When sealed sender context is available:
964
- * 1. Wraps the ciphertext with seal() to hide sender identity
965
- * 2. Uses relay.sendUnidentified() for anonymous delivery
1068
+ * 1. Wraps the ciphertext with the multi-recipient format for one recipient
1069
+ * 2. Uses relay.sendMultiRecipientUnidentified() for anonymous delivery
966
1070
  *
967
1071
  * On sealed sender auth failure, transitions the recipient's
968
1072
  * UnidentifiedAccessMode before falling back to identified delivery:
@@ -974,37 +1078,41 @@ export class SignalProtocolServiceCipher {
974
1078
  * | UNKNOWN | DISABLED | Confirmed doesn't work |
975
1079
  *
976
1080
  */
977
- async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId) {
1081
+ async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender) {
978
1082
  const effectiveClientMessageId = msg.clientMessageId ?? clientMessageId;
979
- // Sealed sender path: wrap with seal() and use anonymous delivery
980
- if (sealedSender && this.relay.sendUnidentified) {
981
- const { sealMessage } = await import('./sealed-sender-ops.js');
982
- const sealedCiphertext = await sealMessage(ciphertextBase64, sealedSender.senderCertificateBase64, sealedSender.senderIdentityPrivate, sealedSender.recipientIdentityPublic, sealedSender.config, this.logger,
983
- // The outer envelope is `unidentified_sender` for every sealed
984
- // message. The inner type has to travel inside the seal, or the
985
- // recipient cannot tell a group message from a pairwise one.
986
- messageType === 'sender_key'
987
- ? SealedSenderContentType.SENDERKEY_MESSAGE
988
- : messageType === 'prekey_bundle'
989
- ? SealedSenderContentType.PREKEY_MESSAGE
990
- : SealedSenderContentType.MESSAGE);
1083
+ if (preparedSealedSender && !this.relay.sendMultiRecipientUnidentified) {
1084
+ if (preparedSealedSender.deliveryMode === 'required') {
1085
+ throw new EncryptionError('Required sealed-sender relay capability is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: msg.recipientUserId });
1086
+ }
1087
+ }
1088
+ // Sealed sender path: use the V2 upload format for one recipient. V2 has
1089
+ // no two-recipient minimum; its recipient-count field permits this exact
1090
+ // direct-delivery shape.
1091
+ if ((sealedSender || preparedSealedSender) && this.relay.sendMultiRecipientUnidentified) {
1092
+ const prepared = preparedSealedSender ??
1093
+ (sealedSender
1094
+ ? {
1095
+ sentMessageBase64: await this.serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender),
1096
+ auth: sealedSender.auth,
1097
+ deliveryMode: sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred',
1098
+ }
1099
+ : undefined);
1100
+ if (!prepared)
1101
+ throw new Error('Missing sealed-sender delivery state');
991
1102
  try {
992
- return await this.relay.sendUnidentified({
993
- targetUserId: msg.recipientUserId,
994
- targetDeviceId: msg.recipientDeviceId,
995
- senderUserId: '', // Hidden from server
996
- senderDeviceId: 0,
997
- ciphertext: sealedCiphertext,
998
- messageType: 'unidentified_sender',
999
- timestamp: msg.timestamp,
1000
- clientMessageId: effectiveClientMessageId,
1001
- contentHint,
1002
- }, sealedSender.auth);
1103
+ const result = await this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId);
1104
+ if (result.uuids404.length > 0) {
1105
+ throw new SealedSenderRecipientRejectedError();
1106
+ }
1107
+ return result;
1003
1108
  }
1004
1109
  catch (error) {
1005
1110
  // Fall back to identified delivery only for sealed-sender authorization
1006
1111
  // failures. Other failures retain their original error semantics.
1007
1112
  if (error instanceof SealedSenderAuthError) {
1113
+ if (prepared.deliveryMode === 'required') {
1114
+ throw error;
1115
+ }
1008
1116
  // Restrict the cached mode after authorization fails.
1009
1117
  try {
1010
1118
  if (this.contactProfileStateStore) {
@@ -1047,6 +1155,7 @@ export class SignalProtocolServiceCipher {
1047
1155
  },
1048
1156
  });
1049
1157
  }
1158
+ await this.reportIdentifiedFallback(msg.recipientUserId);
1050
1159
  // Fall through to identified path below
1051
1160
  }
1052
1161
  else {
@@ -1062,302 +1171,13 @@ export class SignalProtocolServiceCipher {
1062
1171
  senderDeviceId: this.deviceId,
1063
1172
  ciphertext: ciphertextBase64,
1064
1173
  messageType,
1174
+ deliveryClass: 'user-visible',
1065
1175
  timestamp: msg.timestamp,
1066
1176
  clientMessageId: effectiveClientMessageId,
1067
1177
  recipientRegistrationId,
1068
1178
  contentHint,
1069
1179
  });
1070
1180
  }
1071
- /**
1072
- * Attempt V2 multi-recipient sealed sender send.
1073
- * Returns null if unavailable. Caller falls back to V1.
1074
- *
1075
- * Recovery behavior:
1076
- * - 409 (mismatched devices): refresh device lists, rebuild recipient list, retry once
1077
- * - 410 (stale sessions): archive stale sessions, retry once
1078
- * - Other errors: return null for full V1 fallback
1079
- *
1080
- */
1081
- async tryMultiRecipientSend(groupId, otherMembers, encryptedMessageJson, sendTimestamp, clientMessageId) {
1082
- // Guard checks. Return null to trigger V1 fallback
1083
- if (!this.sealedSenderProvider)
1084
- return null;
1085
- if (!this.relay?.sendMultiRecipientUnidentified)
1086
- return null;
1087
- if (otherMembers.length < 2)
1088
- return null;
1089
- // outer recovery state flags. Prevent infinite retry loops
1090
- //
1091
- let hasRetriedDevices = false;
1092
- let hasRetriedSessions = false;
1093
- let currentMembers = otherMembers;
1094
- const attemptV2Send = async () => {
1095
- // Get sender keys (certificate + identity)
1096
- const senderKeys = await this.sealedSenderProvider();
1097
- const { base64ToBytes: b64ToBytes, bytesToBase64: bytesToB64 } = await import('../internal/crypto/index.js');
1098
- // Gather recipient identity keys (per unique userId)
1099
- const identityByUser = new Map();
1100
- const uniqueUserIds = [...new Set(currentMembers.map((m) => m.userId))];
1101
- for (const userId of uniqueUserIds) {
1102
- const address = ProtocolAddress.create(userId, 1);
1103
- const identityRecord = await this.storage.getContactIdentity(address);
1104
- if (identityRecord) {
1105
- identityByUser.set(userId, b64ToBytes(identityRecord.identity.x25519PublicKey));
1106
- }
1107
- }
1108
- // Split V2-eligible vs V1-fallback
1109
- const v2Members = [];
1110
- const v1FallbackMembers = [];
1111
- for (const member of currentMembers) {
1112
- if (identityByUser.has(member.userId)) {
1113
- v2Members.push(member);
1114
- }
1115
- else {
1116
- v1FallbackMembers.push(member);
1117
- }
1118
- }
1119
- // Need at least 2 V2-eligible unique users
1120
- const v2UniqueUsers = new Set(v2Members.map((m) => m.userId));
1121
- if (v2UniqueUsers.size < 2)
1122
- return null;
1123
- // Build V2 recipients with registration IDs from session state
1124
- const v2Recipients = [];
1125
- for (const member of v2Members) {
1126
- const session = await this.storage.getSessionRecord(ProtocolAddress.create(member.userId, member.deviceId));
1127
- let registrationId = 0;
1128
- if (session?.currentSession) {
1129
- registrationId = session.currentSession.remoteRegistrationId;
1130
- }
1131
- v2Recipients.push({
1132
- serviceId: member.userId,
1133
- deviceId: member.deviceId,
1134
- registrationId,
1135
- identityPublic: identityByUser.get(member.userId),
1136
- });
1137
- }
1138
- // Call sealMultiRecipient()
1139
- const { sealMultiRecipient } = await import('../internal/protocol/sealed-sender/index.js');
1140
- const { deserializeSenderCertificate } = await import('../internal/protocol/sealed-sender/index.js');
1141
- // Parse sender certificate
1142
- const certBytes = b64ToBytes(senderKeys.senderCertificateBase64);
1143
- const senderCertificate = deserializeSenderCertificate(certBytes);
1144
- // Convert encryptedMessageJson to bytes for the seal
1145
- const signalProtocolMessage = new TextEncoder().encode(encryptedMessageJson);
1146
- const sealResult = await sealMultiRecipient({
1147
- senderCertificate,
1148
- senderIdentityPrivate: senderKeys.senderIdentityPrivate,
1149
- senderIdentityPublic: senderKeys.senderIdentityPublic,
1150
- recipients: v2Recipients,
1151
- signalProtocolMessage,
1152
- // The group this belongs to stays out of the sealed envelope. The
1153
- // content type says only "decrypt this as a framed SenderKeyMessage".
1154
- // The recipient resolves the group from the frame's distribution
1155
- // identifier against its own sender key store.
1156
- contentType: SealedSenderContentType.SENDERKEY_MESSAGE,
1157
- });
1158
- // Serialize to binary
1159
- const { serializeSentMessage } = await import('../internal/protocol/sealed-sender/v2-binary.js');
1160
- // Group recipients by serviceId for the binary format
1161
- const recipientsByUser = new Map();
1162
- for (const entry of sealResult.recipients) {
1163
- const existing = recipientsByUser.get(entry.serviceId);
1164
- if (existing) {
1165
- existing.devices.push({
1166
- deviceId: entry.deviceId,
1167
- registrationId: entry.registrationId,
1168
- });
1169
- }
1170
- else {
1171
- recipientsByUser.set(entry.serviceId, {
1172
- serviceId: entry.serviceId,
1173
- devices: [
1174
- {
1175
- deviceId: entry.deviceId,
1176
- registrationId: entry.registrationId,
1177
- },
1178
- ],
1179
- encryptedMessageKey: b64ToBytes(entry.encryptedMessageKey),
1180
- authenticationTag: b64ToBytes(entry.authenticationTag),
1181
- });
1182
- }
1183
- }
1184
- const binaryBlob = serializeSentMessage(Array.from(recipientsByUser.values()), [], // No excluded recipients for now
1185
- b64ToBytes(sealResult.ephemeralPublic), b64ToBytes(sealResult.messageCiphertext));
1186
- const sentMessageBase64 = bytesToB64(binaryBlob);
1187
- // Get combined auth token
1188
- if (!this.endorsementManager)
1189
- return null;
1190
- const groupSecretParams = this.groupSecretParamsProvider
1191
- ? await this.groupSecretParamsProvider(groupId)
1192
- : null;
1193
- const v2UserIds = [...v2UniqueUsers];
1194
- // Pre-send endorsement refresh
1195
- const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, v2UserIds);
1196
- if (needsRefresh && this.endorsementRefresher) {
1197
- try {
1198
- await this.endorsementRefresher(groupId, v2UserIds);
1199
- this.logger.debug('Refreshed endorsements before V2 send', {
1200
- category: 'E2EE',
1201
- data: { groupId, reason },
1202
- });
1203
- }
1204
- catch (refreshErr) {
1205
- this.logger.debug('Pre-send endorsement refresh failed, will attempt V1 fallback', {
1206
- category: 'E2EE',
1207
- data: { groupId, error: refreshErr.message },
1208
- });
1209
- }
1210
- }
1211
- const combinedToken = await this.endorsementManager.getCombinedToken(groupId, v2UserIds, groupSecretParams ?? undefined);
1212
- if (!combinedToken)
1213
- return null;
1214
- const auth = {
1215
- type: 'groupSendToken',
1216
- groupSendToken: combinedToken.token,
1217
- // The identities the combined token endorses, straight from the
1218
- // endorsement cache. The relay verifies the token against these
1219
- // claims before reading any account.
1220
- recipientAciBytes: combinedToken.aciBytesByUserId,
1221
- };
1222
- // Send via relay
1223
- const recipientUserIds = Array.from(recipientsByUser.keys());
1224
- const result = await this.relay.sendMultiRecipientUnidentified(sentMessageBase64, auth, sendTimestamp, recipientUserIds, clientMessageId);
1225
- // The server reports recipients it skipped (unregistered device,
1226
- // registration-ID mismatch after a reinstall) in uuids404 while still
1227
- // returning success for the rest. Dropping that field silently loses
1228
- // messages for exactly the members that most need redelivery. So refresh
1229
- // their device lists, and fan out to them per-device alongside the V1
1230
- // fallback members below.
1231
- const v1FallbackTargets = [...v1FallbackMembers];
1232
- if (result.uuids404?.length) {
1233
- this.logger.info('V2 send skipped recipients; refreshing and redelivering per-device', {
1234
- category: 'E2EE',
1235
- data: { groupId, skipped: result.uuids404 },
1236
- });
1237
- const refreshed = await Promise.all(result.uuids404.map((uid) => this.relay.getActiveDevices(uid).catch(() => [])));
1238
- v1FallbackTargets.push(...refreshed.flat().filter((m) => m.userId !== this.userId));
1239
- }
1240
- // Send to V1 fallback members via per-device fanout
1241
- if (v1FallbackTargets.length > 0) {
1242
- const sealedSenderByUser = new Map();
1243
- const fallbackUserIds = [...new Set(v1FallbackTargets.map((m) => m.userId))];
1244
- for (const userId of fallbackUserIds) {
1245
- sealedSenderByUser.set(userId, await this.resolveSealedSenderContext(userId, groupId));
1246
- }
1247
- for (const member of v1FallbackTargets) {
1248
- const sealedSender = sealedSenderByUser.get(member.userId) ?? null;
1249
- await this.sendToDevice({
1250
- recipientUserId: member.userId,
1251
- recipientDeviceId: member.deviceId,
1252
- timestamp: sendTimestamp,
1253
- }, encryptedMessageJson, 'sender_key', undefined, sealedSender, undefined, clientMessageId);
1254
- }
1255
- }
1256
- return {
1257
- messageId: result.messageId,
1258
- serverTimestamp: result.serverTimestamp,
1259
- };
1260
- };
1261
- try {
1262
- return await attemptV2Send();
1263
- }
1264
- catch (error) {
1265
- const errorMessage = error.message ?? '';
1266
- // 409: Mismatched devices. Refresh device lists and retry once
1267
- // the application send pipeline
1268
- if (!hasRetriedDevices && isMismatchedDevicesError(errorMessage)) {
1269
- hasRetriedDevices = true;
1270
- this.logger.info('V2 send got mismatched devices (409), refreshing and retrying', {
1271
- category: 'E2EE',
1272
- data: { groupId },
1273
- });
1274
- try {
1275
- // Refresh device lists for all affected users
1276
- const uniqueUserIds = [...new Set(currentMembers.map((m) => m.userId))];
1277
- const refreshedDevices = await Promise.all(uniqueUserIds.map((uid) => this.relay.getActiveDevices(uid)));
1278
- currentMembers = refreshedDevices.flat().filter((m) => m.userId !== this.userId);
1279
- return await attemptV2Send();
1280
- }
1281
- catch (retryError) {
1282
- this.logger.debug('V2 retry after device refresh failed, falling back to V1', {
1283
- category: 'E2EE',
1284
- data: { groupId, error: retryError.message },
1285
- });
1286
- return null;
1287
- }
1288
- }
1289
- // 410: Stale sessions. Archive and retry once
1290
- // the application send pipeline
1291
- if (!hasRetriedSessions && isStaleSessionV2Error(errorMessage)) {
1292
- hasRetriedSessions = true;
1293
- this.logger.info('V2 send got stale sessions (410), archiving and retrying', {
1294
- category: 'E2EE',
1295
- data: { groupId },
1296
- });
1297
- try {
1298
- // Archive stale sessions for all affected devices and re-establish
1299
- if (this.staleSessionRefresher) {
1300
- for (const member of currentMembers) {
1301
- await this.staleSessionRefresher(member.userId, member.deviceId).catch(() => {
1302
- // Non-fatal: some devices might not have stale sessions
1303
- });
1304
- }
1305
- }
1306
- return await attemptV2Send();
1307
- }
1308
- catch (retryError) {
1309
- this.logger.debug('V2 retry after session refresh failed, falling back to V1', {
1310
- category: 'E2EE',
1311
- data: { groupId, error: retryError.message },
1312
- });
1313
- return null;
1314
- }
1315
- }
1316
- // All other errors: V1 fallback
1317
- this.logger.debug('V2 multi-recipient send failed, falling back to V1', {
1318
- category: 'E2EE',
1319
- data: { groupId, error: errorMessage },
1320
- });
1321
- return null;
1322
- }
1323
- }
1324
- /**
1325
- * V1 per-device sealed sender fanout (legacy path, used as fallback).
1326
- */
1327
- async perDeviceFanoutSend(groupId, otherMembers, encryptedMessageJson, sendTimestamp, clientMessageId) {
1328
- // Pre-send endorsement freshness check (non-blocking, log only)
1329
- // Actual refresh is handled at orchestration layer (group-service.ts)
1330
- if (this.endorsementManager) {
1331
- const uniqueUserIds = [...new Set(otherMembers.map((m) => m.userId))];
1332
- const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, uniqueUserIds);
1333
- if (needsRefresh) {
1334
- this.logger.debug('Group endorsements need refresh before send', {
1335
- category: 'E2EE',
1336
- data: { groupId, reason },
1337
- });
1338
- }
1339
- }
1340
- // Resolve sealed sender context per unique recipient (not per device)
1341
- // Identity keys and endorsement tokens are per-user, shared across devices
1342
- const sealedSenderByUser = new Map();
1343
- const uniqueRecipientIds = [...new Set(otherMembers.map((m) => m.userId))];
1344
- for (const userId of uniqueRecipientIds) {
1345
- sealedSenderByUser.set(userId, await this.resolveSealedSenderContext(userId, groupId));
1346
- }
1347
- // Send to each member device (sendToDevice handles seal + fallback)
1348
- let firstResult;
1349
- for (const member of otherMembers) {
1350
- const sealedSender = sealedSenderByUser.get(member.userId) ?? null;
1351
- const result = await this.sendToDevice({
1352
- recipientUserId: member.userId,
1353
- recipientDeviceId: member.deviceId,
1354
- timestamp: sendTimestamp,
1355
- }, encryptedMessageJson, 'sender_key', undefined, sealedSender, undefined, clientMessageId);
1356
- if (!firstResult)
1357
- firstResult = result;
1358
- }
1359
- return firstResult;
1360
- }
1361
1181
  /**
1362
1182
  * Resolve the group roster to concrete devices via the relay.
1363
1183
  *
@@ -1376,18 +1196,7 @@ export class SignalProtocolServiceCipher {
1376
1196
  const deviceResults = await Promise.all(options.groupMemberUserIds.map((userId) => this.relay.getActiveDevices(userId)));
1377
1197
  return deviceResults.flat();
1378
1198
  }
1379
- /**
1380
- * Encrypt to a group via Sender Keys (O(1) encryption)
1381
- *
1382
- * Prefers V2 multi-recipient sealed sender when available, falls back to
1383
- * V1 per-device fanout.
1384
- */
1385
- async encryptToGroup(groupId, plaintextBytes, options) {
1386
- // Extract actual group ID from prefixed format
1387
- const actualGroupId = extractGroupId(groupId);
1388
- await this.groupSendBarrierChecker?.(actualGroupId);
1389
- // Require sender key to exist - caller (SignalProtocolClient.createGroupSenderKey) must create it first
1390
- // The sender key is then distributed to group members before sending
1199
+ async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options) {
1391
1200
  const existingKey = await this.storage.getSenderKey(actualGroupId, this.userId, this.deviceId);
1392
1201
  if (!existingKey) {
1393
1202
  throw new EncryptionError(`No sender key for group ${actualGroupId}. Call createGroupSenderKey() first to create and distribute the key.`, EncryptionErrorCode.SESSION_NOT_FOUND, {
@@ -1396,116 +1205,69 @@ export class SignalProtocolServiceCipher {
1396
1205
  deviceId: this.deviceId,
1397
1206
  });
1398
1207
  }
1399
- // Encrypt with sender key (O(1) - single encryption for all members)
1400
- // Auto-rotate on SENDER_KEY_EXPIRED
1401
- let encrypted;
1402
- try {
1403
- encrypted = await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes);
1404
- }
1405
- catch (error) {
1406
- if (error instanceof EncryptionError &&
1407
- error.code === EncryptionErrorCode.SENDER_KEY_EXPIRED) {
1208
+ let distributionMessage = await this.senderKeyManager.getPendingSenderKeyDistribution(actualGroupId, this.userId, this.deviceId);
1209
+ if (!distributionMessage) {
1210
+ try {
1211
+ return {
1212
+ ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
1213
+ preMessages: [],
1214
+ };
1215
+ }
1216
+ catch (error) {
1217
+ if (!(error instanceof EncryptionError) ||
1218
+ error.code !== EncryptionErrorCode.SENDER_KEY_EXPIRED) {
1219
+ throw error;
1220
+ }
1408
1221
  this.logger.info('Sender key expired, auto-rotating', {
1409
1222
  category: 'E2EE',
1410
1223
  data: { groupId: actualGroupId },
1411
1224
  });
1412
- // Rotate sender key (generates new key material + increments generation)
1413
- const { distributionMessage } = await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId);
1414
- // Redistribute new sender key to all group members via relay
1415
- if (this.relay) {
1416
- const members = await this.resolveGroupMemberDevices(actualGroupId, options);
1417
- const otherMembers = members.filter((m) => m.userId !== this.userId);
1418
- for (const member of otherMembers) {
1419
- // Send SKDM via pairwise session (same as initial distribution)
1420
- await this.ensureSessionsForUser(member.userId);
1421
- // Serialize SKDM as ProtoContentData with senderKeyDistributionMessage field
1422
- // The string field contains JSON-encoded {groupId, ...distributionMessage}
1423
- const skdmBytes = this.contentAdapter
1424
- ? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
1425
- : new TextEncoder().encode(JSON.stringify({
1426
- senderKeyDistributionMessage: JSON.stringify({
1427
- groupId: actualGroupId,
1428
- ...distributionMessage,
1429
- }),
1430
- }));
1431
- const batch = await this.sesameManager.send(member.userId, skdmBytes, {});
1432
- for (const msg of batch.deviceMessages) {
1433
- const ciphertextBase64 = typeof msg.ciphertext === 'string'
1434
- ? msg.ciphertext
1435
- : CryptoUtils.bytesToBase64(msg.ciphertext);
1436
- await this.relay.send({
1437
- targetUserId: msg.recipientUserId,
1438
- targetDeviceId: msg.recipientDeviceId,
1439
- senderUserId: this.userId,
1440
- senderDeviceId: this.deviceId,
1441
- ciphertext: ciphertextBase64,
1442
- // A distribution message is ordinary pairwise traffic. The
1443
- // group it announces is inside the encrypted payload. Naming
1444
- // it on the envelope would hand the relay the same membership
1445
- // map the message exists to keep off the wire.
1446
- messageType: getEnvelopeMessageType(msg.ciphertext),
1447
- timestamp: msg.timestamp,
1448
- });
1449
- }
1450
- }
1451
- }
1452
- // Retry encryption with the new key (once, no infinite loop)
1453
- encrypted = await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes);
1454
- }
1455
- else {
1456
- throw error;
1225
+ ({ distributionMessage } = await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId, { distributionPending: true }));
1457
1226
  }
1458
1227
  }
1459
- // Send encrypted message via relay
1460
- let messageId = `local-${Date.now()}`;
1461
- let timestamp = Date.now(); // Fallback if no relay
1462
- let recipientDeviceCount = 0;
1228
+ const preMessages = [];
1463
1229
  if (this.relay) {
1464
- // Resolve group members → devices from the caller-provided roster.
1465
- // Membership is local-first (it lives in each client's decrypted group
1466
- // state). The relay deliberately keeps no membership map, so there is
1467
- // no server endpoint to fall back to.
1468
1230
  const members = await this.resolveGroupMemberDevices(actualGroupId, options);
1469
- // Framed SenderKeyMessage bytes → base64 for transport
1470
- const encryptedMessageJson = CryptoUtils.bytesToBase64(encrypted);
1471
- const sendTimestamp = options?.timestamp ?? Date.now();
1472
- // Filter to other members (skip self, the application send pipeline)
1473
- const otherMembers = members.filter((m) => m.userId !== this.userId);
1474
- recipientDeviceCount = otherMembers.length;
1475
- // Try V2 multi-recipient first
1476
- const v2Result = await this.tryMultiRecipientSend(actualGroupId, otherMembers, encryptedMessageJson, sendTimestamp, options?.clientMessageId);
1477
- if (v2Result) {
1478
- messageId = v2Result.messageId;
1479
- timestamp = v2Result.serverTimestamp;
1480
- this.logger.debug('Group message sent via V2 multi-recipient', {
1481
- category: 'E2EE',
1482
- data: { groupId: actualGroupId, recipientDeviceCount, messageId },
1231
+ const otherMembers = members.filter((member) => member.userId !== this.userId);
1232
+ const recipientUserIds = [...new Set(otherMembers.map((member) => member.userId))];
1233
+ for (const recipientUserId of recipientUserIds) {
1234
+ await this.ensureSessionsForUser(recipientUserId);
1235
+ const skdmBytes = this.contentAdapter
1236
+ ? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
1237
+ : new TextEncoder().encode(JSON.stringify({
1238
+ senderKeyDistributionMessage: JSON.stringify({
1239
+ groupId: actualGroupId,
1240
+ ...distributionMessage,
1241
+ }),
1242
+ }));
1243
+ const batch = await this.sesameManager.send(recipientUserId, skdmBytes, {
1244
+ clientTimestamp: options.timestamp,
1245
+ includeSyncMessages: false,
1483
1246
  });
1484
- }
1485
- else {
1486
- // V1 fallback
1487
- const v1Result = await this.perDeviceFanoutSend(actualGroupId, otherMembers, encryptedMessageJson, sendTimestamp, options?.clientMessageId);
1488
- if (v1Result) {
1489
- messageId = v1Result.messageId;
1490
- timestamp = v1Result.serverTimestamp;
1491
- }
1492
- else {
1493
- messageId = `group-${actualGroupId}-${timestamp}`;
1247
+ for (const message of batch.deviceMessages) {
1248
+ const stored = await this.prepareStoredDirectDeviceMessage(message, null);
1249
+ stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
1250
+ preMessages.push(stored);
1494
1251
  }
1495
- this.logger.debug('Group message sent via V1 per-device fanout', {
1496
- category: 'E2EE',
1497
- data: { groupId: actualGroupId, recipientDeviceCount, messageId },
1498
- });
1499
1252
  }
1500
- await this.sendSyncTranscriptToLocalOtherDevices(actualGroupId, plaintextBytes, sendTimestamp);
1501
1253
  }
1502
1254
  return {
1503
- messageId,
1504
- timestamp,
1505
- recipientDeviceCount,
1506
- groupId: actualGroupId,
1255
+ ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
1256
+ preMessages,
1257
+ senderKeyDistributionId: distributionMessage.senderKeyId,
1507
1258
  };
1508
1259
  }
1260
+ /**
1261
+ * Encrypt to a group via Sender Keys (O(1) encryption)
1262
+ *
1263
+ * Uses the multi-recipient sealed-sender transport when anonymous delivery
1264
+ * is available, with exact per-device identified delivery otherwise.
1265
+ */
1266
+ async encryptToGroup(groupId, plaintextBytes, options) {
1267
+ const actualGroupId = extractGroupId(groupId);
1268
+ await this.groupSendBarrierChecker?.(actualGroupId);
1269
+ return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options);
1270
+ }
1509
1271
  /**
1510
1272
  * Encrypt binary attachment with two-layer encryption
1511
1273
  *
@@ -1530,7 +1292,7 @@ export class SignalProtocolServiceCipher {
1530
1292
  const uploaded = await this.prepareAttachmentUpload(data, options);
1531
1293
  const attachmentPayload = serializeMediaAttachmentMessage({
1532
1294
  attachment: uploaded,
1533
- timestamp: options?.timestamp ?? Date.now(),
1295
+ timestamp: options.timestamp ?? Date.now(),
1534
1296
  });
1535
1297
  const attachmentBytes = new TextEncoder().encode(attachmentPayload);
1536
1298
  let result;