@open-e2ee/signal-protocol-sdk 8.1.0 → 8.2.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 (147) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/README.md +2 -2
  3. package/SECURITY.md +2 -2
  4. package/device/README.md +16 -7
  5. package/dist/client/client.d.ts +4 -2
  6. package/dist/client/client.d.ts.map +1 -1
  7. package/dist/client/client.js +23 -18
  8. package/dist/client/client.js.map +1 -1
  9. package/dist/client/group-outbox.d.ts +31 -1
  10. package/dist/client/group-outbox.d.ts.map +1 -1
  11. package/dist/client/group-outbox.js +67 -58
  12. package/dist/client/group-outbox.js.map +1 -1
  13. package/dist/client/hosted-anonymous-delivery.d.ts +9 -1
  14. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  15. package/dist/client/hosted-anonymous-delivery.js +61 -22
  16. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  17. package/dist/client/hosted-transport.d.ts +7 -0
  18. package/dist/client/hosted-transport.d.ts.map +1 -1
  19. package/dist/client/hosted-transport.js +44 -6
  20. package/dist/client/hosted-transport.js.map +1 -1
  21. package/dist/client/key-rotation.d.ts.map +1 -1
  22. package/dist/client/key-rotation.js +2 -4
  23. package/dist/client/key-rotation.js.map +1 -1
  24. package/dist/client/prekeys.d.ts.map +1 -1
  25. package/dist/client/prekeys.js +1 -1
  26. package/dist/client/prekeys.js.map +1 -1
  27. package/dist/client/relay-device-refusal.d.ts +32 -0
  28. package/dist/client/relay-device-refusal.d.ts.map +1 -0
  29. package/dist/client/relay-device-refusal.js +36 -0
  30. package/dist/client/relay-device-refusal.js.map +1 -0
  31. package/dist/client/relay-work.d.ts +26 -0
  32. package/dist/client/relay-work.d.ts.map +1 -1
  33. package/dist/client/relay-work.js +37 -0
  34. package/dist/client/relay-work.js.map +1 -1
  35. package/dist/client/sealed-sender.d.ts.map +1 -1
  36. package/dist/client/sealed-sender.js +12 -17
  37. package/dist/client/sealed-sender.js.map +1 -1
  38. package/dist/client/sessions.d.ts.map +1 -1
  39. package/dist/client/sessions.js +2 -4
  40. package/dist/client/sessions.js.map +1 -1
  41. package/dist/client/signal-service-cipher.d.ts +90 -4
  42. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  43. package/dist/client/signal-service-cipher.js +425 -136
  44. package/dist/client/signal-service-cipher.js.map +1 -1
  45. package/dist/client/types.d.ts +7 -0
  46. package/dist/client/types.d.ts.map +1 -1
  47. package/dist/client/types.js.map +1 -1
  48. package/dist/internal/manager/manager.d.ts +8 -7
  49. package/dist/internal/manager/manager.d.ts.map +1 -1
  50. package/dist/internal/manager/manager.js +34 -36
  51. package/dist/internal/manager/manager.js.map +1 -1
  52. package/dist/internal/protocol/spqr/index.d.ts +1 -1
  53. package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
  54. package/dist/internal/protocol/spqr/index.js +2 -2
  55. package/dist/internal/protocol/spqr/index.js.map +1 -1
  56. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.d.ts.map +1 -1
  57. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js +1 -3
  58. package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js.map +1 -1
  59. package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
  60. package/dist/internal/protocol/spqr/serialize.js +1 -4
  61. package/dist/internal/protocol/spqr/serialize.js.map +1 -1
  62. package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
  63. package/dist/internal/protocol/spqr/spqr.js +1 -2
  64. package/dist/internal/protocol/spqr/spqr.js.map +1 -1
  65. package/dist/internal/sesame/device-registry.d.ts +24 -4
  66. package/dist/internal/sesame/device-registry.d.ts.map +1 -1
  67. package/dist/internal/sesame/device-registry.js +55 -28
  68. package/dist/internal/sesame/device-registry.js.map +1 -1
  69. package/dist/internal/sesame/manager.d.ts +79 -11
  70. package/dist/internal/sesame/manager.d.ts.map +1 -1
  71. package/dist/internal/sesame/manager.js +381 -280
  72. package/dist/internal/sesame/manager.js.map +1 -1
  73. package/dist/internal/session/cipher.d.ts +0 -5
  74. package/dist/internal/session/cipher.d.ts.map +1 -1
  75. package/dist/internal/session/cipher.js +3 -9
  76. package/dist/internal/session/cipher.js.map +1 -1
  77. package/dist/internal/session/record-locks.d.ts +46 -0
  78. package/dist/internal/session/record-locks.d.ts.map +1 -0
  79. package/dist/internal/session/record-locks.js +72 -0
  80. package/dist/internal/session/record-locks.js.map +1 -0
  81. package/dist/local/store/expo/adapter.d.ts +8 -2
  82. package/dist/local/store/expo/adapter.d.ts.map +1 -1
  83. package/dist/local/store/expo/adapter.js +24 -3
  84. package/dist/local/store/expo/adapter.js.map +1 -1
  85. package/dist/local/store/expo/driver.d.ts +7 -0
  86. package/dist/local/store/expo/driver.d.ts.map +1 -1
  87. package/dist/local/store/expo/driver.js +16 -0
  88. package/dist/local/store/expo/driver.js.map +1 -1
  89. package/dist/local/store/key-value/adapter.d.ts.map +1 -1
  90. package/dist/local/store/key-value/adapter.js +61 -38
  91. package/dist/local/store/key-value/adapter.js.map +1 -1
  92. package/dist/local/store/memory/adapter.d.ts +10 -0
  93. package/dist/local/store/memory/adapter.d.ts.map +1 -1
  94. package/dist/local/store/memory/adapter.js +79 -55
  95. package/dist/local/store/memory/adapter.js.map +1 -1
  96. package/dist/local/store/reliability.d.ts +16 -0
  97. package/dist/local/store/reliability.d.ts.map +1 -1
  98. package/dist/local/store/reliability.js +58 -28
  99. package/dist/local/store/reliability.js.map +1 -1
  100. package/dist/local/store/sqlite/store.d.ts.map +1 -1
  101. package/dist/local/store/sqlite/store.js +36 -14
  102. package/dist/local/store/sqlite/store.js.map +1 -1
  103. package/dist/local/store/web/adapter.d.ts.map +1 -1
  104. package/dist/local/store/web/adapter.js +63 -53
  105. package/dist/local/store/web/adapter.js.map +1 -1
  106. package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
  107. package/dist/local/vault/electron-safe-storage.js +15 -2
  108. package/dist/local/vault/electron-safe-storage.js.map +1 -1
  109. package/dist/profile/index.d.ts +2 -1
  110. package/dist/profile/index.d.ts.map +1 -1
  111. package/dist/profile/index.js +2 -1
  112. package/dist/profile/index.js.map +1 -1
  113. package/dist/profile/own-profile-key.d.ts +42 -0
  114. package/dist/profile/own-profile-key.d.ts.map +1 -0
  115. package/dist/profile/own-profile-key.js +64 -0
  116. package/dist/profile/own-profile-key.js.map +1 -0
  117. package/dist/profile/profile-key.d.ts +1 -34
  118. package/dist/profile/profile-key.d.ts.map +1 -1
  119. package/dist/profile/profile-key.js +3 -63
  120. package/dist/profile/profile-key.js.map +1 -1
  121. package/dist/profile/update-service.js +1 -1
  122. package/dist/profile/update-service.js.map +1 -1
  123. package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
  124. package/dist/remote/relay/memory/adapter.js +3 -4
  125. package/dist/remote/relay/memory/adapter.js.map +1 -1
  126. package/dist/username/link.d.ts.map +1 -1
  127. package/dist/username/link.js +1 -5
  128. package/dist/username/link.js.map +1 -1
  129. package/dist/utils/bounded-fan-out.d.ts +99 -0
  130. package/dist/utils/bounded-fan-out.d.ts.map +1 -0
  131. package/dist/utils/bounded-fan-out.js +180 -0
  132. package/dist/utils/bounded-fan-out.js.map +1 -0
  133. package/dist/utils/keyed-lock.d.ts +16 -0
  134. package/dist/utils/keyed-lock.d.ts.map +1 -0
  135. package/dist/utils/keyed-lock.js +39 -0
  136. package/dist/utils/keyed-lock.js.map +1 -0
  137. package/docs/ASSURANCE.md +62 -19
  138. package/docs/DEVIATIONS.md +21 -2
  139. package/examples/browser/index.html +1 -1
  140. package/hooks/README.md +11 -2
  141. package/local/store/expo/README.md +18 -5
  142. package/local/store/key-value/README.md +5 -3
  143. package/local/store/node/README.md +2 -1
  144. package/local/store/web-sqlite/README.md +28 -8
  145. package/local/vault/README.md +21 -2
  146. package/package.json +1 -1
  147. package/remote/object-store/convex-r2/README.md +10 -0
@@ -22,10 +22,12 @@ import { RetryReason, DEFAULT_SESAME_CONFIG, SesameError, SesameDeviceNotFoundEr
22
22
  // Session record helpers
23
23
  updateSessionRecordAfterSend, updateSessionRecordAfterReceive, } from './types.js';
24
24
  import { validateSesameConfig } from './validation.js';
25
+ import { SessionRecord as SessionRecordNS } from '../../types/session.js';
25
26
  import { ProtocolAddress } from '../../types/address.js';
26
27
  import { base64ToBytes, bytesToBase64 } from '../crypto/utils.js';
27
28
  import { deserializePublicKey } from '../crypto/key-prefix.js';
28
29
  import { parsePreKeySignalProtocolMessageEnvelope, decodePreKeySignalProtocolMessage, parseSignalProtocolMessageEnvelope, decodeSignalProtocolMessage, } from '../encoding/proto/index.js';
30
+ import { withDeviceListSyncLock, withDeviceRecordLocks, withUserRecordLock, } from '../session/record-locks.js';
29
31
  import { SessionResolver } from '../session/session-resolver.js';
30
32
  import { EncryptionError } from '../../types/errors.js';
31
33
  import { canonicalizeDeviceIdentityKey, compareDeviceIdentityKeys, decodeCompositeIdentityV1, encodeCompositeIdentityV1, UNPINNED_DEVICE_IDENTITY_KEY, } from '../../keys/identity.js';
@@ -66,6 +68,17 @@ function isPreKeyMessage(ciphertext) {
66
68
  * Manages multi-device sessions following the Signal Protocol SESAME specification.
67
69
  *
68
70
  * Supports event callbacks for observability via the SesameEvents interface.
71
+ *
72
+ * Every write of a user record or a device record reads the record, changes
73
+ * it, and writes it back. A per-user lock orders these writes, so two
74
+ * concurrent writes for one user keep both changes. A write that carries a
75
+ * session also takes the session lock of the device first, so it reads the
76
+ * session that the protocol committed last. A write that does not change the
77
+ * session writes a null session, which keeps the stored one. The locks order
78
+ * the writes of one client process only. They do not order two browser tabs,
79
+ * two workers, or two processes that share one store. The session lock comes
80
+ * before the user lock, so the manager never holds the user lock across a
81
+ * protocol call.
69
82
  */
70
83
  export class DefaultSesameManager {
71
84
  storage;
@@ -149,6 +162,23 @@ export class DefaultSesameManager {
149
162
  getEvents() {
150
163
  return this.events;
151
164
  }
165
+ /**
166
+ * Run a read-modify-write of one user's records under the per-user lock.
167
+ * The lock is not reentrant, and the session lock comes first, so the
168
+ * operation must not take the user lock again or call the protocol. It
169
+ * must not write a session.
170
+ */
171
+ withUserLock(userId, operation) {
172
+ return withUserRecordLock(this.storage, userId, operation);
173
+ }
174
+ /**
175
+ * Run a read-modify-write of one device record and its session under the
176
+ * session lock of the device and then the per-user lock. The operation must
177
+ * not take either lock again or call a protocol encrypt or decrypt.
178
+ */
179
+ withDeviceLocks(userId, deviceId, operation) {
180
+ return withDeviceRecordLocks(this.storage, userId, deviceId, operation);
181
+ }
152
182
  /**
153
183
  * Initialize SESAME manager with local device information
154
184
  */
@@ -170,6 +200,9 @@ export class DefaultSesameManager {
170
200
  * @throws {SesameError} if deviceId is outside valid range (1-5)
171
201
  */
172
202
  async addDevice(userId, deviceId, identityKey, _prekeyBundle) {
203
+ await this.withUserLock(userId, () => this.addDeviceLocked(userId, deviceId, identityKey));
204
+ }
205
+ async addDeviceLocked(userId, deviceId, identityKey) {
173
206
  // Validate device ID range (Signal Protocol limits to 1-5 devices per user)
174
207
  if (deviceId < MIN_DEVICE_ID || deviceId > MAX_DEVICE_ID) {
175
208
  throw new SesameError(`Device ID must be between ${MIN_DEVICE_ID} and ${MAX_DEVICE_ID}, got ${deviceId}`, 'INVALID_DEVICE_ID');
@@ -213,9 +246,13 @@ export class DefaultSesameManager {
213
246
  this.events.onDeviceAdded?.(userId, deviceId);
214
247
  }
215
248
  /**
216
- * Remove a device from a user
249
+ * Remove a device from a user. The removal deletes the device's session, so
250
+ * it waits for a session write that is in progress for the device.
217
251
  */
218
252
  async removeDevice(userId, deviceId) {
253
+ await this.withDeviceLocks(userId, deviceId, () => this.removeDeviceLocked(userId, deviceId));
254
+ }
255
+ async removeDeviceLocked(userId, deviceId) {
219
256
  this.logger.debug('SESAME: Removing device', {
220
257
  category: 'E2EE',
221
258
  data: {
@@ -246,19 +283,21 @@ export class DefaultSesameManager {
246
283
  * This unblocks messaging to the device.
247
284
  */
248
285
  async clearPendingVerification(userId, deviceId) {
249
- const record = await this.storage.getDeviceRecord(userId, deviceId);
250
- if (record && record.pendingVerification) {
251
- record.pendingVerification = false;
252
- await this.storage.setDeviceRecord(userId, deviceId, record);
253
- this.logger.info('SESAME: Cleared pending verification', {
254
- category: 'E2EE',
255
- data: {
256
- operation: 'sesame-clear-verification',
257
- userId,
258
- deviceId,
259
- },
260
- });
261
- }
286
+ await this.withUserLock(userId, async () => {
287
+ const record = await this.storage.getDeviceRecord(userId, deviceId);
288
+ if (record && record.pendingVerification) {
289
+ record.pendingVerification = false;
290
+ await this.storage.setDeviceRecord(userId, deviceId, { ...record, session: null });
291
+ this.logger.info('SESAME: Cleared pending verification', {
292
+ category: 'E2EE',
293
+ data: {
294
+ operation: 'sesame-clear-verification',
295
+ userId,
296
+ deviceId,
297
+ },
298
+ });
299
+ }
300
+ });
262
301
  }
263
302
  /**
264
303
  * Get device record for a specific user and device
@@ -293,6 +332,9 @@ export class DefaultSesameManager {
293
332
  * Uses SessionRecord.archiveCurrent() to move the previous active session to archived.
294
333
  */
295
334
  async setSession(userId, deviceId, sessionRecord) {
335
+ await this.withDeviceLocks(userId, deviceId, () => this.setSessionLocked(userId, deviceId, sessionRecord));
336
+ }
337
+ async setSessionLocked(userId, deviceId, sessionRecord) {
296
338
  const deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
297
339
  if (!deviceRecord) {
298
340
  throw new SesameDeviceNotFoundError(`Device not found: ${userId}/${deviceId}`);
@@ -322,7 +364,9 @@ export class DefaultSesameManager {
322
364
  * Register a newly established Double Ratchet session with SESAME.
323
365
  *
324
366
  * Creates a SessionRecord with SESAME metadata and sets it as the device's session.
325
- * Any existing session is archived in SessionRecord.archivedSessions.
367
+ * Any existing session is archived in SessionRecord.archivedSessions. When
368
+ * the store holds a state of the same session (the same baseKey), the stored
369
+ * state is registered, because it can be newer than `sessionState`.
326
370
  *
327
371
  * This bridges the Double Ratchet layer with the SESAME multi-device layer,
328
372
  * so sessions established via SignalProtocolClient.establishSession() are
@@ -336,21 +380,29 @@ export class DefaultSesameManager {
336
380
  async registerSession(userId, deviceId, sessionState, isInitiator) {
337
381
  const address = ProtocolAddress.create(userId, deviceId);
338
382
  const sessionId = ProtocolAddress.toString(address);
339
- // Create the device record if it is missing
340
- let deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
341
- if (!deviceRecord) {
342
- // Auto-create device record if it does not exist. Pin the peer identity the
343
- // session was actually negotiated against. A placeholder here would later
344
- // compare unequal to that same identity and forge an identity-change event.
345
- await this.addDevice(userId, deviceId, sessionState.remoteIdentity
346
- ? encodeCompositeIdentityV1(sessionState.remoteIdentity)
347
- : UNPINNED_DEVICE_IDENTITY_KEY);
348
- deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
349
- }
350
- // Create or update session record using SessionResolver
351
- const sessionRecord = SessionResolver.insertSession(deviceRecord?.session ?? null, sessionState, isInitiator, this.config.maxInactiveSessions);
352
- // Set the session record
353
- await this.setSession(userId, deviceId, sessionRecord);
383
+ await this.withDeviceLocks(userId, deviceId, async () => {
384
+ // Create the device record if it is missing
385
+ let deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
386
+ if (!deviceRecord) {
387
+ // Auto-create device record if it does not exist. Pin the peer identity the
388
+ // session was actually negotiated against. A placeholder here would later
389
+ // compare unequal to that same identity and forge an identity-change event.
390
+ await this.addDeviceLocked(userId, deviceId, sessionState.remoteIdentity
391
+ ? encodeCompositeIdentityV1(sessionState.remoteIdentity)
392
+ : UNPINNED_DEVICE_IDENTITY_KEY);
393
+ deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
394
+ }
395
+ // The caller read the session state before this lock. A send or a receive
396
+ // can have committed a newer state of the same session since then, so
397
+ // register the state of that session that the store holds now.
398
+ const storedState = deviceRecord?.session
399
+ ? SessionRecordNS.findSession(deviceRecord.session, sessionState.baseKey)
400
+ : null;
401
+ // Create or update session record using SessionResolver
402
+ const sessionRecord = SessionResolver.insertSession(deviceRecord?.session ?? null, storedState ?? sessionState, isInitiator, this.config.maxInactiveSessions);
403
+ // Set the session record
404
+ await this.setSessionLocked(userId, deviceId, sessionRecord);
405
+ });
354
406
  this.logger.debug('SESAME: Session registered', {
355
407
  category: 'E2EE',
356
408
  data: {
@@ -425,13 +477,15 @@ export class DefaultSesameManager {
425
477
  }
426
478
  // Update session lastSentAt timestamp via SessionRecord
427
479
  // Placed AFTER Phase 3 validation so metadata is not persisted if validation fails
428
- const deviceRecord = await this.getDeviceRecord(recipientUserId, recipientDeviceId);
429
- if (deviceRecord?.session) {
430
- const updatedSession = updateSessionRecordAfterSend(deviceRecord.session);
431
- deviceRecord.session = updatedSession;
432
- deviceRecord.updatedAt = Date.now();
433
- await this.storage.setDeviceRecord(recipientUserId, recipientDeviceId, deviceRecord);
434
- }
480
+ await this.withDeviceLocks(recipientUserId, recipientDeviceId, async () => {
481
+ const deviceRecord = await this.getDeviceRecord(recipientUserId, recipientDeviceId);
482
+ if (deviceRecord?.session) {
483
+ const updatedSession = updateSessionRecordAfterSend(deviceRecord.session);
484
+ deviceRecord.session = updatedSession;
485
+ deviceRecord.updatedAt = Date.now();
486
+ await this.storage.setDeviceRecord(recipientUserId, recipientDeviceId, deviceRecord);
487
+ }
488
+ });
435
489
  // Convert Ciphertext to Uint8Array for SesameMessage
436
490
  const ciphertextBytes = this.serializeCiphertext(ciphertext);
437
491
  // Client timestamp for envelope alignment (application send-pipeline ordering)
@@ -673,17 +727,20 @@ export class DefaultSesameManager {
673
727
  const includeSyncMessages = options?.includeSyncMessages ?? true;
674
728
  // M15: Check if UserRecord is marked stale and clear it for this attempt.
675
729
  // Per SESAME spec §3.3: stale records trigger a fresh device list fetch.
676
- const userRecord = await this.getUserRecord(recipientUserId);
730
+ const userRecord = await this.withUserLock(recipientUserId, async () => {
731
+ const record = await this.getUserRecord(recipientUserId);
732
+ if (record?.stale) {
733
+ // Clear stale flag since we are about to use this record
734
+ // (caller should have refreshed the device list before retrying)
735
+ record.stale = false;
736
+ record.updatedAt = Date.now();
737
+ await this.storage.setUserRecord(recipientUserId, record);
738
+ }
739
+ return record;
740
+ });
677
741
  if (!userRecord) {
678
742
  throw new SesameError(`No user record found for ${recipientUserId}`, 'USER_NOT_FOUND');
679
743
  }
680
- if (userRecord.stale) {
681
- // Clear stale flag since we are about to use this record
682
- // (caller should have refreshed the device list before retrying)
683
- userRecord.stale = false;
684
- userRecord.updatedAt = Date.now();
685
- await this.storage.setUserRecord(recipientUserId, userRecord);
686
- }
687
744
  if (userRecord.devices.size === 0) {
688
745
  throw new SesameError(`User ${recipientUserId} has no devices`, 'NO_DEVICES');
689
746
  }
@@ -831,13 +888,7 @@ export class DefaultSesameManager {
831
888
  const result = await this.handlePreKeyMessage(message, senderAddress, ciphertext, receiveId);
832
889
  // TRANSACTIONAL: Only persist after successful decrypt
833
890
  // This prevents session state corruption if decryption fails
834
- if (result.pendingUserRecord) {
835
- await this.storage.setUserRecord(message.senderUserId, result.pendingUserRecord);
836
- }
837
- // Update session index for the newly established session
838
- this.removeDeviceFromSessionIndex(message.senderUserId, message.senderDeviceId);
839
- this.indexSessionRecord(message.senderUserId, message.senderDeviceId, result.pendingDeviceRecord.session);
840
- await this.storage.setDeviceRecord(message.senderUserId, message.senderDeviceId, result.pendingDeviceRecord);
891
+ await this.persistPreKeyResult(senderAddress, result);
841
892
  this.logger.debug('SESAME: Session established from PreKeyMessage (persisted)', {
842
893
  category: 'E2EE',
843
894
  data: {
@@ -883,14 +934,6 @@ export class DefaultSesameManager {
883
934
  }
884
935
  // 5. Handle successful decryption
885
936
  if (decryptedPlaintext && successfulCandidate && sessionRecord) {
886
- // CRITICAL: Sync session from protocol layer to get updated state (Nr, chain keys, etc.)
887
- // The protocol.decrypt() call above mutates and saves the session to KeyStorage.
888
- // We MUST read it back to avoid overwriting with stale data from sessionRecord.
889
- // The protocol layer also handles archived session promotion internally.
890
- const sessionFromProtocol = await this.protocol.getSession(senderAddress);
891
- // Use the protocol's updated session (includes updated Nr, chain keys, and any promotion)
892
- // Fall back to original sessionRecord only if sync fails (should not happen)
893
- const updatedSession = sessionFromProtocol || sessionRecord;
894
937
  // If we decrypted on an archived session, emit convergence event for observability
895
938
  // Note: The actual promotion is already handled by the protocol layer (cipher.ts)
896
939
  if (!successfulCandidate.isActive && successfulCandidate.baseKey) {
@@ -916,8 +959,11 @@ export class DefaultSesameManager {
916
959
  },
917
960
  });
918
961
  }
919
- // Update session metadata and persist
920
- await this.persistSessionAfterReceive(message.senderUserId, message.senderDeviceId, updatedSession);
962
+ // Update session metadata and persist. The protocol.decrypt() call
963
+ // above saved the updated session (Nr, chain keys, and any archived
964
+ // session promotion) to KeyStorage, so the persist reads it back from
965
+ // the protocol rather than writing the stale sessionRecord.
966
+ await this.persistSessionAfterReceive(senderAddress, sessionRecord);
921
967
  return decryptedPlaintext;
922
968
  }
923
969
  // 6. All sessions failed - try PreKeyMessage handling as fallback.
@@ -938,13 +984,7 @@ export class DefaultSesameManager {
938
984
  const result = await this.handlePreKeyMessage(message, senderAddress, ciphertext, receiveId);
939
985
  // TRANSACTIONAL: Only persist after successful decrypt
940
986
  // This prevents session state corruption if decryption fails
941
- if (result.pendingUserRecord) {
942
- await this.storage.setUserRecord(message.senderUserId, result.pendingUserRecord);
943
- }
944
- // Update session index for the newly established session
945
- this.removeDeviceFromSessionIndex(message.senderUserId, message.senderDeviceId);
946
- this.indexSessionRecord(message.senderUserId, message.senderDeviceId, result.pendingDeviceRecord.session);
947
- await this.storage.setDeviceRecord(message.senderUserId, message.senderDeviceId, result.pendingDeviceRecord);
987
+ await this.persistPreKeyResult(senderAddress, result);
948
988
  this.logger.debug('SESAME: Session established from PreKeyMessage fallback (persisted)', {
949
989
  category: 'E2EE',
950
990
  data: {
@@ -1227,10 +1267,12 @@ export class DefaultSesameManager {
1227
1267
  * Handle PreKeyMessage decryption when no existing sessions are found.
1228
1268
  *
1229
1269
  * This method handles the first message from a new sender by:
1230
- * 1. Attempting to decrypt using protocol.decrypt() (handles session establishment)
1231
- * 2. Creating DeviceRecord if sender is unknown
1232
- * 3. Detecting identity key changes for existing senders (device reinstall scenario)
1233
- * 4. Persisting the new session
1270
+ * 1. Reading the sender's DeviceRecord before decrypt
1271
+ * 2. Attempting to decrypt using protocol.decrypt() (handles session establishment)
1272
+ * 3. Reading the sender's identity key from the PreKeyMessage
1273
+ *
1274
+ * persistPreKeyResult() then creates or updates the DeviceRecord, detects an
1275
+ * identity key change (device reinstall scenario), and persists the session.
1234
1276
  *
1235
1277
  * @param message - The incoming SESAME message
1236
1278
  * @param senderAddress - Protocol address of the sender
@@ -1251,15 +1293,10 @@ export class DefaultSesameManager {
1251
1293
  // session. Some storage adapters synthesize DeviceRecord from live
1252
1294
  // protocol state. Looking this up only after decrypt would make a
1253
1295
  // brand-new session appear pre-existing and archive it into itself.
1254
- let deviceRecord = await this.getDeviceRecord(message.senderUserId, message.senderDeviceId);
1296
+ const previousDeviceRecord = await this.getDeviceRecord(message.senderUserId, message.senderDeviceId);
1255
1297
  // Note: this.protocol is guaranteed non-null because receive() checks it before calling this method
1256
1298
  const plaintextString = await this.protocol.decrypt(senderAddress, ciphertext, receiveId);
1257
1299
  const decryptedPlaintext = new TextEncoder().encode(plaintextString);
1258
- // CRITICAL: Sync session from KeyStorage to SESAME layer
1259
- // The protocol.decrypt() call above establishes the session in KeyStorage (protocol layer).
1260
- // SESAME needs this session in DeviceRecord.session (SESAME layer) for subsequent messages.
1261
- // Without this sync, the responder path fails to find the session on later messages.
1262
- const sessionFromProtocol = await this.protocol.getSession(senderAddress);
1263
1300
  // Parse PreKeyMessage to get sender's identity key (binary protobuf format)
1264
1301
  // This is needed for both new senders AND existing senders (to detect identity key changes)
1265
1302
  let incomingIdentityKey;
@@ -1283,113 +1320,8 @@ export class DefaultSesameManager {
1283
1320
  throw e;
1284
1321
  throw new DecryptionFailedError(message.sessionId, 0);
1285
1322
  }
1286
- // Track if we need to create/update UserRecord (for new senders only)
1287
- let pendingUserRecord;
1288
- if (!deviceRecord) {
1289
- // First message from new sender - create DeviceRecord with synced session
1290
- deviceRecord = {
1291
- userId: message.senderUserId,
1292
- deviceId: message.senderDeviceId,
1293
- identityKey: incomingIdentityKey,
1294
- session: sessionFromProtocol ? updateSessionRecordAfterReceive(sessionFromProtocol) : null, // Sync session from protocol layer with metadata
1295
- createdAt: Date.now(),
1296
- updatedAt: Date.now(),
1297
- };
1298
- // Prepare UserRecord (will be persisted by caller after successful decrypt)
1299
- let userRecord = await this.storage.getUserRecord(message.senderUserId);
1300
- if (!userRecord) {
1301
- userRecord = {
1302
- userId: message.senderUserId,
1303
- devices: new Map(),
1304
- createdAt: Date.now(),
1305
- updatedAt: Date.now(),
1306
- };
1307
- }
1308
- userRecord.devices.set(message.senderDeviceId, deviceRecord);
1309
- userRecord.updatedAt = Date.now();
1310
- pendingUserRecord = userRecord;
1311
- // TRANSACTIONAL: DO NOT persist here - caller will persist after successful decrypt
1312
- // This prevents session state corruption if subsequent processing fails
1313
- this.logger.debug('SESAME: Prepared DeviceRecord for new sender (pending persist)', {
1314
- category: 'E2EE',
1315
- data: { userId: message.senderUserId, deviceId: message.senderDeviceId },
1316
- });
1317
- }
1318
- else {
1319
- // Existing device record - compare the pinned identity against the one
1320
- // this PreKeyMessage was authenticated with. Both sides are canonical
1321
- // composite tuples, so a difference is a real identity change and not an
1322
- // encoding artifact. A record that carries no pinned identity yet is
1323
- // first contact, because session bookkeeping created it before any
1324
- // identity was observed. TOFU-pin it silently rather than reporting a
1325
- // change.
1326
- const comparison = compareDeviceIdentityKeys(deviceRecord.identityKey, incomingIdentityKey);
1327
- if (comparison === 'unpinned') {
1328
- deviceRecord.identityKey = incomingIdentityKey;
1329
- this.logger.debug('SESAME: Pinned identity key on first contact (TOFU)', {
1330
- category: 'E2EE',
1331
- data: {
1332
- userId: message.senderUserId,
1333
- deviceId: message.senderDeviceId,
1334
- },
1335
- });
1336
- }
1337
- if (comparison === 'changed') {
1338
- // CRITICAL: Identity key changed - this is either a device reinstall
1339
- // or a potential security issue (man-in-the-middle attack)
1340
- this.logger.warn('SESAME: Identity key changed detected in PreKeyMessage', {
1341
- category: 'SECURITY',
1342
- data: {
1343
- userId: message.senderUserId,
1344
- deviceId: message.senderDeviceId,
1345
- event: 'identity_key_changed',
1346
- },
1347
- });
1348
- // Update the identity key to the new one
1349
- deviceRecord.identityKey = incomingIdentityKey;
1350
- deviceRecord.pendingVerification = true;
1351
- // Emit identity key changed event (safety number changed)
1352
- this.events.onIdentityKeyChanged?.(message.senderUserId, incomingIdentityKey);
1353
- // Also emit security event
1354
- this.events.onSecurityEvent?.(senderAddress, 'identity_key_changed');
1355
- this.logger.info('SESAME: Session archived and identity key updated after device reinstall', {
1356
- category: 'E2EE',
1357
- data: {
1358
- userId: message.senderUserId,
1359
- deviceId: message.senderDeviceId,
1360
- },
1361
- });
1362
- }
1363
- // Sync the new session from protocol layer to DeviceRecord.
1364
- // This is needed whether identity changed or not. The PreKeyMessage
1365
- // established a new session that needs to be synced to SESAME layer.
1366
- if (sessionFromProtocol) {
1367
- // If there was an old session, archive it before setting the new one
1368
- // This preserves session history for convergence per SESAME spec
1369
- if (deviceRecord.session?.currentSession) {
1370
- const archivedRecord = SessionResolver.archiveCurrentSession(deviceRecord.session, this.config.maxInactiveSessions);
1371
- // Merge archived sessions: preserve ALL sessions from both sources
1372
- // Use explicit merge to avoid collision-related data loss from spread operator
1373
- const mergedArchived = {};
1374
- // First, add all from archived record (preserves existing session history)
1375
- for (const [key, session] of Object.entries(archivedRecord.archivedSessions)) {
1376
- if (session)
1377
- mergedArchived[key] = session;
1378
- }
1379
- // Then add from protocol (only if not already present - do not overwrite history)
1380
- for (const [key, session] of Object.entries(sessionFromProtocol.archivedSessions || {})) {
1381
- if (session && !(key in mergedArchived)) {
1382
- mergedArchived[key] = session;
1383
- }
1384
- }
1385
- sessionFromProtocol.archivedSessions = mergedArchived;
1386
- }
1387
- deviceRecord.session = updateSessionRecordAfterReceive(sessionFromProtocol);
1388
- }
1389
- deviceRecord.updatedAt = Date.now();
1390
- // TRANSACTIONAL: DO NOT persist here - caller will persist after successful decrypt
1391
- // This prevents session state corruption if subsequent processing fails
1392
- }
1323
+ // TRANSACTIONAL: DO NOT persist here - caller will persist after successful decrypt
1324
+ // This prevents session state corruption if subsequent processing fails
1393
1325
  this.logger.debug('SESAME: Session prepared from PreKeyMessage (pending persist)', {
1394
1326
  category: 'E2EE',
1395
1327
  data: {
@@ -1398,34 +1330,160 @@ export class DefaultSesameManager {
1398
1330
  senderDeviceId: message.senderDeviceId,
1399
1331
  },
1400
1332
  });
1401
- // Return result with pending records - caller MUST persist after confirming success
1402
1333
  return {
1403
1334
  plaintext: decryptedPlaintext,
1404
- pendingDeviceRecord: deviceRecord,
1405
- pendingUserRecord,
1335
+ previousDeviceRecord,
1336
+ incomingIdentityKey,
1406
1337
  };
1407
1338
  }
1408
1339
  /**
1409
- * Update session metadata after receiving a message and persist to storage.
1410
- *
1411
- * This is a helper method that reduces duplication between the PreKeyMessage
1412
- * handling path and the normal receive path.
1340
+ * Persist the DeviceRecord for a decrypted PreKeyMessage.
1413
1341
  *
1414
- * @param userId - Sender's user ID
1415
- * @param deviceId - Sender's device ID
1416
- * @param session - The session record to update
1342
+ * The session lock of the sender device comes first, so the session read
1343
+ * from the protocol is the one that it committed last. The records are
1344
+ * then read again under the user lock, and the identity decision compares
1345
+ * the incoming identity with the identity that the store pins now. An
1346
+ * identity pinned while the message decrypted is therefore compared, not
1347
+ * replaced. The receive path owns the identity key, the session, and the
1348
+ * update time. Every other field, and every other device of the user, keeps
1349
+ * the value that the store holds now, so a concurrent write for this user
1350
+ * is not lost.
1417
1351
  */
1418
- async persistSessionAfterReceive(userId, deviceId, session) {
1419
- const updatedSession = updateSessionRecordAfterReceive(session);
1420
- const deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
1421
- if (deviceRecord) {
1422
- // Update session index for the new session state
1352
+ async persistPreKeyResult(senderAddress, result) {
1353
+ const { userId, deviceId } = senderAddress;
1354
+ const incomingIdentityKey = result.incomingIdentityKey;
1355
+ const newSender = result.previousDeviceRecord === null;
1356
+ const comparison = await this.withDeviceLocks(userId, deviceId, async () => {
1357
+ const sessionFromProtocol = await this.protocol.getSession(senderAddress);
1358
+ const session = sessionFromProtocol
1359
+ ? updateSessionRecordAfterReceive(this.mergePreKeySession(result.previousDeviceRecord?.session ?? null, sessionFromProtocol))
1360
+ : null;
1361
+ const now = Date.now();
1362
+ const userRecord = newSender
1363
+ ? ((await this.storage.getUserRecord(userId)) ?? {
1364
+ userId,
1365
+ devices: new Map(),
1366
+ createdAt: now,
1367
+ updatedAt: now,
1368
+ })
1369
+ : null;
1370
+ const current = userRecord
1371
+ ? (userRecord.devices.get(deviceId) ?? null)
1372
+ : await this.storage.getDeviceRecord(userId, deviceId);
1373
+ // Both sides are canonical composite tuples, so a difference is a real
1374
+ // identity change and not an encoding artifact. A record that carries
1375
+ // no pinned identity yet is first contact, because session bookkeeping
1376
+ // created it before any identity was observed. TOFU-pin it silently
1377
+ // rather than reporting a change.
1378
+ const comparison = current
1379
+ ? compareDeviceIdentityKeys(current.identityKey, incomingIdentityKey)
1380
+ : null;
1381
+ const deviceRecord = current
1382
+ ? {
1383
+ ...current,
1384
+ identityKey: comparison === 'same' ? current.identityKey : incomingIdentityKey,
1385
+ session,
1386
+ updatedAt: now,
1387
+ ...(comparison === 'changed' ? { pendingVerification: true } : {}),
1388
+ }
1389
+ : {
1390
+ userId,
1391
+ deviceId,
1392
+ identityKey: incomingIdentityKey,
1393
+ session,
1394
+ createdAt: now,
1395
+ updatedAt: now,
1396
+ };
1397
+ if (userRecord) {
1398
+ userRecord.devices.set(deviceId, deviceRecord);
1399
+ userRecord.updatedAt = now;
1400
+ await this.storage.setUserRecord(userId, userRecord);
1401
+ }
1402
+ // Update session index for the newly established session
1423
1403
  this.removeDeviceFromSessionIndex(userId, deviceId);
1424
- this.indexSessionRecord(userId, deviceId, updatedSession);
1425
- deviceRecord.session = updatedSession;
1426
- deviceRecord.updatedAt = Date.now();
1404
+ this.indexSessionRecord(userId, deviceId, deviceRecord.session);
1427
1405
  await this.storage.setDeviceRecord(userId, deviceId, deviceRecord);
1406
+ // A store joins a device that has no pin with the identity of its
1407
+ // session, and the decrypt committed that session. A device that had no
1408
+ // pin before the decrypt is a first-contact pin.
1409
+ return comparison === 'same' && result.previousDeviceRecord?.identityKey.length === 0
1410
+ ? 'unpinned'
1411
+ : comparison;
1412
+ });
1413
+ if (comparison === 'unpinned') {
1414
+ this.logger.debug('SESAME: Pinned identity key on first contact (TOFU)', {
1415
+ category: 'E2EE',
1416
+ data: { userId, deviceId },
1417
+ });
1418
+ }
1419
+ if (comparison === 'changed') {
1420
+ // CRITICAL: Identity key changed - this is either a device reinstall
1421
+ // or a potential security issue (man-in-the-middle attack)
1422
+ this.logger.warn('SESAME: Identity key changed detected in PreKeyMessage', {
1423
+ category: 'SECURITY',
1424
+ data: { userId, deviceId, event: 'identity_key_changed' },
1425
+ });
1426
+ // Emit identity key changed event (safety number changed)
1427
+ this.events.onIdentityKeyChanged?.(userId, incomingIdentityKey);
1428
+ // Also emit security event
1429
+ this.events.onSecurityEvent?.(senderAddress, 'identity_key_changed');
1430
+ this.logger.info('SESAME: Session archived and identity key updated after device reinstall', {
1431
+ category: 'E2EE',
1432
+ data: { userId, deviceId },
1433
+ });
1434
+ }
1435
+ }
1436
+ /**
1437
+ * The session record to store for a session that a PreKeyMessage
1438
+ * established. The previous current session is archived, and the archived
1439
+ * sessions of both records are kept, so SESAME keeps the session history
1440
+ * for convergence.
1441
+ */
1442
+ mergePreKeySession(previous, fromProtocol) {
1443
+ if (!previous?.currentSession)
1444
+ return fromProtocol;
1445
+ const archivedRecord = SessionResolver.archiveCurrentSession(previous, this.config.maxInactiveSessions);
1446
+ // Merge archived sessions: preserve ALL sessions from both sources
1447
+ // Use explicit merge to avoid collision-related data loss from spread operator
1448
+ const mergedArchived = {};
1449
+ // First, add all from archived record (preserves existing session history)
1450
+ for (const [key, session] of Object.entries(archivedRecord.archivedSessions)) {
1451
+ if (session)
1452
+ mergedArchived[key] = session;
1453
+ }
1454
+ // Then add from protocol (only if not already present - do not overwrite history)
1455
+ for (const [key, session] of Object.entries(fromProtocol.archivedSessions || {})) {
1456
+ if (session && !(key in mergedArchived)) {
1457
+ mergedArchived[key] = session;
1458
+ }
1428
1459
  }
1460
+ return { ...fromProtocol, archivedSessions: mergedArchived };
1461
+ }
1462
+ /**
1463
+ * Update session metadata after receiving a message and persist to storage.
1464
+ *
1465
+ * The session is read from the protocol under the session lock of the
1466
+ * sender device, so a session that the protocol committed after the
1467
+ * decrypt is not written back older.
1468
+ *
1469
+ * @param senderAddress - Sender's protocol address
1470
+ * @param fallback - The session record to update if the protocol has none
1471
+ */
1472
+ async persistSessionAfterReceive(senderAddress, fallback) {
1473
+ const { userId, deviceId } = senderAddress;
1474
+ await this.withDeviceLocks(userId, deviceId, async () => {
1475
+ const session = (await this.protocol.getSession(senderAddress)) ?? fallback;
1476
+ const updatedSession = updateSessionRecordAfterReceive(session);
1477
+ const deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
1478
+ if (deviceRecord) {
1479
+ // Update session index for the new session state
1480
+ this.removeDeviceFromSessionIndex(userId, deviceId);
1481
+ this.indexSessionRecord(userId, deviceId, updatedSession);
1482
+ deviceRecord.session = updatedSession;
1483
+ deviceRecord.updatedAt = Date.now();
1484
+ await this.storage.setDeviceRecord(userId, deviceId, deviceRecord);
1485
+ }
1486
+ });
1429
1487
  }
1430
1488
  /**
1431
1489
  * Mark a UserRecord as stale, triggering a fresh device list fetch on next access.
@@ -1435,19 +1493,21 @@ export class DefaultSesameManager {
1435
1493
  * @param userId - The user whose record should be marked stale
1436
1494
  */
1437
1495
  async markUserRecordStale(userId) {
1438
- const userRecord = await this.storage.getUserRecord(userId);
1439
- if (userRecord) {
1440
- userRecord.stale = true;
1441
- userRecord.updatedAt = Date.now();
1442
- await this.storage.setUserRecord(userId, userRecord);
1443
- this.logger.info('SESAME: UserRecord marked stale', {
1444
- category: 'E2EE',
1445
- data: {
1446
- operation: 'sesame-mark-stale',
1447
- userId,
1448
- },
1449
- });
1450
- }
1496
+ await this.withUserLock(userId, async () => {
1497
+ const userRecord = await this.storage.getUserRecord(userId);
1498
+ if (userRecord) {
1499
+ userRecord.stale = true;
1500
+ userRecord.updatedAt = Date.now();
1501
+ await this.storage.setUserRecord(userId, userRecord);
1502
+ this.logger.info('SESAME: UserRecord marked stale', {
1503
+ category: 'E2EE',
1504
+ data: {
1505
+ operation: 'sesame-mark-stale',
1506
+ userId,
1507
+ },
1508
+ });
1509
+ }
1510
+ });
1451
1511
  }
1452
1512
  /**
1453
1513
  * Archive the active session for a specific device
@@ -1456,6 +1516,9 @@ export class DefaultSesameManager {
1456
1516
  * to allow a new session to be established on the next send attempt.
1457
1517
  */
1458
1518
  async archiveSessionForDevice(userId, deviceId) {
1519
+ await this.withDeviceLocks(userId, deviceId, () => this.archiveSessionForDeviceLocked(userId, deviceId));
1520
+ }
1521
+ async archiveSessionForDeviceLocked(userId, deviceId) {
1459
1522
  const deviceRecord = await this.storage.getDeviceRecord(userId, deviceId);
1460
1523
  if (!deviceRecord?.session?.currentSession) {
1461
1524
  // No active session to archive
@@ -1645,8 +1708,13 @@ export class DefaultSesameManager {
1645
1708
  * Synchronize device list from server response
1646
1709
  *
1647
1710
  * SESAME Phase 3 in message sending requires validating the device list is current.
1711
+ * Two syncs of one user run one after the other, so the stored devices and
1712
+ * version come from one list.
1648
1713
  */
1649
1714
  async syncDeviceList(deviceListResponse) {
1715
+ await withDeviceListSyncLock(this.storage, deviceListResponse.userId, () => this.syncDeviceListLocked(deviceListResponse));
1716
+ }
1717
+ async syncDeviceListLocked(deviceListResponse) {
1650
1718
  const { userId, deviceIds, version } = deviceListResponse;
1651
1719
  this.logger.debug('SESAME: Syncing device list', {
1652
1720
  category: 'E2EE',
@@ -1661,81 +1729,114 @@ export class DefaultSesameManager {
1661
1729
  // available. A device the server listed without an identity key stays
1662
1730
  // unpinned rather than being pinned to placeholder bytes.
1663
1731
  const { identityKeys } = deviceListResponse;
1664
- const devices = deviceIds.map((deviceId) => ({
1732
+ const devices = new Map(deviceIds.map((deviceId) => [
1665
1733
  deviceId,
1666
- identityKey: canonicalizeDeviceIdentityKey(identityKeys?.get(deviceId) ?? UNPINNED_DEVICE_IDENTITY_KEY, `Device list identity key for ${userId}:${deviceId}`),
1667
- isActive: true,
1668
- }));
1669
- // Get current user record
1670
- const userRecord = await this.storage.getUserRecord(userId);
1671
- if (!userRecord) {
1672
- // New user - create record with all devices
1673
- for (const device of devices) {
1674
- if (device.isActive) {
1675
- await this.addDevice(userId, device.deviceId, device.identityKey);
1734
+ canonicalizeDeviceIdentityKey(identityKeys?.get(deviceId) ?? UNPINNED_DEVICE_IDENTITY_KEY, `Device list identity key for ${userId}:${deviceId}`),
1735
+ ]));
1736
+ // Add and pin devices under the user lock. A device that the list removes
1737
+ // or re-keys loses its session, and a session write needs the session lock
1738
+ // first, so collect those devices and replace each one after this lock.
1739
+ const replacedDeviceIds = await this.withUserLock(userId, async () => {
1740
+ // Get current user record
1741
+ const userRecord = await this.storage.getUserRecord(userId);
1742
+ if (!userRecord) {
1743
+ // New user - create record with all devices
1744
+ for (const [deviceId, identityKey] of devices) {
1745
+ await this.addDeviceLocked(userId, deviceId, identityKey);
1676
1746
  }
1747
+ return null;
1677
1748
  }
1678
- return;
1679
- }
1680
- // Track which devices exist on server
1681
- const serverDeviceIds = new Set(devices.map((d) => d.deviceId));
1682
- // Remove devices that no longer exist on server
1683
- for (const [deviceId] of userRecord.devices.entries()) {
1684
- if (!serverDeviceIds.has(deviceId)) {
1685
- await this.removeDevice(userId, deviceId);
1686
- }
1687
- }
1688
- // Add or update devices from server
1689
- for (const device of devices) {
1690
- if (!device.isActive) {
1691
- await this.removeDevice(userId, device.deviceId);
1692
- continue;
1693
- }
1694
- const existingDevice = await this.getDeviceRecord(userId, device.deviceId);
1695
- if (!existingDevice) {
1696
- await this.addDevice(userId, device.deviceId, device.identityKey);
1697
- }
1698
- else if (device.identityKey.length > 0) {
1699
- // Only a device list that actually carries an identity key can tell us
1700
- // the identity changed. A response that omits it carries no
1701
- // information about identity, and must not be read as a change.
1702
- // Reading it as a change would drop every live session and raise a
1703
- // security event on each sync.
1704
- const comparison = compareDeviceIdentityKeys(existingDevice.identityKey, device.identityKey);
1705
- if (comparison === 'unpinned') {
1706
- // Device was tracked before its identity was known - TOFU-pin it.
1707
- existingDevice.identityKey = device.identityKey;
1708
- await this.storage.setDeviceRecord(userId, device.deviceId, existingDevice);
1749
+ // Devices that no longer exist on server
1750
+ const replaced = Array.from(userRecord.devices.keys()).filter((deviceId) => !devices.has(deviceId));
1751
+ // Add or update devices from server
1752
+ for (const [deviceId, identityKey] of devices) {
1753
+ const existingDevice = await this.getDeviceRecord(userId, deviceId);
1754
+ if (!existingDevice) {
1755
+ await this.addDeviceLocked(userId, deviceId, identityKey);
1709
1756
  }
1710
- if (comparison === 'changed') {
1711
- // Identity key changed - security event
1712
- // Remove old device and add new one (clears sessions)
1713
- await this.removeDevice(userId, device.deviceId);
1714
- await this.addDevice(userId, device.deviceId, device.identityKey);
1715
- // Mark device as pending verification to block messaging until user verifies
1716
- const newRecord = await this.getDeviceRecord(userId, device.deviceId);
1717
- if (newRecord) {
1718
- newRecord.pendingVerification = true;
1719
- await this.storage.setDeviceRecord(userId, device.deviceId, newRecord);
1757
+ else if (identityKey.length > 0) {
1758
+ // Only a device list that actually carries an identity key can tell us
1759
+ // the identity changed. A response that omits it carries no
1760
+ // information about identity, and must not be read as a change.
1761
+ // Reading it as a change would drop every live session and raise a
1762
+ // security event on each sync.
1763
+ const comparison = compareDeviceIdentityKeys(existingDevice.identityKey, identityKey);
1764
+ if (comparison === 'unpinned') {
1765
+ // Device was tracked before its identity was known - TOFU-pin it.
1766
+ existingDevice.identityKey = identityKey;
1767
+ await this.storage.setDeviceRecord(userId, deviceId, {
1768
+ ...existingDevice,
1769
+ session: null,
1770
+ });
1771
+ }
1772
+ if (comparison === 'changed') {
1773
+ replaced.push(deviceId);
1720
1774
  }
1721
- // Emit identity key changed event (SECURITY)
1722
- this.events.onIdentityKeyChanged?.(userId, device.identityKey);
1723
- // Also emit security event with description
1724
- const address = ProtocolAddress.create(userId, device.deviceId);
1725
- this.events.onSecurityEvent?.(address, 'identity_key_changed');
1726
1775
  }
1727
1776
  }
1777
+ return replaced;
1778
+ });
1779
+ if (replacedDeviceIds === null)
1780
+ return;
1781
+ for (const deviceId of replacedDeviceIds) {
1782
+ const identityKey = devices.get(deviceId);
1783
+ const rekeyed = await this.withDeviceLocks(userId, deviceId, () => this.replaceListedDeviceLocked(userId, deviceId, identityKey));
1784
+ if (rekeyed && identityKey) {
1785
+ // Emit identity key changed event (SECURITY)
1786
+ this.events.onIdentityKeyChanged?.(userId, identityKey);
1787
+ // Also emit security event with description
1788
+ const address = ProtocolAddress.create(userId, deviceId);
1789
+ this.events.onSecurityEvent?.(address, 'identity_key_changed');
1790
+ }
1728
1791
  }
1729
1792
  // Update user record version if provided (Phase 3 version tracking)
1730
1793
  if (version !== undefined) {
1731
- const updatedUserRecord = await this.storage.getUserRecord(userId);
1732
- if (updatedUserRecord) {
1733
- updatedUserRecord.deviceListVersion = version;
1734
- updatedUserRecord.updatedAt = Date.now();
1735
- await this.storage.setUserRecord(userId, updatedUserRecord);
1736
- }
1794
+ await this.withUserLock(userId, async () => {
1795
+ const updatedUserRecord = await this.storage.getUserRecord(userId);
1796
+ if (updatedUserRecord) {
1797
+ updatedUserRecord.deviceListVersion = version;
1798
+ updatedUserRecord.updatedAt = Date.now();
1799
+ await this.storage.setUserRecord(userId, updatedUserRecord);
1800
+ }
1801
+ });
1737
1802
  }
1738
1803
  }
1804
+ /**
1805
+ * Remove a device that the device list no longer lists, or replace a
1806
+ * device whose listed identity key changed. Another write can have changed
1807
+ * the device since the list was compared under the user lock, so the
1808
+ * decision is made again here.
1809
+ *
1810
+ * @param identityKey - The listed identity key, or undefined when the list
1811
+ * does not list the device
1812
+ * @returns true when the device was replaced for a changed identity key
1813
+ */
1814
+ async replaceListedDeviceLocked(userId, deviceId, identityKey) {
1815
+ const existingDevice = await this.getDeviceRecord(userId, deviceId);
1816
+ if (!existingDevice)
1817
+ return false;
1818
+ if (identityKey === undefined) {
1819
+ await this.removeDeviceLocked(userId, deviceId);
1820
+ return false;
1821
+ }
1822
+ if (compareDeviceIdentityKeys(existingDevice.identityKey, identityKey) !== 'changed') {
1823
+ return false;
1824
+ }
1825
+ // Identity key changed - security event
1826
+ // Remove old device and add new one (clears sessions)
1827
+ await this.removeDeviceLocked(userId, deviceId);
1828
+ await this.addDeviceLocked(userId, deviceId, identityKey);
1829
+ // Mark device as pending verification to block messaging until user verifies
1830
+ const newRecord = await this.getDeviceRecord(userId, deviceId);
1831
+ if (newRecord) {
1832
+ newRecord.pendingVerification = true;
1833
+ await this.storage.setDeviceRecord(userId, deviceId, {
1834
+ ...newRecord,
1835
+ session: null,
1836
+ });
1837
+ }
1838
+ return true;
1839
+ }
1739
1840
  /**
1740
1841
  * Get statistics about SESAME state
1741
1842
  */