@open-e2ee/signal-protocol-sdk 8.0.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.
- package/ADAPTERS.md +2 -2
- package/CHANGELOG.md +188 -0
- package/README.md +4 -4
- package/SECURITY.md +2 -2
- package/device/README.md +16 -7
- package/dist/client/client.d.ts +4 -2
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +25 -19
- package/dist/client/client.js.map +1 -1
- package/dist/client/group-outbox.d.ts +31 -1
- package/dist/client/group-outbox.d.ts.map +1 -1
- package/dist/client/group-outbox.js +67 -58
- package/dist/client/group-outbox.js.map +1 -1
- package/dist/client/hosted-anonymous-delivery.d.ts +9 -1
- package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
- package/dist/client/hosted-anonymous-delivery.js +61 -22
- package/dist/client/hosted-anonymous-delivery.js.map +1 -1
- package/dist/client/hosted-transport.d.ts +16 -0
- package/dist/client/hosted-transport.d.ts.map +1 -1
- package/dist/client/hosted-transport.js +93 -19
- package/dist/client/hosted-transport.js.map +1 -1
- package/dist/client/key-rotation.d.ts.map +1 -1
- package/dist/client/key-rotation.js +2 -4
- package/dist/client/key-rotation.js.map +1 -1
- package/dist/client/prekeys.d.ts.map +1 -1
- package/dist/client/prekeys.js +1 -1
- package/dist/client/prekeys.js.map +1 -1
- package/dist/client/relay-device-refusal.d.ts +32 -0
- package/dist/client/relay-device-refusal.d.ts.map +1 -0
- package/dist/client/relay-device-refusal.js +36 -0
- package/dist/client/relay-device-refusal.js.map +1 -0
- package/dist/client/relay-work.d.ts +26 -0
- package/dist/client/relay-work.d.ts.map +1 -1
- package/dist/client/relay-work.js +37 -0
- package/dist/client/relay-work.js.map +1 -1
- package/dist/client/sealed-sender.d.ts.map +1 -1
- package/dist/client/sealed-sender.js +12 -17
- package/dist/client/sealed-sender.js.map +1 -1
- package/dist/client/sessions.d.ts.map +1 -1
- package/dist/client/sessions.js +2 -4
- package/dist/client/sessions.js.map +1 -1
- package/dist/client/signal-service-cipher.d.ts +90 -4
- package/dist/client/signal-service-cipher.d.ts.map +1 -1
- package/dist/client/signal-service-cipher.js +425 -136
- package/dist/client/signal-service-cipher.js.map +1 -1
- package/dist/client/types.d.ts +7 -0
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/types.js.map +1 -1
- package/dist/internal/manager/manager.d.ts +8 -7
- package/dist/internal/manager/manager.d.ts.map +1 -1
- package/dist/internal/manager/manager.js +34 -36
- package/dist/internal/manager/manager.js.map +1 -1
- package/dist/internal/protocol/spqr/index.d.ts +1 -1
- package/dist/internal/protocol/spqr/index.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/index.js +2 -2
- package/dist/internal/protocol/spqr/index.js.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js +1 -3
- package/dist/internal/protocol/spqr/ml-kem-braid/rs/codec.js.map +1 -1
- package/dist/internal/protocol/spqr/serialize.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/serialize.js +1 -4
- package/dist/internal/protocol/spqr/serialize.js.map +1 -1
- package/dist/internal/protocol/spqr/spqr.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/spqr.js +1 -2
- package/dist/internal/protocol/spqr/spqr.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/attributes.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/attributes.js +2 -1
- package/dist/internal/protocol/zk/credentials/attributes.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/credentials.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/credentials.js +8 -6
- package/dist/internal/protocol/zk/credentials/credentials.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/presentation.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/presentation.js +19 -13
- package/dist/internal/protocol/zk/credentials/presentation.js.map +1 -1
- package/dist/internal/protocol/zk/groups/lizard.d.ts +8 -0
- package/dist/internal/protocol/zk/groups/lizard.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/lizard.js +18 -5
- package/dist/internal/protocol/zk/groups/lizard.js.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-commitment.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-commitment.js +7 -6
- package/dist/internal/protocol/zk/groups/profile-key-commitment.js.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-encryption.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-encryption.js +3 -2
- package/dist/internal/protocol/zk/groups/profile-key-encryption.js.map +1 -1
- package/dist/internal/protocol/zk/groups/uid-encryption.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/uid-encryption.js +3 -2
- package/dist/internal/protocol/zk/groups/uid-encryption.js.map +1 -1
- package/dist/internal/protocol/zk/proofs/point-multiplication.d.ts +53 -0
- package/dist/internal/protocol/zk/proofs/point-multiplication.d.ts.map +1 -0
- package/dist/internal/protocol/zk/proofs/point-multiplication.js +164 -0
- package/dist/internal/protocol/zk/proofs/point-multiplication.js.map +1 -0
- package/dist/internal/protocol/zk/proofs/sho.d.ts +1 -0
- package/dist/internal/protocol/zk/proofs/sho.d.ts.map +1 -1
- package/dist/internal/protocol/zk/proofs/sho.js.map +1 -1
- package/dist/internal/protocol/zk/proofs/statement.d.ts.map +1 -1
- package/dist/internal/protocol/zk/proofs/statement.js +11 -11
- package/dist/internal/protocol/zk/proofs/statement.js.map +1 -1
- package/dist/internal/sesame/device-registry.d.ts +24 -4
- package/dist/internal/sesame/device-registry.d.ts.map +1 -1
- package/dist/internal/sesame/device-registry.js +55 -28
- package/dist/internal/sesame/device-registry.js.map +1 -1
- package/dist/internal/sesame/manager.d.ts +79 -11
- package/dist/internal/sesame/manager.d.ts.map +1 -1
- package/dist/internal/sesame/manager.js +381 -280
- package/dist/internal/sesame/manager.js.map +1 -1
- package/dist/internal/session/cipher.d.ts +0 -5
- package/dist/internal/session/cipher.d.ts.map +1 -1
- package/dist/internal/session/cipher.js +3 -9
- package/dist/internal/session/cipher.js.map +1 -1
- package/dist/internal/session/record-locks.d.ts +46 -0
- package/dist/internal/session/record-locks.d.ts.map +1 -0
- package/dist/internal/session/record-locks.js +72 -0
- package/dist/internal/session/record-locks.js.map +1 -0
- package/dist/local/store/expo/adapter.d.ts +8 -2
- package/dist/local/store/expo/adapter.d.ts.map +1 -1
- package/dist/local/store/expo/adapter.js +24 -3
- package/dist/local/store/expo/adapter.js.map +1 -1
- package/dist/local/store/expo/driver.d.ts +7 -0
- package/dist/local/store/expo/driver.d.ts.map +1 -1
- package/dist/local/store/expo/driver.js +16 -0
- package/dist/local/store/expo/driver.js.map +1 -1
- package/dist/local/store/index.d.ts +2 -2
- package/dist/local/store/index.js +2 -2
- package/dist/local/store/key-value/adapter.d.ts.map +1 -1
- package/dist/local/store/key-value/adapter.js +61 -38
- package/dist/local/store/key-value/adapter.js.map +1 -1
- package/dist/local/store/memory/adapter.d.ts +10 -0
- package/dist/local/store/memory/adapter.d.ts.map +1 -1
- package/dist/local/store/memory/adapter.js +79 -55
- package/dist/local/store/memory/adapter.js.map +1 -1
- package/dist/local/store/reliability.d.ts +16 -0
- package/dist/local/store/reliability.d.ts.map +1 -1
- package/dist/local/store/reliability.js +58 -28
- package/dist/local/store/reliability.js.map +1 -1
- package/dist/local/store/sqlite/store.d.ts.map +1 -1
- package/dist/local/store/sqlite/store.js +36 -14
- package/dist/local/store/sqlite/store.js.map +1 -1
- package/dist/local/store/sqlite/web/driver.d.ts.map +1 -1
- package/dist/local/store/sqlite/web/driver.js +3 -1
- package/dist/local/store/sqlite/web/driver.js.map +1 -1
- package/dist/local/store/sqlite/web/protocol.d.ts +1 -1
- package/dist/local/store/sqlite/web/protocol.d.ts.map +1 -1
- package/dist/local/store/sqlite/web/worker.d.ts +7 -4
- package/dist/local/store/sqlite/web/worker.d.ts.map +1 -1
- package/dist/local/store/sqlite/web/worker.js +48 -18
- package/dist/local/store/sqlite/web/worker.js.map +1 -1
- package/dist/local/store/web/adapter.d.ts.map +1 -1
- package/dist/local/store/web/adapter.js +63 -53
- package/dist/local/store/web/adapter.js.map +1 -1
- package/dist/local/store/web-sqlite/adapter.d.ts +3 -0
- package/dist/local/store/web-sqlite/adapter.d.ts.map +1 -1
- package/dist/local/store/web-sqlite/adapter.js +3 -0
- package/dist/local/store/web-sqlite/adapter.js.map +1 -1
- package/dist/local/vault/electron-safe-storage.d.ts.map +1 -1
- package/dist/local/vault/electron-safe-storage.js +15 -2
- package/dist/local/vault/electron-safe-storage.js.map +1 -1
- package/dist/profile/index.d.ts +2 -1
- package/dist/profile/index.d.ts.map +1 -1
- package/dist/profile/index.js +2 -1
- package/dist/profile/index.js.map +1 -1
- package/dist/profile/own-profile-key.d.ts +42 -0
- package/dist/profile/own-profile-key.d.ts.map +1 -0
- package/dist/profile/own-profile-key.js +64 -0
- package/dist/profile/own-profile-key.js.map +1 -0
- package/dist/profile/profile-key.d.ts +1 -34
- package/dist/profile/profile-key.d.ts.map +1 -1
- package/dist/profile/profile-key.js +3 -63
- package/dist/profile/profile-key.js.map +1 -1
- package/dist/profile/update-service.js +1 -1
- package/dist/profile/update-service.js.map +1 -1
- package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
- package/dist/remote/relay/memory/adapter.js +3 -4
- package/dist/remote/relay/memory/adapter.js.map +1 -1
- package/dist/username/link.d.ts.map +1 -1
- package/dist/username/link.js +1 -5
- package/dist/username/link.js.map +1 -1
- package/dist/utils/bounded-fan-out.d.ts +99 -0
- package/dist/utils/bounded-fan-out.d.ts.map +1 -0
- package/dist/utils/bounded-fan-out.js +180 -0
- package/dist/utils/bounded-fan-out.js.map +1 -0
- package/dist/utils/keyed-lock.d.ts +16 -0
- package/dist/utils/keyed-lock.d.ts.map +1 -0
- package/dist/utils/keyed-lock.js +39 -0
- package/dist/utils/keyed-lock.js.map +1 -0
- package/docs/ASSURANCE.md +68 -24
- package/docs/DEVIATIONS.md +21 -2
- package/docs/ERROR_HANDLING.md +1 -1
- package/docs/PACKAGE_SURFACE.md +3 -1
- package/examples/browser/index.html +1 -1
- package/hooks/README.md +11 -2
- package/local/store/README.md +41 -21
- package/local/store/expo/README.md +18 -5
- package/local/store/key-value/README.md +5 -3
- package/local/store/node/README.md +2 -1
- package/local/store/web/README.md +5 -0
- package/local/store/web-sqlite/README.md +36 -8
- package/local/vault/README.md +21 -2
- package/package.json +1 -1
- package/remote/object-store/convex-r2/README.md +10 -0
|
@@ -23,12 +23,14 @@ import { defaultSignalProtocolLogger } from '../logger.js';
|
|
|
23
23
|
import { isGroupId, extractGroupId } from '../internal/groups/index.js';
|
|
24
24
|
import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
|
|
25
25
|
import * as CryptoUtils from '../internal/crypto/index.js';
|
|
26
|
-
import { completeOutgoingMessageIntent, getOutgoingMessageIntent, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
|
|
26
|
+
import { completeOutgoingMessageIntent, getOutgoingMessageIntent, reconcileOutgoingDirectDeviceMessages, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
|
|
27
|
+
import { FanOutError, firstItemError } from '../utils/bounded-fan-out.js';
|
|
27
28
|
import { withRetry } from '../utils/retry.js';
|
|
28
|
-
import { acquireUntilStopped, RelayWorkStopped, rethrowRelayWorkStopped } from './relay-work.js';
|
|
29
|
+
import { acquireUntilStopped, createRelayFanOut, RelayWorkStopped, relaySendsSealedUnderItsBound, rethrowRelayWorkStopped, } from './relay-work.js';
|
|
30
|
+
import { refusesRemovedDevices, relayDeviceRefusal } from './relay-device-refusal.js';
|
|
29
31
|
import { prepareGroupSharedMessage } from './group-sealed-sender.js';
|
|
30
32
|
import { sendGroupWithExactOutbox } from './group-outbox.js';
|
|
31
|
-
import { resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, } from './sealed-sender.js';
|
|
33
|
+
import { reconstructEnvelope, resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, unsealMessage, } from './sealed-sender.js';
|
|
32
34
|
import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
|
|
33
35
|
import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
|
|
34
36
|
/**
|
|
@@ -37,6 +39,20 @@ import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
|
|
|
37
39
|
* first send after it ends.
|
|
38
40
|
*/
|
|
39
41
|
export const RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS = 60_000;
|
|
42
|
+
/**
|
|
43
|
+
* How old a recipient's device list can be for a direct send to post before
|
|
44
|
+
* it reads the list again. Only a relay that refuses a removed device's
|
|
45
|
+
* mailbox allows it, so the age bounds how long the client posts first on a
|
|
46
|
+
* list that no read confirmed, not how long a removed device receives.
|
|
47
|
+
*/
|
|
48
|
+
const RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS = 300_000;
|
|
49
|
+
/** A send-first post that waits for the reconcile pass. */
|
|
50
|
+
class DeferredPost extends Error {
|
|
51
|
+
constructor() {
|
|
52
|
+
super('The post waits for the device-list read');
|
|
53
|
+
this.name = 'DeferredPost';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
40
56
|
export function sortEnvelopesForDecryption(envelopes) {
|
|
41
57
|
return [...envelopes].sort((a, b) => {
|
|
42
58
|
// Treat undefined messageType as non-prekey (ciphertext comes after prekey_bundle)
|
|
@@ -121,7 +137,14 @@ class SealedSenderRecipientRejectedError extends Error {
|
|
|
121
137
|
}
|
|
122
138
|
}
|
|
123
139
|
function isConclusiveDeviceRejection(error) {
|
|
124
|
-
return isStaleSessionError(error) ||
|
|
140
|
+
return (isStaleSessionError(error) ||
|
|
141
|
+
error instanceof SealedSenderRecipientRejectedError ||
|
|
142
|
+
relayDeviceRefusal(error)?.code === 'STALE_DEVICE');
|
|
143
|
+
}
|
|
144
|
+
/** True when the relay refused this post because of the device that it names. */
|
|
145
|
+
function isRefusalOfDevice(error, message) {
|
|
146
|
+
const refusal = relayDeviceRefusal(error);
|
|
147
|
+
return (refusal?.userId === message.recipientUserId && refusal.deviceId === message.recipientDeviceId);
|
|
125
148
|
}
|
|
126
149
|
/**
|
|
127
150
|
* SignalProtocolServiceCipher - Routes encryption and decryption to appropriate ciphers
|
|
@@ -153,6 +176,7 @@ export class SignalProtocolServiceCipher {
|
|
|
153
176
|
remoteObjectStore;
|
|
154
177
|
contentAdapter;
|
|
155
178
|
logger;
|
|
179
|
+
fanOut;
|
|
156
180
|
lock = new AsyncLock();
|
|
157
181
|
sessionCallbacks;
|
|
158
182
|
recipientDeviceListCheckedAt = new Map();
|
|
@@ -166,7 +190,7 @@ export class SignalProtocolServiceCipher {
|
|
|
166
190
|
groupSendBarrierChecker;
|
|
167
191
|
groupReceiveAuthorizer;
|
|
168
192
|
groupSecretParamsProvider;
|
|
169
|
-
constructor(userId, deviceId, sesameManager, senderKeyManager, storage, relay, remoteObjectStore, contentAdapter, logger = defaultSignalProtocolLogger) {
|
|
193
|
+
constructor(userId, deviceId, sesameManager, senderKeyManager, storage, relay, remoteObjectStore, contentAdapter, logger = defaultSignalProtocolLogger, fanOut = createRelayFanOut()) {
|
|
170
194
|
this.userId = userId;
|
|
171
195
|
this.deviceId = deviceId;
|
|
172
196
|
this.sesameManager = sesameManager;
|
|
@@ -176,6 +200,7 @@ export class SignalProtocolServiceCipher {
|
|
|
176
200
|
this.remoteObjectStore = remoteObjectStore;
|
|
177
201
|
this.contentAdapter = contentAdapter;
|
|
178
202
|
this.logger = logger;
|
|
203
|
+
this.fanOut = fanOut;
|
|
179
204
|
}
|
|
180
205
|
getResolvedContentAdapter() {
|
|
181
206
|
return this.contentAdapter ?? createDefaultSignalProtocolContentAdapter();
|
|
@@ -202,23 +227,69 @@ export class SignalProtocolServiceCipher {
|
|
|
202
227
|
return CryptoUtils.bytesToBase64(plaintextBytes);
|
|
203
228
|
}
|
|
204
229
|
async uploadSyncMessages(syncMessages) {
|
|
205
|
-
|
|
230
|
+
const relay = this.relay;
|
|
231
|
+
if (!relay || syncMessages.length === 0) {
|
|
206
232
|
return;
|
|
207
233
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
234
|
+
await this.sendPhase(syncMessages, (syncMsg) => this.fanOut.request(() => relay.send({
|
|
235
|
+
targetUserId: syncMsg.recipientUserId,
|
|
236
|
+
targetDeviceId: syncMsg.recipientDeviceId,
|
|
237
|
+
senderUserId: this.userId,
|
|
238
|
+
senderDeviceId: this.deviceId,
|
|
239
|
+
ciphertext: typeof syncMsg.ciphertext === 'string'
|
|
240
|
+
? syncMsg.ciphertext
|
|
241
|
+
: CryptoUtils.bytesToBase64(syncMsg.ciphertext),
|
|
242
|
+
messageType: getEnvelopeMessageType(syncMsg.ciphertext),
|
|
243
|
+
deliveryClass: 'background-sync',
|
|
244
|
+
timestamp: syncMsg.timestamp,
|
|
245
|
+
})), 'sync');
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Run one relay phase of a send: a task for each device message, at the same
|
|
249
|
+
* time, under the client's relay request bound. Every device is attempted.
|
|
250
|
+
* When devices fail, the phase rejects after every device settles, with the
|
|
251
|
+
* error of the first failed device in input order, so a caller sees the
|
|
252
|
+
* error type that a send in device order threw. Each other failure is logged.
|
|
253
|
+
*/
|
|
254
|
+
async sendPhase(messages, task, phase, stopSignal) {
|
|
255
|
+
try {
|
|
256
|
+
return await this.fanOut.all(messages, task, stopSignal);
|
|
221
257
|
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (!(error instanceof FanOutError))
|
|
260
|
+
throw error;
|
|
261
|
+
const failed = error.outcomes.flatMap((outcome, index) => outcome.ok ? [] : [{ message: messages[index], error: outcome.error }]);
|
|
262
|
+
for (const { message, error: other } of failed.slice(1)) {
|
|
263
|
+
this.logger.warn('A device post of a send failed', {
|
|
264
|
+
category: 'E2EE',
|
|
265
|
+
error: other,
|
|
266
|
+
data: {
|
|
267
|
+
phase,
|
|
268
|
+
recipientUserId: message.recipientUserId,
|
|
269
|
+
deviceId: message.recipientDeviceId,
|
|
270
|
+
failedDevices: failed.length,
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
throw failed[0].error;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Send one relay request of a device post under a slot of the client's
|
|
279
|
+
* bound. An adapter that bounds its own sealed-sender posts takes a slot of
|
|
280
|
+
* the same bound, so its sealed post runs without one here.
|
|
281
|
+
*/
|
|
282
|
+
postToRelay(send, sealed, control) {
|
|
283
|
+
const post = () => {
|
|
284
|
+
control.admit?.();
|
|
285
|
+
return send();
|
|
286
|
+
};
|
|
287
|
+
if (sealed && relaySendsSealedUnderItsBound(this.relay)) {
|
|
288
|
+
if (control.stopSignal?.aborted)
|
|
289
|
+
return Promise.reject(new RelayWorkStopped());
|
|
290
|
+
return new Promise((resolve) => resolve(post()));
|
|
291
|
+
}
|
|
292
|
+
return this.fanOut.request(post, control.stopSignal);
|
|
222
293
|
}
|
|
223
294
|
async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp) {
|
|
224
295
|
if (!this.relay) {
|
|
@@ -388,7 +459,6 @@ export class SignalProtocolServiceCipher {
|
|
|
388
459
|
if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
|
|
389
460
|
throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
|
|
390
461
|
}
|
|
391
|
-
const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender.js');
|
|
392
462
|
// Get recipient's X25519 identity private key for unsealing
|
|
393
463
|
const identityKeyPair = await this.storage.getIdentityKey();
|
|
394
464
|
if (!identityKeyPair) {
|
|
@@ -533,10 +603,10 @@ export class SignalProtocolServiceCipher {
|
|
|
533
603
|
}
|
|
534
604
|
// 2. Detect recipient type (group vs user)
|
|
535
605
|
if (isGroupId(recipientId)) {
|
|
536
|
-
return this.encryptToGroup(recipientId, content, durableOptions, sessions);
|
|
606
|
+
return this.encryptToGroup(recipientId, content, durableOptions, sessions, stopSignal);
|
|
537
607
|
}
|
|
538
608
|
// 3. Send to user (existing SESAME path)
|
|
539
|
-
return this.encryptToUser(recipientId, content, durableOptions, sessions);
|
|
609
|
+
return this.encryptToUser(recipientId, content, durableOptions, sessions, stopSignal);
|
|
540
610
|
}, stopSignal);
|
|
541
611
|
}
|
|
542
612
|
catch (error) {
|
|
@@ -677,17 +747,26 @@ export class SignalProtocolServiceCipher {
|
|
|
677
747
|
* without a relay read. The relay gives no device-set version, so the window
|
|
678
748
|
* is the only bound on how long a linked or removed device goes unseen.
|
|
679
749
|
*
|
|
750
|
+
* A direct send may post before the read when the relay refuses every post
|
|
751
|
+
* to a removed device's mailbox, this client read the list in this process,
|
|
752
|
+
* and that read is younger than
|
|
753
|
+
* RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS. This method then returns
|
|
754
|
+
* true without a read, and the send reads the list while it posts and
|
|
755
|
+
* reconciles after the read. Other relays, and a list that this process did
|
|
756
|
+
* not read or that is too old, await the read. A list time later than the
|
|
757
|
+
* clock is too old.
|
|
758
|
+
*
|
|
759
|
+
* @param sendFirst - The caller can post before the read and reconcile after it
|
|
760
|
+
* @param readDevices - The recipient's devices that this send read. When
|
|
761
|
+
* they are given, a reconcile uses them and does not read the list again
|
|
762
|
+
* @returns True when the caller must read the list after it posts
|
|
680
763
|
* @throws {EncryptionError} SESSION_NOT_FOUND if sessions cannot be established
|
|
681
764
|
*/
|
|
682
|
-
async ensureSessionsForUser(recipientUserId, sessions) {
|
|
683
|
-
const
|
|
684
|
-
const
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
if (hasActiveSession &&
|
|
688
|
-
checkedAt !== undefined &&
|
|
689
|
-
Date.now() - checkedAt < RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS) {
|
|
690
|
-
return;
|
|
765
|
+
async ensureSessionsForUser(recipientUserId, sessions, sendFirst = false, readDevices) {
|
|
766
|
+
const hasActiveSession = await this.hasActiveSession(recipientUserId);
|
|
767
|
+
const listAge = this.recipientDeviceListAge(recipientUserId);
|
|
768
|
+
if (hasActiveSession && listAge < RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS) {
|
|
769
|
+
return false;
|
|
691
770
|
}
|
|
692
771
|
this.logger.debug('Reconciling recipient devices with the relay', {
|
|
693
772
|
category: 'E2EE',
|
|
@@ -695,19 +774,51 @@ export class SignalProtocolServiceCipher {
|
|
|
695
774
|
});
|
|
696
775
|
if (!sessions) {
|
|
697
776
|
if (hasActiveSession)
|
|
698
|
-
return;
|
|
777
|
+
return false;
|
|
699
778
|
throw new EncryptionError(`No session with ${recipientUserId} and auto-establishment not configured`, EncryptionErrorCode.SESSION_NOT_FOUND, { recipientUserId });
|
|
700
779
|
}
|
|
701
780
|
if (!this.relay) {
|
|
702
781
|
if (hasActiveSession)
|
|
703
|
-
return;
|
|
782
|
+
return false;
|
|
704
783
|
throw new EncryptionError('Cannot auto-establish session: relay server not configured', EncryptionErrorCode.INITIALIZATION_FAILED, { recipientUserId });
|
|
705
784
|
}
|
|
785
|
+
if (sendFirst &&
|
|
786
|
+
hasActiveSession &&
|
|
787
|
+
listAge < RECIPIENT_DEVICE_LIST_MAXIMUM_AGE_MILLISECONDS &&
|
|
788
|
+
refusesRemovedDevices(this.relay)) {
|
|
789
|
+
return true;
|
|
790
|
+
}
|
|
791
|
+
await this.readRecipientDeviceList(recipientUserId, sessions, hasActiveSession, undefined, readDevices);
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
async hasActiveSession(recipientUserId) {
|
|
795
|
+
const userRecord = await this.sesameManager.getUserRecord(recipientUserId);
|
|
796
|
+
return (!!userRecord &&
|
|
797
|
+
Array.from(userRecord.devices.values()).some((device) => device.session?.currentSession != null));
|
|
798
|
+
}
|
|
799
|
+
/** The age of this process's last successful read. A read in the future has no age. */
|
|
800
|
+
recipientDeviceListAge(recipientUserId) {
|
|
801
|
+
const checkedAt = this.recipientDeviceListCheckedAt.get(recipientUserId);
|
|
802
|
+
const age = checkedAt === undefined ? Number.POSITIVE_INFINITY : Date.now() - checkedAt;
|
|
803
|
+
return age >= 0 ? age : Number.POSITIVE_INFINITY;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Read the recipient's device list, create the missing sessions, and remove
|
|
807
|
+
* each local device that the list does not show.
|
|
808
|
+
*
|
|
809
|
+
* @param onList - Called with the listed devices as soon as the list arrives,
|
|
810
|
+
* before the unlisted records are removed
|
|
811
|
+
* @param readDevices - The devices that this send read. When they are
|
|
812
|
+
* given, the list is not read again
|
|
813
|
+
* @returns The listed and established devices, or undefined when the read
|
|
814
|
+
* failed and the known devices still receive
|
|
815
|
+
*/
|
|
816
|
+
async readRecipientDeviceList(recipientUserId, sessions, hasActiveSession, onList, readDevices) {
|
|
706
817
|
let result;
|
|
707
818
|
try {
|
|
708
819
|
// Use retry logic for transient network failures
|
|
709
820
|
result = await withRetry(async () => {
|
|
710
|
-
const attempt = await sessions.establishSessions(recipientUserId);
|
|
821
|
+
const attempt = await sessions.establishSessions(recipientUserId, readDevices);
|
|
711
822
|
if (attempt.establishedDevices.length === 0 && attempt.failedDeviceErrors.length > 0) {
|
|
712
823
|
throw attempt.failedDeviceErrors[0].error;
|
|
713
824
|
}
|
|
@@ -728,7 +839,7 @@ export class SignalProtocolServiceCipher {
|
|
|
728
839
|
error: error,
|
|
729
840
|
data: { recipientUserId },
|
|
730
841
|
});
|
|
731
|
-
return;
|
|
842
|
+
return undefined;
|
|
732
843
|
}
|
|
733
844
|
// Re-throw EncryptionErrors, wrap others
|
|
734
845
|
if (error instanceof EncryptionError) {
|
|
@@ -742,6 +853,7 @@ export class SignalProtocolServiceCipher {
|
|
|
742
853
|
throw new EncryptionError(`Failed to establish session with ${recipientUserId} after retries`, EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { originalError: error, recipientUserId });
|
|
743
854
|
}
|
|
744
855
|
const listedDevices = new Set(result.activeDevices);
|
|
856
|
+
onList?.(listedDevices);
|
|
745
857
|
const removedDevices = [];
|
|
746
858
|
const reconciledRecord = await this.sesameManager.getUserRecord(recipientUserId);
|
|
747
859
|
for (const deviceId of Array.from(reconciledRecord?.devices.keys() ?? [])) {
|
|
@@ -765,17 +877,18 @@ export class SignalProtocolServiceCipher {
|
|
|
765
877
|
removedDevices,
|
|
766
878
|
},
|
|
767
879
|
});
|
|
880
|
+
return { listed: listedDevices, established: result.establishedDevices };
|
|
768
881
|
}
|
|
769
882
|
/**
|
|
770
883
|
* Encrypt to a single user (all their devices) via SESAME
|
|
771
884
|
*/
|
|
772
|
-
async encryptToUser(recipientUserId, plaintextBytes, options, sessions) {
|
|
773
|
-
return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions);
|
|
885
|
+
async encryptToUser(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
|
|
886
|
+
return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal);
|
|
774
887
|
}
|
|
775
|
-
async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions) {
|
|
776
|
-
return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions));
|
|
888
|
+
async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
|
|
889
|
+
return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal));
|
|
777
890
|
}
|
|
778
|
-
async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions) {
|
|
891
|
+
async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
|
|
779
892
|
const plaintextDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(plaintextBytes));
|
|
780
893
|
const existing = await getOutgoingMessageIntent(this.storage, options.clientMessageId);
|
|
781
894
|
if (existing) {
|
|
@@ -787,9 +900,9 @@ export class SignalProtocolServiceCipher {
|
|
|
787
900
|
}
|
|
788
901
|
if (existing.result)
|
|
789
902
|
return existing.result;
|
|
790
|
-
return this.sendStoredDirectIntent(existing, plaintextBytes, sessions);
|
|
903
|
+
return this.sendStoredDirectIntent(await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions), plaintextBytes, sessions, stopSignal);
|
|
791
904
|
}
|
|
792
|
-
await this.ensureSessionsForUser(recipientUserId, sessions);
|
|
905
|
+
const sendFirst = await this.ensureSessionsForUser(recipientUserId, sessions, true);
|
|
793
906
|
const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
|
|
794
907
|
const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
|
|
795
908
|
const transportMode = directSealedSender
|
|
@@ -823,7 +936,12 @@ export class SignalProtocolServiceCipher {
|
|
|
823
936
|
syncCount: batch.syncMessages.length,
|
|
824
937
|
},
|
|
825
938
|
});
|
|
826
|
-
|
|
939
|
+
// Local work: a stop does not end it, so the intent keeps the ciphertext.
|
|
940
|
+
const deviceMessages = await this.fanOut
|
|
941
|
+
.all(batch.deviceMessages, (message) => this.prepareStoredDirectDeviceMessage(message, directSealedSender))
|
|
942
|
+
.catch((error) => {
|
|
943
|
+
throw firstItemError(error);
|
|
944
|
+
});
|
|
827
945
|
const syncMessages = batch.syncMessages.map((msg, index) => ({
|
|
828
946
|
recipientUserId: msg.recipientUserId,
|
|
829
947
|
recipientDeviceId: msg.recipientDeviceId,
|
|
@@ -846,11 +964,125 @@ export class SignalProtocolServiceCipher {
|
|
|
846
964
|
...(options.contentHint !== undefined && {
|
|
847
965
|
contentHint: options.contentHint,
|
|
848
966
|
}),
|
|
967
|
+
...(sendFirst && { reconcilePending: true }),
|
|
849
968
|
deviceMessages,
|
|
850
969
|
syncMessages,
|
|
851
970
|
};
|
|
852
971
|
await storeOutgoingMessageIntent(this.storage, intent);
|
|
853
|
-
|
|
972
|
+
if (sendFirst && sessions) {
|
|
973
|
+
return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal);
|
|
974
|
+
}
|
|
975
|
+
return this.sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Post a direct intent to its known devices while the recipient's device
|
|
979
|
+
* list is read, then reconcile the intent with the list and post the rest.
|
|
980
|
+
*
|
|
981
|
+
* The known devices are posted at the same time. A post that the relay
|
|
982
|
+
* refuses because of its device waits for the read, and the read decides it:
|
|
983
|
+
* an unlisted device leaves the intent without a repair, a listed device
|
|
984
|
+
* with STALE_DEVICE is repaired, and a listed device with NOT_FOUND fails
|
|
985
|
+
* the send. A post that has not started when the list arrives waits for the
|
|
986
|
+
* reconcile pass, which starts after the read removes the unlisted device
|
|
987
|
+
* records, so no message goes to a device after the read that shows its
|
|
988
|
+
* removal.
|
|
989
|
+
*/
|
|
990
|
+
async sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal) {
|
|
991
|
+
const arrived = {};
|
|
992
|
+
const read = this.readRecipientDeviceList(intent.recipientId, sessions, true, (listed) => {
|
|
993
|
+
arrived.listed = listed;
|
|
994
|
+
});
|
|
995
|
+
// Every path below awaits the read. This handler only covers the posts.
|
|
996
|
+
read.catch(() => undefined);
|
|
997
|
+
const posts = { accepted: new Map(), refused: new Map() };
|
|
998
|
+
const control = {
|
|
999
|
+
...(stopSignal && { stopSignal }),
|
|
1000
|
+
admit: () => {
|
|
1001
|
+
if (arrived.listed)
|
|
1002
|
+
throw new DeferredPost();
|
|
1003
|
+
},
|
|
1004
|
+
};
|
|
1005
|
+
try {
|
|
1006
|
+
await this.sendPhase(intent.deviceMessages, async (message) => {
|
|
1007
|
+
try {
|
|
1008
|
+
posts.accepted.set(message.recipientDeviceId, await this.sendStoredDirectDeviceMessage(intent, message, control));
|
|
1009
|
+
}
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
if (error instanceof DeferredPost)
|
|
1012
|
+
return;
|
|
1013
|
+
if (!isRefusalOfDevice(error, message))
|
|
1014
|
+
throw error;
|
|
1015
|
+
posts.refused.set(message.recipientDeviceId, { error });
|
|
1016
|
+
}
|
|
1017
|
+
}, 'device', stopSignal);
|
|
1018
|
+
}
|
|
1019
|
+
catch (error) {
|
|
1020
|
+
// The read commits sessions. It ends before the send fails.
|
|
1021
|
+
await read.catch(() => undefined);
|
|
1022
|
+
throw error;
|
|
1023
|
+
}
|
|
1024
|
+
const list = await read;
|
|
1025
|
+
const reconciled = list
|
|
1026
|
+
? await this.reconcileDirectIntent(intent, list, plaintextBytes)
|
|
1027
|
+
: intent;
|
|
1028
|
+
return this.sendStoredDirectIntent(reconciled, plaintextBytes, sessions, stopSignal, posts);
|
|
1029
|
+
}
|
|
1030
|
+
/** A replay whose first attempt posted before its read reads and reconciles first. */
|
|
1031
|
+
async reconcilePendingDirectIntent(intent, plaintextBytes, sessions) {
|
|
1032
|
+
if (!intent.reconcilePending || !sessions || !this.relay)
|
|
1033
|
+
return intent;
|
|
1034
|
+
const list = await this.readRecipientDeviceList(intent.recipientId, sessions, await this.hasActiveSession(intent.recipientId));
|
|
1035
|
+
return list ? this.reconcileDirectIntent(intent, list, plaintextBytes) : intent;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Apply a device-list read to a direct intent: remove each device that the
|
|
1039
|
+
* list does not show, and encrypt the message for each established device
|
|
1040
|
+
* that the intent does not address. A new transmission keeps the intent's
|
|
1041
|
+
* timestamp, so each device receives the same message.
|
|
1042
|
+
*/
|
|
1043
|
+
async reconcileDirectIntent(intent, list, plaintextBytes) {
|
|
1044
|
+
const removed = intent.deviceMessages
|
|
1045
|
+
.map((message) => message.recipientDeviceId)
|
|
1046
|
+
.filter((deviceId) => !list.listed.has(deviceId));
|
|
1047
|
+
const addressed = new Set(intent.deviceMessages.map((message) => message.recipientDeviceId));
|
|
1048
|
+
const added = [];
|
|
1049
|
+
let sealedSender;
|
|
1050
|
+
for (const deviceId of list.established) {
|
|
1051
|
+
if (addressed.has(deviceId))
|
|
1052
|
+
continue;
|
|
1053
|
+
let message;
|
|
1054
|
+
try {
|
|
1055
|
+
message = await this.sesameManager.sendMessage(intent.recipientId, deviceId, plaintextBytes, {
|
|
1056
|
+
clientTimestamp: intent.clientTimestamp,
|
|
1057
|
+
includeSyncMessages: false,
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
catch (error) {
|
|
1061
|
+
this.logger.warn('Could not encrypt a direct message for a newly listed device', {
|
|
1062
|
+
category: 'E2EE',
|
|
1063
|
+
error: error,
|
|
1064
|
+
data: { recipientUserId: intent.recipientId, deviceId },
|
|
1065
|
+
});
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
if (sealedSender === undefined) {
|
|
1069
|
+
sealedSender = await this.resolveStoredDirectSealedSender(intent);
|
|
1070
|
+
}
|
|
1071
|
+
added.push(await this.prepareStoredDirectDeviceMessage(message, sealedSender));
|
|
1072
|
+
}
|
|
1073
|
+
if (removed.length === 0 && added.length === 0)
|
|
1074
|
+
return intent;
|
|
1075
|
+
return reconcileOutgoingDirectDeviceMessages(this.storage, intent.clientMessageId, removed, added);
|
|
1076
|
+
}
|
|
1077
|
+
/** The sealed-sender context of a new transmission for a stored direct intent. */
|
|
1078
|
+
async resolveStoredDirectSealedSender(intent) {
|
|
1079
|
+
if (intent.transportMode === 'identified')
|
|
1080
|
+
return null;
|
|
1081
|
+
const sealedSender = await this.resolveSealedSenderContext(intent.recipientId);
|
|
1082
|
+
if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
|
|
1083
|
+
throw new Error('Cannot build a sealed-sender transmission for a stored direct intent');
|
|
1084
|
+
}
|
|
1085
|
+
return sealedSender;
|
|
854
1086
|
}
|
|
855
1087
|
async prepareStoredDirectDeviceMessage(message, sealedSender) {
|
|
856
1088
|
const messageType = getEnvelopeMessageType(message.ciphertext);
|
|
@@ -874,39 +1106,66 @@ export class SignalProtocolServiceCipher {
|
|
|
874
1106
|
}
|
|
875
1107
|
return storedMessage;
|
|
876
1108
|
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Refresh the session of a rejected device and replace its transmission.
|
|
1111
|
+
* The device posts of a send run at the same time, so the repairs for one
|
|
1112
|
+
* recipient take turns: the first session commit with a user pins the
|
|
1113
|
+
* user's contact identity, and a concurrent commit that read the store
|
|
1114
|
+
* before it fails.
|
|
1115
|
+
*/
|
|
877
1116
|
async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes, sessions) {
|
|
878
1117
|
if (!sessions)
|
|
879
1118
|
throw new Error('Stale-session refresh is not configured');
|
|
1119
|
+
return this.lock.acquire(`direct-repair:${rejected.recipientUserId}`, () => this.repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions));
|
|
1120
|
+
}
|
|
1121
|
+
async repairRejectedDirectDeviceMessageInTurn(intent, rejected, plaintextBytes, sessions) {
|
|
880
1122
|
const refreshed = await sessions.refreshStaleSession(rejected.recipientUserId, rejected.recipientDeviceId);
|
|
881
1123
|
if (!refreshed) {
|
|
882
1124
|
throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: rejected.recipientUserId });
|
|
883
1125
|
}
|
|
884
1126
|
const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
|
|
885
|
-
|
|
886
|
-
if (intent.transportMode !== 'identified') {
|
|
887
|
-
sealedSender = await this.resolveSealedSenderContext(rejected.recipientUserId);
|
|
888
|
-
if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
|
|
889
|
-
throw new Error('Cannot rebuild a sealed-sender transmission after session refresh');
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, sealedSender);
|
|
1127
|
+
const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, await this.resolveStoredDirectSealedSender(intent));
|
|
893
1128
|
await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
|
|
894
1129
|
return replacement;
|
|
895
1130
|
}
|
|
896
|
-
async sendStoredDirectDeviceMessage(intent, message) {
|
|
1131
|
+
async sendStoredDirectDeviceMessage(intent, message, control) {
|
|
897
1132
|
if (intent.transportMode !== 'identified' &&
|
|
898
1133
|
(!message.sealedSenderMessage || !intent.sealedSenderAuth)) {
|
|
899
1134
|
throw new Error('Corrupt sealed-sender outbox intent');
|
|
900
1135
|
}
|
|
901
1136
|
return intent.transportMode === 'identified'
|
|
902
|
-
? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId)
|
|
1137
|
+
? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, undefined, control)
|
|
903
1138
|
: this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, {
|
|
904
1139
|
sentMessageBase64: message.sealedSenderMessage,
|
|
905
1140
|
auth: intent.sealedSenderAuth,
|
|
906
1141
|
deliveryMode: intent.transportMode === 'sealed_sender_required' ? 'required' : 'preferred',
|
|
907
|
-
});
|
|
1142
|
+
}, control);
|
|
908
1143
|
}
|
|
909
|
-
|
|
1144
|
+
/** Post one device message, and repair its session once if the device rejects it. */
|
|
1145
|
+
async postStoredDirectDeviceMessage(intent, message, plaintextBytes, sessions, control, refusal) {
|
|
1146
|
+
let rejection;
|
|
1147
|
+
if (refusal) {
|
|
1148
|
+
rejection = refusal.error;
|
|
1149
|
+
}
|
|
1150
|
+
else {
|
|
1151
|
+
try {
|
|
1152
|
+
return await this.sendStoredDirectDeviceMessage(intent, message, control);
|
|
1153
|
+
}
|
|
1154
|
+
catch (error) {
|
|
1155
|
+
rejection = error;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
if (!isConclusiveDeviceRejection(rejection))
|
|
1159
|
+
throw rejection;
|
|
1160
|
+
const replacement = await this.repairRejectedDirectDeviceMessage(intent, message, plaintextBytes, sessions);
|
|
1161
|
+
return this.sendStoredDirectDeviceMessage(intent, replacement, control);
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Post each device message of a direct intent, then the sync messages, and
|
|
1165
|
+
* complete the intent. A device that a send-first pass already posted keeps
|
|
1166
|
+
* its result or its refusal.
|
|
1167
|
+
*/
|
|
1168
|
+
async sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, posts) {
|
|
910
1169
|
if (intent.kind !== 'direct')
|
|
911
1170
|
throw new Error('Expected a direct outbox intent');
|
|
912
1171
|
if (!this.relay) {
|
|
@@ -919,37 +1178,30 @@ export class SignalProtocolServiceCipher {
|
|
|
919
1178
|
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
|
|
920
1179
|
return result;
|
|
921
1180
|
}
|
|
1181
|
+
const relay = this.relay;
|
|
922
1182
|
let messageId = `local-${intent.clientTimestamp}`;
|
|
923
1183
|
let timestamp = intent.clientTimestamp;
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
}
|
|
929
|
-
catch (error) {
|
|
930
|
-
if (!isConclusiveDeviceRejection(error))
|
|
931
|
-
throw error;
|
|
932
|
-
const replacement = await this.repairRejectedDirectDeviceMessage(intent, msg, plaintextBytes, sessions);
|
|
933
|
-
result = await this.sendStoredDirectDeviceMessage(intent, replacement);
|
|
934
|
-
}
|
|
1184
|
+
const control = { ...(stopSignal && { stopSignal }) };
|
|
1185
|
+
const results = await this.sendPhase(intent.deviceMessages, async (msg) => posts?.accepted.get(msg.recipientDeviceId) ??
|
|
1186
|
+
this.postStoredDirectDeviceMessage(intent, msg, plaintextBytes, sessions, control, posts?.refused.get(msg.recipientDeviceId)), 'device', stopSignal);
|
|
1187
|
+
for (const result of results) {
|
|
935
1188
|
if (messageId.startsWith('local-')) {
|
|
936
1189
|
messageId = result.messageId;
|
|
937
1190
|
timestamp = result.serverTimestamp;
|
|
938
1191
|
}
|
|
939
1192
|
}
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
}
|
|
1193
|
+
// The sync copies start only after every device post settled.
|
|
1194
|
+
await this.sendPhase(intent.syncMessages, (msg) => this.fanOut.request(() => relay.send({
|
|
1195
|
+
targetUserId: msg.recipientUserId,
|
|
1196
|
+
targetDeviceId: msg.recipientDeviceId,
|
|
1197
|
+
senderUserId: this.userId,
|
|
1198
|
+
senderDeviceId: this.deviceId,
|
|
1199
|
+
ciphertext: msg.ciphertext,
|
|
1200
|
+
messageType: msg.messageType,
|
|
1201
|
+
deliveryClass: 'background-sync',
|
|
1202
|
+
timestamp: msg.timestamp,
|
|
1203
|
+
clientMessageId: msg.clientMessageId,
|
|
1204
|
+
}), stopSignal), 'sync', stopSignal);
|
|
953
1205
|
const result = {
|
|
954
1206
|
clientMessageId: intent.clientMessageId,
|
|
955
1207
|
messageId,
|
|
@@ -959,15 +1211,16 @@ export class SignalProtocolServiceCipher {
|
|
|
959
1211
|
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
|
|
960
1212
|
return result;
|
|
961
1213
|
}
|
|
962
|
-
async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions) {
|
|
1214
|
+
async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal) {
|
|
1215
|
+
const control = { ...(stopSignal && { stopSignal }) };
|
|
963
1216
|
return sendGroupWithExactOutbox({
|
|
964
1217
|
storage: this.storage,
|
|
965
1218
|
...(this.relay && { relay: this.relay }),
|
|
966
1219
|
senderUserId: this.userId,
|
|
967
1220
|
senderDeviceId: this.deviceId,
|
|
968
1221
|
deliveryMode: this.sealedSenderDeliveryMode,
|
|
969
|
-
preparePayload: async (groupId, bytes, sendOptions) => {
|
|
970
|
-
const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions, sessions);
|
|
1222
|
+
preparePayload: async (groupId, bytes, sendOptions, readMembers) => {
|
|
1223
|
+
const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions, sessions, readMembers, stopSignal);
|
|
971
1224
|
return {
|
|
972
1225
|
ciphertext: CryptoUtils.bytesToBase64(prepared.ciphertext),
|
|
973
1226
|
preMessages: prepared.preMessages,
|
|
@@ -977,7 +1230,7 @@ export class SignalProtocolServiceCipher {
|
|
|
977
1230
|
};
|
|
978
1231
|
},
|
|
979
1232
|
confirmSenderKeyDistributionSent: (groupId, senderKeyId) => this.senderKeyManager.confirmSenderKeyDistributionSent(groupId, this.userId, this.deviceId, senderKeyId),
|
|
980
|
-
resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions),
|
|
1233
|
+
resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions, stopSignal),
|
|
981
1234
|
prepareSharedMessage: async (groupId, members, ciphertext) => {
|
|
982
1235
|
if (members.length === 0 ||
|
|
983
1236
|
this.sealedSenderDeliveryMode === 'disabled' ||
|
|
@@ -1027,7 +1280,12 @@ export class SignalProtocolServiceCipher {
|
|
|
1027
1280
|
sentMessageBase64: message.sealedSenderMessage,
|
|
1028
1281
|
auth,
|
|
1029
1282
|
deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
|
|
1283
|
+
}, control),
|
|
1284
|
+
prepareEach: (items, task) => this.fanOut.all(items, task).catch((error) => {
|
|
1285
|
+
throw firstItemError(error);
|
|
1030
1286
|
}),
|
|
1287
|
+
sendPhase: (messages, task, phase) => this.sendPhase(messages, task, phase, stopSignal),
|
|
1288
|
+
postToRelay: (send, sealed) => this.postToRelay(send, sealed, control),
|
|
1031
1289
|
}, actualGroupId, plaintextBytes, options);
|
|
1032
1290
|
}
|
|
1033
1291
|
async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp) {
|
|
@@ -1057,14 +1315,19 @@ export class SignalProtocolServiceCipher {
|
|
|
1057
1315
|
const manager = this.endorsementManagerResolver ? await this.endorsementManagerResolver() : this.endorsementManager;
|
|
1058
1316
|
if (!manager || recipientUserIds.length === 0)
|
|
1059
1317
|
return null;
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1318
|
+
// The device posts of a send run at the same time. The lock makes them
|
|
1319
|
+
// check and refresh the group's endorsements one at a time, so one
|
|
1320
|
+
// refresh serves them all. The lock is taken before a slot.
|
|
1321
|
+
await this.lock.acquire(`group-send-endorsements:${groupId}`, async () => {
|
|
1322
|
+
const { needsRefresh, reason } = await manager.shouldRefreshEndorsements(groupId, recipientUserIds);
|
|
1323
|
+
if (needsRefresh && this.endorsementRefresher) {
|
|
1324
|
+
await this.endorsementRefresher(groupId, recipientUserIds);
|
|
1325
|
+
this.logger.debug('Refreshed endorsements before durable group send', {
|
|
1326
|
+
category: 'E2EE',
|
|
1327
|
+
data: { groupId, reason },
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
});
|
|
1068
1331
|
const groupSecretParams = this.groupSecretParamsProvider
|
|
1069
1332
|
? await this.groupSecretParamsProvider(groupId)
|
|
1070
1333
|
: null;
|
|
@@ -1143,8 +1406,11 @@ export class SignalProtocolServiceCipher {
|
|
|
1143
1406
|
* | UNKNOWN | DISABLED | Confirmed doesn't work |
|
|
1144
1407
|
*
|
|
1145
1408
|
*/
|
|
1146
|
-
async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender) {
|
|
1409
|
+
async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender, control = {}) {
|
|
1147
1410
|
const effectiveClientMessageId = msg.clientMessageId ?? clientMessageId;
|
|
1411
|
+
// A fallback continues a post that started, so only the first request is
|
|
1412
|
+
// admitted.
|
|
1413
|
+
let identifiedControl = control;
|
|
1148
1414
|
if (preparedSealedSender && !this.relay.sendMultiRecipientUnidentified) {
|
|
1149
1415
|
if (preparedSealedSender.deliveryMode === 'required') {
|
|
1150
1416
|
throw new EncryptionError('Required sealed-sender relay capability is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: msg.recipientUserId });
|
|
@@ -1164,8 +1430,9 @@ export class SignalProtocolServiceCipher {
|
|
|
1164
1430
|
: undefined);
|
|
1165
1431
|
if (!prepared)
|
|
1166
1432
|
throw new Error('Missing sealed-sender delivery state');
|
|
1433
|
+
identifiedControl = { ...(control.stopSignal && { stopSignal: control.stopSignal }) };
|
|
1167
1434
|
try {
|
|
1168
|
-
const result = await this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId);
|
|
1435
|
+
const result = await this.postToRelay(() => this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, 'user-visible', [msg.recipientUserId], effectiveClientMessageId), true, control);
|
|
1169
1436
|
if (result.uuids404.length > 0) {
|
|
1170
1437
|
throw new SealedSenderRecipientRejectedError();
|
|
1171
1438
|
}
|
|
@@ -1180,27 +1447,33 @@ export class SignalProtocolServiceCipher {
|
|
|
1180
1447
|
}
|
|
1181
1448
|
// Restrict the cached mode after authorization fails.
|
|
1182
1449
|
try {
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1450
|
+
const contactProfileStateStore = this.contactProfileStateStore;
|
|
1451
|
+
if (contactProfileStateStore) {
|
|
1452
|
+
// The device posts of a send run at the same time. The lock
|
|
1453
|
+
// orders their steps, so two failures step down twice, as posts
|
|
1454
|
+
// in device order do.
|
|
1455
|
+
await this.lock.acquire(`unidentified-access-mode:${msg.recipientUserId}`, async () => {
|
|
1456
|
+
const currentMode = await contactProfileStateStore.getUnidentifiedAccessMode(msg.recipientUserId);
|
|
1457
|
+
let newMode;
|
|
1458
|
+
switch (currentMode) {
|
|
1459
|
+
case UnidentifiedAccessMode.UNRESTRICTED:
|
|
1460
|
+
newMode = UnidentifiedAccessMode.UNKNOWN;
|
|
1461
|
+
break;
|
|
1462
|
+
case UnidentifiedAccessMode.ENABLED:
|
|
1463
|
+
case UnidentifiedAccessMode.UNKNOWN:
|
|
1464
|
+
default:
|
|
1465
|
+
newMode = UnidentifiedAccessMode.DISABLED;
|
|
1466
|
+
break;
|
|
1467
|
+
}
|
|
1468
|
+
await contactProfileStateStore.updateUnidentifiedAccessMode(msg.recipientUserId, newMode);
|
|
1469
|
+
this.logger.info('Sealed sender auth failed, transitioned mode and falling back to identified delivery', {
|
|
1470
|
+
category: 'E2EE',
|
|
1471
|
+
data: {
|
|
1472
|
+
recipientUserId: msg.recipientUserId,
|
|
1473
|
+
previousMode: currentMode,
|
|
1474
|
+
newMode,
|
|
1475
|
+
},
|
|
1476
|
+
});
|
|
1204
1477
|
});
|
|
1205
1478
|
}
|
|
1206
1479
|
else {
|
|
@@ -1229,7 +1502,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1229
1502
|
}
|
|
1230
1503
|
}
|
|
1231
1504
|
// Identified sender path: standard relay send
|
|
1232
|
-
return this.relay.send({
|
|
1505
|
+
return this.postToRelay(() => this.relay.send({
|
|
1233
1506
|
targetUserId: msg.recipientUserId,
|
|
1234
1507
|
targetDeviceId: msg.recipientDeviceId,
|
|
1235
1508
|
senderUserId: this.userId,
|
|
@@ -1241,7 +1514,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1241
1514
|
clientMessageId: effectiveClientMessageId,
|
|
1242
1515
|
recipientRegistrationId,
|
|
1243
1516
|
contentHint,
|
|
1244
|
-
});
|
|
1517
|
+
}), false, identifiedControl);
|
|
1245
1518
|
}
|
|
1246
1519
|
/**
|
|
1247
1520
|
* Resolve the group roster to concrete devices via the relay.
|
|
@@ -1252,16 +1525,20 @@ export class SignalProtocolServiceCipher {
|
|
|
1252
1525
|
* map. A groupId → member lookup would hand the relay the social graph
|
|
1253
1526
|
* the zero-knowledge group design exists to hide.
|
|
1254
1527
|
*/
|
|
1255
|
-
async resolveGroupMemberDevices(groupId, options) {
|
|
1528
|
+
async resolveGroupMemberDevices(groupId, options, stopSignal) {
|
|
1256
1529
|
if (!options?.groupMemberUserIds?.length) {
|
|
1257
1530
|
throw new EncryptionError(`Group send for ${groupId} requires options.groupMemberUserIds. ` +
|
|
1258
1531
|
'The relay keeps no server-side membership map; resolve the roster ' +
|
|
1259
1532
|
'from local group state and pass the member user IDs.', EncryptionErrorCode.ENCRYPTION_FAILED, { groupId });
|
|
1260
1533
|
}
|
|
1261
|
-
const deviceResults = await
|
|
1534
|
+
const deviceResults = await this.fanOut
|
|
1535
|
+
.all(options.groupMemberUserIds, (userId) => this.fanOut.request(() => this.relay.getActiveDevices(userId), stopSignal), stopSignal)
|
|
1536
|
+
.catch((error) => {
|
|
1537
|
+
throw firstItemError(error);
|
|
1538
|
+
});
|
|
1262
1539
|
return deviceResults.flat();
|
|
1263
1540
|
}
|
|
1264
|
-
async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options, sessions) {
|
|
1541
|
+
async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options, sessions, readMembers, stopSignal) {
|
|
1265
1542
|
const existingKey = await this.storage.getSenderKey(actualGroupId, this.userId, this.deviceId);
|
|
1266
1543
|
if (!existingKey) {
|
|
1267
1544
|
throw new EncryptionError(`No sender key for group ${actualGroupId}. Call createGroupSenderKey() first to create and distribute the key.`, EncryptionErrorCode.SESSION_NOT_FOUND, {
|
|
@@ -1292,28 +1569,40 @@ export class SignalProtocolServiceCipher {
|
|
|
1292
1569
|
}
|
|
1293
1570
|
const preMessages = [];
|
|
1294
1571
|
if (this.relay) {
|
|
1295
|
-
const members = await
|
|
1572
|
+
const members = await readMembers();
|
|
1296
1573
|
const otherMembers = members.filter((member) => member.userId !== this.userId);
|
|
1297
1574
|
const recipientUserIds = [...new Set(otherMembers.map((member) => member.userId))];
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1575
|
+
const skdmBytes = this.contentAdapter
|
|
1576
|
+
? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
|
|
1577
|
+
: new TextEncoder().encode(JSON.stringify({
|
|
1578
|
+
senderKeyDistributionMessage: JSON.stringify({
|
|
1579
|
+
groupId: actualGroupId,
|
|
1580
|
+
...distributionMessage,
|
|
1581
|
+
}),
|
|
1582
|
+
}));
|
|
1583
|
+
// The recipients are prepared at the same time. The session work of one
|
|
1584
|
+
// recipient stays in turn, and its session setup reuses the devices that
|
|
1585
|
+
// this send read.
|
|
1586
|
+
const prepared = await this.fanOut
|
|
1587
|
+
.all(recipientUserIds, async (recipientUserId) => {
|
|
1588
|
+
await this.ensureSessionsForUser(recipientUserId, sessions, false, otherMembers.filter((member) => member.userId === recipientUserId));
|
|
1308
1589
|
const batch = await this.sesameManager.send(recipientUserId, skdmBytes, {
|
|
1309
1590
|
clientTimestamp: options.timestamp,
|
|
1310
1591
|
includeSyncMessages: false,
|
|
1311
1592
|
});
|
|
1593
|
+
const stored = [];
|
|
1312
1594
|
for (const message of batch.deviceMessages) {
|
|
1313
|
-
|
|
1314
|
-
stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
|
|
1315
|
-
preMessages.push(stored);
|
|
1595
|
+
stored.push(await this.prepareStoredDirectDeviceMessage(message, null));
|
|
1316
1596
|
}
|
|
1597
|
+
return stored;
|
|
1598
|
+
}, stopSignal)
|
|
1599
|
+
.catch((error) => {
|
|
1600
|
+
throw firstItemError(error);
|
|
1601
|
+
});
|
|
1602
|
+
// The index of each pre-message follows the recipient order.
|
|
1603
|
+
for (const stored of prepared.flat()) {
|
|
1604
|
+
stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
|
|
1605
|
+
preMessages.push(stored);
|
|
1317
1606
|
}
|
|
1318
1607
|
}
|
|
1319
1608
|
return {
|
|
@@ -1328,10 +1617,10 @@ export class SignalProtocolServiceCipher {
|
|
|
1328
1617
|
* Uses the multi-recipient sealed-sender transport when anonymous delivery
|
|
1329
1618
|
* is available, with exact per-device identified delivery otherwise.
|
|
1330
1619
|
*/
|
|
1331
|
-
async encryptToGroup(groupId, plaintextBytes, options, sessions) {
|
|
1620
|
+
async encryptToGroup(groupId, plaintextBytes, options, sessions, stopSignal) {
|
|
1332
1621
|
const actualGroupId = extractGroupId(groupId);
|
|
1333
1622
|
await this.groupSendBarrierChecker?.(actualGroupId);
|
|
1334
|
-
return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions);
|
|
1623
|
+
return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal);
|
|
1335
1624
|
}
|
|
1336
1625
|
/**
|
|
1337
1626
|
* Encrypt binary attachment with two-layer encryption
|