@open-e2ee/signal-protocol-sdk 9.3.0 → 9.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 (92) hide show
  1. package/ADAPTERS.md +1 -0
  2. package/CHANGELOG.md +269 -0
  3. package/README.md +1 -1
  4. package/SECURITY.md +2 -2
  5. package/client/README.md +11 -14
  6. package/dist/client/client.d.ts +134 -64
  7. package/dist/client/client.d.ts.map +1 -1
  8. package/dist/client/client.js +333 -179
  9. package/dist/client/client.js.map +1 -1
  10. package/dist/client/config.d.ts +4 -7
  11. package/dist/client/config.d.ts.map +1 -1
  12. package/dist/client/config.js.map +1 -1
  13. package/dist/client/content-adapter.d.ts +8 -0
  14. package/dist/client/content-adapter.d.ts.map +1 -1
  15. package/dist/client/content-adapter.js +4 -0
  16. package/dist/client/content-adapter.js.map +1 -1
  17. package/dist/client/event-hooks.d.ts +1 -1
  18. package/dist/client/group-outbox.d.ts +2 -4
  19. package/dist/client/group-outbox.d.ts.map +1 -1
  20. package/dist/client/group-outbox.js +7 -1
  21. package/dist/client/group-outbox.js.map +1 -1
  22. package/dist/client/hosted-anonymous-delivery.d.ts +1 -1
  23. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  24. package/dist/client/hosted-anonymous-delivery.js +5 -14
  25. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  26. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  27. package/dist/client/hosted-mailbox-subscription.js +136 -15
  28. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  29. package/dist/client/hosted-transport.d.ts +2 -2
  30. package/dist/client/hosted-transport.d.ts.map +1 -1
  31. package/dist/client/hosted-transport.js +20 -5
  32. package/dist/client/hosted-transport.js.map +1 -1
  33. package/dist/client/messages.d.ts.map +1 -1
  34. package/dist/client/messages.js +12 -2
  35. package/dist/client/messages.js.map +1 -1
  36. package/dist/client/relay-acceptance.d.ts +29 -0
  37. package/dist/client/relay-acceptance.d.ts.map +1 -0
  38. package/dist/client/relay-acceptance.js +29 -0
  39. package/dist/client/relay-acceptance.js.map +1 -0
  40. package/dist/client/relay-subscription.d.ts +43 -1
  41. package/dist/client/relay-subscription.d.ts.map +1 -1
  42. package/dist/client/relay-subscription.js +278 -100
  43. package/dist/client/relay-subscription.js.map +1 -1
  44. package/dist/client/relay-work.d.ts +7 -6
  45. package/dist/client/relay-work.d.ts.map +1 -1
  46. package/dist/client/relay-work.js +34 -9
  47. package/dist/client/relay-work.js.map +1 -1
  48. package/dist/client/retry-family.d.ts +119 -0
  49. package/dist/client/retry-family.d.ts.map +1 -0
  50. package/dist/client/retry-family.js +170 -0
  51. package/dist/client/retry-family.js.map +1 -0
  52. package/dist/client/retry-request-envelope.d.ts +106 -0
  53. package/dist/client/retry-request-envelope.d.ts.map +1 -0
  54. package/dist/client/retry-request-envelope.js +245 -0
  55. package/dist/client/retry-request-envelope.js.map +1 -0
  56. package/dist/client/retry.d.ts +66 -24
  57. package/dist/client/retry.d.ts.map +1 -1
  58. package/dist/client/retry.js +239 -139
  59. package/dist/client/retry.js.map +1 -1
  60. package/dist/client/sealed-sender.d.ts +15 -3
  61. package/dist/client/sealed-sender.d.ts.map +1 -1
  62. package/dist/client/sealed-sender.js +22 -3
  63. package/dist/client/sealed-sender.js.map +1 -1
  64. package/dist/client/signal-service-cipher.d.ts +52 -0
  65. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  66. package/dist/client/signal-service-cipher.js +185 -15
  67. package/dist/client/signal-service-cipher.js.map +1 -1
  68. package/dist/client/state.d.ts +12 -64
  69. package/dist/client/state.d.ts.map +1 -1
  70. package/dist/client/state.js +22 -98
  71. package/dist/client/state.js.map +1 -1
  72. package/dist/client/types.d.ts +28 -2
  73. package/dist/client/types.d.ts.map +1 -1
  74. package/dist/client/types.js.map +1 -1
  75. package/dist/internal/protocol/sealed-sender/types.d.ts +1 -1
  76. package/dist/internal/protocol/sealed-sender/types.js +1 -1
  77. package/dist/local/store/received-content.d.ts +16 -2
  78. package/dist/local/store/received-content.d.ts.map +1 -1
  79. package/dist/local/store/received-content.js +18 -3
  80. package/dist/local/store/received-content.js.map +1 -1
  81. package/dist/local/store/reliability.d.ts +260 -2
  82. package/dist/local/store/reliability.d.ts.map +1 -1
  83. package/dist/local/store/reliability.js +390 -12
  84. package/dist/local/store/reliability.js.map +1 -1
  85. package/dist/remote/relay/types.d.ts +31 -31
  86. package/dist/remote/relay/types.d.ts.map +1 -1
  87. package/dist/types/api.d.ts +74 -26
  88. package/dist/types/api.d.ts.map +1 -1
  89. package/docs/ASSURANCE.md +5 -5
  90. package/docs/DEVIATIONS.md +4 -5
  91. package/docs/INTERFACES.md +2 -0
  92. package/package.json +1 -1
@@ -74,6 +74,8 @@ import * as SessionOps from './sessions.js';
74
74
  import * as GroupOps from './groups.js';
75
75
  import * as PreKeyOps from './prekeys.js';
76
76
  import * as RetryOps from './retry.js';
77
+ import { receiveInRetryFamily } from './retry-family.js';
78
+ import { deliveredEnvelopeFingerprint } from '../local/store/received-content.js';
77
79
  import * as RelaySubscriptionOps from './relay-subscription.js';
78
80
  import { SignalProtocolClientState, SIGNAL_PROTOCOL_CLIENT_CONSTANTS } from './state.js';
79
81
  import { clientRelayFanOut, rethrowRelayWorkStopped } from './relay-work.js';
@@ -190,7 +192,6 @@ export class DefaultSignalProtocolClient {
190
192
  return this.relay?.subscribeRelayConnectionState(listener) ?? (() => undefined);
191
193
  }
192
194
  relayUnsubscribe;
193
- retryUnsubscribe;
194
195
  /**
195
196
  * Cached sender certificate for sealed sender.
196
197
  * Lazily fetched and refreshed one hour before its signed expiration.
@@ -202,6 +203,22 @@ export class DefaultSignalProtocolClient {
202
203
  * @see SignalProtocolClientState for state details
203
204
  */
204
205
  state = new SignalProtocolClientState();
206
+ /**
207
+ * The delivery receipt sends in progress, from a batch timer, the batch
208
+ * bound, stopRelaySubscription(), or stop(): the relay work item of each
209
+ * send, and the promise that settles when the send finishes. While stop()
210
+ * holds the batches, only stop() starts a send. stop() waits until its
211
+ * receipt deadline for the sends that are in progress when it starts,
212
+ * except a send that an earlier stop() stopped, and for the sends that it
213
+ * starts. It does not stop them before then.
214
+ */
215
+ deliveryReceiptSends = new Map();
216
+ /**
217
+ * The stop() in progress. It is set before a step of stop() runs, so a
218
+ * stop() call that overlaps it, also from a step, waits for it, and a
219
+ * subscription start is refused.
220
+ */
221
+ stopping;
205
222
  /**
206
223
  * Get retry rate limiting state for retry operations
207
224
  */
@@ -557,26 +574,25 @@ export class DefaultSignalProtocolClient {
557
574
  get retryConfig() {
558
575
  return {
559
576
  keyRotationDebounceMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.KEY_ROTATION_DEBOUNCE_MS,
560
- retryDedupWindowMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.RETRY_DEDUP_WINDOW_MS,
561
- retryCleanupIntervalMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.RETRY_CLEANUP_INTERVAL_MS,
562
577
  };
563
578
  }
564
579
  /**
565
- * Get retry dedup state for retry operations
580
+ * Get retry response state for retry operations
566
581
  */
567
- get retryDedupState() {
568
- return this.state.getRetryDedupState();
582
+ get retryResponseState() {
583
+ return this.state.getRetryResponseState();
569
584
  }
570
585
  /**
571
- * Get retry callbacks for retry operations. Session changes and resends use
572
- * the given context, so their hooks run through its relay work. A resend
573
- * waits for the recipient's lock only until stop() stops the work.
586
+ * Get retry callbacks for retry operations. Session changes use the given
587
+ * context, so their hooks run through its relay work. A resend goes only to
588
+ * the device that asked, and waits for the recipient's lock only until the
589
+ * stop signal aborts.
574
590
  */
575
- retryCallbacks(work, ctx) {
591
+ retryCallbacks(stopSignal, ctx) {
576
592
  return {
577
593
  archiveSession: (address) => SessionOps.archiveSession(ctx, address),
578
594
  establishSession: (address, bundle) => SessionOps.establishSession(ctx, this.sesameManager, address, bundle),
579
- send: (recipientId, content, options) => this.sendWithContext(recipientId, content, options, ctx, work.stopSignal),
595
+ resend: (userId, deviceId, content, options) => this.cipher.resendToDevice(userId, deviceId, content, options, stopSignal),
580
596
  forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds(),
581
597
  };
582
598
  }
@@ -588,17 +604,65 @@ export class DefaultSignalProtocolClient {
588
604
  }
589
605
  /**
590
606
  * Get relay subscription callbacks (delegate back to DefaultSignalProtocolClient methods).
591
- * Receipts and typing indicators use the given context, so their hooks run
592
- * through its relay work. Each receipt send is relay work of its own.
607
+ * Receipts, typing indicators and retry requests use the given context, so
608
+ * their hooks run through its relay work. Each receipt send is relay work of
609
+ * its own. A retry request runs in the current work, so a stop of that work
610
+ * reaches the receive route, and the route keeps the request envelope.
593
611
  */
594
- relaySubscriptionCallbacks(ctx) {
612
+ relaySubscriptionCallbacks(ctx, stopSignal) {
595
613
  return {
596
614
  forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds(),
597
615
  handleDeliveryReceipt: (envelope, receipt) => this.handleDeliveryReceipt(envelope, receipt, ctx),
598
616
  handleTypingIndicator: (envelope, typing) => this.handleTypingIndicator(envelope, typing, ctx),
599
- sendDeliveryReceipt: (userId, timestamps) => this.state.relayWork.run((work) => this.sendDeliveryReceipt(userId, timestamps, this.relayWorkContext(work))),
617
+ sendDeliveryReceipt: (userId, timestamps) => this.sendDeliveryReceiptAsRelayWork(userId, timestamps),
618
+ handleRetryRequest: (request, retry) => RetryOps.handleRetryRequestAndResend(ctx, request, this.retryResponseState, this.retryCallbacks(stopSignal, ctx), this.retryConfig, retry),
600
619
  };
601
620
  }
621
+ /**
622
+ * Send one delivery receipt batch as relay work of its own. The context
623
+ * carries the stop signal of the tracker, which also aborts at a stop
624
+ * after the work ends, so a retry timer of the send sees that stop. The
625
+ * send is in deliveryReceiptSends while it runs.
626
+ */
627
+ sendDeliveryReceiptAsRelayWork(userId, timestamps) {
628
+ return this.state.relayWork.run(async (work) => {
629
+ const send = this.sendDeliveryReceipt(userId, timestamps, {
630
+ ...this.relayWorkContext(work),
631
+ stopSignal: this.state.relayWork.stopSignal,
632
+ });
633
+ this.deliveryReceiptSends.set(work, send);
634
+ try {
635
+ await send;
636
+ }
637
+ finally {
638
+ this.deliveryReceiptSends.delete(work);
639
+ }
640
+ });
641
+ }
642
+ /**
643
+ * Start the send of every batched delivery receipt, once each. The batches
644
+ * leave the accumulator, so no batch timer sends them again. The returned
645
+ * promises settle when the sends finish. They never reject.
646
+ */
647
+ flushPendingDeliveryReceipts() {
648
+ return RelaySubscriptionOps.flushPendingReceipts(this.relaySubscriptionState.receiptAccumulator, (userId, timestamps) => this.sendDeliveryReceiptAsRelayWork(userId, timestamps), this.logger);
649
+ }
650
+ /**
651
+ * Wait for the receipt sends that stop() waits for, with their app hooks,
652
+ * for no more than the given time.
653
+ */
654
+ async waitForStopReceiptSends(sends, ms) {
655
+ let timer;
656
+ const bound = new Promise((resolve) => {
657
+ timer = setTimeout(resolve, Math.max(0, ms));
658
+ });
659
+ try {
660
+ await Promise.race([Promise.allSettled(sends), bound]);
661
+ }
662
+ finally {
663
+ clearTimeout(timer);
664
+ }
665
+ }
602
666
  /** Client context whose hooks call the app through the given relay work. */
603
667
  relayWorkContext(work) {
604
668
  return { ...this.ctx, hooks: work.wrapHooks(this.hooks) };
@@ -822,10 +886,6 @@ export class DefaultSignalProtocolClient {
822
886
  if (!syncFailed && finalConfig?.relay && finalConfig?.hooks?.onMessageDecrypted) {
823
887
  client.startRelaySubscription();
824
888
  }
825
- // Start retry request subscription if relay supports it (SESAME spec §6.2)
826
- if (!syncFailed && finalConfig?.relay?.subscribeRetryRequests) {
827
- client.startRetryRequestSubscription();
828
- }
829
889
  // Validate sender keys config and warn on extreme values
830
890
  if (finalConfig?.senderKeys) {
831
891
  const sk = finalConfig.senderKeys;
@@ -1171,12 +1231,78 @@ export class DefaultSignalProtocolClient {
1171
1231
  * 3. On retryable error: sends retry request via relay or options callback
1172
1232
  * 4. Re-throws error for caller to handle
1173
1233
  *
1234
+ * A `retry_request` envelope holds no plaintext. This method rejects it
1235
+ * before decryption and sends no retry request. Give it to
1236
+ * `receiveIncomingEnvelopes`, which handles it.
1237
+ *
1238
+ * A failed envelope that this client asked a resend for, and each resend
1239
+ * or null message for it, gives plaintext at most once on both receive
1240
+ * paths. When this client processed the envelope, or the application
1241
+ * already has that content, this method acknowledges the envelope and
1242
+ * throws MESSAGE_DUPLICATE with no decrypt.
1243
+ *
1244
+ * A null message carries no content. The client consumes a null message
1245
+ * when the content adapter reports `nullMessage: true`, and a custom
1246
+ * adapter must report it for its own null encoding. This method never
1247
+ * returns a null message. It marks the null message processed,
1248
+ * acknowledges it and throws MESSAGE_DUPLICATE. A null message for a
1249
+ * failed envelope marks that envelope processed, so a redelivery of it
1250
+ * is dropped, but a content resend for it that comes later still gives
1251
+ * its plaintext.
1252
+ *
1253
+ * A resend or null message that fails to decrypt, or whose seal fails to
1254
+ * open, asks again for its failed envelope under the same retry ID. When
1255
+ * the processed record of the failed envelope fails to store after a
1256
+ * decrypt, the client writes a warning with the behavior
1257
+ * RETRY_FULFILL_WRITE_FAILED, as on every receive path, and this method
1258
+ * returns the plaintext. A redelivery of the failed envelope or of
1259
+ * another family member can then give the content again. When a
1260
+ * processed record of a null message or of its failed envelope fails to
1261
+ * store, the client writes a warning with the behavior
1262
+ * RETRY_NULL_WRITE_FAILED, as on every receive path, and this method
1263
+ * still throws MESSAGE_DUPLICATE. A redelivery of the failed envelope
1264
+ * can then give the content.
1265
+ *
1174
1266
  * @param envelope - The encrypted message envelope
1175
1267
  * @param options - Transport callbacks for background (no relay) scenarios
1176
1268
  * @returns Decrypted plaintext
1177
1269
  * @throws EncryptionError after sending retry request if decryption fails
1270
+ * @throws EncryptionError INVALID_CIPHERTEXT for a `retry_request` envelope
1271
+ * @throws EncryptionError MESSAGE_DUPLICATE when this client processed the
1272
+ * envelope, the application already has the content of the failed
1273
+ * envelope of a retry request, or the envelope is a null message
1178
1274
  */
1179
1275
  async processIncomingEnvelope(envelope, options) {
1276
+ if (envelope.messageType === 'retry_request') {
1277
+ throw new EncryptionError('A retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
1278
+ }
1279
+ // The fingerprint covers the envelope as the Relay delivered it, before
1280
+ // any unseal, so every receive path stores one value for it.
1281
+ const fingerprint = envelope.id
1282
+ ? await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope)
1283
+ : undefined;
1284
+ return receiveInRetryFamily(this._storage, this.logger, envelope, async (family) => {
1285
+ if (!(await family.admit())) {
1286
+ await this.markMessageDeliveredSilently(envelope.id, options);
1287
+ throw new EncryptionError('The application already has the content of this failed envelope', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1288
+ }
1289
+ const plaintext = await this.decryptIncomingEnvelope(envelope, family, fingerprint, options);
1290
+ // A null message carries no content, so the caller never gets it.
1291
+ if (this.contentAdapter.inspectContent(plaintext).nullMessage) {
1292
+ await family.consumeNull(fingerprint);
1293
+ await this.markMessageDeliveredSilently(envelope.id, options);
1294
+ throw new EncryptionError('A null message carries no content', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1295
+ }
1296
+ await family.fulfill();
1297
+ return plaintext;
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Decrypt one envelope that is not a `retry_request`, under its retry family
1302
+ * lock. The fingerprint is that of the delivered envelope, also for the
1303
+ * inner envelope of a seal.
1304
+ */
1305
+ async decryptIncomingEnvelope(envelope, family, fingerprint, options) {
1180
1306
  // Handle sealed sender envelopes: unseal to reveal sender before decrypting
1181
1307
  if (envelope.messageType === 'unidentified_sender' && this.config.sealedSender) {
1182
1308
  const identityKeyPair = await this._storage.getIdentityKey();
@@ -1184,18 +1310,30 @@ export class DefaultSignalProtocolClient {
1184
1310
  throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
1185
1311
  }
1186
1312
  const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
1187
- const unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1313
+ let unsealed;
1314
+ try {
1315
+ unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1316
+ }
1317
+ catch (error) {
1318
+ // A member whose seal fails to open asks the device of its request
1319
+ // for the next attempt, as a member whose decrypt fails does.
1320
+ if (family.member !== undefined) {
1321
+ await this.sendRetryRequestInternal(family.withRequestedSender(envelope), error, family, fingerprint, options);
1322
+ }
1323
+ throw error;
1324
+ }
1188
1325
  // Process the inner envelope with revealed sender identity. The inner
1189
- // type travels inside the seal. Nothing outside it distinguishes a
1190
- // group message from a pairwise one. The same mapping serves the other
1191
- // receive path via `reconstructEnvelope`.
1192
- return this.processIncomingEnvelope({
1326
+ // type and the content hint travel inside the seal. Nothing outside it
1327
+ // distinguishes a group message from a pairwise one. The same mapping
1328
+ // serves the other receive path via `reconstructEnvelope`.
1329
+ return this.decryptIncomingEnvelope({
1193
1330
  ...envelope,
1194
1331
  senderUserId: unsealed.senderUserId,
1195
1332
  senderDeviceId: unsealed.senderDeviceId,
1196
1333
  ciphertext: unsealed.innerCiphertextBase64,
1197
1334
  messageType: envelopeTypeForContent(unsealed.contentType),
1198
- }, options);
1335
+ contentHint: unsealed.contentHint,
1336
+ }, family, fingerprint, options);
1199
1337
  }
1200
1338
  // Route group messages to sender key decryption. `sender_key` says the
1201
1339
  // payload is a framed SenderKeyMessage. It does not say which group, so
@@ -1223,7 +1361,7 @@ export class DefaultSignalProtocolClient {
1223
1361
  catch (error) {
1224
1362
  // Send retry request if error is retryable (per SESAME spec §4.1)
1225
1363
  if (isRetryableDecryptionError(error)) {
1226
- await this.sendRetryRequestInternal(envelope, error, options);
1364
+ await this.sendRetryRequestInternal(envelope, error, family, fingerprint, options);
1227
1365
  }
1228
1366
  // Re-throw so caller can handle (log, skip message, etc.)
1229
1367
  throw error;
@@ -1278,7 +1416,10 @@ export class DefaultSignalProtocolClient {
1278
1416
  /**
1279
1417
  * Receive a pulled batch through the subscription content handler.
1280
1418
  * The application must register onMessageDecrypted before calling this method.
1281
- * Successful IDs are ready for transport acknowledgment.
1419
+ * Processed IDs are ready for transport acknowledgment. They include
1420
+ * each envelope that the client drops as a duplicate, and each null
1421
+ * message that the content adapter reports, which the client consumes
1422
+ * and never gives to onMessageDecrypted.
1282
1423
  */
1283
1424
  async receiveIncomingEnvelopes(envelopes) {
1284
1425
  if (!this.hooks?.onMessageDecrypted) {
@@ -1312,10 +1453,12 @@ export class DefaultSignalProtocolClient {
1312
1453
  *
1313
1454
  * @param envelope - The failed message envelope
1314
1455
  * @param error - The decryption error
1456
+ * @param family - The retry family of the delivered envelope
1457
+ * @param fingerprint - The fingerprint of the delivered envelope
1315
1458
  * @param options - Optional transport callbacks (for background without relay)
1316
1459
  */
1317
- async sendRetryRequestInternal(envelope, error, options) {
1318
- return RetryOps.sendRetryRequestInternal(this.ctx, envelope, error, this.rateLimitState, { forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds() }, this.retryConfig, options);
1460
+ async sendRetryRequestInternal(envelope, error, family, fingerprint, options) {
1461
+ return RetryOps.sendRetryRequestInternal(this.ctx, envelope, error, this.rateLimitState, { forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds() }, this.retryConfig, family, fingerprint, options);
1319
1462
  }
1320
1463
  // ============================================================================
1321
1464
  // FILE ENCRYPTION/DECRYPTION (delegated to files.ts)
@@ -1508,23 +1651,7 @@ export class DefaultSignalProtocolClient {
1508
1651
  }
1509
1652
  /** Accept an authenticated composite-identity rotation and reset bound sessions. */
1510
1653
  async acceptIdentityRotation(userId, identity, identityType = 'aci') {
1511
- const accepted = await SessionOps.acceptIdentityRotation(this.ctx, userId, identity, identityType);
1512
- // A retry that first discovered the changed tuple may already have failed
1513
- // closed and entered the short-lived dedup window. Explicit acceptance is
1514
- // the authority to try those still-pending requests again. It is never
1515
- // inferred from the retry request itself.
1516
- const retryPrefix = `${userId}:`;
1517
- for (const key of this.retryDedupState.recentRetryRequests.keys()) {
1518
- if (key.startsWith(retryPrefix)) {
1519
- this.retryDedupState.recentRetryRequests.delete(key);
1520
- }
1521
- }
1522
- if (this.retryUnsubscribe) {
1523
- this.retryUnsubscribe();
1524
- this.retryUnsubscribe = undefined;
1525
- this.startRetryRequestSubscription();
1526
- }
1527
- return accepted;
1654
+ return SessionOps.acceptIdentityRotation(this.ctx, userId, identity, identityType);
1528
1655
  }
1529
1656
  /**
1530
1657
  * Mark a message as read/delivered
@@ -1599,6 +1726,8 @@ export class DefaultSignalProtocolClient {
1599
1726
  *
1600
1727
  * Callers can run this manually after registering hooks via registerHook().
1601
1728
  * Called automatically by create() when relay + hook configured.
1729
+ * A call while stop() runs is refused and logged; start again after stop()
1730
+ * resolves.
1602
1731
  *
1603
1732
  * @see SignalProtocolClient.startRelaySubscription
1604
1733
  */
@@ -1615,6 +1744,13 @@ export class DefaultSignalProtocolClient {
1615
1744
  });
1616
1745
  return;
1617
1746
  }
1747
+ // A start while stop() runs would outlive stop()
1748
+ if (this.stopping) {
1749
+ this.logger.debug('Relay subscription not started: stop() in progress', {
1750
+ category: 'E2EE',
1751
+ });
1752
+ return;
1753
+ }
1618
1754
  // Avoid duplicate subscriptions
1619
1755
  if (this.relayUnsubscribe) {
1620
1756
  this.logger.debug('Relay subscription already active', {
@@ -1627,18 +1763,23 @@ export class DefaultSignalProtocolClient {
1627
1763
  data: { userId: this.userId, deviceId: this.deviceId },
1628
1764
  });
1629
1765
  this.relayUnsubscribe = this.relay.subscribe(this.userId, this.deviceId, (envelope) => {
1630
- this.state.relayWork
1631
- .run((work) => {
1766
+ const handled = this.state.relayWork.run((work) => {
1632
1767
  const ctx = this.relayWorkContext(work);
1633
- return RelaySubscriptionOps.handleRelayMessage({ ...ctx, cipher: this.cipher, stopSignal: work.stopSignal }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx), this.relaySubscriptionConfig);
1634
- })
1635
- .catch((error) => {
1636
- // The relay does not wait for the handler. It delivers the envelope again.
1768
+ return RelaySubscriptionOps.handleRelayMessage({ ...ctx, cipher: this.cipher, stopSignal: work.stopSignal }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx, work.stopSignal), this.relaySubscriptionConfig);
1769
+ });
1770
+ handled.catch((error) => {
1771
+ // The relay delivers an envelope that it did not acknowledge again.
1637
1772
  this.logger.error('Failed to handle relay envelope', {
1638
1773
  category: 'E2EE',
1639
1774
  data: { envelopeId: envelope.id, error: error.message },
1640
1775
  });
1641
1776
  });
1777
+ // A relay that waits for the work, as the hosted transport does, ends
1778
+ // its batch and accepts an ephemeral message only after the work
1779
+ // settles, and pulls again after the work fails. A relay that does not
1780
+ // wait ignores the promise, and the handler above already holds its
1781
+ // failure.
1782
+ return handled;
1642
1783
  }, {
1643
1784
  // Batching callbacks for notification coalescing
1644
1785
  onBatchStart: () => this.contentAdapter.setRelayBatching(true),
@@ -1657,19 +1798,11 @@ export class DefaultSignalProtocolClient {
1657
1798
  * @see SignalProtocolClient.stopRelaySubscription
1658
1799
  */
1659
1800
  stopRelaySubscription() {
1660
- // Flush any pending batched delivery receipts before unsubscribing
1661
- const { receiptAccumulator } = this.relaySubscriptionState;
1662
- for (const [userId, timestamps] of receiptAccumulator.pending) {
1663
- if (timestamps.length > 0) {
1664
- this.state.relayWork
1665
- .run((work) => this.sendDeliveryReceipt(userId, timestamps, this.relayWorkContext(work)))
1666
- .catch((_error) => {
1667
- this.logger.warn('Failed to send delivery receipt', {
1668
- category: 'E2EE',
1669
- data: { userId },
1670
- });
1671
- });
1672
- }
1801
+ // Send the batched delivery receipts before unsubscribing. During the
1802
+ // hold, stop() sends the batches that wait at each of its flushes and
1803
+ // drops a batch made after its last flush.
1804
+ if (!this.relaySubscriptionState.receiptAccumulator.held) {
1805
+ this.flushPendingDeliveryReceipts();
1673
1806
  }
1674
1807
  if (this.relayUnsubscribe) {
1675
1808
  this.relayUnsubscribe();
@@ -1680,64 +1813,6 @@ export class DefaultSignalProtocolClient {
1680
1813
  });
1681
1814
  }
1682
1815
  }
1683
- /**
1684
- * Start listening for retry requests from recipients (SESAME spec §6.2)
1685
- *
1686
- * When a recipient cannot decrypt a message, they send a retry request.
1687
- * This method subscribes to incoming retry requests and processes them
1688
- * by resending the original message with a new session.
1689
- *
1690
- * Automatically started if relay.subscribeRetryRequests is available.
1691
- * Call this manually if you need to restart the subscription.
1692
- */
1693
- startRetryRequestSubscription() {
1694
- if (!this.relay || !this.relay.subscribeRetryRequests) {
1695
- this.logger.debug('Relay does not support retry request subscription', {
1696
- category: 'E2EE',
1697
- });
1698
- return;
1699
- }
1700
- // Avoid duplicate subscriptions
1701
- if (this.retryUnsubscribe) {
1702
- this.logger.debug('Retry request subscription already active', {
1703
- category: 'E2EE',
1704
- });
1705
- return;
1706
- }
1707
- this.logger.debug('Starting retry request subscription', {
1708
- category: 'E2EE',
1709
- data: { userId: this.userId, deviceId: this.deviceId },
1710
- });
1711
- this.retryUnsubscribe = this.relay.subscribeRetryRequests(this.userId, this.deviceId, async (retryRequest) => {
1712
- await this.handleRetryRequestAndResend(retryRequest);
1713
- });
1714
- }
1715
- /**
1716
- * Handle a retry request and resend the original message
1717
- *
1718
- * Per SESAME spec §4.1 (Resending Process):
1719
- * 1. Look up MessageRecord by sequence number
1720
- * 2. Validate retry limits and message TTL
1721
- * 3. Check session state:
1722
- * - If NO active session OR active session IS orphaned (matches MessageRecord.sessionStateId):
1723
- * → Fetch prekey bundle and create new session
1724
- * - If DIFFERENT active session exists:
1725
- * → Use it directly (no prekey fetch, prevents rate limit issues)
1726
- * 4. Re-encrypt and send the original message
1727
- *
1728
- * This prevents infinite retry loops where each retry creates a new session
1729
- * with different header keys.
1730
- *
1731
- * The request runs as relay work, so its hooks run through that work.
1732
- *
1733
- * @param retryRequest - The retry request from the recipient
1734
- */
1735
- handleRetryRequestAndResend(retryRequest) {
1736
- return this.state.relayWork.run((work) => {
1737
- const ctx = this.relayWorkContext(work);
1738
- return RetryOps.handleRetryRequestAndResend(ctx, retryRequest, this.retryDedupState, this.retryCallbacks(work, ctx), this.retryConfig);
1739
- });
1740
- }
1741
1816
  /**
1742
1817
  * Send delivery receipt to original sender (all devices)
1743
1818
  *
@@ -1752,7 +1827,7 @@ export class DefaultSignalProtocolClient {
1752
1827
  * @param ctx - Client context, whose hooks run through the relay work of the send
1753
1828
  *
1754
1829
  */
1755
- async sendDeliveryReceipt(recipientUserId, timestamps, ctx = this.ctx) {
1830
+ async sendDeliveryReceipt(recipientUserId, timestamps, ctx = this.receiptContext()) {
1756
1831
  return this.sendReceipt(recipientUserId, timestamps, ReceiptType.DELIVERY, ctx);
1757
1832
  }
1758
1833
  /**
@@ -1876,12 +1951,23 @@ export class DefaultSignalProtocolClient {
1876
1951
  async sendTypingIndicator(recipientUserId, recipientDeviceId, conversationId, action, groupId) {
1877
1952
  return MessageOps.sendTypingIndicator(this.ctx, recipientUserId, recipientDeviceId, conversationId, action, groupId);
1878
1953
  }
1954
+ /**
1955
+ * Client context of a receipt send outside relay work, such as a read
1956
+ * receipt that the app sends. It carries the stop signal of the tracker,
1957
+ * so the next stop() clears the retry timer of the send. stop() does not
1958
+ * wait for the send.
1959
+ */
1960
+ receiptContext() {
1961
+ return { ...this.ctx, stopSignal: this.state.relayWork.stopSignal };
1962
+ }
1879
1963
  /**
1880
1964
  * Internal method to send receipt (delivery or read)
1881
1965
  *
1882
- * Delegates to MessageOps.sendReceipt for implementation.
1966
+ * Delegates to MessageOps.sendReceipt for implementation. The context
1967
+ * carries the stop signal of the tracker, so the next stop() clears the
1968
+ * retry timer of the send.
1883
1969
  */
1884
- async sendReceipt(recipientUserId, timestamps, type, ctx = this.ctx) {
1970
+ async sendReceipt(recipientUserId, timestamps, type, ctx = this.receiptContext()) {
1885
1971
  return MessageOps.sendReceipt(ctx, recipientUserId, timestamps, type);
1886
1972
  }
1887
1973
  /**
@@ -1904,13 +1990,34 @@ export class DefaultSignalProtocolClient {
1904
1990
  * Stop the Signal Protocol client and clean up resources
1905
1991
  *
1906
1992
  * Call this when the user logs out or the app shuts down.
1907
- * Unsubscribes from relay server, waits for the SDK work of the
1908
- * deliveries, retry requests, and receipt sends in progress, and cleans up
1909
- * any pending operations.
1910
- *
1911
- * It does not wait for app hooks, so a hook can await stop(). When a hook
1912
- * returns after stop(), the SDK drops the work after the hook and writes
1913
- * nothing more. The relay delivers the envelope again after the next start.
1993
+ * It starts the send of each batched delivery receipt, once each, and
1994
+ * unsubscribes from the relay server. Then it waits for delivery receipt
1995
+ * sends, with their app hooks, until one receipt deadline 5 s after stop()
1996
+ * starts. It waits for each receipt send that is in progress when stop()
1997
+ * starts, except a send that an earlier stop() stopped, and for the sends
1998
+ * that it starts. A delivery that finishes during the wait batches its
1999
+ * receipt. At the end of each wait, stop() sends the batches that wait and
2000
+ * waits for those sends until the same deadline. It does this again while
2001
+ * the deadline is not past. stop() holds the receipt batches from its
2002
+ * first flush until it clears its tracking state. During the hold,
2003
+ * stopRelaySubscription() does not send them, and stop() drops a receipt
2004
+ * batched after its last flush. At the deadline it stops each receipt
2005
+ * send that is left: a send that waits in an app hook stops, and that
2006
+ * receipt is not sent. A send that is in its relay call at the deadline
2007
+ * is waited for, and that receipt can still be sent. It also
2008
+ * waits for the SDK work of the deliveries and retry requests in progress.
2009
+ * Then it cleans up any pending operations.
2010
+ *
2011
+ * Apart from the receipt wait, it does not wait for app hooks, so a hook
2012
+ * can await stop(). A hook of a delivery receipt send that awaits stop()
2013
+ * holds stop() until the receipt deadline. stop() does not wait for read
2014
+ * and viewed receipt sends. When a hook returns after stop(), the SDK drops
2015
+ * the work after the hook and writes nothing more. The relay delivers the
2016
+ * envelope again after the next start.
2017
+ *
2018
+ * A call to startRelaySubscription() while stop() runs is refused and
2019
+ * logged; start again after stop() resolves. A stop() call that overlaps a
2020
+ * running stop() waits for it and settles as it settles.
1914
2021
  *
1915
2022
  * @example
1916
2023
  * ```typescript
@@ -1919,28 +2026,99 @@ export class DefaultSignalProtocolClient {
1919
2026
  * ```
1920
2027
  */
1921
2028
  async stop() {
1922
- // 1. Stop relay subscription
1923
- if (this.relayUnsubscribe) {
1924
- this.relayUnsubscribe();
1925
- this.relayUnsubscribe = undefined;
1926
- this.logger.debug('Relay subscription stopped', { category: 'E2EE' });
1927
- }
1928
- // 2. Stop retry request subscription
1929
- if (this.retryUnsubscribe) {
1930
- this.retryUnsubscribe();
1931
- this.retryUnsubscribe = undefined;
1932
- this.logger.debug('Retry request subscription stopped', {
1933
- category: 'E2EE',
1934
- });
2029
+ if (this.stopping) {
2030
+ // An overlapping call waits for the running stop() and settles as it
2031
+ // settles. No subscription can start during the run
2032
+ await this.stopping;
2033
+ return;
1935
2034
  }
1936
- // 3. Stop the relay work in progress and wait for its SDK work. Work
1937
- // that waits in an app hook is not awaited. It writes nothing after
1938
- // the hook, and the relay delivers it again after the next start
1939
- await this.state.relayWork.settle();
1940
- // 4. Clear internal tracking state via state manager. This cancels the
1941
- // receipt timers, so no receipt starts after the wait
1942
- this.state.clearForStop();
1943
- // 5. Cleanup expired Sesame sessions
2035
+ this.stopping = this.stopOnce();
2036
+ try {
2037
+ await this.stopping;
2038
+ }
2039
+ finally {
2040
+ this.stopping = undefined;
2041
+ }
2042
+ }
2043
+ /** The steps of one stop(). A stop() call that overlaps it waits for it. */
2044
+ async stopOnce() {
2045
+ // stop() sets this.stopping before step 1 runs. So a stop() call from a
2046
+ // step, such as from a relay connection state listener in step 2, waits
2047
+ // for this run and does not start a second run. A subscription start
2048
+ // from a step is refused
2049
+ await Promise.resolve();
2050
+ // 1. Start the receipt deadline, 5 s from now. Take the receipt sends in
2051
+ // progress, except a send that an earlier stop() stopped, and start the
2052
+ // send of the batched delivery receipts, once each, as relay work. Until
2053
+ // the end of step 6, a delivery that finishes batches its receipt with no
2054
+ // timer, and stopRelaySubscription() does not send it. Step 5 sends the
2055
+ // batches that wait at the end of each wait, again while the deadline is
2056
+ // not past. A receipt batched after its last flush is dropped in step 6
2057
+ const receiptDeadline = Date.now() + RelaySubscriptionOps.STOP_RECEIPT_FLUSH_MS;
2058
+ const receiptSends = [
2059
+ ...[...this.deliveryReceiptSends]
2060
+ .filter(([work]) => !work.stopSignal.aborted)
2061
+ .map(([, send]) => send),
2062
+ ...this.flushPendingDeliveryReceipts(),
2063
+ ];
2064
+ const receiptAccumulator = this.relaySubscriptionState.receiptAccumulator;
2065
+ receiptAccumulator.held = true;
2066
+ try {
2067
+ // 2. Stop relay subscription. Clear it before the call, so a call that
2068
+ // the unsubscribe makes does not unsubscribe it again. If the call
2069
+ // throws, put it back, so the next stop() calls it again
2070
+ const relayUnsubscribe = this.relayUnsubscribe;
2071
+ this.relayUnsubscribe = undefined;
2072
+ if (relayUnsubscribe) {
2073
+ try {
2074
+ relayUnsubscribe();
2075
+ }
2076
+ catch (error) {
2077
+ this.relayUnsubscribe ??= relayUnsubscribe;
2078
+ throw error;
2079
+ }
2080
+ this.logger.debug('Relay subscription stopped', { category: 'E2EE' });
2081
+ }
2082
+ // 3. Stop all relay work except the delivery receipt sends, then wait
2083
+ // for the receipt sends of step 1, with their app hooks, until the
2084
+ // receipt deadline. A delivery or retry request whose app hook returns
2085
+ // during the wait writes nothing more, and the relay delivers it again
2086
+ // after the next start. A receipt send is not stopped here, because the
2087
+ // relay has the acknowledgment of its messages and does not deliver
2088
+ // them again
2089
+ if (receiptSends.length > 0) {
2090
+ this.state.relayWork.stopAllExcept(new Set(this.deliveryReceiptSends.keys()));
2091
+ await this.waitForStopReceiptSends(receiptSends, receiptDeadline - Date.now());
2092
+ }
2093
+ // 4. Stop the relay work in progress and wait for its SDK work. Work
2094
+ // that waits in an app hook is not awaited. It writes nothing after
2095
+ // the hook, and the relay delivers it again after the next start. So a
2096
+ // receipt send that waits in an app hook after the deadline stops, and
2097
+ // that receipt is not sent. A receipt send that is still in its relay
2098
+ // call is waited for, and that receipt can still be sent
2099
+ await this.state.relayWork.settle();
2100
+ // 5. A delivery can finish during steps 3, 4, and 5, and the relay does
2101
+ // not deliver it again. Send the receipts that such deliveries batched,
2102
+ // wait for them until the same receipt deadline, and stop what is left
2103
+ // as step 4 does. Do this again while a batch waits and the deadline
2104
+ // is not past
2105
+ do {
2106
+ const lateReceiptSends = this.flushPendingDeliveryReceipts();
2107
+ if (lateReceiptSends.length === 0)
2108
+ break;
2109
+ await this.waitForStopReceiptSends(lateReceiptSends, receiptDeadline - Date.now());
2110
+ await this.state.relayWork.settle();
2111
+ } while (Date.now() < receiptDeadline);
2112
+ // 6. Clear internal tracking state via state manager. This drops the
2113
+ // receipts batched after the last flush of step 5, which is the last
2114
+ // flush before the deadline or the first flush after step 4. Then the
2115
+ // hold ends, and new batches set their timers again
2116
+ this.state.clearForStop();
2117
+ }
2118
+ finally {
2119
+ receiptAccumulator.held = false;
2120
+ }
2121
+ // 7. Cleanup expired Sesame sessions
1944
2122
  try {
1945
2123
  await this.sesameManager.cleanupExpiredSessions();
1946
2124
  }
@@ -1950,7 +2128,7 @@ export class DefaultSignalProtocolClient {
1950
2128
  data: { error: error.message },
1951
2129
  });
1952
2130
  }
1953
- // 6. Cleanup expired message records (SESAME spec §6.2)
2131
+ // 8. Cleanup expired message records (SESAME spec §6.2)
1954
2132
  try {
1955
2133
  const deleted = await this._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
1956
2134
  if (deleted > 0) {
@@ -2009,30 +2187,6 @@ export class DefaultSignalProtocolClient {
2009
2187
  });
2010
2188
  return cleaned;
2011
2189
  }
2012
- /**
2013
- * Run periodic cleanup of internal tracking state.
2014
- *
2015
- * Safe to call frequently - internally throttled to avoid overhead.
2016
- * Recommended call sites:
2017
- * - App foreground transition
2018
- * - After successful message batch processing
2019
- * - Periodically during long sessions
2020
- *
2021
- * Cleans up:
2022
- * - Expired retry dedup entries (recentRetryRequests)
2023
- *
2024
- * @returns Number of entries cleaned up
2025
- */
2026
- runPeriodicCleanup() {
2027
- const result = this.state.runPeriodicCleanup();
2028
- if (result.cleaned > 0) {
2029
- this.logger.debug('Periodic cleanup completed', {
2030
- category: 'E2EE',
2031
- data: { cleaned: result.cleaned },
2032
- });
2033
- }
2034
- return result.cleaned;
2035
- }
2036
2190
  // ============================================================================
2037
2191
  // KEY ROTATION (delegated to key-rotation.ts)
2038
2192
  // ============================================================================