@open-e2ee/signal-protocol-sdk 13.5.1 → 14.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 (145) hide show
  1. package/CHANGELOG.md +329 -0
  2. package/README.md +2 -2
  3. package/SECURITY.md +2 -2
  4. package/device/README.md +4 -3
  5. package/dist/client/client.d.ts +20 -55
  6. package/dist/client/client.d.ts.map +1 -1
  7. package/dist/client/client.js +133 -165
  8. package/dist/client/client.js.map +1 -1
  9. package/dist/client/content-adapter.d.ts +35 -6
  10. package/dist/client/content-adapter.d.ts.map +1 -1
  11. package/dist/client/content-adapter.js +28 -0
  12. package/dist/client/content-adapter.js.map +1 -1
  13. package/dist/client/event-hooks.d.ts +22 -11
  14. package/dist/client/event-hooks.d.ts.map +1 -1
  15. package/dist/client/event-hooks.js.map +1 -1
  16. package/dist/client/group-fetcher.d.ts.map +1 -1
  17. package/dist/client/group-fetcher.js +43 -0
  18. package/dist/client/group-fetcher.js.map +1 -1
  19. package/dist/client/group-key-sync.d.ts +65 -0
  20. package/dist/client/group-key-sync.d.ts.map +1 -0
  21. package/dist/client/group-key-sync.js +286 -0
  22. package/dist/client/group-key-sync.js.map +1 -0
  23. package/dist/client/group-outbox.d.ts +20 -6
  24. package/dist/client/group-outbox.d.ts.map +1 -1
  25. package/dist/client/group-outbox.js +153 -80
  26. package/dist/client/group-outbox.js.map +1 -1
  27. package/dist/client/group-receive-authorization.d.ts +16 -9
  28. package/dist/client/group-receive-authorization.d.ts.map +1 -1
  29. package/dist/client/group-receive-authorization.js +25 -16
  30. package/dist/client/group-receive-authorization.js.map +1 -1
  31. package/dist/client/hosted.d.ts +7 -7
  32. package/dist/client/hosted.js +7 -7
  33. package/dist/client/index.d.ts +1 -1
  34. package/dist/client/index.d.ts.map +1 -1
  35. package/dist/client/index.js.map +1 -1
  36. package/dist/client/receive-queue.d.ts +3 -4
  37. package/dist/client/receive-queue.d.ts.map +1 -1
  38. package/dist/client/receive-queue.js +24 -32
  39. package/dist/client/receive-queue.js.map +1 -1
  40. package/dist/client/relay-subscription.d.ts.map +1 -1
  41. package/dist/client/relay-subscription.js +4 -9
  42. package/dist/client/relay-subscription.js.map +1 -1
  43. package/dist/client/retry-request-envelope.d.ts +4 -2
  44. package/dist/client/retry-request-envelope.d.ts.map +1 -1
  45. package/dist/client/retry-request-envelope.js +6 -4
  46. package/dist/client/retry-request-envelope.js.map +1 -1
  47. package/dist/client/retry-request-lifecycle.d.ts +7 -8
  48. package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
  49. package/dist/client/retry-request-lifecycle.js +10 -7
  50. package/dist/client/retry-request-lifecycle.js.map +1 -1
  51. package/dist/client/retry-terminal-recovery.d.ts +14 -15
  52. package/dist/client/retry-terminal-recovery.d.ts.map +1 -1
  53. package/dist/client/retry-terminal-recovery.js +16 -17
  54. package/dist/client/retry-terminal-recovery.js.map +1 -1
  55. package/dist/client/retry-utils.d.ts +22 -0
  56. package/dist/client/retry-utils.d.ts.map +1 -1
  57. package/dist/client/retry-utils.js +30 -0
  58. package/dist/client/retry-utils.js.map +1 -1
  59. package/dist/client/send-deadline.js +1 -1
  60. package/dist/client/send-deadline.js.map +1 -1
  61. package/dist/client/send-timestamp.d.ts +71 -14
  62. package/dist/client/send-timestamp.d.ts.map +1 -1
  63. package/dist/client/send-timestamp.js +87 -19
  64. package/dist/client/send-timestamp.js.map +1 -1
  65. package/dist/client/signal-service-cipher.d.ts +125 -13
  66. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  67. package/dist/client/signal-service-cipher.js +413 -102
  68. package/dist/client/signal-service-cipher.js.map +1 -1
  69. package/dist/client/types.d.ts +21 -16
  70. package/dist/client/types.d.ts.map +1 -1
  71. package/dist/client/types.js.map +1 -1
  72. package/dist/index.d.ts +1 -1
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js.map +1 -1
  75. package/dist/internal/groups/key-sync-ledger.d.ts +65 -0
  76. package/dist/internal/groups/key-sync-ledger.d.ts.map +1 -0
  77. package/dist/internal/groups/key-sync-ledger.js +104 -0
  78. package/dist/internal/groups/key-sync-ledger.js.map +1 -0
  79. package/dist/internal/groups/receive-record.d.ts +4 -1
  80. package/dist/internal/groups/receive-record.d.ts.map +1 -1
  81. package/dist/internal/groups/receive-record.js.map +1 -1
  82. package/dist/internal/session/cipher.d.ts.map +1 -1
  83. package/dist/internal/session/cipher.js +14 -0
  84. package/dist/internal/session/cipher.js.map +1 -1
  85. package/dist/local/store/conformance/cases/durability.d.ts.map +1 -1
  86. package/dist/local/store/conformance/cases/durability.js +6 -0
  87. package/dist/local/store/conformance/cases/durability.js.map +1 -1
  88. package/dist/local/store/conformance/records.d.ts.map +1 -1
  89. package/dist/local/store/conformance/records.js +3 -0
  90. package/dist/local/store/conformance/records.js.map +1 -1
  91. package/dist/local/store/expo/adapter.js +2 -2
  92. package/dist/local/store/expo/adapter.js.map +1 -1
  93. package/dist/local/store/key-value/adapter.d.ts +6 -5
  94. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  95. package/dist/local/store/key-value/adapter.js +21 -19
  96. package/dist/local/store/key-value/adapter.js.map +1 -1
  97. package/dist/local/store/key-value/receive-work.d.ts +0 -5
  98. package/dist/local/store/key-value/receive-work.d.ts.map +1 -1
  99. package/dist/local/store/key-value/receive-work.js +0 -16
  100. package/dist/local/store/key-value/receive-work.js.map +1 -1
  101. package/dist/local/store/node/adapter.js +2 -2
  102. package/dist/local/store/node/adapter.js.map +1 -1
  103. package/dist/local/store/react-native/adapter.js +2 -2
  104. package/dist/local/store/react-native/adapter.js.map +1 -1
  105. package/dist/local/store/receive-work.d.ts +32 -32
  106. package/dist/local/store/receive-work.d.ts.map +1 -1
  107. package/dist/local/store/receive-work.js +112 -65
  108. package/dist/local/store/receive-work.js.map +1 -1
  109. package/dist/local/store/received-content.d.ts +0 -5
  110. package/dist/local/store/received-content.d.ts.map +1 -1
  111. package/dist/local/store/received-content.js +0 -17
  112. package/dist/local/store/received-content.js.map +1 -1
  113. package/dist/local/store/reliability.d.ts +191 -53
  114. package/dist/local/store/reliability.d.ts.map +1 -1
  115. package/dist/local/store/reliability.js +517 -37
  116. package/dist/local/store/reliability.js.map +1 -1
  117. package/dist/local/store/sqlite/key-storage/metadata.d.ts +1 -8
  118. package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
  119. package/dist/local/store/sqlite/key-storage/metadata.js +1 -18
  120. package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
  121. package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
  122. package/dist/local/store/sqlite/migrations.js +8 -0
  123. package/dist/local/store/sqlite/migrations.js.map +1 -1
  124. package/dist/local/store/sqlite/store.d.ts +5 -5
  125. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  126. package/dist/local/store/sqlite/store.js +29 -9
  127. package/dist/local/store/sqlite/store.js.map +1 -1
  128. package/dist/local/store/web/adapter.d.ts +11 -10
  129. package/dist/local/store/web/adapter.d.ts.map +1 -1
  130. package/dist/local/store/web/adapter.js +69 -51
  131. package/dist/local/store/web/adapter.js.map +1 -1
  132. package/dist/local/store/web-sqlite/adapter.js +2 -2
  133. package/dist/local/store/web-sqlite/adapter.js.map +1 -1
  134. package/dist/types/api.d.ts +50 -71
  135. package/dist/types/api.d.ts.map +1 -1
  136. package/dist/types/errors.d.ts +52 -18
  137. package/dist/types/errors.d.ts.map +1 -1
  138. package/dist/types/errors.js +58 -17
  139. package/dist/types/errors.js.map +1 -1
  140. package/docs/ASSURANCE.md +5 -5
  141. package/docs/DEVIATIONS.md +126 -9
  142. package/docs/ERROR_HANDLING.md +38 -23
  143. package/docs/GETTING_STARTED.md +17 -0
  144. package/local/store/README.md +32 -8
  145. package/package.json +1 -1
@@ -23,15 +23,15 @@ import { isRemovedDevice, } from '../internal/sesame/types.js';
23
23
  import { defaultSignalProtocolLogger } from '../logger.js';
24
24
  import { SenderKeyHandoffLedger, } from '../internal/protocol/sender-keys/handoff-ledger.js';
25
25
  import { isGroupId, extractGroupId } from '../internal/groups/index.js';
26
- import { GroupReceiveRefusedError, GroupReceiveUnavailableError, refuseSyncFromOtherAccount, classifyGroupContent, groupOfContext, } from './group-receive-authorization.js';
27
- import { sizedReceiveWork } from '../local/store/receive-work.js';
26
+ import { GroupReceiveRefusedError, GroupReceiveUnavailableError, refuseSyncFromOtherAccount, classifyGroupContent, groupOfContext, isManagedGroupId, } from './group-receive-authorization.js';
28
27
  import { envelopeCiphertextBytes } from './delivery-error.js';
29
28
  import { GroupSenderKeyOperations } from './group-sender-key-operations.js';
30
- import { checkNewSendTimestamp, SEND_TIMESTAMP_ORIGIN, withCheckedSendTimestamp, } from './send-timestamp.js';
29
+ import { checkNewSendTimestamp, releaseNewSendTimestamp, releaseNewSendTimestampWithLock, reserveNewSendTimestamp, SEND_TIMESTAMP_ORIGIN, } from './send-timestamp.js';
31
30
  import { intentBinaryAttachment, SEND_BINARY_ATTACHMENT, } from './binary-send.js';
32
31
  import { ContentHint } from '../types/messages.js';
33
32
  import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
34
33
  import * as CryptoUtils from '../internal/crypto/index.js';
34
+ import { withAcceptedSyncDevices, } from '../internal/groups/key-sync-ledger.js';
35
35
  import { completeOutgoingMessageIntent, completeOutgoingSyncPhase, endOutgoingMessageIntent, getOutgoingMessageIntent, markOutgoingDeviceSetUnresolved, outgoingDestinationProgressKey, outgoingMessageDeadlineAt, outgoingMessageIntentResult, recordOutgoingDestinationProgress, repairOutgoingDeviceSet, getRetryResend, getSentClientMessageIds, reconcileOutgoingDirectDeviceMessages, reconcileOutgoingSyncMessages, replaceOutgoingDirectDeviceMessage, replaceOutgoingGroupPreMessages, retryAttemptClientMessageId, retryNullMessageClientMessageId, retryRequestAttempt, retryResendClientMessageId, storeOutgoingMessageIntent, storeRetryResend, withOutgoingMessageIntentLock, addOutgoingManualResend, endOutgoingManualResend, isOpenManualResend, manualResendMessageId, OUTGOING_POSTING_WINDOW_MS, outgoingManualResends, recordOutgoingManualResendProgress, RELIABILITY_RECORD_TTL_MS, } from '../local/store/reliability.js';
36
36
  import { FanOutError, firstItemError } from '../utils/bounded-fan-out.js';
37
37
  import { withRetry } from '../utils/retry.js';
@@ -227,6 +227,14 @@ function storedDeviceSetUnresolved(unresolved) {
227
227
  function declaredDeviceKey(device) {
228
228
  return `${device.userId}\u0000${String(device.deviceId)}`;
229
229
  }
230
+ /** The byte length of a group master key that a `GroupKeySync` applies. */
231
+ const GROUP_KEY_SYNC_MASTER_KEY_LENGTH = 32;
232
+ /** The own devices of accepted sync copies that name a registration. */
233
+ function acceptedSyncDevices(copies) {
234
+ return copies.flatMap((copy) => copy?.recipientRegistrationId !== undefined
235
+ ? [{ deviceId: copy.recipientDeviceId, registrationId: copy.recipientRegistrationId }]
236
+ : []);
237
+ }
230
238
  /**
231
239
  * The device IDs of a user record that are not marked removed. A removed
232
240
  * record gets no fan-out, so a declared send neither declares it nor counts
@@ -437,6 +445,8 @@ export class SignalProtocolServiceCipher {
437
445
  sealedSenderDeliveryMode = 'preferred';
438
446
  sealedSenderIdentifiedFallback;
439
447
  relayProtocolErrorReporter;
448
+ ownDevicesFirstSeen;
449
+ groupKeySyncReceiver;
440
450
  contactProfileStateStore;
441
451
  endorsementManager;
442
452
  endorsementManagerResolver;
@@ -487,12 +497,25 @@ export class SignalProtocolServiceCipher {
487
497
  }
488
498
  return CryptoUtils.bytesToBase64(plaintextBytes);
489
499
  }
490
- async uploadSyncMessages(syncMessages, payloadBytes, timestamp) {
500
+ /**
501
+ * Post sync copies to own devices, with no intent.
502
+ *
503
+ * @returns Each own device whose copy the relay accepted, with the
504
+ * registration that the accepted copy named. A copy that named no
505
+ * registration, or that left the send, gives no device.
506
+ * @throws The error of the first failed device. The `accepted` list of
507
+ * the target holds the devices whose copy the relay accepted before the
508
+ * failure.
509
+ */
510
+ async uploadSyncMessages(syncMessages, payloadBytes, timestamp, target) {
511
+ const stopSignal = target?.stopSignal;
491
512
  const relay = this.relay;
492
513
  if (!relay || syncMessages.length === 0) {
493
- return;
514
+ return [];
494
515
  }
495
516
  const prepared = await Promise.all(syncMessages.map((message) => this.prepareStoredSyncMessage(message)));
517
+ // The copy that a stale repair posts in place of the first copy.
518
+ const replacements = new Map();
496
519
  const repair = {
497
520
  sessions: this.sessionCallbacks,
498
521
  rebuild: async (deviceId) => {
@@ -501,10 +524,21 @@ export class SignalProtocolServiceCipher {
501
524
  includeSyncMessages: false,
502
525
  listedDeviceIds: [deviceId],
503
526
  });
504
- return message && this.prepareStoredSyncMessage(message);
527
+ const fresh = message && (await this.prepareStoredSyncMessage(message));
528
+ if (fresh)
529
+ replacements.set(deviceId, fresh);
530
+ return fresh;
505
531
  },
506
532
  };
507
- await this.sendPhase(prepared, (message) => this.postSyncMessage(relay, message, {}, repair), 'sync');
533
+ const posted = await this.sendPhase(prepared, async (message) => {
534
+ const control = stopSignal ? { stopSignal } : {};
535
+ if (!(await this.postSyncMessage(relay, message, control, repair)))
536
+ return undefined;
537
+ const copy = replacements.get(message.recipientDeviceId) ?? message;
538
+ target?.accepted?.push(...acceptedSyncDevices([copy]));
539
+ return copy;
540
+ }, 'sync', stopSignal);
541
+ return acceptedSyncDevices(posted);
508
542
  }
509
543
  /** A stored sync copy that names the registration of the own device's current session. */
510
544
  async prepareStoredSyncMessage(message, clientMessageId) {
@@ -539,7 +573,9 @@ export class SignalProtocolServiceCipher {
539
573
  * uses the `beforeRequest` of `control`.
540
574
  *
541
575
  * @returns The relay receipt of the copy or of its repaired copy, or
542
- * undefined when the copy left the intent
576
+ * undefined when the copy left the intent. A copy leaves the intent when
577
+ * the relay refuses its repaired copy too, or when the send has no
578
+ * transcript to repair it with.
543
579
  * @throws {EncryptionError} SESSION_ESTABLISHMENT_FAILED when the refresh
544
580
  * fails or the rebuild gives the device no copy. The copy stays in the
545
581
  * intent, so a replay posts it again.
@@ -558,6 +594,8 @@ export class SignalProtocolServiceCipher {
558
594
  const replacement = sessions
559
595
  ? await this.inRepairTurn(message.recipientUserId, () => this.repairRefusedSyncCopyInTurn(message, repair, sessions))
560
596
  : undefined;
597
+ if (replacement === 'no-transcript')
598
+ return undefined;
561
599
  if (replacement) {
562
600
  try {
563
601
  return await this.postSyncCopy(relay, replacement, controlOf(replacement));
@@ -582,8 +620,11 @@ export class SignalProtocolServiceCipher {
582
620
  /**
583
621
  * Refresh the session of an own device that refused a sync copy as stale,
584
622
  * encrypt the transcript again for the device, and replace the stored copy
585
- * before its post. The refused ciphertext is never posted again.
623
+ * before its post. The refused ciphertext is never posted again. When the
624
+ * send has no transcript, the stored copy leaves the intent and the
625
+ * refreshed session stays.
586
626
  *
627
+ * @returns The new copy, or `no-transcript` when the copy left the intent
587
628
  * @throws {EncryptionError} SESSION_ESTABLISHMENT_FAILED when the refresh
588
629
  * fails or the rebuild gives the device no copy. The stored copy stays,
589
630
  * and the refreshed session is not archived.
@@ -594,6 +635,13 @@ export class SignalProtocolServiceCipher {
594
635
  throw new EncryptionError('Failed to refresh a rejected own device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: refused.recipientUserId });
595
636
  }
596
637
  const fresh = await repair.rebuild(refused.recipientDeviceId);
638
+ if (fresh === 'no-transcript') {
639
+ if (repair.intentId !== undefined) {
640
+ const removed = [refused.recipientDeviceId];
641
+ await reconcileOutgoingSyncMessages(this.storage, repair.intentId, removed, []);
642
+ }
643
+ return fresh;
644
+ }
597
645
  if (!fresh) {
598
646
  throw new EncryptionError('Failed to encrypt a sync copy again for a refreshed own device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: refused.recipientUserId });
599
647
  }
@@ -696,21 +744,69 @@ export class SignalProtocolServiceCipher {
696
744
  * epoch of the sync. A caller that passes an application-supplied time
697
745
  * checks it first, as a new send checks its timestamp.
698
746
  */
699
- async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp) {
747
+ async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp, target) {
700
748
  if (!this.relay) {
701
- return;
749
+ return [];
702
750
  }
703
751
  if (this.declaresDeviceSets()) {
704
- await this.sendDeclaredSyncPayload(payloadBytes, timestamp);
705
- return;
752
+ return this.sendDeclaredSyncPayload(payloadBytes, timestamp, target);
706
753
  }
707
- const listed = await this.readOwnDeviceList(this.sessionCallbacks, undefined);
754
+ const listed = await this.readOwnDeviceList(this.sessionCallbacks, target?.stopSignal);
708
755
  const syncMessages = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
709
756
  clientTimestamp: timestamp,
710
757
  includeSyncMessages: false,
711
- listedDeviceIds: listed.map((device) => device.deviceId),
758
+ listedDeviceIds: listed
759
+ .map((device) => device.deviceId)
760
+ .filter((deviceId) => target?.deviceIds?.includes(deviceId) ?? true),
712
761
  });
713
- await this.uploadSyncMessages(syncMessages, payloadBytes, timestamp);
762
+ return this.uploadSyncMessages(syncMessages, payloadBytes, timestamp, target);
763
+ }
764
+ /**
765
+ * The other own devices that have a local device record not marked
766
+ * removed, each with the registration of its current session when the
767
+ * session names one.
768
+ */
769
+ async localOwnSyncDevices() {
770
+ const devices = [];
771
+ for (const { deviceId } of await this.localOwnDevices()) {
772
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(this.userId, deviceId);
773
+ devices.push({ deviceId, ...(registrationId !== undefined && { registrationId }) });
774
+ }
775
+ return devices;
776
+ }
777
+ /**
778
+ * Post the key of one managed group to the other own devices, through
779
+ * the identified sync copy path. On a relay that compares device sets, a
780
+ * send to every own device reads the own list once when this device holds
781
+ * no own device record, because a sync post alone never learns of an own
782
+ * device.
783
+ *
784
+ * @param input - The group master key and the revision at the send
785
+ * @param deviceIds - The own devices to post to. Without it, the send
786
+ * posts to each own device.
787
+ * @param stopSignal - The stop signal of the send. No post or wait starts
788
+ * after it aborts.
789
+ * @returns Each own device whose copy the relay accepted, with the
790
+ * registration that the accepted copy named
791
+ * @throws When the send fails or stops. Each error of the send, also one
792
+ * from before the first post, carries the devices whose copy the relay
793
+ * accepted before the failure, which `syncDevicesAcceptedBefore` reads.
794
+ */
795
+ async sendGroupKeySyncToLocalOtherDevices(input, deviceIds, stopSignal) {
796
+ const accepted = [];
797
+ try {
798
+ const timestamp = Date.now();
799
+ const payloadBytes = this.getResolvedContentAdapter().serializeGroupKeySync(input);
800
+ return await this.sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp, {
801
+ ...(deviceIds && { deviceIds }),
802
+ readOwnListWithoutRecord: deviceIds === undefined,
803
+ ...(stopSignal && { stopSignal }),
804
+ accepted,
805
+ });
806
+ }
807
+ catch (error) {
808
+ throw withAcceptedSyncDevices(error, accepted);
809
+ }
714
810
  }
715
811
  async sendReadSyncToLocalOtherDevices(entries) {
716
812
  if (entries.length === 0) {
@@ -793,6 +889,17 @@ export class SignalProtocolServiceCipher {
793
889
  setRelayProtocolErrorReporter(report) {
794
890
  this.relayProtocolErrorReporter = report;
795
891
  }
892
+ /**
893
+ * Set the listener of own devices that this device sees for the first
894
+ * time: a listed own device that gets its first device record from an own
895
+ * device list read, or an own device that a declared-phase repair starts a
896
+ * session with as a missing device. The listener runs after the read or
897
+ * the repair, and must not send in the turn of the send that saw the
898
+ * device. Called by SignalProtocolClient after construction.
899
+ */
900
+ setOwnDevicesFirstSeenListener(listener) {
901
+ this.ownDevicesFirstSeen = listener;
902
+ }
796
903
  async reportIdentifiedFallback(recipientUserId) {
797
904
  try {
798
905
  await this.sealedSenderIdentifiedFallback?.({
@@ -913,13 +1020,38 @@ export class SignalProtocolServiceCipher {
913
1020
  setGroupContextProvider(provider) {
914
1021
  this.groupContextProvider = provider;
915
1022
  }
916
- /** The content of a new group send, with the context of a managed group in it. */
1023
+ /**
1024
+ * The content of a new group send, with the context of a managed group in it.
1025
+ *
1026
+ * @throws EncryptionError `GROUP_MASTER_KEY_MISSING` when the group is a
1027
+ * managed group and the provider has no master key for it. Receivers
1028
+ * deny managed group content with no context, so the send posts nothing.
1029
+ */
917
1030
  async contentWithGroupContext(groupId, plaintextBytes) {
918
- const context = await this.groupContextProvider?.(groupId);
1031
+ const context = await this.groupSendContext(groupId);
919
1032
  return context
920
1033
  ? this.getResolvedContentAdapter().serializeContentWithGroupContext(plaintextBytes, context)
921
1034
  : plaintextBytes;
922
1035
  }
1036
+ /**
1037
+ * The group context that a new send to a group carries. Undefined when the
1038
+ * client has no group context provider, or when the group is an ad hoc
1039
+ * group with no master key.
1040
+ *
1041
+ * @throws EncryptionError `GROUP_MASTER_KEY_MISSING` when the group is a
1042
+ * managed group and the provider has no master key for it
1043
+ */
1044
+ async groupSendContext(groupId) {
1045
+ if (!this.groupContextProvider)
1046
+ return undefined;
1047
+ const context = await this.groupContextProvider(groupId);
1048
+ if (context)
1049
+ return context;
1050
+ if (isManagedGroupId(groupId)) {
1051
+ throw new EncryptionError('No group master key is stored for this managed group', EncryptionErrorCode.GROUP_MASTER_KEY_MISSING, { groupId });
1052
+ }
1053
+ return undefined;
1054
+ }
923
1055
  // ============================================================================
924
1056
  // Public API
925
1057
  // ============================================================================
@@ -930,6 +1062,62 @@ export class SignalProtocolServiceCipher {
930
1062
  setGroupReceiveEvaluator(evaluate) {
931
1063
  this.groupReceiveEvaluator = evaluate;
932
1064
  }
1065
+ /**
1066
+ * Apply the group master key of a `GroupKeySync` from an own device. The
1067
+ * receiver gets the sending own device with the registration of its
1068
+ * session, when the session names one. Without a receiver, a
1069
+ * `GroupKeySync` is consumed and writes nothing: a device without
1070
+ * `config.groups` drops the sync, the sender does not send it again, and
1071
+ * that device gets the key only from group traffic.
1072
+ */
1073
+ setGroupKeySyncReceiver(receive) {
1074
+ this.groupKeySyncReceiver = receive;
1075
+ }
1076
+ /**
1077
+ * Consume committed content that carries a `GroupKeySync`.
1078
+ * `processIncomingEnvelope`, the Relay subscription and the receive queue
1079
+ * call this method, so they never give that content to the application.
1080
+ * `decryptEnvelope` and the raw decrypt methods `receive`,
1081
+ * `decryptMessage` and `decryptMessages` do not call it. They return the
1082
+ * sync unapplied, master key included. The commit and `restoreCommitted`
1083
+ * already refused a sync from another account, so the content comes from
1084
+ * an own device.
1085
+ *
1086
+ * The receiver gets only a 32-byte master key and a non-negative safe
1087
+ * integer revision, as a group context must carry. A custom content
1088
+ * adapter can give other values. Such a sync is consumed, writes nothing,
1089
+ * and logs a warning.
1090
+ *
1091
+ * @returns True when the content is a `GroupKeySync`, which the caller
1092
+ * then completes with no delivery. False for other content.
1093
+ */
1094
+ async consumeGroupKeySync(content) {
1095
+ const sync = content.inspected.sync;
1096
+ if (sync?.type !== 'groupKeySync')
1097
+ return false;
1098
+ const key = sync.groupKey;
1099
+ if (!key || !this.groupKeySyncReceiver)
1100
+ return true;
1101
+ if (!(key.masterKey instanceof Uint8Array) ||
1102
+ key.masterKey.length !== GROUP_KEY_SYNC_MASTER_KEY_LENGTH ||
1103
+ !Number.isSafeInteger(key.revision) ||
1104
+ key.revision < 0) {
1105
+ this.logger.warn('A group key sync carried a malformed group key', {
1106
+ category: 'E2EE',
1107
+ data: {
1108
+ behavior: 'GROUP_KEY_SYNC_MALFORMED',
1109
+ senderDeviceId: content.senderDeviceId,
1110
+ },
1111
+ });
1112
+ return true;
1113
+ }
1114
+ const registrationId = await this.sesameManager.getRemoteRegistrationId(content.senderUserId, content.senderDeviceId);
1115
+ await this.groupKeySyncReceiver(key, {
1116
+ deviceId: content.senderDeviceId,
1117
+ ...(registrationId !== undefined && { registrationId }),
1118
+ });
1119
+ return true;
1120
+ }
933
1121
  /**
934
1122
  * Decrypt incoming envelope - routes to appropriate cipher
935
1123
  *
@@ -1046,9 +1234,6 @@ export class SignalProtocolServiceCipher {
1046
1234
  existing.groupId ??
1047
1235
  (await this.resolveFramedGroup(envelope, envelopeCiphertextBytes(envelope.ciphertext)));
1048
1236
  }
1049
- if (existing.awaitingEnvelope && seed) {
1050
- record = await this.fillAwaitingEnvelope(existing, seed, transportGroupId);
1051
- }
1052
1237
  }
1053
1238
  else {
1054
1239
  // Route on the envelope type. `sender_key` says "decrypt this as a
@@ -1148,31 +1333,6 @@ export class SignalProtocolServiceCipher {
1148
1333
  // Reconstruct envelope with revealed sender identity
1149
1334
  return reconstructEnvelope(envelope, unsealed);
1150
1335
  }
1151
- /**
1152
- * Fill the sender fields of a converted legacy record from its
1153
- * redelivered envelope. The record keeps its age and its arrival order.
1154
- */
1155
- async fillAwaitingEnvelope(existing, seed, groupId) {
1156
- const seeded = seed({
1157
- plaintext: existing.plaintext,
1158
- ...(groupId !== null && { groupId }),
1159
- });
1160
- const filled = sizedReceiveWork({
1161
- ...seeded,
1162
- workId: existing.workId,
1163
- revision: existing.revision + 1,
1164
- stage: existing.stage,
1165
- arrivalSeq: existing.arrivalSeq,
1166
- receivedAt: existing.receivedAt,
1167
- dueAt: existing.dueAt,
1168
- plaintext: existing.plaintext,
1169
- ...(existing.groupId !== undefined && { groupId: existing.groupId }),
1170
- ...(existing.blockedOn !== undefined && { blockedOn: existing.blockedOn }),
1171
- });
1172
- if (await this.storage.putReceiveWork(filled, existing.revision))
1173
- return filled;
1174
- return (await this.storage.getReceiveWork(existing.workId)) ?? existing;
1175
- }
1176
1336
  /**
1177
1337
  * The checks of committed content that run before its distribution
1178
1338
  * installs: the replay check, sync content from another account, and a
@@ -1220,8 +1380,7 @@ export class SignalProtocolServiceCipher {
1220
1380
  * Test: "gives the content once, and the failed message is a duplicate
1221
1381
  * after a restart".
1222
1382
  *
1223
- * @param record - A record that holds plaintext and its sender. A
1224
- * converted legacy record waits for its envelope, and has no sender.
1383
+ * @param record - A record that holds plaintext and its sender.
1225
1384
  * @param stopSignal - Stops the wait for the sender key lock.
1226
1385
  * @returns `committed` with the content, or `denied` when a check fails
1227
1386
  */
@@ -1688,7 +1847,7 @@ export class SignalProtocolServiceCipher {
1688
1847
  }
1689
1848
  /**
1690
1849
  * Archive the session with one device, for the session reset of a retry
1691
- * request that ended as `expired-content` or `posting-deadline`.
1850
+ * request that ended as `posting-deadline`.
1692
1851
  *
1693
1852
  * The archive takes the decrypt lock of the device first, so each decrypt
1694
1853
  * from the device in progress ends before it, and a decrypt that starts
@@ -1980,6 +2139,9 @@ export class SignalProtocolServiceCipher {
1980
2139
  return [];
1981
2140
  const listed = await this.fanOut.request(() => relay.getActiveDevices(this.userId), stopSignal);
1982
2141
  const others = listed.filter((device) => device.userId === this.userId && device.deviceId !== this.deviceId);
2142
+ const recorded = this.ownDevicesFirstSeen
2143
+ ? new Set(unremovedDeviceIds(await this.sesameManager.getUserRecord(this.userId)))
2144
+ : undefined;
1983
2145
  if (others.length > 0 && sessions) {
1984
2146
  try {
1985
2147
  // A device that fails gets no copy from this send.
@@ -1996,6 +2158,16 @@ export class SignalProtocolServiceCipher {
1996
2158
  const listedIds = new Set(others.map((device) => device.deviceId));
1997
2159
  listedIds.add(this.deviceId);
1998
2160
  await this.reconcileDeviceRecords(this.userId, listedIds);
2161
+ if (recorded) {
2162
+ // A listed device that got its first record from this read. A device
2163
+ // with no session gets no record, so a later read sees it again.
2164
+ const now = new Set(unremovedDeviceIds(await this.sesameManager.getUserRecord(this.userId)));
2165
+ const seen = others
2166
+ .map((device) => device.deviceId)
2167
+ .filter((deviceId) => !recorded.has(deviceId) && now.has(deviceId));
2168
+ if (seen.length > 0)
2169
+ this.ownDevicesFirstSeen?.(seen);
2170
+ }
1999
2171
  return others;
2000
2172
  }
2001
2173
  /**
@@ -2054,10 +2226,43 @@ export class SignalProtocolServiceCipher {
2054
2226
  const reconciled = await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions);
2055
2227
  return this.sendStoredDirectIntent(await this.reconcileDirectSyncDevices(reconciled, plaintextBytes, sessions, stopSignal), plaintextBytes, sessions, stopSignal, replay);
2056
2228
  }
2057
- // A new send checks the timestamp before the session setup, which can
2058
- // post to the Relay. The replays above keep the stored timestamp.
2059
- checkNewSendTimestamp(options);
2060
- const sendFirst = await this.ensureSessionsForUser(recipientUserId, sessions, true);
2229
+ // A new send checks and reserves the timestamp before the session setup,
2230
+ // which can post to the Relay. The replays above keep the stored
2231
+ // timestamp. A failure before the intent write removes the reservation.
2232
+ const reservation = await reserveNewSendTimestamp(this.storage, options);
2233
+ let stored;
2234
+ try {
2235
+ stored = await this.storeNewDirectIntent(recipientUserId, plaintextBytes, plaintextDigest, reservation.timestamp, options, sessions, stopSignal);
2236
+ }
2237
+ catch (error) {
2238
+ // A failed release does not replace the error of the send.
2239
+ try {
2240
+ await releaseNewSendTimestamp(this.storage, reservation);
2241
+ }
2242
+ catch (releaseError) {
2243
+ this.warnReleaseFailure(reservation, releaseError);
2244
+ }
2245
+ throw error;
2246
+ }
2247
+ const { intent, declared, sendFirst } = stored;
2248
+ const evidence = this.sendCallEvidence(intent);
2249
+ if (declared) {
2250
+ return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
2251
+ }
2252
+ if (sendFirst && sessions) {
2253
+ return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal, evidence);
2254
+ }
2255
+ return this.sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
2256
+ }
2257
+ /**
2258
+ * Prepare and store a new direct intent with its reserved client
2259
+ * timestamp. The session setup can post to the Relay.
2260
+ */
2261
+ async storeNewDirectIntent(recipientUserId, plaintextBytes, plaintextDigest, clientTimestamp, options, sessions, stopSignal) {
2262
+ // A note to self has no recipient post to send before the list read,
2263
+ // and the read of a later pass would address the own devices again.
2264
+ const ownAccount = recipientUserId === this.userId;
2265
+ const sendFirst = await this.ensureSessionsForUser(recipientUserId, sessions, !ownAccount);
2061
2266
  const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
2062
2267
  const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
2063
2268
  const transportMode = directSealedSender
@@ -2069,7 +2274,6 @@ export class SignalProtocolServiceCipher {
2069
2274
  throw new Error('Direct sealed-sender delivery requires access-key authorization');
2070
2275
  }
2071
2276
  const sealedSenderAuth = directSealedSender?.auth.type === 'accessKey' ? { ...directSealedSender.auth } : undefined;
2072
- const clientTimestamp = options.timestamp ?? Date.now();
2073
2277
  const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
2074
2278
  const declared = this.declaresDeviceSets();
2075
2279
  const ownDevices = declared
@@ -2077,10 +2281,22 @@ export class SignalProtocolServiceCipher {
2077
2281
  : await this.readOwnDeviceList(sessions, stopSignal);
2078
2282
  let batch;
2079
2283
  try {
2080
- batch = await this.sesameManager.send(recipientUserId, plaintextBytes, {
2081
- clientTimestamp,
2082
- includeSyncMessages: false,
2083
- });
2284
+ // A note to self posts only the sent transcript to the other own
2285
+ // devices. This matches the Signal sync transcript contract. With no
2286
+ // other own device, the batch is empty and the send posts nothing.
2287
+ batch = ownAccount
2288
+ ? {
2289
+ deviceMessages: [],
2290
+ syncMessages: [],
2291
+ recipientUserId,
2292
+ timestamp: clientTimestamp,
2293
+ attemptedDevices: 0,
2294
+ failedDevices: 0,
2295
+ }
2296
+ : await this.sesameManager.send(recipientUserId, plaintextBytes, {
2297
+ clientTimestamp,
2298
+ includeSyncMessages: false,
2299
+ });
2084
2300
  batch.syncMessages.push(...(await this.sesameManager.sendToLocalOtherDevices(syncPlaintext, {
2085
2301
  clientTimestamp,
2086
2302
  includeSyncMessages: false,
@@ -2129,15 +2345,8 @@ export class SignalProtocolServiceCipher {
2129
2345
  progressFromStart: true,
2130
2346
  ...(options[SEND_END_REPORT]?.internal && { internal: true }),
2131
2347
  };
2132
- const evidence = this.sendCallEvidence(intent);
2133
2348
  await storeOutgoingMessageIntent(this.storage, intent);
2134
- if (declared) {
2135
- return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
2136
- }
2137
- if (sendFirst && sessions) {
2138
- return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal, evidence);
2139
- }
2140
- return this.sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
2349
+ return { intent, declared, sendFirst };
2141
2350
  }
2142
2351
  /**
2143
2352
  * The evidence of one `send()` call of a direct or group intent. It starts
@@ -2462,7 +2671,7 @@ export class SignalProtocolServiceCipher {
2462
2671
  if (report)
2463
2672
  report.ended = { intent, resend: ended };
2464
2673
  if (ended.result)
2465
- return { ...ended.result };
2674
+ return { ...ended.result, clientTimestamp: intent.clientTimestamp };
2466
2675
  throw storedSendEndError(manualResendIntent(intent, ended));
2467
2676
  }
2468
2677
  return this.postManualResend(intent, resend, stopSignal, report);
@@ -2579,7 +2788,7 @@ export class SignalProtocolServiceCipher {
2579
2788
  const ended = await endOutgoingManualResend(this.storage, clientMessageId, manualMessageId, { result });
2580
2789
  if (ended && report)
2581
2790
  report.ended = { intent, resend: ended };
2582
- return result;
2791
+ return { ...result, clientTimestamp: intent.clientTimestamp };
2583
2792
  }
2584
2793
  /**
2585
2794
  * End a manual resend that is due after a failed post (contract §3.4), and
@@ -2924,7 +3133,7 @@ export class SignalProtocolServiceCipher {
2924
3133
  recipientDeviceCount: intent.deviceMessages.length,
2925
3134
  };
2926
3135
  await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
2927
- return result;
3136
+ return { ...result, clientTimestamp: intent.clientTimestamp };
2928
3137
  }
2929
3138
  const relay = this.relay;
2930
3139
  const control = this.postingControl(evidence, { ...(stopSignal && { stopSignal }) });
@@ -2981,7 +3190,8 @@ export class SignalProtocolServiceCipher {
2981
3190
  await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result, {
2982
3191
  syncPending,
2983
3192
  });
2984
- return syncPending ? { ...result, syncPending: true } : result;
3193
+ const returned = { ...result, clientTimestamp: intent.clientTimestamp };
3194
+ return syncPending ? { ...returned, syncPending: true } : returned;
2985
3195
  }
2986
3196
  /** True when the relay compares declared device sets, so each send declares them. */
2987
3197
  declaresDeviceSets() {
@@ -3027,6 +3237,10 @@ export class SignalProtocolServiceCipher {
3027
3237
  const postable = (list) => list.filter((message) => message.recipientUserId !== this.userId || message.recipientDeviceId !== this.deviceId);
3028
3238
  let messages = postable(run.messages);
3029
3239
  let unposted = [...(run.bundleMissing ?? [])];
3240
+ // The devices that the phase has no transcript for. Each pass declares
3241
+ // them beside the posts of their account, so the relay accepts the
3242
+ // other copies of the account.
3243
+ const uncopied = new Map((run.uncopied ?? []).map((device) => [declaredDeviceKey(device), device]));
3030
3244
  // The accounts that the last pass refused here, because they had no post.
3031
3245
  let unpostedAccounts = new Set();
3032
3246
  const posts = await runDeviceSetPhase({
@@ -3040,6 +3254,8 @@ export class SignalProtocolServiceCipher {
3040
3254
  deviceIds.push(message.recipientDeviceId);
3041
3255
  declared.set(message.recipientUserId, deviceIds);
3042
3256
  }
3257
+ for (const device of uncopied.values())
3258
+ declared.get(device.userId)?.push(device.deviceId);
3043
3259
  for (const deviceIds of declared.values())
3044
3260
  deviceIds.sort((a, b) => a - b);
3045
3261
  // An account whose devices all lack a bundle has no post to refuse.
@@ -3087,6 +3303,7 @@ export class SignalProtocolServiceCipher {
3087
3303
  const removed = [];
3088
3304
  const added = [];
3089
3305
  const bundleMissing = [];
3306
+ const untranscribed = [];
3090
3307
  const posted = new Map(messages.map((message) => [
3091
3308
  declaredDeviceKey({
3092
3309
  userId: message.recipientUserId,
@@ -3107,7 +3324,10 @@ export class SignalProtocolServiceCipher {
3107
3324
  bundleMissing.push(...repaired.bundleMissing);
3108
3325
  for (const device of repaired.ready) {
3109
3326
  const message = await run.encrypt(device);
3110
- if (message) {
3327
+ if (message === 'no-transcript') {
3328
+ untranscribed.push(device);
3329
+ }
3330
+ else if (message) {
3111
3331
  added.push(message);
3112
3332
  }
3113
3333
  else {
@@ -3116,6 +3336,13 @@ export class SignalProtocolServiceCipher {
3116
3336
  }
3117
3337
  });
3118
3338
  }
3339
+ // A removed device leaves the declaration. A stale device that has
3340
+ // no transcript is removed, so its stored copy leaves the intent, and
3341
+ // it is declared again here.
3342
+ for (const device of removed)
3343
+ uncopied.delete(declaredDeviceKey(device));
3344
+ for (const device of untranscribed)
3345
+ uncopied.set(declaredDeviceKey(device), device);
3119
3346
  if (run.intentId !== undefined) {
3120
3347
  const intent = await repairOutgoingDeviceSet(this.storage, run.intentId, {
3121
3348
  phase: run.phase,
@@ -3204,12 +3431,16 @@ export class SignalProtocolServiceCipher {
3204
3431
  const removed = [];
3205
3432
  const ready = [];
3206
3433
  const bundleMissing = [];
3434
+ // The own devices that this repair sees for the first time.
3435
+ const firstSeen = [];
3207
3436
  /**
3208
3437
  * Start sessions with devices that have none. A missing bundle is not an
3209
3438
  * error. A started session clears the removed marker of its record, so
3210
3439
  * the next pass declares the device.
3440
+ *
3441
+ * @param unrecorded - True for devices that had no current record
3211
3442
  */
3212
- const establish = async (deviceIds) => {
3443
+ const establish = async (deviceIds, unrecorded) => {
3213
3444
  const result = await sessions.establishSessions(userId, deviceIds.map((deviceId) => ({ userId, deviceId })));
3214
3445
  const failure = result.failedDeviceErrors[0];
3215
3446
  if (failure)
@@ -3219,6 +3450,8 @@ export class SignalProtocolServiceCipher {
3219
3450
  if (established.has(deviceId)) {
3220
3451
  await this.sesameManager.relistDevice(userId, deviceId);
3221
3452
  ready.push({ userId, deviceId });
3453
+ if (unrecorded && userId === this.userId)
3454
+ firstSeen.push(deviceId);
3222
3455
  }
3223
3456
  else {
3224
3457
  bundleMissing.push({ userId, deviceId });
@@ -3259,11 +3492,11 @@ export class SignalProtocolServiceCipher {
3259
3492
  else {
3260
3493
  // The refresh archived the stale session or found none. A second
3261
3494
  // start tells a missing bundle from a session start that failed.
3262
- await establish([deviceId]);
3495
+ await establish([deviceId], false);
3263
3496
  }
3264
3497
  }
3265
3498
  if (repair.missingDeviceIds.length > 0)
3266
- await establish(repair.missingDeviceIds);
3499
+ await establish(repair.missingDeviceIds, true);
3267
3500
  if (options.unposted && bundleMissing.length > 0) {
3268
3501
  for (const device of bundleMissing.splice(0)) {
3269
3502
  await this.sesameManager.removeDevice(userId, device.deviceId);
@@ -3277,7 +3510,7 @@ export class SignalProtocolServiceCipher {
3277
3510
  const remainingIds = held.filter((id) => !handled.has(id));
3278
3511
  const relay = this.relay;
3279
3512
  if (remainingIds.length > 0) {
3280
- await establish(remainingIds);
3513
+ await establish(remainingIds, false);
3281
3514
  }
3282
3515
  else if (relay && held.length === 0) {
3283
3516
  const listed = await this.fanOut.request(() => relay.getActiveDevices(userId), options.stopSignal);
@@ -3285,9 +3518,11 @@ export class SignalProtocolServiceCipher {
3285
3518
  .filter((device) => device.userId === userId && !own(device.deviceId))
3286
3519
  .map((device) => device.deviceId);
3287
3520
  if (deviceIds.length > 0)
3288
- await establish(deviceIds);
3521
+ await establish(deviceIds, true);
3289
3522
  }
3290
3523
  }
3524
+ if (firstSeen.length > 0)
3525
+ this.ownDevicesFirstSeen?.(firstSeen);
3291
3526
  return { removed, ready, bundleMissing };
3292
3527
  }
3293
3528
  /**
@@ -3447,7 +3682,11 @@ export class SignalProtocolServiceCipher {
3447
3682
  ? await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal, evidence.check, evidence)
3448
3683
  : { synced: true, accepted: [] };
3449
3684
  const route = intent.transportMode === 'identified' ? 'identified-direct' : 'anonymous-direct';
3450
- return this.markUncheckedDeclaredPosts({ ...result, ...((!sync.synced || syncUnread) && { syncPending: true }) }, [
3685
+ return this.markUncheckedDeclaredPosts({
3686
+ ...result,
3687
+ clientTimestamp: intent.clientTimestamp,
3688
+ ...((!sync.synced || syncUnread) && { syncPending: true }),
3689
+ }, [
3451
3690
  ...accepted.map((acceptance) => [acceptance, route]),
3452
3691
  ...syncPostReceipts(sync.accepted),
3453
3692
  ], intent.clientMessageId);
@@ -3518,33 +3757,60 @@ export class SignalProtocolServiceCipher {
3518
3757
  * payload has no send result, so the reporter gives the protocol error of
3519
3758
  * an accepted post without the `deviceSetChecked` mark to the app.
3520
3759
  *
3521
- * @throws {DeviceSetReconciliationError} when the phase ends unresolved
3760
+ * A target with device IDs posts only to those devices, and each pass
3761
+ * declares the other own devices beside the posts. A target that reads
3762
+ * the own list without a record reads it once when this device holds no
3763
+ * own device record.
3764
+ *
3765
+ * @returns Each own device whose copy the relay accepted, with the
3766
+ * registration that the accepted copy named
3767
+ * @throws {DeviceSetReconciliationError} when the phase ends unresolved.
3768
+ * The `accepted` list of the target holds the devices whose copy the
3769
+ * relay accepted before the failure.
3522
3770
  */
3523
- async sendDeclaredSyncPayload(payloadBytes, timestamp) {
3771
+ async sendDeclaredSyncPayload(payloadBytes, timestamp, target) {
3524
3772
  const relay = this.relay;
3525
- const ownDevices = await this.localOwnDevices();
3526
- if (ownDevices.length === 0)
3527
- return;
3773
+ let ownDevices = await this.localOwnDevices();
3774
+ if (ownDevices.length === 0 && target?.readOwnListWithoutRecord) {
3775
+ await this.readOwnDeviceList(this.sessionCallbacks, target.stopSignal);
3776
+ ownDevices = await this.localOwnDevices();
3777
+ }
3778
+ const targeted = (deviceId) => target?.deviceIds?.includes(deviceId) ?? true;
3779
+ const targets = ownDevices.filter((device) => targeted(device.deviceId));
3780
+ if (targets.length === 0)
3781
+ return [];
3528
3782
  const copies = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
3529
3783
  clientTimestamp: timestamp,
3530
3784
  includeSyncMessages: false,
3531
- listedDeviceIds: ownDevices.map((device) => device.deviceId),
3785
+ listedDeviceIds: targets.map((device) => device.deviceId),
3532
3786
  });
3533
3787
  if (copies.length === 0)
3534
- return;
3788
+ return [];
3535
3789
  const operationId = await CryptoUtils.generateUuidV4();
3536
3790
  const prepare = (message) => this.prepareStoredSyncMessage(message, syncMessageId(operationId, message));
3537
3791
  const accepted = [];
3792
+ // The last accepted copy of each device.
3793
+ const delivered = new Map();
3538
3794
  try {
3539
3795
  await this.runDeclaredPhase({
3540
3796
  phase: 'sync',
3541
3797
  clientMessageId: operationId,
3542
3798
  restarts: 0,
3543
3799
  messages: await Promise.all(copies.map(prepare)),
3800
+ uncopied: ownDevices.filter((device) => !targeted(device.deviceId)),
3544
3801
  post: async (message, declaredDeviceIds) => {
3545
- accepted.push(await this.postSyncCopy(relay, message, { declaredDeviceIds }));
3802
+ const control = {
3803
+ declaredDeviceIds,
3804
+ ...(target?.stopSignal && { stopSignal: target.stopSignal }),
3805
+ };
3806
+ accepted.push(await this.postSyncCopy(relay, message, control));
3807
+ delivered.set(message.recipientDeviceId, message);
3808
+ target?.accepted?.push(...acceptedSyncDevices([message]));
3546
3809
  },
3547
3810
  encrypt: async (device) => {
3811
+ if (device.userId !== this.userId || !targeted(device.deviceId)) {
3812
+ return 'no-transcript';
3813
+ }
3548
3814
  const [message] = await this.sesameManager.sendToLocalOtherDevices(payloadBytes, {
3549
3815
  clientTimestamp: timestamp,
3550
3816
  includeSyncMessages: false,
@@ -3553,7 +3819,7 @@ export class SignalProtocolServiceCipher {
3553
3819
  return message && prepare(message);
3554
3820
  },
3555
3821
  sessions: this.sessionCallbacks,
3556
- stopSignal: undefined,
3822
+ stopSignal: target?.stopSignal,
3557
3823
  });
3558
3824
  }
3559
3825
  finally {
@@ -3563,6 +3829,7 @@ export class SignalProtocolServiceCipher {
3563
3829
  if (error)
3564
3830
  await this.relayProtocolErrorReporter?.(error);
3565
3831
  }
3832
+ return acceptedSyncDevices([...delivered.values()]);
3566
3833
  }
3567
3834
  async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal) {
3568
3835
  // The outbox binds the evidence of the call once it holds the stored
@@ -3585,6 +3852,9 @@ export class SignalProtocolServiceCipher {
3585
3852
  groupEvidence = this.sendCallEvidence(intent);
3586
3853
  },
3587
3854
  refreshEntry: (device, entry) => boundGroupEvidence().refreshEntry(device, entry),
3855
+ warn: (message, data) => {
3856
+ this.logger.warn(message, { category: 'E2EE', data });
3857
+ },
3588
3858
  endRecipientPhase: (intent, error) => this.endOrRethrow(intent, boundGroupEvidence(), error),
3589
3859
  storage: this.storage,
3590
3860
  ...(this.relay && { relay: this.relay }),
@@ -4768,6 +5038,7 @@ export class SignalProtocolServiceCipher {
4768
5038
  let message;
4769
5039
  let pointer;
4770
5040
  let sendOptions;
5041
+ let reservation;
4771
5042
  if (stored) {
4772
5043
  // A repeat sends the stored message under the stored timestamp, so the
4773
5044
  // locked send replays the stored intent and uploads nothing. Another
@@ -4789,32 +5060,62 @@ export class SignalProtocolServiceCipher {
4789
5060
  sendOptions = { ...options, timestamp: stored.clientTimestamp };
4790
5061
  }
4791
5062
  else {
4792
- // The upload posts the file, so a new send checks its timestamp first,
4793
- // once, against one clock reading. Without a caller timestamp, the SDK
4794
- // reads its clock once, before the upload, and the message and the
4795
- // intent take that timestamp. The timestamp mark stops the checks of
4796
- // the send after the upload, which would read a later clock. The
4797
- // attachment mark puts the message in the intent.
4798
- const checked = withCheckedSendTimestamp(options);
4799
- const timestamp = checked.timestamp ?? Date.now();
4800
- const uploaded = await this.prepareAttachmentUpload(data, checked);
4801
- message = serializeMediaAttachmentMessage({ attachment: uploaded, timestamp });
5063
+ // The upload posts the file, so a new send checks and reserves its
5064
+ // timestamp first, once, against one clock reading. Without a caller
5065
+ // timestamp, the SDK reads its clock once, before the upload, and the
5066
+ // message and the intent take the reserved timestamp. The timestamp
5067
+ // mark stops the checks of the send after the upload, which would read
5068
+ // a later clock, and the inner reservation of the send finds the entry
5069
+ // with its own ID. The attachment mark puts the message in the intent.
5070
+ // A send to a managed group with no master key throws before the
5071
+ // upload, so it uploads, stores and posts nothing.
5072
+ if (isGroupId(recipientId))
5073
+ await this.groupSendContext(extractGroupId(recipientId));
5074
+ reservation = await reserveNewSendTimestamp(this.storage, options);
5075
+ const timestamp = reservation.timestamp;
5076
+ const checked = { ...options, timestamp, [SEND_TIMESTAMP_ORIGIN]: 'checked' };
5077
+ try {
5078
+ const uploaded = await this.prepareAttachmentUpload(data, checked);
5079
+ message = serializeMediaAttachmentMessage({ attachment: uploaded, timestamp });
5080
+ }
5081
+ catch (error) {
5082
+ try {
5083
+ await releaseNewSendTimestampWithLock(this.storage, reservation);
5084
+ }
5085
+ catch (releaseError) {
5086
+ this.warnReleaseFailure(reservation, releaseError);
5087
+ }
5088
+ throw error;
5089
+ }
4802
5090
  // The pointer of the result comes from the message, as on a repeat.
4803
5091
  pointer = attachmentPointerOf(message);
4804
5092
  sendOptions = {
4805
5093
  ...checked,
4806
- timestamp,
4807
- [SEND_TIMESTAMP_ORIGIN]: checked[SEND_TIMESTAMP_ORIGIN] ?? 'sdk-clock',
4808
5094
  [SEND_BINARY_ATTACHMENT]: { fileDigest, message },
4809
5095
  };
4810
5096
  }
4811
5097
  const attachmentBytes = new TextEncoder().encode(message);
4812
5098
  let result;
4813
- if (isGroupId(recipientId)) {
4814
- result = await this.encryptToGroup(recipientId, attachmentBytes, sendOptions, sessions, stopSignal);
5099
+ try {
5100
+ if (isGroupId(recipientId)) {
5101
+ result = await this.encryptToGroup(recipientId, attachmentBytes, sendOptions, sessions, stopSignal);
5102
+ }
5103
+ else {
5104
+ result = await this.encryptToUser(recipientId, attachmentBytes, sendOptions, sessions);
5105
+ }
4815
5106
  }
4816
- else {
4817
- result = await this.encryptToUser(recipientId, attachmentBytes, sendOptions, sessions);
5107
+ catch (error) {
5108
+ // The inner send found the reservation with its own ID, so it does not
5109
+ // remove it. A failure before the intent write removes it here.
5110
+ if (reservation) {
5111
+ try {
5112
+ await releaseNewSendTimestampWithLock(this.storage, reservation);
5113
+ }
5114
+ catch (releaseError) {
5115
+ this.warnReleaseFailure(reservation, releaseError);
5116
+ }
5117
+ }
5118
+ throw error;
4818
5119
  }
4819
5120
  return {
4820
5121
  ...result,
@@ -4825,6 +5126,16 @@ export class SignalProtocolServiceCipher {
4825
5126
  contentType: pointer.contentType,
4826
5127
  };
4827
5128
  }
5129
+ /**
5130
+ * Log a failed release of a send timestamp reservation. The send then
5131
+ * throws its own error, not the release error.
5132
+ */
5133
+ warnReleaseFailure(reservation, error) {
5134
+ this.logger.warn('Failed to release the send timestamp reservation', {
5135
+ category: 'E2EE',
5136
+ data: { clientMessageId: reservation.clientMessageId, error: error.message },
5137
+ });
5138
+ }
4828
5139
  async prepareAttachmentUpload(data, options) {
4829
5140
  if (!this.remoteObjectStore) {
4830
5141
  throw new EncryptionError('Remote object storage not configured. Provide remoteObjectStore in DefaultSignalProtocolClient.create() config.', EncryptionErrorCode.INITIALIZATION_FAILED);