@open-e2ee/signal-protocol-sdk 13.3.0 → 13.5.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 (187) hide show
  1. package/CHANGELOG.md +436 -0
  2. package/README.md +1 -1
  3. package/SECURITY.md +2 -2
  4. package/dist/client/binary-send.d.ts +28 -0
  5. package/dist/client/binary-send.d.ts.map +1 -0
  6. package/dist/client/binary-send.js +26 -0
  7. package/dist/client/binary-send.js.map +1 -0
  8. package/dist/client/client.d.ts +47 -6
  9. package/dist/client/client.d.ts.map +1 -1
  10. package/dist/client/client.js +288 -136
  11. package/dist/client/client.js.map +1 -1
  12. package/dist/client/content-adapter.d.ts +18 -0
  13. package/dist/client/content-adapter.d.ts.map +1 -1
  14. package/dist/client/content-adapter.js.map +1 -1
  15. package/dist/client/device-set-reconciliation.d.ts +23 -8
  16. package/dist/client/device-set-reconciliation.d.ts.map +1 -1
  17. package/dist/client/device-set-reconciliation.js +25 -11
  18. package/dist/client/device-set-reconciliation.js.map +1 -1
  19. package/dist/client/event-hooks.d.ts +88 -8
  20. package/dist/client/event-hooks.d.ts.map +1 -1
  21. package/dist/client/event-hooks.js +1 -0
  22. package/dist/client/event-hooks.js.map +1 -1
  23. package/dist/client/group-outbox.d.ts +45 -10
  24. package/dist/client/group-outbox.d.ts.map +1 -1
  25. package/dist/client/group-outbox.js +246 -154
  26. package/dist/client/group-outbox.js.map +1 -1
  27. package/dist/client/group-receive-authorization.d.ts +10 -1
  28. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  29. package/dist/client/group-receive-authorization.js.map +1 -1
  30. package/dist/client/hosted-anonymous-delivery.d.ts +18 -1
  31. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  32. package/dist/client/hosted-anonymous-delivery.js +84 -12
  33. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  34. package/dist/client/hosted-connection.js +1 -1
  35. package/dist/client/hosted-connection.js.map +1 -1
  36. package/dist/client/hosted-group-authority.d.ts +6 -2
  37. package/dist/client/hosted-group-authority.d.ts.map +1 -1
  38. package/dist/client/hosted-group-authority.js +11 -7
  39. package/dist/client/hosted-group-authority.js.map +1 -1
  40. package/dist/client/hosted-groups.d.ts +5 -1
  41. package/dist/client/hosted-groups.d.ts.map +1 -1
  42. package/dist/client/hosted-groups.js +8 -4
  43. package/dist/client/hosted-groups.js.map +1 -1
  44. package/dist/client/hosted-http-error.d.ts +5 -1
  45. package/dist/client/hosted-http-error.d.ts.map +1 -1
  46. package/dist/client/hosted-http-error.js +5 -1
  47. package/dist/client/hosted-http-error.js.map +1 -1
  48. package/dist/client/hosted-mailbox-subscription.d.ts +2 -0
  49. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  50. package/dist/client/hosted-mailbox-subscription.js +5 -5
  51. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  52. package/dist/client/hosted-resume-error.d.ts +19 -0
  53. package/dist/client/hosted-resume-error.d.ts.map +1 -0
  54. package/dist/client/hosted-resume-error.js +44 -0
  55. package/dist/client/hosted-resume-error.js.map +1 -0
  56. package/dist/client/hosted-resume.d.ts +24 -0
  57. package/dist/client/hosted-resume.d.ts.map +1 -0
  58. package/dist/client/hosted-resume.js +82 -0
  59. package/dist/client/hosted-resume.js.map +1 -0
  60. package/dist/client/hosted-transport.d.ts +11 -1
  61. package/dist/client/hosted-transport.d.ts.map +1 -1
  62. package/dist/client/hosted-transport.js +102 -33
  63. package/dist/client/hosted-transport.js.map +1 -1
  64. package/dist/client/hosted.d.ts.map +1 -1
  65. package/dist/client/hosted.js +29 -6
  66. package/dist/client/hosted.js.map +1 -1
  67. package/dist/client/index.d.ts +3 -1
  68. package/dist/client/index.d.ts.map +1 -1
  69. package/dist/client/index.js +2 -0
  70. package/dist/client/index.js.map +1 -1
  71. package/dist/client/receive-queue.d.ts +5 -2
  72. package/dist/client/receive-queue.d.ts.map +1 -1
  73. package/dist/client/receive-queue.js +55 -18
  74. package/dist/client/receive-queue.js.map +1 -1
  75. package/dist/client/relay-acceptance.d.ts +49 -6
  76. package/dist/client/relay-acceptance.d.ts.map +1 -1
  77. package/dist/client/relay-acceptance.js +49 -3
  78. package/dist/client/relay-acceptance.js.map +1 -1
  79. package/dist/client/relay-protocol.d.ts +37 -7
  80. package/dist/client/relay-protocol.d.ts.map +1 -1
  81. package/dist/client/relay-protocol.js +53 -10
  82. package/dist/client/relay-protocol.js.map +1 -1
  83. package/dist/client/retry-family.d.ts +3 -3
  84. package/dist/client/retry-family.js +1 -1
  85. package/dist/client/retry-family.js.map +1 -1
  86. package/dist/client/retry-request-envelope.d.ts +18 -8
  87. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  88. package/dist/client/retry-request-envelope.js +57 -29
  89. package/dist/client/retry-request-envelope.js.map +1 -1
  90. package/dist/client/retry-request-lifecycle.d.ts +24 -11
  91. package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
  92. package/dist/client/retry-request-lifecycle.js +46 -20
  93. package/dist/client/retry-request-lifecycle.js.map +1 -1
  94. package/dist/client/retry-terminal-recovery.d.ts +11 -8
  95. package/dist/client/retry-terminal-recovery.d.ts.map +1 -1
  96. package/dist/client/retry-terminal-recovery.js +18 -12
  97. package/dist/client/retry-terminal-recovery.js.map +1 -1
  98. package/dist/client/retry.d.ts +8 -7
  99. package/dist/client/retry.d.ts.map +1 -1
  100. package/dist/client/retry.js +30 -22
  101. package/dist/client/retry.js.map +1 -1
  102. package/dist/client/send-deadline.d.ts +308 -0
  103. package/dist/client/send-deadline.d.ts.map +1 -0
  104. package/dist/client/send-deadline.js +914 -0
  105. package/dist/client/send-deadline.js.map +1 -0
  106. package/dist/client/send-intent-driver.d.ts +116 -0
  107. package/dist/client/send-intent-driver.d.ts.map +1 -0
  108. package/dist/client/send-intent-driver.js +373 -0
  109. package/dist/client/send-intent-driver.js.map +1 -0
  110. package/dist/client/signal-service-cipher.d.ts +257 -27
  111. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  112. package/dist/client/signal-service-cipher.js +1274 -283
  113. package/dist/client/signal-service-cipher.js.map +1 -1
  114. package/dist/client/startup-cleanup.d.ts +2 -0
  115. package/dist/client/startup-cleanup.d.ts.map +1 -0
  116. package/dist/client/startup-cleanup.js +14 -0
  117. package/dist/client/startup-cleanup.js.map +1 -0
  118. package/dist/client/types.d.ts +48 -5
  119. package/dist/client/types.d.ts.map +1 -1
  120. package/dist/client/types.js.map +1 -1
  121. package/dist/index.d.ts +3 -1
  122. package/dist/index.d.ts.map +1 -1
  123. package/dist/index.js +1 -0
  124. package/dist/index.js.map +1 -1
  125. package/dist/internal/manager/manager.d.ts +1 -0
  126. package/dist/internal/manager/manager.d.ts.map +1 -1
  127. package/dist/internal/manager/manager.js +17 -2
  128. package/dist/internal/manager/manager.js.map +1 -1
  129. package/dist/internal/manager/retained-identity.d.ts +2 -0
  130. package/dist/internal/manager/retained-identity.d.ts.map +1 -0
  131. package/dist/internal/manager/retained-identity.js +57 -0
  132. package/dist/internal/manager/retained-identity.js.map +1 -0
  133. package/dist/local/store/conformance/cases/metadata.d.ts +3 -2
  134. package/dist/local/store/conformance/cases/metadata.d.ts.map +1 -1
  135. package/dist/local/store/conformance/cases/metadata.js +153 -2
  136. package/dist/local/store/conformance/cases/metadata.js.map +1 -1
  137. package/dist/local/store/key-value/adapter.d.ts +2 -1
  138. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  139. package/dist/local/store/key-value/adapter.js +9 -0
  140. package/dist/local/store/key-value/adapter.js.map +1 -1
  141. package/dist/local/store/memory/adapter.d.ts +2 -1
  142. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  143. package/dist/local/store/memory/adapter.js +4 -0
  144. package/dist/local/store/memory/adapter.js.map +1 -1
  145. package/dist/local/store/metadata-keys.d.ts +13 -0
  146. package/dist/local/store/metadata-keys.d.ts.map +1 -0
  147. package/dist/local/store/metadata-keys.js +20 -0
  148. package/dist/local/store/metadata-keys.js.map +1 -0
  149. package/dist/local/store/receive-work.d.ts.map +1 -1
  150. package/dist/local/store/receive-work.js +12 -1
  151. package/dist/local/store/receive-work.js.map +1 -1
  152. package/dist/local/store/reliability.d.ts +482 -33
  153. package/dist/local/store/reliability.d.ts.map +1 -1
  154. package/dist/local/store/reliability.js +690 -48
  155. package/dist/local/store/reliability.js.map +1 -1
  156. package/dist/local/store/sqlite/key-storage/index.d.ts +2 -1
  157. package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
  158. package/dist/local/store/sqlite/key-storage/index.js +3 -0
  159. package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
  160. package/dist/local/store/sqlite/key-storage/metadata.d.ts +9 -0
  161. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  162. package/dist/local/store/sqlite/key-storage/metadata.js +12 -0
  163. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  164. package/dist/local/store/sqlite/store.d.ts +2 -1
  165. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  166. package/dist/local/store/sqlite/store.js +3 -0
  167. package/dist/local/store/sqlite/store.js.map +1 -1
  168. package/dist/local/store/web/adapter.d.ts +8 -1
  169. package/dist/local/store/web/adapter.d.ts.map +1 -1
  170. package/dist/local/store/web/adapter.js +18 -0
  171. package/dist/local/store/web/adapter.js.map +1 -1
  172. package/dist/remote/relay/request-admission.d.ts +49 -0
  173. package/dist/remote/relay/request-admission.d.ts.map +1 -0
  174. package/dist/remote/relay/request-admission.js +74 -0
  175. package/dist/remote/relay/request-admission.js.map +1 -0
  176. package/dist/types/api.d.ts +77 -0
  177. package/dist/types/api.d.ts.map +1 -1
  178. package/dist/types/errors.d.ts +144 -1
  179. package/dist/types/errors.d.ts.map +1 -1
  180. package/dist/types/errors.js +146 -1
  181. package/dist/types/errors.js.map +1 -1
  182. package/docs/ASSURANCE.md +5 -5
  183. package/docs/DEVIATIONS.md +34 -4
  184. package/docs/ERROR_HANDLING.md +134 -7
  185. package/docs/PACKAGE_SURFACE.md +21 -0
  186. package/docs/RECIPES.md +3 -2
  187. package/package.json +1 -1
@@ -40,6 +40,8 @@
40
40
  * });
41
41
  * ```
42
42
  */
43
+ import { initializeManagerFromRetainedIdentities } from '../internal/manager/manager.js';
44
+ import { ClientStartupCleanupError } from './startup-cleanup.js';
43
45
  import { utf8Decode } from '../internal/platform/index.js';
44
46
  import AsyncLock from 'async-lock';
45
47
  import { DefaultSignalProtocolManager } from '../internal/manager/index.js';
@@ -87,7 +89,9 @@ import { receiveInRetryFamily } from './retry-family.js';
87
89
  import { RetryRequestScheduler } from './retry-request-lifecycle.js';
88
90
  import { ResendJobDriver } from './recovery-driver.js';
89
91
  import { retryRequestPost } from './retry-request-envelope.js';
90
- import { getOutgoingMessageIntent, migrateRetryRequestRecords } from '../local/store/reliability.js';
92
+ import { getOutgoingMessageIntent, migrateOutgoingIntentRecords, migrateRetryRequestRecords, } from '../local/store/reliability.js';
93
+ import { manualResendOutcomeEvent, SEND_END_REPORT, sendOutcomeEvent, } from './send-deadline.js';
94
+ import { intentContent, SendIntentDriver } from './send-intent-driver.js';
91
95
  import { checkNewSendTimestamp, SEND_TIMESTAMP_ORIGIN, } from './send-timestamp.js';
92
96
  import { deliveredEnvelopeFingerprint } from '../local/store/received-content.js';
93
97
  import { RECEIVE_WORK_DEFAULT_LIMIT, sizedReceiveWork } from '../local/store/receive-work.js';
@@ -141,6 +145,14 @@ function isDataMessage(content) {
141
145
  !(content instanceof Uint8Array) &&
142
146
  !ArrayBuffer.isView(content));
143
147
  }
148
+ /** @internal Same client lifecycle with an owner-enforced existing identity. */
149
+ export function createClientWithRetainedIdentities(userId, config, identities) {
150
+ if (config.protocolManager !== undefined) {
151
+ throw new TypeError('Retained startup requires the SDK protocol manager.');
152
+ }
153
+ return createRetainedClient(userId, config, identities);
154
+ }
155
+ let createRetainedClient;
144
156
  /**
145
157
  * Modern Signal Protocol Client
146
158
  *
@@ -158,6 +170,7 @@ function isDataMessage(content) {
158
170
  * @category Primary API
159
171
  */
160
172
  export class DefaultSignalProtocolClient {
173
+ static #retainedFactory = (createRetainedClient = (userId, config, identities) => DefaultSignalProtocolClient.#createOwned(userId, config, identities));
161
174
  manager;
162
175
  _storage;
163
176
  relay;
@@ -309,6 +322,17 @@ export class DefaultSignalProtocolClient {
309
322
  });
310
323
  /** Ends the subscription of the resend job driver to relay connection states. */
311
324
  resendJobsOnConnect;
325
+ /**
326
+ * Replays the open sends of the outbox, and ends each at its posting
327
+ * deadline. It starts with the retry request scheduler, at each relay
328
+ * transition to connected, and at the earliest deadline of an open send,
329
+ * and stop() stops it. Each pass is relay work, so its hooks run through
330
+ * that work. A replay runs the send path of an application call, so it
331
+ * takes the intent lock of the send.
332
+ */
333
+ sendIntents;
334
+ /** Ends the subscription of the send driver to relay connection states. */
335
+ sendDriverOnConnect;
312
336
  /**
313
337
  * The stop() in progress. It is set before a step of stop() runs, so a
314
338
  * stop() call that overlaps it, also from a step, waits for it, and a
@@ -358,6 +382,26 @@ export class DefaultSignalProtocolClient {
358
382
  throw new Error('Storage must be provided by DefaultSignalProtocolClient.create() callers');
359
383
  }
360
384
  this._storage = config.storage;
385
+ this.sendIntents = new SendIntentDriver(this.state.relayWork, this._storage, this.logger, (work) => {
386
+ const context = this.relayWorkContext(work);
387
+ return {
388
+ end: (clientMessageId, report) => this.cipher.endPastDeadlineIntent(clientMessageId, report),
389
+ replay: async (intent, content, report) => {
390
+ await this.sendWithContext(intent.kind === 'group' ? createGroupId(intent.recipientId) : intent.recipientId, content, {
391
+ clientMessageId: intent.clientMessageId,
392
+ timestamp: intent.clientTimestamp,
393
+ ...(intent.contentHint !== undefined && { contentHint: intent.contentHint }),
394
+ ...(intent.kind === 'group' && { groupMemberUserIds: intent.groupMemberUserIds }),
395
+ }, context, work.stopSignal, report);
396
+ },
397
+ resend: (clientMessageId, report) => this.cipher.replayManualResend(clientMessageId, {
398
+ ...(work.stopSignal && { stopSignal: work.stopSignal }),
399
+ report,
400
+ }),
401
+ endResend: (clientMessageId, manualMessageId) => this.cipher.endPastDeadlineManualResend(clientMessageId, manualMessageId),
402
+ report: (event) => callHook(context.hooks, 'onSendOutcome', event),
403
+ };
404
+ });
361
405
  // The store declares its protection. The policy decides from it whether
362
406
  // the client keeps resendable content.
363
407
  this.contentRecoveryPolicy = resolveContentRecoveryPolicy(config.protocol?.contentRecovery);
@@ -900,9 +944,9 @@ export class DefaultSignalProtocolClient {
900
944
  }
901
945
  /**
902
946
  * The session reset steps of a retry request that ended as
903
- * `expired-content`. Their session hooks run through the given context,
904
- * and its stop signal stops their lock waits and relay requests. There are
905
- * none without a relay.
947
+ * `expired-content` or `posting-deadline`. Their session hooks run through
948
+ * the given context, and its stop signal stops their lock waits and relay
949
+ * requests. There are none without a relay.
906
950
  */
907
951
  retryTerminalReset(context) {
908
952
  const relay = this.relay;
@@ -1156,6 +1200,9 @@ export class DefaultSignalProtocolClient {
1156
1200
  * ```
1157
1201
  */
1158
1202
  static async create(userId, config) {
1203
+ return DefaultSignalProtocolClient.#createOwned(userId, config);
1204
+ }
1205
+ static async #createOwned(userId, config, retained) {
1159
1206
  const deviceId = config?.deviceId ?? 1; // Default to primary device
1160
1207
  // Use locking to prevent race conditions when multiple create() calls happen concurrently.
1161
1208
  // The lock allows only one storage instance per userId, which prevents database lock
@@ -1177,7 +1224,7 @@ export class DefaultSignalProtocolClient {
1177
1224
  storage: config.storage,
1178
1225
  };
1179
1226
  const activeIdentityTypes = getActiveIdentityTypes(finalConfig);
1180
- if (deviceId > 1) {
1227
+ if (deviceId > 1 && !retained) {
1181
1228
  for (const identityType of activeIdentityTypes) {
1182
1229
  const hasIdentityKey = await finalConfig.storage.hasIdentityKey(identityType);
1183
1230
  if (!hasIdentityKey) {
@@ -1188,84 +1235,98 @@ export class DefaultSignalProtocolClient {
1188
1235
  }
1189
1236
  }
1190
1237
  const client = new DefaultSignalProtocolClient(userId, deviceId, finalConfig);
1191
- await client.initialize();
1192
- await client.hydratePersistedState();
1193
- await migrateRetryRequestRecords(client._storage);
1194
- await client.applyContentRecoveryDecision();
1195
- // A failed sweep fails the start and runs again at the next start.
1196
- await removeDistributionsFromMessageRecords(client._storage, client.contentAdapter, client.logger);
1197
- // Delete the handoff rows that a crash or a key write outside the
1198
- // sender-key manager left behind. A failed sweep does not fail the start,
1199
- // because a row with an old senderKeyId never matches the current key.
1200
- try {
1201
- await client.cipher.sweepSenderKeyHandoffs();
1202
- }
1203
- catch (sweepError) {
1204
- client.logger.warn('Startup sender-key handoff sweep failed', {
1205
- category: 'E2EE',
1206
- data: { error: sweepError.message },
1207
- });
1208
- }
1209
- // Cleanup expired sessions and resendable content on startup.
1210
- // The reference implementation relies on event-driven cleanup (identity change, retry, end-session).
1211
- // We also enforce our maxRecv TTL here to prevent unbounded session growth.
1212
1238
  try {
1213
- await client.sesameManager.cleanupExpiredSessions();
1214
- await client.resendableContent.sweep();
1215
- }
1216
- catch (cleanupError) {
1217
- // Non-fatal: cleanup failures should not prevent client creation
1218
- client.logger.debug('Startup session/record cleanup failed', {
1219
- category: 'E2EE',
1220
- data: { error: cleanupError.message },
1221
- });
1222
- }
1223
- // Auto-sync to server if relay provided
1224
- let syncFailed = false;
1225
- if (finalConfig?.relay) {
1239
+ await client.initialize(retained);
1240
+ await client.hydratePersistedState();
1241
+ await migrateRetryRequestRecords(client._storage);
1242
+ await migrateOutgoingIntentRecords(client._storage);
1243
+ await client.applyContentRecoveryDecision();
1244
+ // A failed sweep fails the start and runs again at the next start.
1245
+ await removeDistributionsFromMessageRecords(client._storage, client.contentAdapter, client.logger);
1246
+ // Delete the handoff rows that a crash or a key write outside the
1247
+ // sender-key manager left behind. A failed sweep does not fail the start,
1248
+ // because a row with an old senderKeyId never matches the current key.
1226
1249
  try {
1227
- await client.syncToServer(finalConfig.onProgress);
1250
+ await client.cipher.sweepSenderKeyHandoffs();
1228
1251
  }
1229
- catch (e) {
1230
- client.logger.warn('Initial sync failed, client created in offline mode', {
1252
+ catch (sweepError) {
1253
+ client.logger.warn('Startup sender-key handoff sweep failed', {
1231
1254
  category: 'E2EE',
1232
- data: { error: e },
1255
+ data: { error: sweepError.message },
1233
1256
  });
1234
- syncFailed = true;
1235
1257
  }
1236
- }
1237
- client._syncStatus = finalConfig?.relay ? (syncFailed ? 'failed' : 'synced') : 'none';
1238
- // Start relay subscription if relay is configured with onMessageDecrypted hook
1239
- // Only subscribe if sync succeeded - subscriptions require a valid server session
1240
- if (!syncFailed && finalConfig?.relay && finalConfig?.hooks?.onMessageDecrypted) {
1241
- client.startRelaySubscription();
1242
- }
1243
- // Post the stored retry requests whose next attempt time has come, and
1244
- // end the requests past their deadlines. Run the pending resend jobs.
1245
- // The passes run in the background.
1246
- // The receive queue resumes the stored receive records first. With no
1247
- // relay, it serves the helper receives alone.
1248
- if (finalConfig?.relay)
1249
- client.startRetryRequests();
1250
- else
1251
- void client.receiveQueue.start();
1252
- // Validate sender keys config and warn on extreme values
1253
- if (finalConfig?.senderKeys) {
1254
- const sk = finalConfig.senderKeys;
1255
- if (sk.maxChainAdvance !== undefined && sk.maxChainAdvance < 100) {
1256
- client.logger.warn('senderKeys.maxChainAdvance < 100 may reject legitimate delayed messages', {
1257
- category: 'E2EE',
1258
- data: { value: sk.maxChainAdvance },
1259
- });
1258
+ // Cleanup expired sessions and resendable content on startup.
1259
+ // The reference implementation relies on event-driven cleanup (identity change, retry, end-session).
1260
+ // We also enforce our maxRecv TTL here to prevent unbounded session growth.
1261
+ try {
1262
+ await client.sesameManager.cleanupExpiredSessions();
1263
+ await client.resendableContent.sweep();
1260
1264
  }
1261
- if (sk.maxSkippedKeys !== undefined && sk.maxSkippedKeys > 10000) {
1262
- client.logger.warn('senderKeys.maxSkippedKeys > 10000 may cause memory issues', {
1265
+ catch (cleanupError) {
1266
+ // Non-fatal: cleanup failures should not prevent client creation
1267
+ client.logger.debug('Startup session/record cleanup failed', {
1263
1268
  category: 'E2EE',
1264
- data: { value: sk.maxSkippedKeys },
1269
+ data: { error: cleanupError.message },
1265
1270
  });
1266
1271
  }
1272
+ // Auto-sync to server if relay provided
1273
+ let syncFailed = false;
1274
+ if (finalConfig?.relay) {
1275
+ try {
1276
+ await client.syncToServer(finalConfig.onProgress);
1277
+ }
1278
+ catch (e) {
1279
+ client.logger.warn('Initial sync failed, client created in offline mode', {
1280
+ category: 'E2EE',
1281
+ data: { error: e },
1282
+ });
1283
+ syncFailed = true;
1284
+ }
1285
+ }
1286
+ client._syncStatus = finalConfig?.relay ? (syncFailed ? 'failed' : 'synced') : 'none';
1287
+ // Start relay subscription if relay is configured with onMessageDecrypted hook
1288
+ // Only subscribe if sync succeeded - subscriptions require a valid server session
1289
+ if (!syncFailed && finalConfig?.relay && finalConfig?.hooks?.onMessageDecrypted) {
1290
+ client.startRelaySubscription();
1291
+ }
1292
+ // Post the stored retry requests whose next attempt time has come, and
1293
+ // end the requests past their deadlines. Run the pending resend jobs.
1294
+ // The passes run in the background.
1295
+ // The receive queue resumes the stored receive records first. With no
1296
+ // relay, it serves the helper receives alone.
1297
+ if (finalConfig?.relay)
1298
+ client.startRetryRequests();
1299
+ else
1300
+ void client.receiveQueue.start();
1301
+ // Validate sender keys config and warn on extreme values
1302
+ if (finalConfig?.senderKeys) {
1303
+ const sk = finalConfig.senderKeys;
1304
+ if (sk.maxChainAdvance !== undefined && sk.maxChainAdvance < 100) {
1305
+ client.logger.warn('senderKeys.maxChainAdvance < 100 may reject legitimate delayed messages', {
1306
+ category: 'E2EE',
1307
+ data: { value: sk.maxChainAdvance },
1308
+ });
1309
+ }
1310
+ if (sk.maxSkippedKeys !== undefined && sk.maxSkippedKeys > 10000) {
1311
+ client.logger.warn('senderKeys.maxSkippedKeys > 10000 may cause memory issues', {
1312
+ category: 'E2EE',
1313
+ data: { value: sk.maxSkippedKeys },
1314
+ });
1315
+ }
1316
+ }
1317
+ return client;
1318
+ }
1319
+ catch (failure) {
1320
+ if (retained) {
1321
+ try {
1322
+ await client.stop();
1323
+ }
1324
+ catch (cleanupFailure) {
1325
+ throw new ClientStartupCleanupError(failure, cleanupFailure, () => client.stop());
1326
+ }
1327
+ }
1328
+ throw failure;
1267
1329
  }
1268
- return client;
1269
1330
  });
1270
1331
  }
1271
1332
  // ============================================================================
@@ -1276,9 +1337,17 @@ export class DefaultSignalProtocolClient {
1276
1337
  *
1277
1338
  * Generates identity keys if they do not exist and prepares the client for use.
1278
1339
  */
1279
- async initialize() {
1340
+ async initialize(retained) {
1280
1341
  try {
1281
- await this.manager.initialize(getActiveIdentityTypes(this.config));
1342
+ const types = getActiveIdentityTypes(this.config);
1343
+ if (retained) {
1344
+ if (!(this.manager instanceof DefaultSignalProtocolManager)) {
1345
+ throw new TypeError('Retained startup requires the SDK protocol manager.');
1346
+ }
1347
+ await initializeManagerFromRetainedIdentities(this.manager, types, retained);
1348
+ }
1349
+ else
1350
+ await this.manager.initialize(types);
1282
1351
  // Set local identity so manager knows who we are for session operations
1283
1352
  // This is needed even without server sync (local-only mode)
1284
1353
  this.manager.setLocalIdentity(this.userId, this.deviceId);
@@ -1290,6 +1359,8 @@ export class DefaultSignalProtocolClient {
1290
1359
  });
1291
1360
  }
1292
1361
  catch (error) {
1362
+ if (retained)
1363
+ throw error;
1293
1364
  throw new EncryptionError('Failed to initialize Signal Protocol', EncryptionErrorCode.INITIALIZATION_FAILED, { originalError: error });
1294
1365
  }
1295
1366
  }
@@ -2458,6 +2529,25 @@ export class DefaultSignalProtocolClient {
2458
2529
  *
2459
2530
  * The client normalizes all inputs to Uint8Array before they reach the cipher layer.
2460
2531
  *
2532
+ * A direct or group send has a posting deadline: the earlier of 24 hours
2533
+ * after the SDK first stores the send and 24 hours after its timestamp. A
2534
+ * replay with the same `clientMessageId` or a restart never moves it. At or
2535
+ * after the deadline, the SDK starts no relay request for the send. A
2536
+ * request that started before it still counts when its answer arrives
2537
+ * later. When the deadline ends with a device of unknown acceptance, the
2538
+ * send throws `SendAcceptanceUnknownError`. Otherwise the send ends failed:
2539
+ * when the call raised a refusal (a thrown refusal or a refusal in the
2540
+ * receipt of a shared body), it throws the first such refusal. Otherwise it
2541
+ * throws an `Error` with the stored code of the first refused device that
2542
+ * has one, in the order of the destinations. Otherwise it throws
2543
+ * `SendNeverAcceptedByRelayError` with code `SEND_NEVER_ACCEPTED`. A send
2544
+ * error before the deadline gives `deadlineAt`, and `retryable` is true
2545
+ * when a replay can still post the send.
2546
+ *
2547
+ * A backdated `timestamp` shortens the deadline. A send with a timestamp
2548
+ * 23 hours old has at most 1 hour to post. A send with a timestamp 24 hours
2549
+ * old posts nothing and throws `SendNeverAcceptedByRelayError`.
2550
+ *
2461
2551
  * @param recipientId - User ID or group ID (groups use the package group ID prefix)
2462
2552
  * @param content - DataMessageInput, string, or Uint8Array to encrypt and send
2463
2553
  * @param options - Optional send options (isBinary for blob encryption, etc.)
@@ -2486,20 +2576,32 @@ export class DefaultSignalProtocolClient {
2486
2576
  /**
2487
2577
  * Send with session callbacks whose hooks run through the given context.
2488
2578
  * The stop signal of relay work ends a wait for the recipient's lock.
2579
+ *
2580
+ * The send driver gives a driven `report`: the end write of the send then
2581
+ * marks the intent, and the driver reports the end. For an application
2582
+ * call, the end write or the completion write of this call records the end
2583
+ * in memory, and `onSendOutcome` runs once before the call returns or
2584
+ * throws.
2489
2585
  */
2490
- async sendWithContext(recipientId, content, options, context, stopSignal) {
2586
+ async sendWithContext(recipientId, content, options, context, stopSignal, report = { driven: false }) {
2491
2587
  // Every send error carries the logical-send identifier, also an error
2492
2588
  // before the encryption, such as a failed content serialization.
2493
2589
  const clientMessageId = options?.clientMessageId ?? (await generateUuidV4());
2494
2590
  try {
2495
- return await this.sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId);
2591
+ return await this.sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId, report);
2496
2592
  }
2497
2593
  catch (error) {
2498
2594
  throw attachClientMessageId(error, clientMessageId);
2499
2595
  }
2596
+ finally {
2597
+ // An internal send, such as a sender key distribution, is never reported.
2598
+ if (!report.driven && !report.internal && report.ended && !report.ended.internal) {
2599
+ await callHook(context.hooks, 'onSendOutcome', sendOutcomeEvent(report.ended));
2600
+ }
2601
+ }
2500
2602
  }
2501
2603
  /** Send under a logical-send identifier that the caller already chose. */
2502
- async sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId) {
2604
+ async sendIdentified(recipientId, content, options, context, stopSignal, clientMessageId, report) {
2503
2605
  // Normalize all inputs to Uint8Array before calling cipher.encrypt()
2504
2606
  let plaintextBytes;
2505
2607
  let clientTimestamp;
@@ -2512,61 +2614,75 @@ export class DefaultSignalProtocolClient {
2512
2614
  const applicationTimestamp = isDataMessage(content)
2513
2615
  ? content.timestamp
2514
2616
  : options?.timestamp;
2515
- let timestampOrigin;
2516
- if (applicationTimestamp == null) {
2517
- if (isDataMessage(content))
2518
- timestampOrigin = 'sdk-clock';
2519
- }
2520
- else {
2521
- try {
2522
- checkNewSendTimestamp({ timestamp: applicationTimestamp });
2523
- timestampOrigin = 'checked';
2524
- }
2525
- catch (error) {
2526
- const existing = await getOutgoingMessageIntent(this._storage, clientMessageId);
2527
- if (existing?.clientTimestamp !== applicationTimestamp)
2528
- throw error;
2529
- }
2530
- }
2531
- // A 1:1 send to a contact carries this account's profile key when an exchange is bound.
2532
- const profileKeys = isGroupId(recipientId) || recipientId === this.userId ? undefined : profileKeyExchange(this);
2617
+ // A 1:1 send to a contact carries this account's profile key when an
2618
+ // exchange is bound. A replay of the send driver sends the stored
2619
+ // content, so it does no profile key work.
2620
+ const profileKeys = report.driven || isGroupId(recipientId) || recipientId === this.userId
2621
+ ? undefined
2622
+ : profileKeyExchange(this);
2533
2623
  let profileKey;
2534
- if (isDataMessage(content)) {
2535
- // DataMessage path: build Content, set timestamp, serialize to protobuf (application send-pipeline ordering)
2536
- const timestamp = content.timestamp ?? Date.now();
2537
- clientTimestamp = timestamp;
2538
- profileKey = await profileKeys?.outgoing();
2539
- const dm = { ...content, timestamp, ...(profileKey && { profileKey }) };
2540
- plaintextBytes = this.contentAdapter.serializeDataMessage(dm);
2541
- }
2542
- else if (typeof content === 'string') {
2543
- await profileKeys?.offer(recipientId);
2544
- plaintextBytes = new TextEncoder().encode(content);
2545
- }
2546
- else {
2547
- await profileKeys?.offer(recipientId);
2548
- plaintextBytes = content; // already Uint8Array
2549
- }
2550
- const contentHint = isGroupId(recipientId)
2551
- ? this.groupContentHint(options?.contentHint, clientTimestamp !== undefined)
2552
- : options?.contentHint;
2553
- if (isGroupId(recipientId) && contentHint === ContentHint.Resendable) {
2554
- await this.sweepResendableContentDaily();
2555
- }
2556
- // The public options type of the cipher has no mark, so the marked
2557
- // options go in as a value of that type.
2558
- const sendOptions = {
2559
- ...options,
2560
- clientMessageId,
2561
- ...(clientTimestamp !== undefined && { timestamp: clientTimestamp }),
2562
- [SEND_TIMESTAMP_ORIGIN]: timestampOrigin,
2563
- ...(contentHint !== undefined && { contentHint }),
2564
- };
2565
- const encrypt = (sendContext) => this.cipher.encrypt(recipientId, plaintextBytes, sendOptions, this.sendSessionCallbacks(() => sendContext, stopSignal), stopSignal);
2566
- // A receipt for this send waits until the send resolves.
2567
- this.deliveries.beginSend(clientMessageId);
2624
+ let timestampOrigin;
2568
2625
  let result;
2626
+ // A receipt for this send waits until the send resolves. The hold starts
2627
+ // before the stored-intent read, so a receipt for a replay of a sent
2628
+ // message also waits.
2629
+ this.deliveries.beginSend(clientMessageId);
2569
2630
  try {
2631
+ // A send that names its identifier can repeat a stored intent. A
2632
+ // DataMessage replay then takes the stored timestamp, so it serializes
2633
+ // the same plaintext. The read is outside the intent lock: the locked
2634
+ // send reads the intent again and compares the plaintext digest.
2635
+ const stored = options?.clientMessageId !== undefined
2636
+ ? await getOutgoingMessageIntent(this._storage, clientMessageId)
2637
+ : null;
2638
+ if (applicationTimestamp == null) {
2639
+ if (isDataMessage(content))
2640
+ timestampOrigin = stored ? 'checked' : 'sdk-clock';
2641
+ }
2642
+ else {
2643
+ try {
2644
+ checkNewSendTimestamp({ timestamp: applicationTimestamp });
2645
+ timestampOrigin = 'checked';
2646
+ }
2647
+ catch (error) {
2648
+ if (stored?.clientTimestamp !== applicationTimestamp)
2649
+ throw error;
2650
+ }
2651
+ }
2652
+ if (isDataMessage(content)) {
2653
+ // DataMessage path: build Content, set timestamp, serialize to protobuf (application send-pipeline ordering)
2654
+ const timestamp = content.timestamp ?? stored?.clientTimestamp ?? Date.now();
2655
+ clientTimestamp = timestamp;
2656
+ profileKey = await profileKeys?.outgoing();
2657
+ const dm = { ...content, timestamp, ...(profileKey && { profileKey }) };
2658
+ plaintextBytes = this.contentAdapter.serializeDataMessage(dm);
2659
+ }
2660
+ else if (typeof content === 'string') {
2661
+ await profileKeys?.offer(recipientId);
2662
+ plaintextBytes = new TextEncoder().encode(content);
2663
+ }
2664
+ else {
2665
+ await profileKeys?.offer(recipientId);
2666
+ plaintextBytes = content; // already Uint8Array
2667
+ }
2668
+ // A replay of the send driver gives the stored content hint.
2669
+ const contentHint = isGroupId(recipientId) && !report.driven
2670
+ ? this.groupContentHint(options?.contentHint, clientTimestamp !== undefined)
2671
+ : options?.contentHint;
2672
+ if (isGroupId(recipientId) && !report.driven && contentHint === ContentHint.Resendable) {
2673
+ await this.sweepResendableContentDaily();
2674
+ }
2675
+ // The public options type of the cipher has no marks, so the marked
2676
+ // options go in as a value of that type.
2677
+ const sendOptions = {
2678
+ ...options,
2679
+ clientMessageId,
2680
+ ...(clientTimestamp !== undefined && { timestamp: clientTimestamp }),
2681
+ [SEND_TIMESTAMP_ORIGIN]: timestampOrigin,
2682
+ [SEND_END_REPORT]: report,
2683
+ ...(contentHint !== undefined && { contentHint }),
2684
+ };
2685
+ const encrypt = (sendContext) => this.cipher.encrypt(recipientId, plaintextBytes, sendOptions, this.sendSessionCallbacks(() => sendContext, stopSignal), stopSignal);
2570
2686
  // A group send sets up sessions while it holds the group's Sender Key lock.
2571
2687
  result = await (isGroupId(recipientId)
2572
2688
  ? this.withDeferredHooks(context, encrypt)
@@ -2585,6 +2701,26 @@ export class DefaultSignalProtocolClient {
2585
2701
  await callHook(context.hooks, 'onRelayProtocolError', protocolError);
2586
2702
  return clientTimestamp !== undefined ? { ...result, clientTimestamp } : result;
2587
2703
  }
2704
+ /** @see SignalProtocolClient.resendMessage */
2705
+ async resendMessage(clientMessageId) {
2706
+ const report = {};
2707
+ try {
2708
+ const intent = await getOutgoingMessageIntent(this._storage, clientMessageId);
2709
+ if (!intent)
2710
+ throw new Error('No stored send has this clientMessageId');
2711
+ // An open resend posts its stored bytes, so only a new one reads the content.
2712
+ const content = await intentContent(this._storage, intent, (plaintext) => this.cipher.withoutGroupContext(plaintext));
2713
+ return await this.cipher.resendOutgoingMessage(clientMessageId, content, { report });
2714
+ }
2715
+ catch (error) {
2716
+ throw attachClientMessageId(error, clientMessageId);
2717
+ }
2718
+ finally {
2719
+ if (report.ended) {
2720
+ await callHook(this.ctx.hooks, 'onSendOutcome', manualResendOutcomeEvent(report.ended.intent, report.ended.resend));
2721
+ }
2722
+ }
2723
+ }
2588
2724
  /** @see SignalProtocolClient.forgetSentContent */
2589
2725
  async forgetSentContent(clientMessageId) {
2590
2726
  return this.resendableContent.forget(clientMessageId);
@@ -2817,9 +2953,11 @@ export class DefaultSignalProtocolClient {
2817
2953
  void this.receiveQueue.start(() => this.startRetryLifecycle());
2818
2954
  }
2819
2955
  /**
2820
- * Start the retry request scheduler and the resend job driver, each with a
2821
- * pass in the background. Each relay transition to connected runs the
2822
- * resend jobs again until stop().
2956
+ * Start the retry request scheduler, the resend job driver and the send
2957
+ * driver, each with a pass in the background. Each relay transition to
2958
+ * connected runs the resend jobs and the send driver again until stop().
2959
+ * On a store with no `listMetadataKeys`, the send driver logs one line and
2960
+ * stays disabled, with no subscription.
2823
2961
  */
2824
2962
  startRetryLifecycle() {
2825
2963
  void this.retryRequests.start();
@@ -2837,6 +2975,13 @@ export class DefaultSignalProtocolClient {
2837
2975
  void this.resendJobs.start();
2838
2976
  });
2839
2977
  }
2978
+ void this.sendIntents.start();
2979
+ if (this.sendDriverOnConnect === undefined && relay && this.sendIntents.enabled) {
2980
+ this.sendDriverOnConnect = relay.subscribeRelayConnectionState((connection) => {
2981
+ if (connection.state === 'connected')
2982
+ void this.sendIntents.start();
2983
+ });
2984
+ }
2840
2985
  }
2841
2986
  /**
2842
2987
  * Stop the relay subscription
@@ -3105,15 +3250,18 @@ export class DefaultSignalProtocolClient {
3105
3250
  // for this run and does not start a second run. A subscription start
3106
3251
  // from a step is refused
3107
3252
  await Promise.resolve();
3108
- // 0. Stop the retry request scheduler, the resend job driver, the group
3109
- // fetcher, and the receive queue, so no pass starts. Step 4 waits for a
3110
- // pass in progress, as for other relay work
3253
+ // 0. Stop the retry request scheduler, the resend job driver, the send
3254
+ // driver, the group fetcher, and the receive queue, so no pass starts.
3255
+ // Step 4 waits for a pass in progress, as for other relay work
3111
3256
  this.retryRequests.stop();
3112
3257
  this.resendJobs.stop();
3258
+ this.sendIntents.stop();
3113
3259
  this.groupFetcher?.stop();
3114
3260
  this.receiveQueue.stop();
3115
3261
  this.resendJobsOnConnect?.();
3116
3262
  this.resendJobsOnConnect = undefined;
3263
+ this.sendDriverOnConnect?.();
3264
+ this.sendDriverOnConnect = undefined;
3117
3265
  // 1. Start the receipt deadline, 5 s from now. Take the receipt sends in
3118
3266
  // progress, except a send that an earlier stop() stopped, and start the
3119
3267
  // send of the batched delivery receipts, once each, as relay work. Until
@@ -3565,7 +3713,11 @@ export class DefaultSignalProtocolClient {
3565
3713
  }
3566
3714
  async sendSenderKeyDistribution(groupId, recipientUserId, distribution, context) {
3567
3715
  const payload = this.contentAdapter.serializeSenderKeyDistributionText(groupId, distribution);
3568
- await this.sendWithContext(recipientUserId, payload, undefined, context, undefined);
3716
+ // An internal send: its intent stores `internal`, so no end reaches onSendOutcome.
3717
+ await this.sendWithContext(recipientUserId, payload, undefined, context, undefined, {
3718
+ driven: false,
3719
+ internal: true,
3720
+ });
3569
3721
  this.logger.debug('Distributed sender key to user', {
3570
3722
  category: 'E2EE',
3571
3723
  data: { groupId, recipientUserId, generation: distribution.generation },