@open-e2ee/signal-protocol-sdk 9.4.0 → 10.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 (118) hide show
  1. package/ADAPTERS.md +1 -0
  2. package/CHANGELOG.md +229 -0
  3. package/README.md +1 -1
  4. package/SECURITY.md +4 -4
  5. package/client/README.md +29 -12
  6. package/dist/client/client.d.ts +75 -63
  7. package/dist/client/client.d.ts.map +1 -1
  8. package/dist/client/client.js +207 -179
  9. package/dist/client/client.js.map +1 -1
  10. package/dist/client/config.d.ts +18 -3
  11. package/dist/client/config.d.ts.map +1 -1
  12. package/dist/client/config.js.map +1 -1
  13. package/dist/client/constants.d.ts +2 -10
  14. package/dist/client/constants.d.ts.map +1 -1
  15. package/dist/client/constants.js +3 -12
  16. package/dist/client/constants.js.map +1 -1
  17. package/dist/client/content-adapter.d.ts +8 -0
  18. package/dist/client/content-adapter.d.ts.map +1 -1
  19. package/dist/client/content-adapter.js +4 -0
  20. package/dist/client/content-adapter.js.map +1 -1
  21. package/dist/client/delivery-status.d.ts +50 -0
  22. package/dist/client/delivery-status.d.ts.map +1 -0
  23. package/dist/client/delivery-status.js +121 -0
  24. package/dist/client/delivery-status.js.map +1 -0
  25. package/dist/client/event-hooks.d.ts +44 -10
  26. package/dist/client/event-hooks.d.ts.map +1 -1
  27. package/dist/client/event-hooks.js +26 -0
  28. package/dist/client/event-hooks.js.map +1 -1
  29. package/dist/client/hosted-anonymous-delivery.d.ts +2 -2
  30. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  31. package/dist/client/hosted-anonymous-delivery.js +7 -4
  32. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  33. package/dist/client/hosted-mailbox-subscription.d.ts +39 -6
  34. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  35. package/dist/client/hosted-mailbox-subscription.js +133 -26
  36. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  37. package/dist/client/hosted-push.d.ts +4 -3
  38. package/dist/client/hosted-push.d.ts.map +1 -1
  39. package/dist/client/hosted-push.js +18 -6
  40. package/dist/client/hosted-push.js.map +1 -1
  41. package/dist/client/hosted-transport.d.ts +26 -6
  42. package/dist/client/hosted-transport.d.ts.map +1 -1
  43. package/dist/client/hosted-transport.js +101 -14
  44. package/dist/client/hosted-transport.js.map +1 -1
  45. package/dist/client/index.d.ts +1 -1
  46. package/dist/client/index.d.ts.map +1 -1
  47. package/dist/client/index.js.map +1 -1
  48. package/dist/client/messages.d.ts +4 -2
  49. package/dist/client/messages.d.ts.map +1 -1
  50. package/dist/client/messages.js +32 -7
  51. package/dist/client/messages.js.map +1 -1
  52. package/dist/client/relay-acceptance.d.ts +8 -0
  53. package/dist/client/relay-acceptance.d.ts.map +1 -1
  54. package/dist/client/relay-acceptance.js +7 -0
  55. package/dist/client/relay-acceptance.js.map +1 -1
  56. package/dist/client/relay-receipt-intake.d.ts +70 -0
  57. package/dist/client/relay-receipt-intake.d.ts.map +1 -0
  58. package/dist/client/relay-receipt-intake.js +111 -0
  59. package/dist/client/relay-receipt-intake.js.map +1 -0
  60. package/dist/client/relay-receipt-join.d.ts +50 -0
  61. package/dist/client/relay-receipt-join.d.ts.map +1 -0
  62. package/dist/client/relay-receipt-join.js +106 -0
  63. package/dist/client/relay-receipt-join.js.map +1 -0
  64. package/dist/client/relay-subscription.d.ts +12 -0
  65. package/dist/client/relay-subscription.d.ts.map +1 -1
  66. package/dist/client/relay-subscription.js +246 -83
  67. package/dist/client/relay-subscription.js.map +1 -1
  68. package/dist/client/retry-family.d.ts +119 -0
  69. package/dist/client/retry-family.d.ts.map +1 -0
  70. package/dist/client/retry-family.js +170 -0
  71. package/dist/client/retry-family.js.map +1 -0
  72. package/dist/client/retry-request-envelope.d.ts +106 -0
  73. package/dist/client/retry-request-envelope.d.ts.map +1 -0
  74. package/dist/client/retry-request-envelope.js +245 -0
  75. package/dist/client/retry-request-envelope.js.map +1 -0
  76. package/dist/client/retry.d.ts +63 -22
  77. package/dist/client/retry.d.ts.map +1 -1
  78. package/dist/client/retry.js +234 -136
  79. package/dist/client/retry.js.map +1 -1
  80. package/dist/client/sealed-sender.d.ts +15 -3
  81. package/dist/client/sealed-sender.d.ts.map +1 -1
  82. package/dist/client/sealed-sender.js +22 -3
  83. package/dist/client/sealed-sender.js.map +1 -1
  84. package/dist/client/signal-service-cipher.d.ts +64 -1
  85. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  86. package/dist/client/signal-service-cipher.js +212 -17
  87. package/dist/client/signal-service-cipher.js.map +1 -1
  88. package/dist/client/state.d.ts +7 -60
  89. package/dist/client/state.d.ts.map +1 -1
  90. package/dist/client/state.js +8 -86
  91. package/dist/client/state.js.map +1 -1
  92. package/dist/client/types.d.ts +11 -3
  93. package/dist/client/types.d.ts.map +1 -1
  94. package/dist/client/types.js.map +1 -1
  95. package/dist/index.d.ts +2 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js.map +1 -1
  98. package/dist/internal/protocol/sealed-sender/types.d.ts +1 -1
  99. package/dist/internal/protocol/sealed-sender/types.js +1 -1
  100. package/dist/local/store/received-content.d.ts +16 -2
  101. package/dist/local/store/received-content.d.ts.map +1 -1
  102. package/dist/local/store/received-content.js +18 -3
  103. package/dist/local/store/received-content.js.map +1 -1
  104. package/dist/local/store/reliability.d.ts +291 -2
  105. package/dist/local/store/reliability.d.ts.map +1 -1
  106. package/dist/local/store/reliability.js +451 -13
  107. package/dist/local/store/reliability.js.map +1 -1
  108. package/dist/remote/relay/index.d.ts +1 -1
  109. package/dist/remote/relay/index.d.ts.map +1 -1
  110. package/dist/remote/relay/index.js.map +1 -1
  111. package/dist/remote/relay/types.d.ts +34 -30
  112. package/dist/remote/relay/types.d.ts.map +1 -1
  113. package/dist/types/api.d.ts +43 -22
  114. package/dist/types/api.d.ts.map +1 -1
  115. package/docs/ASSURANCE.md +5 -5
  116. package/docs/DEVIATIONS.md +4 -5
  117. package/docs/INTERFACES.md +2 -0
  118. package/package.json +1 -1
@@ -46,11 +46,13 @@ import { DefaultSignalProtocolManager } from '../internal/manager/index.js';
46
46
  import { DefaultSesameManager } from '../internal/sesame/index.js';
47
47
  import { createCompositeIdentityV1 } from '../keys/identity.js';
48
48
  import { EncryptionError, EncryptionErrorCode } from '../types/index.js';
49
- import { base64ToBytes, bytesToBase64, constantTimeEqual } from '../internal/crypto/index.js';
49
+ import { base64ToBytes, bytesToBase64, constantTimeEqual, generateUuidV4 } from '../internal/crypto/index.js';
50
50
  import { deriveGroupSecretParams, getGroupPublicParams } from '../internal/protocol/zk/groups/index.js';
51
51
  import { SERVICE_ID_ACI } from '../internal/protocol/zk/groups/uid-struct.js';
52
52
  import { deserializeSenderCertificate, validateSenderCertificate, } from '../internal/protocol/sealed-sender/index.js';
53
- import { deferHooks } from './event-hooks.js';
53
+ import { assertHookName, callHook, deferHooks, } from './event-hooks.js';
54
+ import { DeliveryStatusTracker } from './delivery-status.js';
55
+ import { relayReceiptIntakeOf } from './relay-receipt-intake.js';
54
56
  import { ProtocolAddress } from '../types/address.js';
55
57
  import { getActiveIdentityTypes, resolveSignalProtocolStrategy, SEALED_SENDER_CERTIFICATE_MARGIN_MS, } from './config.js';
56
58
  import { resolveSignalProtocolLogger } from '../logger.js';
@@ -74,16 +76,18 @@ import * as SessionOps from './sessions.js';
74
76
  import * as GroupOps from './groups.js';
75
77
  import * as PreKeyOps from './prekeys.js';
76
78
  import * as RetryOps from './retry.js';
79
+ import { receiveInRetryFamily } from './retry-family.js';
80
+ import { deliveredEnvelopeFingerprint } from '../local/store/received-content.js';
77
81
  import * as RelaySubscriptionOps from './relay-subscription.js';
82
+ import { relayReceiptJoinOf } from './relay-receipt-join.js';
78
83
  import { SignalProtocolClientState, SIGNAL_PROTOCOL_CLIENT_CONSTANTS } from './state.js';
79
- import { clientRelayFanOut, rethrowRelayWorkStopped } from './relay-work.js';
84
+ import { clientRelayFanOut, rethrowRelayWorkStopped, RelayWorkStopped, } from './relay-work.js';
80
85
  import { deleteMediaAttachment, resolveMediaAttachment, } from '../media/index.js';
81
86
  import { StorageBackedSignalProtocolClientMedia } from './media.js';
82
87
  // Group state (Signal Private Group System)
83
88
  import { GroupManager, decodeGroupTrustRoot } from '../internal/groups/index.js';
84
89
  import { SignalProtocolGroupStateStore } from '../internal/groups/sdk-store.js';
85
90
  import { deriveAccessKey } from '../internal/protocol/sealed-sender/delivery-token.js';
86
- export { IMPLICIT_ENVELOPE_TYPES } from './constants.js';
87
91
  /**
88
92
  * Module-level lock for storage initialization.
89
93
  * Prevents multiple concurrent DefaultSignalProtocolClient.create() calls from creating
@@ -128,6 +132,8 @@ export class DefaultSignalProtocolClient {
128
132
  _userId;
129
133
  logger;
130
134
  hooks;
135
+ /** The delivery status of the outgoing messages of this client. */
136
+ deliveries;
131
137
  contentAdapter;
132
138
  // Multi-device support (Phase 2)
133
139
  deviceId; // 1 = primary, 2-5 = linked devices
@@ -190,7 +196,6 @@ export class DefaultSignalProtocolClient {
190
196
  return this.relay?.subscribeRelayConnectionState(listener) ?? (() => undefined);
191
197
  }
192
198
  relayUnsubscribe;
193
- retryUnsubscribe;
194
199
  /**
195
200
  * Cached sender certificate for sealed sender.
196
201
  * Lazily fetched and refreshed one hour before its signed expiration.
@@ -242,6 +247,8 @@ export class DefaultSignalProtocolClient {
242
247
  this.deviceId = deviceId;
243
248
  this.config = config;
244
249
  this.logger = resolveSignalProtocolLogger(config.logger);
250
+ for (const name of Object.keys(config.hooks ?? {}))
251
+ assertHookName(name);
245
252
  this.hooks = config.hooks || {};
246
253
  this.contentAdapter = config.contentAdapter ?? createDefaultSignalProtocolContentAdapter();
247
254
  // Dependency injection: use the provided relay adapter when configured.
@@ -255,6 +262,7 @@ export class DefaultSignalProtocolClient {
255
262
  throw new Error('Storage must be provided by DefaultSignalProtocolClient.create() callers');
256
263
  }
257
264
  this._storage = config.storage;
265
+ this.deliveries = new DeliveryStatusTracker(this._storage);
258
266
  this._storage.setLogger?.(this.logger);
259
267
  this.media = new StorageBackedSignalProtocolClientMedia({
260
268
  storage: this._storage,
@@ -346,6 +354,10 @@ export class DefaultSignalProtocolClient {
346
354
  if (this.groupManager) {
347
355
  this.cipher.setGroupSendBarrierChecker((groupId) => this.groupManager.assertGroupSendAllowed(groupId));
348
356
  }
357
+ // The client applies each Relay delivery receipt of its relay.
358
+ if (this.relay) {
359
+ relayReceiptIntakeOf(this.relay)?.subscribe((receipt) => this.receiveRelayReceipt(receipt));
360
+ }
349
361
  // Set up auto-session establishment and stale-session refresh.
350
362
  // This enables lazy session creation when sending to users without established sessions
351
363
  const sessions = this.sendSessionCallbacks(() => this.ctx);
@@ -484,8 +496,48 @@ export class DefaultSignalProtocolClient {
484
496
  sesameManager: this.sesameManager,
485
497
  contentAdapter: this.contentAdapter,
486
498
  profileKeys: profileKeyExchange(this),
499
+ deliveries: this.deliveries,
500
+ sealReceipt: (recipientUserId, recipientDeviceId, ciphertextBase64) => this.cipher.sealReceipt(recipientUserId, recipientDeviceId, ciphertextBase64),
487
501
  };
488
502
  }
503
+ /**
504
+ * Apply one Relay delivery receipt, then announce its deliveries. A
505
+ * receipt that stop() kept from its write throws, so the Relay replays it.
506
+ */
507
+ async receiveRelayReceipt(receipt) {
508
+ let applied = false;
509
+ await this.state.relayWork.run(async (work) => {
510
+ work.proceed();
511
+ const events = await this.deliveries.applyRelayReceipt(receipt);
512
+ applied = true;
513
+ await this.announceDeliveries(work.wrapHooks(this.hooks), events);
514
+ });
515
+ if (!applied)
516
+ throw new RelayWorkStopped();
517
+ }
518
+ /** Run the onDelivered hook once for each event, in order. */
519
+ async announceDeliveries(hooks, events) {
520
+ for (const event of events)
521
+ await callHook(hooks, 'onDelivered', event);
522
+ }
523
+ /**
524
+ * Announce the deliveries that waited for a send of this client message ID
525
+ * to resolve.
526
+ */
527
+ releaseDeliveries(clientMessageId) {
528
+ void this.state.relayWork
529
+ .run(async (work) => {
530
+ work.proceed();
531
+ const events = await this.deliveries.release(clientMessageId);
532
+ await this.announceDeliveries(work.wrapHooks(this.hooks), events);
533
+ })
534
+ .catch((error) => {
535
+ this.logger.warn('Failed to announce deliveries', {
536
+ category: 'E2EE',
537
+ data: { clientMessageId, error: error.message },
538
+ });
539
+ });
540
+ }
489
541
  /**
490
542
  * Whether the client enables and configures sealed sender.
491
543
  */
@@ -573,26 +625,25 @@ export class DefaultSignalProtocolClient {
573
625
  get retryConfig() {
574
626
  return {
575
627
  keyRotationDebounceMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.KEY_ROTATION_DEBOUNCE_MS,
576
- retryDedupWindowMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.RETRY_DEDUP_WINDOW_MS,
577
- retryCleanupIntervalMs: SIGNAL_PROTOCOL_CLIENT_CONSTANTS.RETRY_CLEANUP_INTERVAL_MS,
578
628
  };
579
629
  }
580
630
  /**
581
- * Get retry dedup state for retry operations
631
+ * Get retry response state for retry operations
582
632
  */
583
- get retryDedupState() {
584
- return this.state.getRetryDedupState();
633
+ get retryResponseState() {
634
+ return this.state.getRetryResponseState();
585
635
  }
586
636
  /**
587
- * Get retry callbacks for retry operations. Session changes and resends use
588
- * the given context, so their hooks run through its relay work. A resend
589
- * waits for the recipient's lock only until stop() stops the work.
637
+ * Get retry callbacks for retry operations. Session changes use the given
638
+ * context, so their hooks run through its relay work. A resend goes only to
639
+ * the device that asked, and waits for the recipient's lock only until the
640
+ * stop signal aborts.
590
641
  */
591
- retryCallbacks(work, ctx) {
642
+ retryCallbacks(stopSignal, ctx) {
592
643
  return {
593
644
  archiveSession: (address) => SessionOps.archiveSession(ctx, address),
594
645
  establishSession: (address, bundle) => SessionOps.establishSession(ctx, this.sesameManager, address, bundle),
595
- send: (recipientId, content, options) => this.sendWithContext(recipientId, content, options, ctx, work.stopSignal),
646
+ resend: (userId, deviceId, content, options) => this.cipher.resendToDevice(userId, deviceId, content, options, stopSignal),
596
647
  forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds(),
597
648
  };
598
649
  }
@@ -604,15 +655,18 @@ export class DefaultSignalProtocolClient {
604
655
  }
605
656
  /**
606
657
  * Get relay subscription callbacks (delegate back to DefaultSignalProtocolClient methods).
607
- * Receipts and typing indicators use the given context, so their hooks run
608
- * through its relay work. Each receipt send is relay work of its own.
658
+ * Receipts, typing indicators and retry requests use the given context, so
659
+ * their hooks run through its relay work. Each receipt send is relay work of
660
+ * its own. A retry request runs in the current work, so a stop of that work
661
+ * reaches the receive route, and the route keeps the request envelope.
609
662
  */
610
- relaySubscriptionCallbacks(ctx) {
663
+ relaySubscriptionCallbacks(ctx, stopSignal) {
611
664
  return {
612
665
  forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds(),
613
666
  handleDeliveryReceipt: (envelope, receipt) => this.handleDeliveryReceipt(envelope, receipt, ctx),
614
667
  handleTypingIndicator: (envelope, typing) => this.handleTypingIndicator(envelope, typing, ctx),
615
668
  sendDeliveryReceipt: (userId, timestamps) => this.sendDeliveryReceiptAsRelayWork(userId, timestamps),
669
+ handleRetryRequest: (request, retry) => RetryOps.handleRetryRequestAndResend(ctx, request, this.retryResponseState, this.retryCallbacks(stopSignal, ctx), this.retryConfig, retry),
616
670
  };
617
671
  }
618
672
  /**
@@ -883,10 +937,6 @@ export class DefaultSignalProtocolClient {
883
937
  if (!syncFailed && finalConfig?.relay && finalConfig?.hooks?.onMessageDecrypted) {
884
938
  client.startRelaySubscription();
885
939
  }
886
- // Start retry request subscription if relay supports it (SESAME spec §6.2)
887
- if (!syncFailed && finalConfig?.relay?.subscribeRetryRequests) {
888
- client.startRetryRequestSubscription();
889
- }
890
940
  // Validate sender keys config and warn on extreme values
891
941
  if (finalConfig?.senderKeys) {
892
942
  const sk = finalConfig.senderKeys;
@@ -1232,12 +1282,78 @@ export class DefaultSignalProtocolClient {
1232
1282
  * 3. On retryable error: sends retry request via relay or options callback
1233
1283
  * 4. Re-throws error for caller to handle
1234
1284
  *
1285
+ * A `retry_request` envelope holds no plaintext. This method rejects it
1286
+ * before decryption and sends no retry request. Give it to
1287
+ * `receiveIncomingEnvelopes`, which handles it.
1288
+ *
1289
+ * A failed envelope that this client asked a resend for, and each resend
1290
+ * or null message for it, gives plaintext at most once on both receive
1291
+ * paths. When this client processed the envelope, or the application
1292
+ * already has that content, this method acknowledges the envelope and
1293
+ * throws MESSAGE_DUPLICATE with no decrypt.
1294
+ *
1295
+ * A null message carries no content. The client consumes a null message
1296
+ * when the content adapter reports `nullMessage: true`, and a custom
1297
+ * adapter must report it for its own null encoding. This method never
1298
+ * returns a null message. It marks the null message processed,
1299
+ * acknowledges it and throws MESSAGE_DUPLICATE. A null message for a
1300
+ * failed envelope marks that envelope processed, so a redelivery of it
1301
+ * is dropped, but a content resend for it that comes later still gives
1302
+ * its plaintext.
1303
+ *
1304
+ * A resend or null message that fails to decrypt, or whose seal fails to
1305
+ * open, asks again for its failed envelope under the same retry ID. When
1306
+ * the processed record of the failed envelope fails to store after a
1307
+ * decrypt, the client writes a warning with the behavior
1308
+ * RETRY_FULFILL_WRITE_FAILED, as on every receive path, and this method
1309
+ * returns the plaintext. A redelivery of the failed envelope or of
1310
+ * another family member can then give the content again. When a
1311
+ * processed record of a null message or of its failed envelope fails to
1312
+ * store, the client writes a warning with the behavior
1313
+ * RETRY_NULL_WRITE_FAILED, as on every receive path, and this method
1314
+ * still throws MESSAGE_DUPLICATE. A redelivery of the failed envelope
1315
+ * can then give the content.
1316
+ *
1235
1317
  * @param envelope - The encrypted message envelope
1236
1318
  * @param options - Transport callbacks for background (no relay) scenarios
1237
1319
  * @returns Decrypted plaintext
1238
1320
  * @throws EncryptionError after sending retry request if decryption fails
1321
+ * @throws EncryptionError INVALID_CIPHERTEXT for a `retry_request` envelope
1322
+ * @throws EncryptionError MESSAGE_DUPLICATE when this client processed the
1323
+ * envelope, the application already has the content of the failed
1324
+ * envelope of a retry request, or the envelope is a null message
1239
1325
  */
1240
1326
  async processIncomingEnvelope(envelope, options) {
1327
+ if (envelope.messageType === 'retry_request') {
1328
+ throw new EncryptionError('A retry_request envelope holds no plaintext; give it to receiveIncomingEnvelopes', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType, senderId: envelope.senderUserId });
1329
+ }
1330
+ // The fingerprint covers the envelope as the Relay delivered it, before
1331
+ // any unseal, so every receive path stores one value for it.
1332
+ const fingerprint = envelope.id
1333
+ ? await deliveredEnvelopeFingerprint(this.userId, this.deviceId, envelope)
1334
+ : undefined;
1335
+ return receiveInRetryFamily(this._storage, this.logger, envelope, async (family) => {
1336
+ if (!(await family.admit())) {
1337
+ await this.markMessageDeliveredSilently(envelope.id, options);
1338
+ throw new EncryptionError('The application already has the content of this failed envelope', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1339
+ }
1340
+ const plaintext = await this.decryptIncomingEnvelope(envelope, family, fingerprint, options);
1341
+ // A null message carries no content, so the caller never gets it.
1342
+ if (this.contentAdapter.inspectContent(plaintext).nullMessage) {
1343
+ await family.consumeNull(fingerprint);
1344
+ await this.markMessageDeliveredSilently(envelope.id, options);
1345
+ throw new EncryptionError('A null message carries no content', EncryptionErrorCode.MESSAGE_DUPLICATE, { senderId: envelope.senderUserId });
1346
+ }
1347
+ await family.fulfill();
1348
+ return plaintext;
1349
+ });
1350
+ }
1351
+ /**
1352
+ * Decrypt one envelope that is not a `retry_request`, under its retry family
1353
+ * lock. The fingerprint is that of the delivered envelope, also for the
1354
+ * inner envelope of a seal.
1355
+ */
1356
+ async decryptIncomingEnvelope(envelope, family, fingerprint, options) {
1241
1357
  // Handle sealed sender envelopes: unseal to reveal sender before decrypting
1242
1358
  if (envelope.messageType === 'unidentified_sender' && this.config.sealedSender) {
1243
1359
  const identityKeyPair = await this._storage.getIdentityKey();
@@ -1245,18 +1361,30 @@ export class DefaultSignalProtocolClient {
1245
1361
  throw new EncryptionError('No identity key pair for sealed sender decryption', EncryptionErrorCode.DECRYPTION_FAILED);
1246
1362
  }
1247
1363
  const recipientPrivateKeyBytes = base64ToBytes(identityKeyPair.dhKey.privateKey);
1248
- const unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1364
+ let unsealed;
1365
+ try {
1366
+ unsealed = await unsealMessage(envelope.ciphertext, recipientPrivateKeyBytes, this.userId, this.deviceId, this.config.sealedSender, envelope.serverTimestamp, this.logger);
1367
+ }
1368
+ catch (error) {
1369
+ // A member whose seal fails to open asks the device of its request
1370
+ // for the next attempt, as a member whose decrypt fails does.
1371
+ if (family.member !== undefined) {
1372
+ await this.sendRetryRequestInternal(family.withRequestedSender(envelope), error, family, fingerprint, options);
1373
+ }
1374
+ throw error;
1375
+ }
1249
1376
  // Process the inner envelope with revealed sender identity. The inner
1250
- // type travels inside the seal. Nothing outside it distinguishes a
1251
- // group message from a pairwise one. The same mapping serves the other
1252
- // receive path via `reconstructEnvelope`.
1253
- return this.processIncomingEnvelope({
1377
+ // type and the content hint travel inside the seal. Nothing outside it
1378
+ // distinguishes a group message from a pairwise one. The same mapping
1379
+ // serves the other receive path via `reconstructEnvelope`.
1380
+ return this.decryptIncomingEnvelope({
1254
1381
  ...envelope,
1255
1382
  senderUserId: unsealed.senderUserId,
1256
1383
  senderDeviceId: unsealed.senderDeviceId,
1257
1384
  ciphertext: unsealed.innerCiphertextBase64,
1258
1385
  messageType: envelopeTypeForContent(unsealed.contentType),
1259
- }, options);
1386
+ contentHint: unsealed.contentHint,
1387
+ }, family, fingerprint, options);
1260
1388
  }
1261
1389
  // Route group messages to sender key decryption. `sender_key` says the
1262
1390
  // payload is a framed SenderKeyMessage. It does not say which group, so
@@ -1284,7 +1412,7 @@ export class DefaultSignalProtocolClient {
1284
1412
  catch (error) {
1285
1413
  // Send retry request if error is retryable (per SESAME spec §4.1)
1286
1414
  if (isRetryableDecryptionError(error)) {
1287
- await this.sendRetryRequestInternal(envelope, error, options);
1415
+ await this.sendRetryRequestInternal(envelope, error, family, fingerprint, options);
1288
1416
  }
1289
1417
  // Re-throw so caller can handle (log, skip message, etc.)
1290
1418
  throw error;
@@ -1339,7 +1467,10 @@ export class DefaultSignalProtocolClient {
1339
1467
  /**
1340
1468
  * Receive a pulled batch through the subscription content handler.
1341
1469
  * The application must register onMessageDecrypted before calling this method.
1342
- * Successful IDs are ready for transport acknowledgment.
1470
+ * Processed IDs are ready for transport acknowledgment. They include
1471
+ * each envelope that the client drops as a duplicate, and each null
1472
+ * message that the content adapter reports, which the client consumes
1473
+ * and never gives to onMessageDecrypted.
1343
1474
  */
1344
1475
  async receiveIncomingEnvelopes(envelopes) {
1345
1476
  if (!this.hooks?.onMessageDecrypted) {
@@ -1373,10 +1504,12 @@ export class DefaultSignalProtocolClient {
1373
1504
  *
1374
1505
  * @param envelope - The failed message envelope
1375
1506
  * @param error - The decryption error
1507
+ * @param family - The retry family of the delivered envelope
1508
+ * @param fingerprint - The fingerprint of the delivered envelope
1376
1509
  * @param options - Optional transport callbacks (for background without relay)
1377
1510
  */
1378
- async sendRetryRequestInternal(envelope, error, options) {
1379
- return RetryOps.sendRetryRequestInternal(this.ctx, envelope, error, this.rateLimitState, { forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds() }, this.retryConfig, options);
1511
+ async sendRetryRequestInternal(envelope, error, family, fingerprint, options) {
1512
+ return RetryOps.sendRetryRequestInternal(this.ctx, envelope, error, this.rateLimitState, { forcePreKeyRotation: () => this.regeneratePreKeysWithFreshIds() }, this.retryConfig, family, fingerprint, options);
1380
1513
  }
1381
1514
  // ============================================================================
1382
1515
  // FILE ENCRYPTION/DECRYPTION (delegated to files.ts)
@@ -1500,14 +1633,25 @@ export class DefaultSignalProtocolClient {
1500
1633
  await profileKeys?.offer(recipientId);
1501
1634
  plaintextBytes = content; // already Uint8Array
1502
1635
  }
1636
+ // A receipt for this send waits until the send resolves.
1637
+ const clientMessageId = options?.clientMessageId ?? (await generateUuidV4());
1503
1638
  const encrypt = (sendContext) => this.cipher.encrypt(recipientId, plaintextBytes, {
1504
1639
  ...options,
1640
+ clientMessageId,
1505
1641
  ...(clientTimestamp !== undefined && { timestamp: clientTimestamp }),
1506
1642
  }, this.sendSessionCallbacks(() => sendContext, stopSignal), stopSignal);
1507
- // A group send sets up sessions while it holds the group's Sender Key lock.
1508
- const result = await (isGroupId(recipientId)
1509
- ? this.withDeferredHooks(context, encrypt)
1510
- : encrypt(context));
1643
+ this.deliveries.beginSend(clientMessageId);
1644
+ let result;
1645
+ try {
1646
+ // A group send sets up sessions while it holds the group's Sender Key lock.
1647
+ result = await (isGroupId(recipientId)
1648
+ ? this.withDeferredHooks(context, encrypt)
1649
+ : encrypt(context));
1650
+ }
1651
+ finally {
1652
+ this.deliveries.endSend(clientMessageId);
1653
+ }
1654
+ this.releaseDeliveries(clientMessageId);
1511
1655
  if (profileKey)
1512
1656
  await profileKeys?.delivered(recipientId, profileKey);
1513
1657
  return clientTimestamp !== undefined ? { ...result, clientTimestamp } : result;
@@ -1569,23 +1713,7 @@ export class DefaultSignalProtocolClient {
1569
1713
  }
1570
1714
  /** Accept an authenticated composite-identity rotation and reset bound sessions. */
1571
1715
  async acceptIdentityRotation(userId, identity, identityType = 'aci') {
1572
- const accepted = await SessionOps.acceptIdentityRotation(this.ctx, userId, identity, identityType);
1573
- // A retry that first discovered the changed tuple may already have failed
1574
- // closed and entered the short-lived dedup window. Explicit acceptance is
1575
- // the authority to try those still-pending requests again. It is never
1576
- // inferred from the retry request itself.
1577
- const retryPrefix = `${userId}:`;
1578
- for (const key of this.retryDedupState.recentRetryRequests.keys()) {
1579
- if (key.startsWith(retryPrefix)) {
1580
- this.retryDedupState.recentRetryRequests.delete(key);
1581
- }
1582
- }
1583
- if (this.retryUnsubscribe) {
1584
- this.retryUnsubscribe();
1585
- this.retryUnsubscribe = undefined;
1586
- this.startRetryRequestSubscription();
1587
- }
1588
- return accepted;
1716
+ return SessionOps.acceptIdentityRotation(this.ctx, userId, identity, identityType);
1589
1717
  }
1590
1718
  /**
1591
1719
  * Mark a message as read/delivered
@@ -1637,6 +1765,7 @@ export class DefaultSignalProtocolClient {
1637
1765
  * @see SignalProtocolClient.registerHook
1638
1766
  */
1639
1767
  registerHook(name, callback) {
1768
+ assertHookName(name);
1640
1769
  this.hooks[name] = callback;
1641
1770
  this.logger.debug('Hook registered', {
1642
1771
  category: 'E2EE',
@@ -1699,7 +1828,7 @@ export class DefaultSignalProtocolClient {
1699
1828
  this.relayUnsubscribe = this.relay.subscribe(this.userId, this.deviceId, (envelope) => {
1700
1829
  const handled = this.state.relayWork.run((work) => {
1701
1830
  const ctx = this.relayWorkContext(work);
1702
- return RelaySubscriptionOps.handleRelayMessage({ ...ctx, cipher: this.cipher, stopSignal: work.stopSignal }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx), this.relaySubscriptionConfig);
1831
+ return RelaySubscriptionOps.handleRelayMessage({ ...ctx, cipher: this.cipher, stopSignal: work.stopSignal }, envelope, this.relaySubscriptionState, this.relaySubscriptionCallbacks(ctx, work.stopSignal), this.relaySubscriptionConfig);
1703
1832
  });
1704
1833
  handled.catch((error) => {
1705
1834
  // The relay delivers an envelope that it did not acknowledge again.
@@ -1747,73 +1876,6 @@ export class DefaultSignalProtocolClient {
1747
1876
  });
1748
1877
  }
1749
1878
  }
1750
- /**
1751
- * Start listening for retry requests from recipients (SESAME spec §6.2)
1752
- *
1753
- * When a recipient cannot decrypt a message, they send a retry request.
1754
- * This method subscribes to incoming retry requests and processes them
1755
- * by resending the original message with a new session.
1756
- *
1757
- * Automatically started if relay.subscribeRetryRequests is available.
1758
- * Call this manually if you need to restart the subscription.
1759
- * A call while stop() runs is refused and logged; start again after stop()
1760
- * resolves.
1761
- */
1762
- startRetryRequestSubscription() {
1763
- if (!this.relay || !this.relay.subscribeRetryRequests) {
1764
- this.logger.debug('Relay does not support retry request subscription', {
1765
- category: 'E2EE',
1766
- });
1767
- return;
1768
- }
1769
- // A start while stop() runs would outlive stop()
1770
- if (this.stopping) {
1771
- this.logger.debug('Retry request subscription not started: stop() in progress', {
1772
- category: 'E2EE',
1773
- });
1774
- return;
1775
- }
1776
- // Avoid duplicate subscriptions
1777
- if (this.retryUnsubscribe) {
1778
- this.logger.debug('Retry request subscription already active', {
1779
- category: 'E2EE',
1780
- });
1781
- return;
1782
- }
1783
- this.logger.debug('Starting retry request subscription', {
1784
- category: 'E2EE',
1785
- data: { userId: this.userId, deviceId: this.deviceId },
1786
- });
1787
- this.retryUnsubscribe = this.relay.subscribeRetryRequests(this.userId, this.deviceId, async (retryRequest) => {
1788
- await this.handleRetryRequestAndResend(retryRequest);
1789
- });
1790
- }
1791
- /**
1792
- * Handle a retry request and resend the original message
1793
- *
1794
- * Per SESAME spec §4.1 (Resending Process):
1795
- * 1. Look up MessageRecord by sequence number
1796
- * 2. Validate retry limits and message TTL
1797
- * 3. Check session state:
1798
- * - If NO active session OR active session IS orphaned (matches MessageRecord.sessionStateId):
1799
- * → Fetch prekey bundle and create new session
1800
- * - If DIFFERENT active session exists:
1801
- * → Use it directly (no prekey fetch, prevents rate limit issues)
1802
- * 4. Re-encrypt and send the original message
1803
- *
1804
- * This prevents infinite retry loops where each retry creates a new session
1805
- * with different header keys.
1806
- *
1807
- * The request runs as relay work, so its hooks run through that work.
1808
- *
1809
- * @param retryRequest - The retry request from the recipient
1810
- */
1811
- handleRetryRequestAndResend(retryRequest) {
1812
- return this.state.relayWork.run((work) => {
1813
- const ctx = this.relayWorkContext(work);
1814
- return RetryOps.handleRetryRequestAndResend(ctx, retryRequest, this.retryDedupState, this.retryCallbacks(work, ctx), this.retryConfig);
1815
- });
1816
- }
1817
1879
  /**
1818
1880
  * Send delivery receipt to original sender (all devices)
1819
1881
  *
@@ -2016,10 +2078,9 @@ export class DefaultSignalProtocolClient {
2016
2078
  * the work after the hook and writes nothing more. The relay delivers the
2017
2079
  * envelope again after the next start.
2018
2080
  *
2019
- * A call to startRelaySubscription() or startRetryRequestSubscription()
2020
- * while stop() runs is refused and logged; start again after stop()
2021
- * resolves. A stop() call that overlaps a running stop() waits for it and
2022
- * settles as it settles.
2081
+ * A call to startRelaySubscription() while stop() runs is refused and
2082
+ * logged; start again after stop() resolves. A stop() call that overlaps a
2083
+ * running stop() waits for it and settles as it settles.
2023
2084
  *
2024
2085
  * @example
2025
2086
  * ```typescript
@@ -2052,10 +2113,10 @@ export class DefaultSignalProtocolClient {
2052
2113
  // 1. Start the receipt deadline, 5 s from now. Take the receipt sends in
2053
2114
  // progress, except a send that an earlier stop() stopped, and start the
2054
2115
  // send of the batched delivery receipts, once each, as relay work. Until
2055
- // the end of step 7, a delivery that finishes batches its receipt with no
2056
- // timer, and stopRelaySubscription() does not send it. Step 6 sends the
2116
+ // the end of step 6, a delivery that finishes batches its receipt with no
2117
+ // timer, and stopRelaySubscription() does not send it. Step 5 sends the
2057
2118
  // batches that wait at the end of each wait, again while the deadline is
2058
- // not past. A receipt batched after its last flush is dropped in step 7
2119
+ // not past. A receipt batched after its last flush is dropped in step 6
2059
2120
  const receiptDeadline = Date.now() + RelaySubscriptionOps.STOP_RECEIPT_FLUSH_MS;
2060
2121
  const receiptSends = [
2061
2122
  ...[...this.deliveryReceiptSends]
@@ -2081,23 +2142,7 @@ export class DefaultSignalProtocolClient {
2081
2142
  }
2082
2143
  this.logger.debug('Relay subscription stopped', { category: 'E2EE' });
2083
2144
  }
2084
- // 3. Stop retry request subscription. Clear it before the call, and put
2085
- // it back if the call throws, as step 2 does
2086
- const retryUnsubscribe = this.retryUnsubscribe;
2087
- this.retryUnsubscribe = undefined;
2088
- if (retryUnsubscribe) {
2089
- try {
2090
- retryUnsubscribe();
2091
- }
2092
- catch (error) {
2093
- this.retryUnsubscribe ??= retryUnsubscribe;
2094
- throw error;
2095
- }
2096
- this.logger.debug('Retry request subscription stopped', {
2097
- category: 'E2EE',
2098
- });
2099
- }
2100
- // 4. Stop all relay work except the delivery receipt sends, then wait
2145
+ // 3. Stop all relay work except the delivery receipt sends, then wait
2101
2146
  // for the receipt sends of step 1, with their app hooks, until the
2102
2147
  // receipt deadline. A delivery or retry request whose app hook returns
2103
2148
  // during the wait writes nothing more, and the relay delivers it again
@@ -2108,35 +2153,42 @@ export class DefaultSignalProtocolClient {
2108
2153
  this.state.relayWork.stopAllExcept(new Set(this.deliveryReceiptSends.keys()));
2109
2154
  await this.waitForStopReceiptSends(receiptSends, receiptDeadline - Date.now());
2110
2155
  }
2111
- // 5. Stop the relay work in progress and wait for its SDK work. Work
2156
+ // 4. Stop the relay work in progress and wait for its SDK work. Work
2112
2157
  // that waits in an app hook is not awaited. It writes nothing after
2113
2158
  // the hook, and the relay delivers it again after the next start. So a
2114
2159
  // receipt send that waits in an app hook after the deadline stops, and
2115
2160
  // that receipt is not sent. A receipt send that is still in its relay
2116
2161
  // call is waited for, and that receipt can still be sent
2117
2162
  await this.state.relayWork.settle();
2118
- // 6. A delivery can finish during steps 4, 5, and 6, and the relay does
2119
- // not deliver it again. Send the receipts that such deliveries batched,
2163
+ // 5. A delivery can finish during steps 3, 4, and 5, and the relay does
2164
+ // not deliver it again. A delivery that waits for the Relay reply to its
2165
+ // acknowledgment gets no reply after the unsubscribe, so release it to
2166
+ // its E2EE receipt. Send the receipts that such deliveries batched,
2120
2167
  // wait for them until the same receipt deadline, and stop what is left
2121
- // as step 5 does. Do this again while a batch waits and the deadline
2168
+ // as step 4 does. Do this again while a batch waits and the deadline
2122
2169
  // is not past
2170
+ const receiptJoin = this.relay === undefined ? undefined : relayReceiptJoinOf(this.relay);
2123
2171
  do {
2172
+ receiptJoin?.release();
2124
2173
  const lateReceiptSends = this.flushPendingDeliveryReceipts();
2125
2174
  if (lateReceiptSends.length === 0)
2126
2175
  break;
2127
2176
  await this.waitForStopReceiptSends(lateReceiptSends, receiptDeadline - Date.now());
2128
2177
  await this.state.relayWork.settle();
2129
2178
  } while (Date.now() < receiptDeadline);
2130
- // 7. Clear internal tracking state via state manager. This drops the
2131
- // receipts batched after the last flush of step 6, which is the last
2132
- // flush before the deadline or the first flush after step 5. Then the
2133
- // hold ends, and new batches set their timers again
2179
+ // 6. Release a delivery that started to wait for its reply after the
2180
+ // last release, so that no reply timer batches its receipt after
2181
+ // stop(). Then clear internal tracking state via state manager. This
2182
+ // drops the receipts batched after the last flush of step 5, which is
2183
+ // the last flush before the deadline or the first flush after step 4.
2184
+ // Then the hold ends, and new batches set their timers again
2185
+ receiptJoin?.release();
2134
2186
  this.state.clearForStop();
2135
2187
  }
2136
2188
  finally {
2137
2189
  receiptAccumulator.held = false;
2138
2190
  }
2139
- // 8. Cleanup expired Sesame sessions
2191
+ // 7. Cleanup expired Sesame sessions
2140
2192
  try {
2141
2193
  await this.sesameManager.cleanupExpiredSessions();
2142
2194
  }
@@ -2146,7 +2198,7 @@ export class DefaultSignalProtocolClient {
2146
2198
  data: { error: error.message },
2147
2199
  });
2148
2200
  }
2149
- // 9. Cleanup expired message records (SESAME spec §6.2)
2201
+ // 8. Cleanup expired message records (SESAME spec §6.2)
2150
2202
  try {
2151
2203
  const deleted = await this._storage.deleteExpiredMessageRecords(MESSAGE_RECORD_TTL_MS);
2152
2204
  if (deleted > 0) {
@@ -2205,30 +2257,6 @@ export class DefaultSignalProtocolClient {
2205
2257
  });
2206
2258
  return cleaned;
2207
2259
  }
2208
- /**
2209
- * Run periodic cleanup of internal tracking state.
2210
- *
2211
- * Safe to call frequently - internally throttled to avoid overhead.
2212
- * Recommended call sites:
2213
- * - App foreground transition
2214
- * - After successful message batch processing
2215
- * - Periodically during long sessions
2216
- *
2217
- * Cleans up:
2218
- * - Expired retry dedup entries (recentRetryRequests)
2219
- *
2220
- * @returns Number of entries cleaned up
2221
- */
2222
- runPeriodicCleanup() {
2223
- const result = this.state.runPeriodicCleanup();
2224
- if (result.cleaned > 0) {
2225
- this.logger.debug('Periodic cleanup completed', {
2226
- category: 'E2EE',
2227
- data: { cleaned: result.cleaned },
2228
- });
2229
- }
2230
- return result.cleaned;
2231
- }
2232
2260
  // ============================================================================
2233
2261
  // KEY ROTATION (delegated to key-rotation.ts)
2234
2262
  // ============================================================================