@open-e2ee/signal-protocol-sdk 0.4.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -5
- package/README.md +10 -7
- package/SECURITY.md +2 -2
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/device/README.md +7 -5
- package/dist/client/client.d.ts +3 -2
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +58 -25
- package/dist/client/client.js.map +1 -1
- package/dist/client/config.d.ts +46 -7
- package/dist/client/config.d.ts.map +1 -1
- package/dist/client/config.js +2 -2
- package/dist/client/config.js.map +1 -1
- package/dist/client/group-outbox.d.ts +38 -0
- package/dist/client/group-outbox.d.ts.map +1 -0
- package/dist/client/group-outbox.js +221 -0
- package/dist/client/group-outbox.js.map +1 -0
- package/dist/client/group-sealed-sender.d.ts +28 -0
- package/dist/client/group-sealed-sender.d.ts.map +1 -0
- package/dist/client/group-sealed-sender.js +74 -0
- package/dist/client/group-sealed-sender.js.map +1 -0
- package/dist/client/hosted-push.d.ts +77 -0
- package/dist/client/hosted-push.d.ts.map +1 -0
- package/dist/client/hosted-push.js +90 -0
- package/dist/client/hosted-push.js.map +1 -0
- package/dist/client/hosted.d.ts +207 -0
- package/dist/client/hosted.d.ts.map +1 -0
- package/dist/client/hosted.js +505 -0
- package/dist/client/hosted.js.map +1 -0
- package/dist/client/index.d.ts +4 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/relay-subscription.d.ts.map +1 -1
- package/dist/client/relay-subscription.js +34 -7
- package/dist/client/relay-subscription.js.map +1 -1
- package/dist/client/{sealed-sender-ops.d.ts → sealed-sender.d.ts} +39 -22
- package/dist/client/sealed-sender.d.ts.map +1 -0
- package/dist/client/sealed-sender.js +296 -0
- package/dist/client/sealed-sender.js.map +1 -0
- package/dist/client/signal-service-cipher.d.ts +23 -26
- package/dist/client/signal-service-cipher.d.ts.map +1 -1
- package/dist/client/signal-service-cipher.js +465 -706
- package/dist/client/signal-service-cipher.js.map +1 -1
- package/dist/client/types.d.ts +18 -3
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/types.js +6 -0
- package/dist/client/types.js.map +1 -1
- package/dist/device/index.d.ts +2 -2
- package/dist/device/index.d.ts.map +1 -1
- package/dist/device/index.js +1 -1
- package/dist/device/index.js.map +1 -1
- package/dist/device/transfer.d.ts +7 -43
- package/dist/device/transfer.d.ts.map +1 -1
- package/dist/device/transfer.js +31 -150
- package/dist/device/transfer.js.map +1 -1
- package/dist/device/types.d.ts +6 -47
- package/dist/device/types.d.ts.map +1 -1
- package/dist/device/types.js +1 -1
- package/dist/device/types.js.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/encoding/proto/pq-ratchet-serialize.js +1 -1
- package/dist/internal/encoding/proto/pq-ratchet-serialize.js.map +1 -1
- package/dist/internal/encoding/proto/primitives.js +1 -1
- package/dist/internal/encoding/proto/primitives.js.map +1 -1
- package/dist/internal/groups/manager.d.ts +3 -3
- package/dist/internal/groups/manager.d.ts.map +1 -1
- package/dist/internal/groups/manager.js +5 -4
- package/dist/internal/groups/manager.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/certificate.d.ts +10 -4
- package/dist/internal/protocol/sealed-sender/certificate.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/certificate.js +64 -7
- package/dist/internal/protocol/sealed-sender/certificate.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/decryption.d.ts +34 -47
- package/dist/internal/protocol/sealed-sender/decryption.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/decryption.js +95 -182
- package/dist/internal/protocol/sealed-sender/decryption.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/encryption.d.ts +49 -64
- package/dist/internal/protocol/sealed-sender/encryption.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/encryption.js +120 -123
- package/dist/internal/protocol/sealed-sender/encryption.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/index.d.ts +5 -7
- package/dist/internal/protocol/sealed-sender/index.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/index.js +4 -12
- package/dist/internal/protocol/sealed-sender/index.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/{v2-helpers.d.ts → multi-recipient-crypto.d.ts} +1 -1
- package/dist/internal/protocol/sealed-sender/multi-recipient-crypto.d.ts.map +1 -0
- package/dist/internal/protocol/sealed-sender/{v2-helpers.js → multi-recipient-crypto.js} +1 -1
- package/dist/internal/protocol/sealed-sender/multi-recipient-crypto.js.map +1 -0
- package/dist/internal/protocol/sealed-sender/{v2-binary.d.ts → multi-recipient-message.d.ts} +3 -2
- package/dist/internal/protocol/sealed-sender/multi-recipient-message.d.ts.map +1 -0
- package/dist/internal/protocol/sealed-sender/{v2-binary.js → multi-recipient-message.js} +16 -8
- package/dist/internal/protocol/sealed-sender/multi-recipient-message.js.map +1 -0
- package/dist/internal/protocol/sealed-sender/proto/index.d.ts +3 -0
- package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/proto/index.js +25 -2
- package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/trust-root.d.ts +11 -1
- package/dist/internal/protocol/sealed-sender/trust-root.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/trust-root.js +13 -1
- package/dist/internal/protocol/sealed-sender/trust-root.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/types.d.ts +20 -135
- package/dist/internal/protocol/sealed-sender/types.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/types.js +15 -6
- package/dist/internal/protocol/sealed-sender/types.js.map +1 -1
- package/dist/internal/protocol/sender-keys/manager.d.ts +22 -1
- package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
- package/dist/internal/protocol/sender-keys/manager.js +39 -4
- package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
- package/dist/internal/protocol/spqr/braid-serialize.js +1 -1
- package/dist/internal/protocol/spqr/braid-serialize.js.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js +4 -4
- package/dist/internal/protocol/spqr/ml-kem-braid/state-machine.js.map +1 -1
- package/dist/internal/protocol/zk/groups/index.d.ts +1 -1
- package/dist/internal/protocol/zk/groups/index.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/index.js +1 -1
- package/dist/internal/protocol/zk/groups/index.js.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts +37 -12
- package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-credential.js +104 -31
- package/dist/internal/protocol/zk/groups/profile-key-credential.js.map +1 -1
- package/dist/local/store/expo/adapter.d.ts +1 -0
- package/dist/local/store/expo/adapter.d.ts.map +1 -1
- package/dist/local/store/expo/adapter.js +3 -0
- package/dist/local/store/expo/adapter.js.map +1 -1
- package/dist/local/store/expo/key-storage.d.ts +1 -0
- package/dist/local/store/expo/key-storage.d.ts.map +1 -1
- package/dist/local/store/expo/key-storage.js +4 -0
- package/dist/local/store/expo/key-storage.js.map +1 -1
- package/dist/local/store/memory/adapter.d.ts +1 -0
- package/dist/local/store/memory/adapter.d.ts.map +1 -1
- package/dist/local/store/memory/adapter.js +4 -0
- package/dist/local/store/memory/adapter.js.map +1 -1
- package/dist/local/store/node/adapter.d.ts +1 -0
- package/dist/local/store/node/adapter.d.ts.map +1 -1
- package/dist/local/store/node/adapter.js +3 -0
- package/dist/local/store/node/adapter.js.map +1 -1
- package/dist/local/store/node/database.d.ts +1 -0
- package/dist/local/store/node/database.d.ts.map +1 -1
- package/dist/local/store/node/database.js +5 -0
- package/dist/local/store/node/database.js.map +1 -1
- package/dist/local/store/react-native/adapter.d.ts +1 -0
- package/dist/local/store/react-native/adapter.d.ts.map +1 -1
- package/dist/local/store/react-native/adapter.js +4 -0
- package/dist/local/store/react-native/adapter.js.map +1 -1
- package/dist/local/store/react-native/reference-backend.js +1 -1
- package/dist/local/store/react-native/reference-backend.js.map +1 -1
- package/dist/local/store/reliability.d.ts +63 -0
- package/dist/local/store/reliability.d.ts.map +1 -0
- package/dist/local/store/reliability.js +219 -0
- package/dist/local/store/reliability.js.map +1 -0
- package/dist/local/store/web/adapter.d.ts +1 -0
- package/dist/local/store/web/adapter.d.ts.map +1 -1
- package/dist/local/store/web/adapter.js +5 -0
- package/dist/local/store/web/adapter.js.map +1 -1
- package/dist/remote/relay/convex/backend.d.ts +4 -14
- package/dist/remote/relay/convex/backend.d.ts.map +1 -1
- package/dist/remote/relay/convex/backend.js +11 -20
- package/dist/remote/relay/convex/backend.js.map +1 -1
- package/dist/remote/relay/convex/component/_generated/component.d.ts +7 -14
- package/dist/remote/relay/convex/component/_generated/component.d.ts.map +1 -1
- package/dist/remote/relay/convex/component/certificates.d.ts.map +1 -1
- package/dist/remote/relay/convex/component/certificates.js +14 -5
- package/dist/remote/relay/convex/component/certificates.js.map +1 -1
- package/dist/remote/relay/convex/component/messages.d.ts +0 -13
- package/dist/remote/relay/convex/component/messages.d.ts.map +1 -1
- package/dist/remote/relay/convex/component/messages.js +13 -47
- package/dist/remote/relay/convex/component/messages.js.map +1 -1
- package/dist/remote/relay/convex/component/schema.d.ts +3 -1
- package/dist/remote/relay/convex/component/schema.js +1 -0
- package/dist/remote/relay/convex/component/schema.js.map +1 -1
- package/dist/remote/relay/convex/component/zkAuth.d.ts +7 -1
- package/dist/remote/relay/convex/component/zkAuth.d.ts.map +1 -1
- package/dist/remote/relay/convex/component/zkAuth.js +29 -14
- package/dist/remote/relay/convex/component/zkAuth.js.map +1 -1
- package/dist/remote/relay/convex/relay.d.ts +2 -5
- package/dist/remote/relay/convex/relay.d.ts.map +1 -1
- package/dist/remote/relay/convex/relay.js +17 -47
- package/dist/remote/relay/convex/relay.js.map +1 -1
- package/dist/remote/relay/memory/adapter.d.ts +4 -10
- package/dist/remote/relay/memory/adapter.d.ts.map +1 -1
- package/dist/remote/relay/memory/adapter.js +31 -34
- package/dist/remote/relay/memory/adapter.js.map +1 -1
- package/dist/remote/relay/types.d.ts +6 -19
- package/dist/remote/relay/types.d.ts.map +1 -1
- package/dist/types/api.d.ts +2 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/errors.d.ts +3 -1
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +4 -2
- package/dist/types/errors.js.map +1 -1
- package/dist/types/protocol-config.d.ts +1 -1
- package/dist/username/link.d.ts.map +1 -1
- package/dist/username/link.js +1 -1
- package/dist/username/link.js.map +1 -1
- package/docs/ASSURANCE.md +5 -5
- package/docs/DEVIATIONS.md +32 -61
- package/docs/GETTING_STARTED.md +7 -0
- package/docs/SECURITY.md +6 -0
- package/package.json +1 -1
- package/remote/relay/convex/component/README.md +20 -14
- package/scripts/oe-groups.mjs +5 -1
- package/dist/client/sealed-sender-ops.d.ts.map +0 -1
- package/dist/client/sealed-sender-ops.js +0 -203
- package/dist/client/sealed-sender-ops.js.map +0 -1
- package/dist/internal/protocol/sealed-sender/decryption-v2.d.ts +0 -46
- package/dist/internal/protocol/sealed-sender/decryption-v2.d.ts.map +0 -1
- package/dist/internal/protocol/sealed-sender/decryption-v2.js +0 -198
- package/dist/internal/protocol/sealed-sender/decryption-v2.js.map +0 -1
- package/dist/internal/protocol/sealed-sender/encryption-v2.d.ts +0 -56
- package/dist/internal/protocol/sealed-sender/encryption-v2.d.ts.map +0 -1
- package/dist/internal/protocol/sealed-sender/encryption-v2.js +0 -163
- package/dist/internal/protocol/sealed-sender/encryption-v2.js.map +0 -1
- package/dist/internal/protocol/sealed-sender/v2-binary.d.ts.map +0 -1
- package/dist/internal/protocol/sealed-sender/v2-binary.js.map +0 -1
- package/dist/internal/protocol/sealed-sender/v2-helpers.d.ts.map +0 -1
- package/dist/internal/protocol/sealed-sender/v2-helpers.js.map +0 -1
|
@@ -20,10 +20,13 @@ import { recordServerClockSample } from '../server-clock.js';
|
|
|
20
20
|
import { ProtocolAddress } from '../types/address.js';
|
|
21
21
|
import { defaultSignalProtocolLogger } from '../logger.js';
|
|
22
22
|
import { isGroupId, extractGroupId } from '../internal/groups/index.js';
|
|
23
|
-
import { SealedSenderContentType } from '../internal/protocol/sealed-sender/types.js';
|
|
24
23
|
import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
|
|
25
24
|
import * as CryptoUtils from '../internal/crypto/index.js';
|
|
25
|
+
import { completeOutgoingMessageIntent, getOutgoingMessageIntent, replaceOutgoingDirectDeviceMessage, storeOutgoingMessageIntent, withOutgoingMessageIntentLock, } from '../local/store/reliability.js';
|
|
26
26
|
import { withRetry } from '../utils/retry.js';
|
|
27
|
+
import { prepareGroupSharedMessage } from './group-sealed-sender.js';
|
|
28
|
+
import { sendGroupWithExactOutbox } from './group-outbox.js';
|
|
29
|
+
import { resolveSealedSenderContext as resolveSealedSenderSendContext, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, } from './sealed-sender.js';
|
|
27
30
|
import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
|
|
28
31
|
import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
|
|
29
32
|
export function sortEnvelopesForDecryption(envelopes) {
|
|
@@ -61,6 +64,26 @@ function getEnvelopeMessageType(ciphertext) {
|
|
|
61
64
|
}
|
|
62
65
|
return 'ciphertext';
|
|
63
66
|
}
|
|
67
|
+
function attachClientMessageId(error, clientMessageId) {
|
|
68
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
69
|
+
try {
|
|
70
|
+
Object.defineProperty(normalized, 'clientMessageId', {
|
|
71
|
+
configurable: true,
|
|
72
|
+
enumerable: true,
|
|
73
|
+
value: clientMessageId,
|
|
74
|
+
});
|
|
75
|
+
return normalized;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
const wrapped = new Error(normalized.message);
|
|
79
|
+
wrapped.name = normalized.name;
|
|
80
|
+
Object.defineProperty(wrapped, 'clientMessageId', {
|
|
81
|
+
enumerable: true,
|
|
82
|
+
value: clientMessageId,
|
|
83
|
+
});
|
|
84
|
+
return wrapped;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
64
87
|
/**
|
|
65
88
|
* Detect if an error is a stale session error from the server
|
|
66
89
|
*
|
|
@@ -83,27 +106,14 @@ function isStaleSessionError(error) {
|
|
|
83
106
|
}
|
|
84
107
|
return false;
|
|
85
108
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
* The matcher remains for relay implementations that reject the whole send
|
|
92
|
-
* with a mismatched-device error instead.
|
|
93
|
-
*/
|
|
94
|
-
function isMismatchedDevicesError(message) {
|
|
95
|
-
return message.includes('MISMATCHED_DEVICES');
|
|
109
|
+
class SealedSenderRecipientRejectedError extends Error {
|
|
110
|
+
constructor() {
|
|
111
|
+
super('Sealed sender recipient was not accepted');
|
|
112
|
+
this.name = 'SealedSenderRecipientRejectedError';
|
|
113
|
+
}
|
|
96
114
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
*
|
|
100
|
-
* The Convex component throws STALE_DEVICE only on the single-recipient
|
|
101
|
-
* `send` path (structured `data.code`, see `isStaleSessionError`). Its
|
|
102
|
-
* multi-recipient path reports mismatches via `uuids404` instead. The
|
|
103
|
-
* matcher remains for relay implementations that reject the whole send.
|
|
104
|
-
*/
|
|
105
|
-
function isStaleSessionV2Error(message) {
|
|
106
|
-
return message.includes('STALE_DEVICE');
|
|
115
|
+
function isConclusiveDeviceRejection(error) {
|
|
116
|
+
return isStaleSessionError(error) || error instanceof SealedSenderRecipientRejectedError;
|
|
107
117
|
}
|
|
108
118
|
/**
|
|
109
119
|
* SignalProtocolServiceCipher - Routes encryption and decryption to appropriate ciphers
|
|
@@ -139,6 +149,8 @@ export class SignalProtocolServiceCipher {
|
|
|
139
149
|
sessionEstablisher;
|
|
140
150
|
staleSessionRefresher;
|
|
141
151
|
sealedSenderProvider;
|
|
152
|
+
sealedSenderDeliveryMode = 'preferred';
|
|
153
|
+
sealedSenderIdentifiedFallback;
|
|
142
154
|
contactProfileStateStore;
|
|
143
155
|
endorsementManager;
|
|
144
156
|
endorsementRefresher;
|
|
@@ -197,10 +209,6 @@ export class SignalProtocolServiceCipher {
|
|
|
197
209
|
});
|
|
198
210
|
}
|
|
199
211
|
}
|
|
200
|
-
async sendSyncTranscriptToLocalOtherDevices(conversationId, plaintextBytes, timestamp, recipientUserId) {
|
|
201
|
-
const transcriptBytes = this.buildSentSyncTranscript(conversationId, plaintextBytes, timestamp, recipientUserId);
|
|
202
|
-
await this.sendSyncPayloadToLocalOtherDevices(transcriptBytes, timestamp);
|
|
203
|
-
}
|
|
204
212
|
async sendSyncPayloadToLocalOtherDevices(payloadBytes, timestamp) {
|
|
205
213
|
if (!this.relay) {
|
|
206
214
|
return;
|
|
@@ -279,6 +287,35 @@ export class SignalProtocolServiceCipher {
|
|
|
279
287
|
setSealedSenderProvider(provider) {
|
|
280
288
|
this.sealedSenderProvider = provider;
|
|
281
289
|
}
|
|
290
|
+
setSealedSenderDeliveryMode(mode) {
|
|
291
|
+
this.sealedSenderDeliveryMode = mode;
|
|
292
|
+
}
|
|
293
|
+
setSealedSenderIdentifiedFallback(callback) {
|
|
294
|
+
this.sealedSenderIdentifiedFallback = callback;
|
|
295
|
+
}
|
|
296
|
+
async reportIdentifiedFallback(recipientUserId) {
|
|
297
|
+
try {
|
|
298
|
+
await this.sealedSenderIdentifiedFallback?.({
|
|
299
|
+
recipientUserId,
|
|
300
|
+
reason: 'authorization-rejected',
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
catch (fallbackHookError) {
|
|
304
|
+
this.logger.warn('Sealed sender identified-fallback hook failed', {
|
|
305
|
+
category: 'E2EE',
|
|
306
|
+
data: {
|
|
307
|
+
recipientUserId,
|
|
308
|
+
error: fallbackHookError.message,
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
useIdentifiedDeliveryOrThrow(recipientUserId, reason) {
|
|
314
|
+
if (this.sealedSenderDeliveryMode === 'required') {
|
|
315
|
+
throw new EncryptionError(`Sealed sender is required but unavailable: ${reason}`, EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId, operation: 'resolveSealedSenderContext', reason });
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
282
319
|
setContactProfileStateStore(store) {
|
|
283
320
|
this.contactProfileStateStore = store;
|
|
284
321
|
}
|
|
@@ -341,7 +378,7 @@ export class SignalProtocolServiceCipher {
|
|
|
341
378
|
if (!sealedSenderConfig || sealedSenderConfig.trustRoots.length === 0) {
|
|
342
379
|
throw new EncryptionError('Received sealed sender message but no trust roots configured', EncryptionErrorCode.INVALID_CIPHERTEXT, { messageType: envelope.messageType });
|
|
343
380
|
}
|
|
344
|
-
const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender
|
|
381
|
+
const { unsealMessage, reconstructEnvelope } = await import('./sealed-sender.js');
|
|
345
382
|
// Get recipient's X25519 identity private key for unsealing
|
|
346
383
|
const identityKeyPair = await this.storage.getIdentityKey();
|
|
347
384
|
if (!identityKeyPair) {
|
|
@@ -352,7 +389,7 @@ export class SignalProtocolServiceCipher {
|
|
|
352
389
|
const ciphertextStr = typeof envelope.ciphertext === 'string'
|
|
353
390
|
? envelope.ciphertext
|
|
354
391
|
: CryptoUtils.bytesToBase64(envelope.ciphertext);
|
|
355
|
-
const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, this.logger);
|
|
392
|
+
const unsealed = await unsealMessage(ciphertextStr, recipientPrivateKeyBytes, this.userId, this.deviceId, sealedSenderConfig, envelope.serverTimestamp, this.logger);
|
|
356
393
|
// Reconstruct envelope with revealed sender identity
|
|
357
394
|
const innerEnvelope = reconstructEnvelope(envelope, unsealed);
|
|
358
395
|
// Recursively decrypt the inner message (now a standard ciphertext)
|
|
@@ -458,19 +495,26 @@ export class SignalProtocolServiceCipher {
|
|
|
458
495
|
* @see https://signal.org/docs/specifications/sesame/
|
|
459
496
|
*/
|
|
460
497
|
async encrypt(recipientId, content, options) {
|
|
498
|
+
const clientMessageId = options?.clientMessageId ?? (await CryptoUtils.generateUuidV4());
|
|
499
|
+
const durableOptions = { ...options, clientMessageId };
|
|
461
500
|
const lockKey = `encrypt:${recipientId}`;
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
501
|
+
try {
|
|
502
|
+
return await this.lock.acquire(lockKey, async () => {
|
|
503
|
+
// 1. Route binary file data (Uint8Array with isBinary flag) to blob encryption
|
|
504
|
+
if (durableOptions.isBinary) {
|
|
505
|
+
return this.encryptBinaryAttachment(recipientId, content, durableOptions);
|
|
506
|
+
}
|
|
507
|
+
// 2. Detect recipient type (group vs user)
|
|
508
|
+
if (isGroupId(recipientId)) {
|
|
509
|
+
return this.encryptToGroup(recipientId, content, durableOptions);
|
|
510
|
+
}
|
|
511
|
+
// 3. Send to user (existing SESAME path)
|
|
512
|
+
return this.encryptToUser(recipientId, content, durableOptions);
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
throw attachClientMessageId(error, clientMessageId);
|
|
517
|
+
}
|
|
474
518
|
}
|
|
475
519
|
/**
|
|
476
520
|
* Encrypt and upload attachment data without sending a standalone message.
|
|
@@ -624,8 +668,7 @@ export class SignalProtocolServiceCipher {
|
|
|
624
668
|
// Use retry logic for transient network failures
|
|
625
669
|
result = await withRetry(async () => {
|
|
626
670
|
const attempt = await this.sessionEstablisher(recipientUserId);
|
|
627
|
-
if (attempt.establishedDevices.length === 0 &&
|
|
628
|
-
attempt.failedDeviceErrors.length > 0) {
|
|
671
|
+
if (attempt.establishedDevices.length === 0 && attempt.failedDeviceErrors.length > 0) {
|
|
629
672
|
throw attempt.failedDeviceErrors[0].error;
|
|
630
673
|
}
|
|
631
674
|
return attempt;
|
|
@@ -663,23 +706,49 @@ export class SignalProtocolServiceCipher {
|
|
|
663
706
|
* Encrypt to a single user (all their devices) via SESAME
|
|
664
707
|
*/
|
|
665
708
|
async encryptToUser(recipientUserId, plaintextBytes, options) {
|
|
666
|
-
|
|
709
|
+
return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options);
|
|
710
|
+
}
|
|
711
|
+
async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options) {
|
|
712
|
+
return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options));
|
|
713
|
+
}
|
|
714
|
+
async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options) {
|
|
715
|
+
const plaintextDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(plaintextBytes));
|
|
716
|
+
const existing = await getOutgoingMessageIntent(this.storage, options.clientMessageId);
|
|
717
|
+
if (existing) {
|
|
718
|
+
if (existing.recipientId !== recipientUserId ||
|
|
719
|
+
existing.plaintextDigest !== plaintextDigest ||
|
|
720
|
+
(options.timestamp !== undefined && existing.clientTimestamp !== options.timestamp) ||
|
|
721
|
+
existing.contentHint !== options.contentHint) {
|
|
722
|
+
throw new Error('A clientMessageId cannot identify two different logical sends');
|
|
723
|
+
}
|
|
724
|
+
if (existing.result)
|
|
725
|
+
return existing.result;
|
|
726
|
+
return this.sendStoredDirectIntent(existing, plaintextBytes);
|
|
727
|
+
}
|
|
667
728
|
await this.ensureSessionsForUser(recipientUserId);
|
|
668
|
-
|
|
729
|
+
const sealedSender = this.relay ? await this.resolveSealedSenderContext(recipientUserId) : null;
|
|
730
|
+
const directSealedSender = sealedSender && this.relay?.sendMultiRecipientUnidentified ? sealedSender : null;
|
|
731
|
+
const transportMode = directSealedSender
|
|
732
|
+
? directSealedSender.config.deliveryMode === 'required'
|
|
733
|
+
? 'sealed_sender_required'
|
|
734
|
+
: 'sealed_sender_preferred'
|
|
735
|
+
: 'identified';
|
|
736
|
+
if (directSealedSender && directSealedSender.auth.type !== 'accessKey') {
|
|
737
|
+
throw new Error('Direct sealed-sender delivery requires access-key authorization');
|
|
738
|
+
}
|
|
739
|
+
const sealedSenderAuth = directSealedSender?.auth.type === 'accessKey' ? { ...directSealedSender.auth } : undefined;
|
|
740
|
+
const clientTimestamp = options.timestamp ?? Date.now();
|
|
741
|
+
const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
|
|
669
742
|
let batch;
|
|
670
743
|
try {
|
|
671
|
-
const clientTimestamp = options?.timestamp ?? Date.now();
|
|
672
|
-
const syncPlaintext = this.buildSentSyncTranscript(this.getDirectConversationId(recipientUserId), plaintextBytes, clientTimestamp, recipientUserId);
|
|
673
744
|
batch = await this.sesameManager.send(recipientUserId, plaintextBytes, {
|
|
674
745
|
clientTimestamp,
|
|
675
746
|
syncPlaintext,
|
|
676
747
|
});
|
|
677
748
|
}
|
|
678
749
|
catch (error) {
|
|
679
|
-
|
|
680
|
-
if (error instanceof EncryptionError) {
|
|
750
|
+
if (error instanceof EncryptionError)
|
|
681
751
|
throw error;
|
|
682
|
-
}
|
|
683
752
|
throw new EncryptionError('Failed to encrypt message for user', EncryptionErrorCode.ENCRYPTION_FAILED, { originalError: error, recipientUserId });
|
|
684
753
|
}
|
|
685
754
|
this.logger.debug('Message encrypted for user devices', {
|
|
@@ -690,97 +759,260 @@ export class SignalProtocolServiceCipher {
|
|
|
690
759
|
syncCount: batch.syncMessages.length,
|
|
691
760
|
},
|
|
692
761
|
});
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
762
|
+
const deviceMessages = await Promise.all(batch.deviceMessages.map((message) => this.prepareStoredDirectDeviceMessage(message, directSealedSender)));
|
|
763
|
+
const syncMessages = batch.syncMessages.map((msg, index) => ({
|
|
764
|
+
recipientUserId: msg.recipientUserId,
|
|
765
|
+
recipientDeviceId: msg.recipientDeviceId,
|
|
766
|
+
timestamp: msg.timestamp,
|
|
767
|
+
clientMessageId: `${options.clientMessageId}:sync:${index}`,
|
|
768
|
+
ciphertext: typeof msg.ciphertext === 'string'
|
|
769
|
+
? msg.ciphertext
|
|
770
|
+
: CryptoUtils.bytesToBase64(msg.ciphertext),
|
|
771
|
+
messageType: getEnvelopeMessageType(msg.ciphertext),
|
|
772
|
+
}));
|
|
773
|
+
const intent = {
|
|
774
|
+
kind: 'direct',
|
|
775
|
+
clientMessageId: options.clientMessageId,
|
|
776
|
+
recipientId: recipientUserId,
|
|
777
|
+
plaintextDigest,
|
|
778
|
+
clientTimestamp,
|
|
779
|
+
createdAt: Date.now(),
|
|
780
|
+
transportMode,
|
|
781
|
+
...(sealedSenderAuth && { sealedSenderAuth }),
|
|
782
|
+
...(options.contentHint !== undefined && {
|
|
783
|
+
contentHint: options.contentHint,
|
|
784
|
+
}),
|
|
785
|
+
deviceMessages,
|
|
786
|
+
syncMessages,
|
|
787
|
+
};
|
|
788
|
+
await storeOutgoingMessageIntent(this.storage, intent);
|
|
789
|
+
return this.sendStoredDirectIntent(intent, plaintextBytes);
|
|
790
|
+
}
|
|
791
|
+
async prepareStoredDirectDeviceMessage(message, sealedSender) {
|
|
792
|
+
const messageType = getEnvelopeMessageType(message.ciphertext);
|
|
793
|
+
const session = messageType === 'prekey_bundle'
|
|
794
|
+
? await this.sesameManager.getSession(message.recipientUserId, message.recipientDeviceId)
|
|
795
|
+
: null;
|
|
796
|
+
const storedMessage = {
|
|
797
|
+
recipientUserId: message.recipientUserId,
|
|
798
|
+
recipientDeviceId: message.recipientDeviceId,
|
|
799
|
+
timestamp: message.timestamp,
|
|
800
|
+
ciphertext: typeof message.ciphertext === 'string'
|
|
801
|
+
? message.ciphertext
|
|
802
|
+
: CryptoUtils.bytesToBase64(message.ciphertext),
|
|
803
|
+
messageType,
|
|
804
|
+
...(session?.currentSession?.remoteRegistrationId !== undefined && {
|
|
805
|
+
recipientRegistrationId: session.currentSession.remoteRegistrationId,
|
|
806
|
+
}),
|
|
807
|
+
};
|
|
808
|
+
if (sealedSender) {
|
|
809
|
+
storedMessage.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(storedMessage, storedMessage.ciphertext, storedMessage.messageType, storedMessage.recipientRegistrationId, sealedSender);
|
|
810
|
+
}
|
|
811
|
+
return storedMessage;
|
|
812
|
+
}
|
|
813
|
+
async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes) {
|
|
814
|
+
if (!this.staleSessionRefresher)
|
|
815
|
+
throw new Error('Stale-session refresh is not configured');
|
|
816
|
+
const refreshed = await this.staleSessionRefresher(rejected.recipientUserId, rejected.recipientDeviceId);
|
|
817
|
+
if (!refreshed) {
|
|
818
|
+
throw new EncryptionError('Failed to refresh a rejected recipient device', EncryptionErrorCode.SESSION_ESTABLISHMENT_FAILED, { recipientUserId: rejected.recipientUserId });
|
|
819
|
+
}
|
|
820
|
+
const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
|
|
821
|
+
let sealedSender = null;
|
|
822
|
+
if (intent.transportMode !== 'identified') {
|
|
823
|
+
sealedSender = await this.resolveSealedSenderContext(rejected.recipientUserId);
|
|
824
|
+
if (!sealedSender || sealedSender.auth.type !== 'accessKey') {
|
|
825
|
+
throw new Error('Cannot rebuild a sealed-sender transmission after session refresh');
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, sealedSender);
|
|
829
|
+
await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
|
|
830
|
+
return replacement;
|
|
831
|
+
}
|
|
832
|
+
async sendStoredDirectDeviceMessage(intent, message) {
|
|
833
|
+
if (intent.transportMode !== 'identified' &&
|
|
834
|
+
(!message.sealedSenderMessage || !intent.sealedSenderAuth)) {
|
|
835
|
+
throw new Error('Corrupt sealed-sender outbox intent');
|
|
836
|
+
}
|
|
837
|
+
return intent.transportMode === 'identified'
|
|
838
|
+
? this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId)
|
|
839
|
+
: this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, intent.contentHint, intent.clientMessageId, {
|
|
840
|
+
sentMessageBase64: message.sealedSenderMessage,
|
|
841
|
+
auth: intent.sealedSenderAuth,
|
|
842
|
+
deliveryMode: intent.transportMode === 'sealed_sender_required' ? 'required' : 'preferred',
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
async sendStoredDirectIntent(intent, plaintextBytes) {
|
|
846
|
+
if (intent.kind !== 'direct')
|
|
847
|
+
throw new Error('Expected a direct outbox intent');
|
|
848
|
+
if (!this.relay) {
|
|
849
|
+
const result = {
|
|
850
|
+
clientMessageId: intent.clientMessageId,
|
|
851
|
+
messageId: `local-${intent.clientTimestamp}`,
|
|
852
|
+
timestamp: intent.clientTimestamp,
|
|
853
|
+
recipientDeviceCount: intent.deviceMessages.length,
|
|
854
|
+
};
|
|
855
|
+
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
|
|
856
|
+
return result;
|
|
857
|
+
}
|
|
858
|
+
let messageId = `local-${intent.clientTimestamp}`;
|
|
859
|
+
let timestamp = intent.clientTimestamp;
|
|
860
|
+
for (const msg of intent.deviceMessages) {
|
|
861
|
+
let result;
|
|
862
|
+
try {
|
|
863
|
+
result = await this.sendStoredDirectDeviceMessage(intent, msg);
|
|
864
|
+
}
|
|
865
|
+
catch (error) {
|
|
866
|
+
if (!isConclusiveDeviceRejection(error))
|
|
774
867
|
throw error;
|
|
775
|
-
|
|
868
|
+
const replacement = await this.repairRejectedDirectDeviceMessage(intent, msg, plaintextBytes);
|
|
869
|
+
result = await this.sendStoredDirectDeviceMessage(intent, replacement);
|
|
870
|
+
}
|
|
871
|
+
if (messageId.startsWith('local-')) {
|
|
872
|
+
messageId = result.messageId;
|
|
873
|
+
timestamp = result.serverTimestamp;
|
|
776
874
|
}
|
|
777
|
-
await this.uploadSyncMessages(batch.syncMessages);
|
|
778
875
|
}
|
|
779
|
-
|
|
876
|
+
for (const msg of intent.syncMessages) {
|
|
877
|
+
await this.relay.send({
|
|
878
|
+
targetUserId: msg.recipientUserId,
|
|
879
|
+
targetDeviceId: msg.recipientDeviceId,
|
|
880
|
+
senderUserId: this.userId,
|
|
881
|
+
senderDeviceId: this.deviceId,
|
|
882
|
+
ciphertext: msg.ciphertext,
|
|
883
|
+
messageType: msg.messageType,
|
|
884
|
+
timestamp: msg.timestamp,
|
|
885
|
+
clientMessageId: msg.clientMessageId,
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
const result = {
|
|
889
|
+
clientMessageId: intent.clientMessageId,
|
|
780
890
|
messageId,
|
|
781
891
|
timestamp,
|
|
782
|
-
recipientDeviceCount:
|
|
892
|
+
recipientDeviceCount: intent.deviceMessages.length,
|
|
783
893
|
};
|
|
894
|
+
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result);
|
|
895
|
+
return result;
|
|
896
|
+
}
|
|
897
|
+
async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options) {
|
|
898
|
+
return sendGroupWithExactOutbox({
|
|
899
|
+
storage: this.storage,
|
|
900
|
+
...(this.relay && { relay: this.relay }),
|
|
901
|
+
senderUserId: this.userId,
|
|
902
|
+
senderDeviceId: this.deviceId,
|
|
903
|
+
deliveryMode: this.sealedSenderDeliveryMode,
|
|
904
|
+
preparePayload: async (groupId, bytes, sendOptions) => {
|
|
905
|
+
const prepared = await this.prepareGroupSenderKeyPayload(groupId, bytes, sendOptions);
|
|
906
|
+
return {
|
|
907
|
+
ciphertext: CryptoUtils.bytesToBase64(prepared.ciphertext),
|
|
908
|
+
preMessages: prepared.preMessages,
|
|
909
|
+
...(prepared.senderKeyDistributionId && {
|
|
910
|
+
senderKeyDistributionId: prepared.senderKeyDistributionId,
|
|
911
|
+
}),
|
|
912
|
+
};
|
|
913
|
+
},
|
|
914
|
+
confirmSenderKeyDistributionSent: (groupId, senderKeyId) => this.senderKeyManager.confirmSenderKeyDistributionSent(groupId, this.userId, this.deviceId, senderKeyId),
|
|
915
|
+
resolveMemberDevices: (groupId, sendOptions) => this.resolveGroupMemberDevices(groupId, sendOptions),
|
|
916
|
+
prepareSharedMessage: async (groupId, members, ciphertext) => {
|
|
917
|
+
if (members.length === 0 ||
|
|
918
|
+
this.sealedSenderDeliveryMode === 'disabled' ||
|
|
919
|
+
!this.sealedSenderProvider ||
|
|
920
|
+
!this.endorsementManager ||
|
|
921
|
+
!this.relay?.sendMultiRecipientUnidentified) {
|
|
922
|
+
return undefined;
|
|
923
|
+
}
|
|
924
|
+
const prepared = await prepareGroupSharedMessage({
|
|
925
|
+
storage: this.storage,
|
|
926
|
+
senderKeys: await this.sealedSenderProvider(),
|
|
927
|
+
members,
|
|
928
|
+
encryptedMessageBase64: ciphertext,
|
|
929
|
+
});
|
|
930
|
+
return prepared
|
|
931
|
+
? {
|
|
932
|
+
groupId,
|
|
933
|
+
sentMessageBase64: prepared.sentMessageBase64,
|
|
934
|
+
recipientUserIds: prepared.recipientUserIds,
|
|
935
|
+
deliveryMode: this.sealedSenderDeliveryMode === 'required' ? 'required' : 'preferred',
|
|
936
|
+
}
|
|
937
|
+
: undefined;
|
|
938
|
+
},
|
|
939
|
+
prepareDeviceMessage: (member, groupId, ciphertext, timestamp) => this.prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp),
|
|
940
|
+
prepareSyncMessages: async (groupId, bytes, timestamp, clientMessageId) => {
|
|
941
|
+
if (!this.relay)
|
|
942
|
+
return [];
|
|
943
|
+
const syncPayload = this.buildSentSyncTranscript(groupId, bytes, timestamp);
|
|
944
|
+
const prepared = await this.sesameManager.sendToLocalOtherDevices(syncPayload, {
|
|
945
|
+
clientTimestamp: timestamp,
|
|
946
|
+
includeSyncMessages: false,
|
|
947
|
+
});
|
|
948
|
+
return prepared.map((message, index) => ({
|
|
949
|
+
recipientUserId: message.recipientUserId,
|
|
950
|
+
recipientDeviceId: message.recipientDeviceId,
|
|
951
|
+
timestamp: message.timestamp,
|
|
952
|
+
clientMessageId: `${clientMessageId}:sync:${index}`,
|
|
953
|
+
ciphertext: typeof message.ciphertext === 'string'
|
|
954
|
+
? message.ciphertext
|
|
955
|
+
: CryptoUtils.bytesToBase64(message.ciphertext),
|
|
956
|
+
messageType: getEnvelopeMessageType(message.ciphertext),
|
|
957
|
+
}));
|
|
958
|
+
},
|
|
959
|
+
resolveGroupAuthorization: (groupId, recipients) => this.resolveGroupSendAuthorization(groupId, recipients),
|
|
960
|
+
reportIdentifiedFallback: (recipientUserId) => this.reportIdentifiedFallback(recipientUserId),
|
|
961
|
+
sendPreparedSealedDevice: (intent, message, auth) => this.sendToDevice(message, message.ciphertext, message.messageType, undefined, null, undefined, intent.clientMessageId, {
|
|
962
|
+
sentMessageBase64: message.sealedSenderMessage,
|
|
963
|
+
auth,
|
|
964
|
+
deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
|
|
965
|
+
}),
|
|
966
|
+
}, actualGroupId, plaintextBytes, options);
|
|
967
|
+
}
|
|
968
|
+
async prepareStoredGroupDeviceMessage(member, groupId, ciphertext, timestamp) {
|
|
969
|
+
const stored = {
|
|
970
|
+
recipientUserId: member.userId,
|
|
971
|
+
recipientDeviceId: member.deviceId,
|
|
972
|
+
timestamp,
|
|
973
|
+
ciphertext,
|
|
974
|
+
messageType: 'sender_key',
|
|
975
|
+
};
|
|
976
|
+
const sealedSender = await this.resolveSealedSenderContext(member.userId, groupId);
|
|
977
|
+
if (!sealedSender || !this.relay?.sendMultiRecipientUnidentified)
|
|
978
|
+
return stored;
|
|
979
|
+
stored.sealedSenderMessage = await this.serializeDirectSealedSenderMessage(stored, ciphertext, 'sender_key', undefined, sealedSender);
|
|
980
|
+
stored.sealedSenderDeliveryMode =
|
|
981
|
+
sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred';
|
|
982
|
+
if (sealedSender.auth.type === 'accessKey') {
|
|
983
|
+
stored.sealedSenderAuthorization = 'access_key';
|
|
984
|
+
stored.sealedSenderAccessKey = sealedSender.auth.unidentifiedAccessKey;
|
|
985
|
+
}
|
|
986
|
+
else {
|
|
987
|
+
stored.sealedSenderAuthorization = 'group_send_token';
|
|
988
|
+
}
|
|
989
|
+
return stored;
|
|
990
|
+
}
|
|
991
|
+
async resolveGroupSendAuthorization(groupId, recipientUserIds) {
|
|
992
|
+
if (!this.endorsementManager || recipientUserIds.length === 0)
|
|
993
|
+
return null;
|
|
994
|
+
const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, recipientUserIds);
|
|
995
|
+
if (needsRefresh && this.endorsementRefresher) {
|
|
996
|
+
await this.endorsementRefresher(groupId, recipientUserIds);
|
|
997
|
+
this.logger.debug('Refreshed endorsements before durable group send', {
|
|
998
|
+
category: 'E2EE',
|
|
999
|
+
data: { groupId, reason },
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
const groupSecretParams = this.groupSecretParamsProvider
|
|
1003
|
+
? await this.groupSecretParamsProvider(groupId)
|
|
1004
|
+
: null;
|
|
1005
|
+
const combined = await this.endorsementManager.getCombinedToken(groupId, recipientUserIds, groupSecretParams ?? undefined);
|
|
1006
|
+
return combined
|
|
1007
|
+
? {
|
|
1008
|
+
type: 'groupSendToken',
|
|
1009
|
+
groupSendToken: combined.token,
|
|
1010
|
+
recipientAciBytes: combined.aciBytesByUserId,
|
|
1011
|
+
}
|
|
1012
|
+
: null;
|
|
1013
|
+
}
|
|
1014
|
+
async serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender) {
|
|
1015
|
+
return serializeDirectSealedSenderTransport(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender);
|
|
784
1016
|
}
|
|
785
1017
|
/**
|
|
786
1018
|
* Resolve sealed sender context for a recipient.
|
|
@@ -807,162 +1039,32 @@ export class SignalProtocolServiceCipher {
|
|
|
807
1039
|
*
|
|
808
1040
|
*/
|
|
809
1041
|
async resolveSealedSenderContext(recipientUserId, groupId) {
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
return {
|
|
830
|
-
senderCertificateBase64,
|
|
831
|
-
senderIdentityPrivate,
|
|
832
|
-
recipientIdentityPublic,
|
|
833
|
-
config,
|
|
834
|
-
auth: {
|
|
835
|
-
type: 'groupSendToken',
|
|
836
|
-
groupSendToken: endorsementToken.token,
|
|
837
|
-
// The identity the token endorses. The relay verifies the
|
|
838
|
-
// token against this claim before reading any account.
|
|
839
|
-
recipientAciBytes: new Map([
|
|
840
|
-
[recipientUserId, endorsementToken.aciBytes],
|
|
841
|
-
]),
|
|
842
|
-
},
|
|
843
|
-
};
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
catch (endorsementError) {
|
|
848
|
-
// Endorsement lookup failed. Fall through to UAK path
|
|
849
|
-
this.logger.debug('Endorsement lookup failed, trying UAK', {
|
|
850
|
-
category: 'E2EE',
|
|
851
|
-
data: {
|
|
852
|
-
recipientUserId,
|
|
853
|
-
groupId,
|
|
854
|
-
error: endorsementError.message,
|
|
855
|
-
},
|
|
856
|
-
});
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
// Priority 2: Per-contact mode-based UAK (existing path)
|
|
860
|
-
// Check mode first. DISABLED skips sealed sender entirely
|
|
861
|
-
const contactStateStore = this.contactProfileStateStore;
|
|
862
|
-
if (!contactStateStore) {
|
|
863
|
-
this.logger.debug('No contact profile state store configured, using identified delivery', {
|
|
864
|
-
category: 'E2EE',
|
|
865
|
-
data: { recipientUserId, groupId },
|
|
866
|
-
});
|
|
867
|
-
return null;
|
|
868
|
-
}
|
|
869
|
-
const mode = await contactStateStore.getUnidentifiedAccessMode(recipientUserId);
|
|
870
|
-
if (mode === UnidentifiedAccessMode.DISABLED) {
|
|
871
|
-
this.logger.debug('Sealed sender disabled for recipient, using identified delivery', {
|
|
872
|
-
category: 'E2EE',
|
|
873
|
-
data: { recipientUserId, mode },
|
|
874
|
-
});
|
|
875
|
-
return null;
|
|
876
|
-
}
|
|
877
|
-
// Resolve access key based on mode
|
|
878
|
-
const { deriveAccessKey } = await import('../internal/protocol/sealed-sender/delivery-token.js');
|
|
879
|
-
const { bytesToBase64 } = await import('../internal/crypto/index.js');
|
|
880
|
-
let auth;
|
|
881
|
-
switch (mode) {
|
|
882
|
-
case UnidentifiedAccessMode.UNRESTRICTED: {
|
|
883
|
-
// Anyone can send sealed sender. Use zeroed 16-byte key
|
|
884
|
-
const zeroedKey = new Uint8Array(16);
|
|
885
|
-
auth = {
|
|
886
|
-
type: 'accessKey',
|
|
887
|
-
unidentifiedAccessKey: bytesToBase64(zeroedKey),
|
|
888
|
-
};
|
|
889
|
-
break;
|
|
890
|
-
}
|
|
891
|
-
case UnidentifiedAccessMode.ENABLED: {
|
|
892
|
-
// Must derive from profile key. Fail if unavailable
|
|
893
|
-
const recipientProfileKey = await contactStateStore.getContactProfileKey(recipientUserId);
|
|
894
|
-
if (!recipientProfileKey) {
|
|
895
|
-
this.logger.debug('No profile key for ENABLED recipient, using identified delivery', {
|
|
896
|
-
category: 'E2EE',
|
|
897
|
-
data: { recipientUserId },
|
|
898
|
-
});
|
|
899
|
-
return null;
|
|
900
|
-
}
|
|
901
|
-
const accessKey = await deriveAccessKey(recipientProfileKey);
|
|
902
|
-
auth = {
|
|
903
|
-
type: 'accessKey',
|
|
904
|
-
unidentifiedAccessKey: bytesToBase64(accessKey),
|
|
905
|
-
};
|
|
906
|
-
break;
|
|
907
|
-
}
|
|
908
|
-
case UnidentifiedAccessMode.UNKNOWN:
|
|
909
|
-
default: {
|
|
910
|
-
// Best effort: use derived key if available, else zeroed key
|
|
911
|
-
const recipientProfileKey = await contactStateStore.getContactProfileKey(recipientUserId);
|
|
912
|
-
if (recipientProfileKey) {
|
|
913
|
-
const accessKey = await deriveAccessKey(recipientProfileKey);
|
|
914
|
-
auth = {
|
|
915
|
-
type: 'accessKey',
|
|
916
|
-
unidentifiedAccessKey: bytesToBase64(accessKey),
|
|
917
|
-
};
|
|
918
|
-
}
|
|
919
|
-
else {
|
|
920
|
-
const zeroedKey = new Uint8Array(16);
|
|
921
|
-
auth = {
|
|
922
|
-
type: 'accessKey',
|
|
923
|
-
unidentifiedAccessKey: bytesToBase64(zeroedKey),
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
break;
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
// Get sender certificate and identity keys
|
|
930
|
-
const { senderCertificateBase64, senderIdentityPrivate, config } = await this.sealedSenderProvider();
|
|
931
|
-
// Get recipient's identity public key (needed for sealed sender DH)
|
|
932
|
-
const recipientAddress = ProtocolAddress.create(recipientUserId, 1);
|
|
933
|
-
const recipientIdentityRecord = await this.storage.getContactIdentity(recipientAddress);
|
|
934
|
-
if (!recipientIdentityRecord) {
|
|
935
|
-
// No identity key on file - fall back to identified delivery
|
|
936
|
-
this.logger.debug('No identity key for recipient, using identified delivery', {
|
|
937
|
-
category: 'E2EE',
|
|
938
|
-
data: { recipientUserId },
|
|
939
|
-
});
|
|
940
|
-
return null;
|
|
941
|
-
}
|
|
942
|
-
const recipientIdentityPublic = base64ToBytes(recipientIdentityRecord.identity.x25519PublicKey);
|
|
943
|
-
return {
|
|
944
|
-
senderCertificateBase64,
|
|
945
|
-
senderIdentityPrivate,
|
|
946
|
-
recipientIdentityPublic,
|
|
947
|
-
config,
|
|
948
|
-
auth,
|
|
949
|
-
};
|
|
950
|
-
}
|
|
951
|
-
catch (error) {
|
|
952
|
-
// Sealed sender is best-effort. Fall back to identified delivery on failure
|
|
953
|
-
this.logger.warn('Failed to resolve sealed sender context, using identified delivery', {
|
|
954
|
-
category: 'E2EE',
|
|
955
|
-
data: { recipientUserId, error: error.message },
|
|
956
|
-
});
|
|
957
|
-
return null;
|
|
958
|
-
}
|
|
1042
|
+
return resolveSealedSenderSendContext({
|
|
1043
|
+
storage: this.storage,
|
|
1044
|
+
deliveryMode: this.sealedSenderDeliveryMode,
|
|
1045
|
+
relaySupportsUnidentified: Boolean(this.relay?.sendMultiRecipientUnidentified),
|
|
1046
|
+
...(this.sealedSenderProvider && {
|
|
1047
|
+
provider: this.sealedSenderProvider,
|
|
1048
|
+
}),
|
|
1049
|
+
...(this.contactProfileStateStore && {
|
|
1050
|
+
contactProfileStateStore: this.contactProfileStateStore,
|
|
1051
|
+
}),
|
|
1052
|
+
...(this.endorsementManager && {
|
|
1053
|
+
endorsementManager: this.endorsementManager,
|
|
1054
|
+
}),
|
|
1055
|
+
...(this.groupSecretParamsProvider && {
|
|
1056
|
+
groupSecretParamsProvider: this.groupSecretParamsProvider,
|
|
1057
|
+
}),
|
|
1058
|
+
logger: this.logger,
|
|
1059
|
+
useIdentifiedDeliveryOrThrow: (userId, reason) => this.useIdentifiedDeliveryOrThrow(userId, reason),
|
|
1060
|
+
}, recipientUserId, groupId);
|
|
959
1061
|
}
|
|
960
1062
|
/**
|
|
961
1063
|
* Send a single ciphertext to a device, optionally wrapping with sealed sender.
|
|
962
1064
|
*
|
|
963
1065
|
* When sealed sender context is available:
|
|
964
|
-
* 1. Wraps the ciphertext with
|
|
965
|
-
* 2. Uses relay.
|
|
1066
|
+
* 1. Wraps the ciphertext with the multi-recipient format for one recipient
|
|
1067
|
+
* 2. Uses relay.sendMultiRecipientUnidentified() for anonymous delivery
|
|
966
1068
|
*
|
|
967
1069
|
* On sealed sender auth failure, transitions the recipient's
|
|
968
1070
|
* UnidentifiedAccessMode before falling back to identified delivery:
|
|
@@ -974,37 +1076,41 @@ export class SignalProtocolServiceCipher {
|
|
|
974
1076
|
* | UNKNOWN | DISABLED | Confirmed doesn't work |
|
|
975
1077
|
*
|
|
976
1078
|
*/
|
|
977
|
-
async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId) {
|
|
1079
|
+
async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender) {
|
|
978
1080
|
const effectiveClientMessageId = msg.clientMessageId ?? clientMessageId;
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
1081
|
+
if (preparedSealedSender && !this.relay.sendMultiRecipientUnidentified) {
|
|
1082
|
+
if (preparedSealedSender.deliveryMode === 'required') {
|
|
1083
|
+
throw new EncryptionError('Required sealed-sender relay capability is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: msg.recipientUserId });
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
// Sealed sender path: use the V2 upload format for one recipient. V2 has
|
|
1087
|
+
// no two-recipient minimum; its recipient-count field permits this exact
|
|
1088
|
+
// direct-delivery shape.
|
|
1089
|
+
if ((sealedSender || preparedSealedSender) && this.relay.sendMultiRecipientUnidentified) {
|
|
1090
|
+
const prepared = preparedSealedSender ??
|
|
1091
|
+
(sealedSender
|
|
1092
|
+
? {
|
|
1093
|
+
sentMessageBase64: await this.serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender),
|
|
1094
|
+
auth: sealedSender.auth,
|
|
1095
|
+
deliveryMode: sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred',
|
|
1096
|
+
}
|
|
1097
|
+
: undefined);
|
|
1098
|
+
if (!prepared)
|
|
1099
|
+
throw new Error('Missing sealed-sender delivery state');
|
|
991
1100
|
try {
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
ciphertext: sealedCiphertext,
|
|
998
|
-
messageType: 'unidentified_sender',
|
|
999
|
-
timestamp: msg.timestamp,
|
|
1000
|
-
clientMessageId: effectiveClientMessageId,
|
|
1001
|
-
contentHint,
|
|
1002
|
-
}, sealedSender.auth);
|
|
1101
|
+
const result = await this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, prepared.auth, msg.timestamp, [msg.recipientUserId], effectiveClientMessageId);
|
|
1102
|
+
if (result.uuids404.length > 0) {
|
|
1103
|
+
throw new SealedSenderRecipientRejectedError();
|
|
1104
|
+
}
|
|
1105
|
+
return result;
|
|
1003
1106
|
}
|
|
1004
1107
|
catch (error) {
|
|
1005
1108
|
// Fall back to identified delivery only for sealed-sender authorization
|
|
1006
1109
|
// failures. Other failures retain their original error semantics.
|
|
1007
1110
|
if (error instanceof SealedSenderAuthError) {
|
|
1111
|
+
if (prepared.deliveryMode === 'required') {
|
|
1112
|
+
throw error;
|
|
1113
|
+
}
|
|
1008
1114
|
// Restrict the cached mode after authorization fails.
|
|
1009
1115
|
try {
|
|
1010
1116
|
if (this.contactProfileStateStore) {
|
|
@@ -1047,6 +1153,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1047
1153
|
},
|
|
1048
1154
|
});
|
|
1049
1155
|
}
|
|
1156
|
+
await this.reportIdentifiedFallback(msg.recipientUserId);
|
|
1050
1157
|
// Fall through to identified path below
|
|
1051
1158
|
}
|
|
1052
1159
|
else {
|
|
@@ -1068,296 +1175,6 @@ export class SignalProtocolServiceCipher {
|
|
|
1068
1175
|
contentHint,
|
|
1069
1176
|
});
|
|
1070
1177
|
}
|
|
1071
|
-
/**
|
|
1072
|
-
* Attempt V2 multi-recipient sealed sender send.
|
|
1073
|
-
* Returns null if unavailable. Caller falls back to V1.
|
|
1074
|
-
*
|
|
1075
|
-
* Recovery behavior:
|
|
1076
|
-
* - 409 (mismatched devices): refresh device lists, rebuild recipient list, retry once
|
|
1077
|
-
* - 410 (stale sessions): archive stale sessions, retry once
|
|
1078
|
-
* - Other errors: return null for full V1 fallback
|
|
1079
|
-
*
|
|
1080
|
-
*/
|
|
1081
|
-
async tryMultiRecipientSend(groupId, otherMembers, encryptedMessageJson, sendTimestamp, clientMessageId) {
|
|
1082
|
-
// Guard checks. Return null to trigger V1 fallback
|
|
1083
|
-
if (!this.sealedSenderProvider)
|
|
1084
|
-
return null;
|
|
1085
|
-
if (!this.relay?.sendMultiRecipientUnidentified)
|
|
1086
|
-
return null;
|
|
1087
|
-
if (otherMembers.length < 2)
|
|
1088
|
-
return null;
|
|
1089
|
-
// outer recovery state flags. Prevent infinite retry loops
|
|
1090
|
-
//
|
|
1091
|
-
let hasRetriedDevices = false;
|
|
1092
|
-
let hasRetriedSessions = false;
|
|
1093
|
-
let currentMembers = otherMembers;
|
|
1094
|
-
const attemptV2Send = async () => {
|
|
1095
|
-
// Get sender keys (certificate + identity)
|
|
1096
|
-
const senderKeys = await this.sealedSenderProvider();
|
|
1097
|
-
const { base64ToBytes: b64ToBytes, bytesToBase64: bytesToB64 } = await import('../internal/crypto/index.js');
|
|
1098
|
-
// Gather recipient identity keys (per unique userId)
|
|
1099
|
-
const identityByUser = new Map();
|
|
1100
|
-
const uniqueUserIds = [...new Set(currentMembers.map((m) => m.userId))];
|
|
1101
|
-
for (const userId of uniqueUserIds) {
|
|
1102
|
-
const address = ProtocolAddress.create(userId, 1);
|
|
1103
|
-
const identityRecord = await this.storage.getContactIdentity(address);
|
|
1104
|
-
if (identityRecord) {
|
|
1105
|
-
identityByUser.set(userId, b64ToBytes(identityRecord.identity.x25519PublicKey));
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
// Split V2-eligible vs V1-fallback
|
|
1109
|
-
const v2Members = [];
|
|
1110
|
-
const v1FallbackMembers = [];
|
|
1111
|
-
for (const member of currentMembers) {
|
|
1112
|
-
if (identityByUser.has(member.userId)) {
|
|
1113
|
-
v2Members.push(member);
|
|
1114
|
-
}
|
|
1115
|
-
else {
|
|
1116
|
-
v1FallbackMembers.push(member);
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
// Need at least 2 V2-eligible unique users
|
|
1120
|
-
const v2UniqueUsers = new Set(v2Members.map((m) => m.userId));
|
|
1121
|
-
if (v2UniqueUsers.size < 2)
|
|
1122
|
-
return null;
|
|
1123
|
-
// Build V2 recipients with registration IDs from session state
|
|
1124
|
-
const v2Recipients = [];
|
|
1125
|
-
for (const member of v2Members) {
|
|
1126
|
-
const session = await this.storage.getSessionRecord(ProtocolAddress.create(member.userId, member.deviceId));
|
|
1127
|
-
let registrationId = 0;
|
|
1128
|
-
if (session?.currentSession) {
|
|
1129
|
-
registrationId = session.currentSession.remoteRegistrationId;
|
|
1130
|
-
}
|
|
1131
|
-
v2Recipients.push({
|
|
1132
|
-
serviceId: member.userId,
|
|
1133
|
-
deviceId: member.deviceId,
|
|
1134
|
-
registrationId,
|
|
1135
|
-
identityPublic: identityByUser.get(member.userId),
|
|
1136
|
-
});
|
|
1137
|
-
}
|
|
1138
|
-
// Call sealMultiRecipient()
|
|
1139
|
-
const { sealMultiRecipient } = await import('../internal/protocol/sealed-sender/index.js');
|
|
1140
|
-
const { deserializeSenderCertificate } = await import('../internal/protocol/sealed-sender/index.js');
|
|
1141
|
-
// Parse sender certificate
|
|
1142
|
-
const certBytes = b64ToBytes(senderKeys.senderCertificateBase64);
|
|
1143
|
-
const senderCertificate = deserializeSenderCertificate(certBytes);
|
|
1144
|
-
// Convert encryptedMessageJson to bytes for the seal
|
|
1145
|
-
const signalProtocolMessage = new TextEncoder().encode(encryptedMessageJson);
|
|
1146
|
-
const sealResult = await sealMultiRecipient({
|
|
1147
|
-
senderCertificate,
|
|
1148
|
-
senderIdentityPrivate: senderKeys.senderIdentityPrivate,
|
|
1149
|
-
senderIdentityPublic: senderKeys.senderIdentityPublic,
|
|
1150
|
-
recipients: v2Recipients,
|
|
1151
|
-
signalProtocolMessage,
|
|
1152
|
-
// The group this belongs to stays out of the sealed envelope. The
|
|
1153
|
-
// content type says only "decrypt this as a framed SenderKeyMessage".
|
|
1154
|
-
// The recipient resolves the group from the frame's distribution
|
|
1155
|
-
// identifier against its own sender key store.
|
|
1156
|
-
contentType: SealedSenderContentType.SENDERKEY_MESSAGE,
|
|
1157
|
-
});
|
|
1158
|
-
// Serialize to binary
|
|
1159
|
-
const { serializeSentMessage } = await import('../internal/protocol/sealed-sender/v2-binary.js');
|
|
1160
|
-
// Group recipients by serviceId for the binary format
|
|
1161
|
-
const recipientsByUser = new Map();
|
|
1162
|
-
for (const entry of sealResult.recipients) {
|
|
1163
|
-
const existing = recipientsByUser.get(entry.serviceId);
|
|
1164
|
-
if (existing) {
|
|
1165
|
-
existing.devices.push({
|
|
1166
|
-
deviceId: entry.deviceId,
|
|
1167
|
-
registrationId: entry.registrationId,
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
else {
|
|
1171
|
-
recipientsByUser.set(entry.serviceId, {
|
|
1172
|
-
serviceId: entry.serviceId,
|
|
1173
|
-
devices: [
|
|
1174
|
-
{
|
|
1175
|
-
deviceId: entry.deviceId,
|
|
1176
|
-
registrationId: entry.registrationId,
|
|
1177
|
-
},
|
|
1178
|
-
],
|
|
1179
|
-
encryptedMessageKey: b64ToBytes(entry.encryptedMessageKey),
|
|
1180
|
-
authenticationTag: b64ToBytes(entry.authenticationTag),
|
|
1181
|
-
});
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
const binaryBlob = serializeSentMessage(Array.from(recipientsByUser.values()), [], // No excluded recipients for now
|
|
1185
|
-
b64ToBytes(sealResult.ephemeralPublic), b64ToBytes(sealResult.messageCiphertext));
|
|
1186
|
-
const sentMessageBase64 = bytesToB64(binaryBlob);
|
|
1187
|
-
// Get combined auth token
|
|
1188
|
-
if (!this.endorsementManager)
|
|
1189
|
-
return null;
|
|
1190
|
-
const groupSecretParams = this.groupSecretParamsProvider
|
|
1191
|
-
? await this.groupSecretParamsProvider(groupId)
|
|
1192
|
-
: null;
|
|
1193
|
-
const v2UserIds = [...v2UniqueUsers];
|
|
1194
|
-
// Pre-send endorsement refresh
|
|
1195
|
-
const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, v2UserIds);
|
|
1196
|
-
if (needsRefresh && this.endorsementRefresher) {
|
|
1197
|
-
try {
|
|
1198
|
-
await this.endorsementRefresher(groupId, v2UserIds);
|
|
1199
|
-
this.logger.debug('Refreshed endorsements before V2 send', {
|
|
1200
|
-
category: 'E2EE',
|
|
1201
|
-
data: { groupId, reason },
|
|
1202
|
-
});
|
|
1203
|
-
}
|
|
1204
|
-
catch (refreshErr) {
|
|
1205
|
-
this.logger.debug('Pre-send endorsement refresh failed, will attempt V1 fallback', {
|
|
1206
|
-
category: 'E2EE',
|
|
1207
|
-
data: { groupId, error: refreshErr.message },
|
|
1208
|
-
});
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
const combinedToken = await this.endorsementManager.getCombinedToken(groupId, v2UserIds, groupSecretParams ?? undefined);
|
|
1212
|
-
if (!combinedToken)
|
|
1213
|
-
return null;
|
|
1214
|
-
const auth = {
|
|
1215
|
-
type: 'groupSendToken',
|
|
1216
|
-
groupSendToken: combinedToken.token,
|
|
1217
|
-
// The identities the combined token endorses, straight from the
|
|
1218
|
-
// endorsement cache. The relay verifies the token against these
|
|
1219
|
-
// claims before reading any account.
|
|
1220
|
-
recipientAciBytes: combinedToken.aciBytesByUserId,
|
|
1221
|
-
};
|
|
1222
|
-
// Send via relay
|
|
1223
|
-
const recipientUserIds = Array.from(recipientsByUser.keys());
|
|
1224
|
-
const result = await this.relay.sendMultiRecipientUnidentified(sentMessageBase64, auth, sendTimestamp, recipientUserIds, clientMessageId);
|
|
1225
|
-
// The server reports recipients it skipped (unregistered device,
|
|
1226
|
-
// registration-ID mismatch after a reinstall) in uuids404 while still
|
|
1227
|
-
// returning success for the rest. Dropping that field silently loses
|
|
1228
|
-
// messages for exactly the members that most need redelivery. So refresh
|
|
1229
|
-
// their device lists, and fan out to them per-device alongside the V1
|
|
1230
|
-
// fallback members below.
|
|
1231
|
-
const v1FallbackTargets = [...v1FallbackMembers];
|
|
1232
|
-
if (result.uuids404?.length) {
|
|
1233
|
-
this.logger.info('V2 send skipped recipients; refreshing and redelivering per-device', {
|
|
1234
|
-
category: 'E2EE',
|
|
1235
|
-
data: { groupId, skipped: result.uuids404 },
|
|
1236
|
-
});
|
|
1237
|
-
const refreshed = await Promise.all(result.uuids404.map((uid) => this.relay.getActiveDevices(uid).catch(() => [])));
|
|
1238
|
-
v1FallbackTargets.push(...refreshed.flat().filter((m) => m.userId !== this.userId));
|
|
1239
|
-
}
|
|
1240
|
-
// Send to V1 fallback members via per-device fanout
|
|
1241
|
-
if (v1FallbackTargets.length > 0) {
|
|
1242
|
-
const sealedSenderByUser = new Map();
|
|
1243
|
-
const fallbackUserIds = [...new Set(v1FallbackTargets.map((m) => m.userId))];
|
|
1244
|
-
for (const userId of fallbackUserIds) {
|
|
1245
|
-
sealedSenderByUser.set(userId, await this.resolveSealedSenderContext(userId, groupId));
|
|
1246
|
-
}
|
|
1247
|
-
for (const member of v1FallbackTargets) {
|
|
1248
|
-
const sealedSender = sealedSenderByUser.get(member.userId) ?? null;
|
|
1249
|
-
await this.sendToDevice({
|
|
1250
|
-
recipientUserId: member.userId,
|
|
1251
|
-
recipientDeviceId: member.deviceId,
|
|
1252
|
-
timestamp: sendTimestamp,
|
|
1253
|
-
}, encryptedMessageJson, 'sender_key', undefined, sealedSender, undefined, clientMessageId);
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
return {
|
|
1257
|
-
messageId: result.messageId,
|
|
1258
|
-
serverTimestamp: result.serverTimestamp,
|
|
1259
|
-
};
|
|
1260
|
-
};
|
|
1261
|
-
try {
|
|
1262
|
-
return await attemptV2Send();
|
|
1263
|
-
}
|
|
1264
|
-
catch (error) {
|
|
1265
|
-
const errorMessage = error.message ?? '';
|
|
1266
|
-
// 409: Mismatched devices. Refresh device lists and retry once
|
|
1267
|
-
// the application send pipeline
|
|
1268
|
-
if (!hasRetriedDevices && isMismatchedDevicesError(errorMessage)) {
|
|
1269
|
-
hasRetriedDevices = true;
|
|
1270
|
-
this.logger.info('V2 send got mismatched devices (409), refreshing and retrying', {
|
|
1271
|
-
category: 'E2EE',
|
|
1272
|
-
data: { groupId },
|
|
1273
|
-
});
|
|
1274
|
-
try {
|
|
1275
|
-
// Refresh device lists for all affected users
|
|
1276
|
-
const uniqueUserIds = [...new Set(currentMembers.map((m) => m.userId))];
|
|
1277
|
-
const refreshedDevices = await Promise.all(uniqueUserIds.map((uid) => this.relay.getActiveDevices(uid)));
|
|
1278
|
-
currentMembers = refreshedDevices.flat().filter((m) => m.userId !== this.userId);
|
|
1279
|
-
return await attemptV2Send();
|
|
1280
|
-
}
|
|
1281
|
-
catch (retryError) {
|
|
1282
|
-
this.logger.debug('V2 retry after device refresh failed, falling back to V1', {
|
|
1283
|
-
category: 'E2EE',
|
|
1284
|
-
data: { groupId, error: retryError.message },
|
|
1285
|
-
});
|
|
1286
|
-
return null;
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
// 410: Stale sessions. Archive and retry once
|
|
1290
|
-
// the application send pipeline
|
|
1291
|
-
if (!hasRetriedSessions && isStaleSessionV2Error(errorMessage)) {
|
|
1292
|
-
hasRetriedSessions = true;
|
|
1293
|
-
this.logger.info('V2 send got stale sessions (410), archiving and retrying', {
|
|
1294
|
-
category: 'E2EE',
|
|
1295
|
-
data: { groupId },
|
|
1296
|
-
});
|
|
1297
|
-
try {
|
|
1298
|
-
// Archive stale sessions for all affected devices and re-establish
|
|
1299
|
-
if (this.staleSessionRefresher) {
|
|
1300
|
-
for (const member of currentMembers) {
|
|
1301
|
-
await this.staleSessionRefresher(member.userId, member.deviceId).catch(() => {
|
|
1302
|
-
// Non-fatal: some devices might not have stale sessions
|
|
1303
|
-
});
|
|
1304
|
-
}
|
|
1305
|
-
}
|
|
1306
|
-
return await attemptV2Send();
|
|
1307
|
-
}
|
|
1308
|
-
catch (retryError) {
|
|
1309
|
-
this.logger.debug('V2 retry after session refresh failed, falling back to V1', {
|
|
1310
|
-
category: 'E2EE',
|
|
1311
|
-
data: { groupId, error: retryError.message },
|
|
1312
|
-
});
|
|
1313
|
-
return null;
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
// All other errors: V1 fallback
|
|
1317
|
-
this.logger.debug('V2 multi-recipient send failed, falling back to V1', {
|
|
1318
|
-
category: 'E2EE',
|
|
1319
|
-
data: { groupId, error: errorMessage },
|
|
1320
|
-
});
|
|
1321
|
-
return null;
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
/**
|
|
1325
|
-
* V1 per-device sealed sender fanout (legacy path, used as fallback).
|
|
1326
|
-
*/
|
|
1327
|
-
async perDeviceFanoutSend(groupId, otherMembers, encryptedMessageJson, sendTimestamp, clientMessageId) {
|
|
1328
|
-
// Pre-send endorsement freshness check (non-blocking, log only)
|
|
1329
|
-
// Actual refresh is handled at orchestration layer (group-service.ts)
|
|
1330
|
-
if (this.endorsementManager) {
|
|
1331
|
-
const uniqueUserIds = [...new Set(otherMembers.map((m) => m.userId))];
|
|
1332
|
-
const { needsRefresh, reason } = await this.endorsementManager.shouldRefreshEndorsements(groupId, uniqueUserIds);
|
|
1333
|
-
if (needsRefresh) {
|
|
1334
|
-
this.logger.debug('Group endorsements need refresh before send', {
|
|
1335
|
-
category: 'E2EE',
|
|
1336
|
-
data: { groupId, reason },
|
|
1337
|
-
});
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
// Resolve sealed sender context per unique recipient (not per device)
|
|
1341
|
-
// Identity keys and endorsement tokens are per-user, shared across devices
|
|
1342
|
-
const sealedSenderByUser = new Map();
|
|
1343
|
-
const uniqueRecipientIds = [...new Set(otherMembers.map((m) => m.userId))];
|
|
1344
|
-
for (const userId of uniqueRecipientIds) {
|
|
1345
|
-
sealedSenderByUser.set(userId, await this.resolveSealedSenderContext(userId, groupId));
|
|
1346
|
-
}
|
|
1347
|
-
// Send to each member device (sendToDevice handles seal + fallback)
|
|
1348
|
-
let firstResult;
|
|
1349
|
-
for (const member of otherMembers) {
|
|
1350
|
-
const sealedSender = sealedSenderByUser.get(member.userId) ?? null;
|
|
1351
|
-
const result = await this.sendToDevice({
|
|
1352
|
-
recipientUserId: member.userId,
|
|
1353
|
-
recipientDeviceId: member.deviceId,
|
|
1354
|
-
timestamp: sendTimestamp,
|
|
1355
|
-
}, encryptedMessageJson, 'sender_key', undefined, sealedSender, undefined, clientMessageId);
|
|
1356
|
-
if (!firstResult)
|
|
1357
|
-
firstResult = result;
|
|
1358
|
-
}
|
|
1359
|
-
return firstResult;
|
|
1360
|
-
}
|
|
1361
1178
|
/**
|
|
1362
1179
|
* Resolve the group roster to concrete devices via the relay.
|
|
1363
1180
|
*
|
|
@@ -1376,18 +1193,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1376
1193
|
const deviceResults = await Promise.all(options.groupMemberUserIds.map((userId) => this.relay.getActiveDevices(userId)));
|
|
1377
1194
|
return deviceResults.flat();
|
|
1378
1195
|
}
|
|
1379
|
-
|
|
1380
|
-
* Encrypt to a group via Sender Keys (O(1) encryption)
|
|
1381
|
-
*
|
|
1382
|
-
* Prefers V2 multi-recipient sealed sender when available, falls back to
|
|
1383
|
-
* V1 per-device fanout.
|
|
1384
|
-
*/
|
|
1385
|
-
async encryptToGroup(groupId, plaintextBytes, options) {
|
|
1386
|
-
// Extract actual group ID from prefixed format
|
|
1387
|
-
const actualGroupId = extractGroupId(groupId);
|
|
1388
|
-
await this.groupSendBarrierChecker?.(actualGroupId);
|
|
1389
|
-
// Require sender key to exist - caller (SignalProtocolClient.createGroupSenderKey) must create it first
|
|
1390
|
-
// The sender key is then distributed to group members before sending
|
|
1196
|
+
async prepareGroupSenderKeyPayload(actualGroupId, plaintextBytes, options) {
|
|
1391
1197
|
const existingKey = await this.storage.getSenderKey(actualGroupId, this.userId, this.deviceId);
|
|
1392
1198
|
if (!existingKey) {
|
|
1393
1199
|
throw new EncryptionError(`No sender key for group ${actualGroupId}. Call createGroupSenderKey() first to create and distribute the key.`, EncryptionErrorCode.SESSION_NOT_FOUND, {
|
|
@@ -1396,116 +1202,69 @@ export class SignalProtocolServiceCipher {
|
|
|
1396
1202
|
deviceId: this.deviceId,
|
|
1397
1203
|
});
|
|
1398
1204
|
}
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1205
|
+
let distributionMessage = await this.senderKeyManager.getPendingSenderKeyDistribution(actualGroupId, this.userId, this.deviceId);
|
|
1206
|
+
if (!distributionMessage) {
|
|
1207
|
+
try {
|
|
1208
|
+
return {
|
|
1209
|
+
ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
|
|
1210
|
+
preMessages: [],
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
catch (error) {
|
|
1214
|
+
if (!(error instanceof EncryptionError) ||
|
|
1215
|
+
error.code !== EncryptionErrorCode.SENDER_KEY_EXPIRED) {
|
|
1216
|
+
throw error;
|
|
1217
|
+
}
|
|
1408
1218
|
this.logger.info('Sender key expired, auto-rotating', {
|
|
1409
1219
|
category: 'E2EE',
|
|
1410
1220
|
data: { groupId: actualGroupId },
|
|
1411
1221
|
});
|
|
1412
|
-
|
|
1413
|
-
const { distributionMessage } = await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId);
|
|
1414
|
-
// Redistribute new sender key to all group members via relay
|
|
1415
|
-
if (this.relay) {
|
|
1416
|
-
const members = await this.resolveGroupMemberDevices(actualGroupId, options);
|
|
1417
|
-
const otherMembers = members.filter((m) => m.userId !== this.userId);
|
|
1418
|
-
for (const member of otherMembers) {
|
|
1419
|
-
// Send SKDM via pairwise session (same as initial distribution)
|
|
1420
|
-
await this.ensureSessionsForUser(member.userId);
|
|
1421
|
-
// Serialize SKDM as ProtoContentData with senderKeyDistributionMessage field
|
|
1422
|
-
// The string field contains JSON-encoded {groupId, ...distributionMessage}
|
|
1423
|
-
const skdmBytes = this.contentAdapter
|
|
1424
|
-
? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
|
|
1425
|
-
: new TextEncoder().encode(JSON.stringify({
|
|
1426
|
-
senderKeyDistributionMessage: JSON.stringify({
|
|
1427
|
-
groupId: actualGroupId,
|
|
1428
|
-
...distributionMessage,
|
|
1429
|
-
}),
|
|
1430
|
-
}));
|
|
1431
|
-
const batch = await this.sesameManager.send(member.userId, skdmBytes, {});
|
|
1432
|
-
for (const msg of batch.deviceMessages) {
|
|
1433
|
-
const ciphertextBase64 = typeof msg.ciphertext === 'string'
|
|
1434
|
-
? msg.ciphertext
|
|
1435
|
-
: CryptoUtils.bytesToBase64(msg.ciphertext);
|
|
1436
|
-
await this.relay.send({
|
|
1437
|
-
targetUserId: msg.recipientUserId,
|
|
1438
|
-
targetDeviceId: msg.recipientDeviceId,
|
|
1439
|
-
senderUserId: this.userId,
|
|
1440
|
-
senderDeviceId: this.deviceId,
|
|
1441
|
-
ciphertext: ciphertextBase64,
|
|
1442
|
-
// A distribution message is ordinary pairwise traffic. The
|
|
1443
|
-
// group it announces is inside the encrypted payload. Naming
|
|
1444
|
-
// it on the envelope would hand the relay the same membership
|
|
1445
|
-
// map the message exists to keep off the wire.
|
|
1446
|
-
messageType: getEnvelopeMessageType(msg.ciphertext),
|
|
1447
|
-
timestamp: msg.timestamp,
|
|
1448
|
-
});
|
|
1449
|
-
}
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
// Retry encryption with the new key (once, no infinite loop)
|
|
1453
|
-
encrypted = await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes);
|
|
1454
|
-
}
|
|
1455
|
-
else {
|
|
1456
|
-
throw error;
|
|
1222
|
+
({ distributionMessage } = await this.senderKeyManager.rotateSenderKey(actualGroupId, this.userId, this.deviceId, { distributionPending: true }));
|
|
1457
1223
|
}
|
|
1458
1224
|
}
|
|
1459
|
-
|
|
1460
|
-
let messageId = `local-${Date.now()}`;
|
|
1461
|
-
let timestamp = Date.now(); // Fallback if no relay
|
|
1462
|
-
let recipientDeviceCount = 0;
|
|
1225
|
+
const preMessages = [];
|
|
1463
1226
|
if (this.relay) {
|
|
1464
|
-
// Resolve group members → devices from the caller-provided roster.
|
|
1465
|
-
// Membership is local-first (it lives in each client's decrypted group
|
|
1466
|
-
// state). The relay deliberately keeps no membership map, so there is
|
|
1467
|
-
// no server endpoint to fall back to.
|
|
1468
1227
|
const members = await this.resolveGroupMemberDevices(actualGroupId, options);
|
|
1469
|
-
|
|
1470
|
-
const
|
|
1471
|
-
const
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1228
|
+
const otherMembers = members.filter((member) => member.userId !== this.userId);
|
|
1229
|
+
const recipientUserIds = [...new Set(otherMembers.map((member) => member.userId))];
|
|
1230
|
+
for (const recipientUserId of recipientUserIds) {
|
|
1231
|
+
await this.ensureSessionsForUser(recipientUserId);
|
|
1232
|
+
const skdmBytes = this.contentAdapter
|
|
1233
|
+
? this.contentAdapter.serializeSenderKeyDistributionBytes(actualGroupId, distributionMessage)
|
|
1234
|
+
: new TextEncoder().encode(JSON.stringify({
|
|
1235
|
+
senderKeyDistributionMessage: JSON.stringify({
|
|
1236
|
+
groupId: actualGroupId,
|
|
1237
|
+
...distributionMessage,
|
|
1238
|
+
}),
|
|
1239
|
+
}));
|
|
1240
|
+
const batch = await this.sesameManager.send(recipientUserId, skdmBytes, {
|
|
1241
|
+
clientTimestamp: options.timestamp,
|
|
1242
|
+
includeSyncMessages: false,
|
|
1483
1243
|
});
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
if (v1Result) {
|
|
1489
|
-
messageId = v1Result.messageId;
|
|
1490
|
-
timestamp = v1Result.serverTimestamp;
|
|
1491
|
-
}
|
|
1492
|
-
else {
|
|
1493
|
-
messageId = `group-${actualGroupId}-${timestamp}`;
|
|
1244
|
+
for (const message of batch.deviceMessages) {
|
|
1245
|
+
const stored = await this.prepareStoredDirectDeviceMessage(message, null);
|
|
1246
|
+
stored.clientMessageId = `${options.clientMessageId}:sender-key-distribution:${preMessages.length}`;
|
|
1247
|
+
preMessages.push(stored);
|
|
1494
1248
|
}
|
|
1495
|
-
this.logger.debug('Group message sent via V1 per-device fanout', {
|
|
1496
|
-
category: 'E2EE',
|
|
1497
|
-
data: { groupId: actualGroupId, recipientDeviceCount, messageId },
|
|
1498
|
-
});
|
|
1499
1249
|
}
|
|
1500
|
-
await this.sendSyncTranscriptToLocalOtherDevices(actualGroupId, plaintextBytes, sendTimestamp);
|
|
1501
1250
|
}
|
|
1502
1251
|
return {
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
groupId: actualGroupId,
|
|
1252
|
+
ciphertext: await this.senderKeyManager.encryptGroupMessage(actualGroupId, this.userId, this.deviceId, plaintextBytes),
|
|
1253
|
+
preMessages,
|
|
1254
|
+
senderKeyDistributionId: distributionMessage.senderKeyId,
|
|
1507
1255
|
};
|
|
1508
1256
|
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Encrypt to a group via Sender Keys (O(1) encryption)
|
|
1259
|
+
*
|
|
1260
|
+
* Uses the multi-recipient sealed-sender transport when anonymous delivery
|
|
1261
|
+
* is available, with exact per-device identified delivery otherwise.
|
|
1262
|
+
*/
|
|
1263
|
+
async encryptToGroup(groupId, plaintextBytes, options) {
|
|
1264
|
+
const actualGroupId = extractGroupId(groupId);
|
|
1265
|
+
await this.groupSendBarrierChecker?.(actualGroupId);
|
|
1266
|
+
return this.encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options);
|
|
1267
|
+
}
|
|
1509
1268
|
/**
|
|
1510
1269
|
* Encrypt binary attachment with two-layer encryption
|
|
1511
1270
|
*
|
|
@@ -1530,7 +1289,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1530
1289
|
const uploaded = await this.prepareAttachmentUpload(data, options);
|
|
1531
1290
|
const attachmentPayload = serializeMediaAttachmentMessage({
|
|
1532
1291
|
attachment: uploaded,
|
|
1533
|
-
timestamp: options
|
|
1292
|
+
timestamp: options.timestamp ?? Date.now(),
|
|
1534
1293
|
});
|
|
1535
1294
|
const attachmentBytes = new TextEncoder().encode(attachmentPayload);
|
|
1536
1295
|
let result;
|