@open-e2ee/signal-protocol-sdk 13.4.0 → 13.5.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 +417 -0
- package/README.md +1 -1
- package/SECURITY.md +2 -2
- package/dist/client/binary-send.d.ts +28 -0
- package/dist/client/binary-send.d.ts.map +1 -0
- package/dist/client/binary-send.js +26 -0
- package/dist/client/binary-send.js.map +1 -0
- package/dist/client/client.d.ts +46 -6
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +181 -66
- package/dist/client/client.js.map +1 -1
- package/dist/client/content-adapter.d.ts +18 -0
- package/dist/client/content-adapter.d.ts.map +1 -1
- package/dist/client/content-adapter.js.map +1 -1
- package/dist/client/device-set-reconciliation.d.ts +23 -8
- package/dist/client/device-set-reconciliation.d.ts.map +1 -1
- package/dist/client/device-set-reconciliation.js +25 -11
- package/dist/client/device-set-reconciliation.js.map +1 -1
- package/dist/client/event-hooks.d.ts +88 -8
- package/dist/client/event-hooks.d.ts.map +1 -1
- package/dist/client/event-hooks.js +1 -0
- package/dist/client/event-hooks.js.map +1 -1
- package/dist/client/group-outbox.d.ts +45 -10
- package/dist/client/group-outbox.d.ts.map +1 -1
- package/dist/client/group-outbox.js +246 -154
- package/dist/client/group-outbox.js.map +1 -1
- package/dist/client/group-receive-authorization.d.ts +10 -1
- package/dist/client/group-receive-authorization.d.ts.map +1 -1
- package/dist/client/group-receive-authorization.js.map +1 -1
- package/dist/client/hosted-anonymous-delivery.d.ts +18 -1
- package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
- package/dist/client/hosted-anonymous-delivery.js +84 -12
- package/dist/client/hosted-anonymous-delivery.js.map +1 -1
- package/dist/client/hosted-connection.js +1 -1
- package/dist/client/hosted-connection.js.map +1 -1
- package/dist/client/hosted-group-authority.d.ts +6 -2
- package/dist/client/hosted-group-authority.d.ts.map +1 -1
- package/dist/client/hosted-group-authority.js +11 -7
- package/dist/client/hosted-group-authority.js.map +1 -1
- package/dist/client/hosted-groups.d.ts +5 -1
- package/dist/client/hosted-groups.d.ts.map +1 -1
- package/dist/client/hosted-groups.js +8 -4
- package/dist/client/hosted-groups.js.map +1 -1
- package/dist/client/hosted-http-error.d.ts +5 -1
- package/dist/client/hosted-http-error.d.ts.map +1 -1
- package/dist/client/hosted-http-error.js +5 -1
- package/dist/client/hosted-http-error.js.map +1 -1
- package/dist/client/hosted-mailbox-subscription.d.ts +2 -0
- package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
- package/dist/client/hosted-mailbox-subscription.js +5 -5
- package/dist/client/hosted-mailbox-subscription.js.map +1 -1
- package/dist/client/hosted-transport.d.ts +11 -1
- package/dist/client/hosted-transport.d.ts.map +1 -1
- package/dist/client/hosted-transport.js +75 -30
- package/dist/client/hosted-transport.js.map +1 -1
- package/dist/client/hosted.d.ts.map +1 -1
- package/dist/client/hosted.js +1 -1
- package/dist/client/hosted.js.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/receive-queue.d.ts +5 -2
- package/dist/client/receive-queue.d.ts.map +1 -1
- package/dist/client/receive-queue.js +55 -18
- package/dist/client/receive-queue.js.map +1 -1
- package/dist/client/relay-acceptance.d.ts +49 -6
- package/dist/client/relay-acceptance.d.ts.map +1 -1
- package/dist/client/relay-acceptance.js +49 -3
- package/dist/client/relay-acceptance.js.map +1 -1
- package/dist/client/relay-protocol.d.ts +37 -7
- package/dist/client/relay-protocol.d.ts.map +1 -1
- package/dist/client/relay-protocol.js +53 -10
- package/dist/client/relay-protocol.js.map +1 -1
- package/dist/client/retry-family.d.ts +3 -3
- package/dist/client/retry-family.js +1 -1
- package/dist/client/retry-family.js.map +1 -1
- package/dist/client/retry-request-envelope.d.ts +18 -8
- package/dist/client/retry-request-envelope.d.ts.map +1 -1
- package/dist/client/retry-request-envelope.js +57 -29
- package/dist/client/retry-request-envelope.js.map +1 -1
- package/dist/client/retry-request-lifecycle.d.ts +24 -11
- package/dist/client/retry-request-lifecycle.d.ts.map +1 -1
- package/dist/client/retry-request-lifecycle.js +46 -20
- package/dist/client/retry-request-lifecycle.js.map +1 -1
- package/dist/client/retry-terminal-recovery.d.ts +11 -8
- package/dist/client/retry-terminal-recovery.d.ts.map +1 -1
- package/dist/client/retry-terminal-recovery.js +18 -12
- package/dist/client/retry-terminal-recovery.js.map +1 -1
- package/dist/client/retry.d.ts +8 -7
- package/dist/client/retry.d.ts.map +1 -1
- package/dist/client/retry.js +30 -22
- package/dist/client/retry.js.map +1 -1
- package/dist/client/send-deadline.d.ts +308 -0
- package/dist/client/send-deadline.d.ts.map +1 -0
- package/dist/client/send-deadline.js +914 -0
- package/dist/client/send-deadline.js.map +1 -0
- package/dist/client/send-intent-driver.d.ts +116 -0
- package/dist/client/send-intent-driver.d.ts.map +1 -0
- package/dist/client/send-intent-driver.js +373 -0
- package/dist/client/send-intent-driver.js.map +1 -0
- package/dist/client/signal-service-cipher.d.ts +257 -27
- package/dist/client/signal-service-cipher.d.ts.map +1 -1
- package/dist/client/signal-service-cipher.js +1274 -283
- package/dist/client/signal-service-cipher.js.map +1 -1
- package/dist/client/types.d.ts +48 -5
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/types.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/local/store/conformance/cases/metadata.d.ts +3 -2
- package/dist/local/store/conformance/cases/metadata.d.ts.map +1 -1
- package/dist/local/store/conformance/cases/metadata.js +153 -2
- package/dist/local/store/conformance/cases/metadata.js.map +1 -1
- package/dist/local/store/key-value/adapter.d.ts +2 -1
- package/dist/local/store/key-value/adapter.d.ts.map +1 -1
- package/dist/local/store/key-value/adapter.js +9 -0
- package/dist/local/store/key-value/adapter.js.map +1 -1
- package/dist/local/store/memory/adapter.d.ts +2 -1
- 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/metadata-keys.d.ts +13 -0
- package/dist/local/store/metadata-keys.d.ts.map +1 -0
- package/dist/local/store/metadata-keys.js +20 -0
- package/dist/local/store/metadata-keys.js.map +1 -0
- package/dist/local/store/receive-work.d.ts.map +1 -1
- package/dist/local/store/receive-work.js +12 -1
- package/dist/local/store/receive-work.js.map +1 -1
- package/dist/local/store/reliability.d.ts +482 -33
- package/dist/local/store/reliability.d.ts.map +1 -1
- package/dist/local/store/reliability.js +690 -48
- package/dist/local/store/reliability.js.map +1 -1
- package/dist/local/store/sqlite/key-storage/index.d.ts +2 -1
- package/dist/local/store/sqlite/key-storage/index.d.ts.map +1 -1
- package/dist/local/store/sqlite/key-storage/index.js +3 -0
- package/dist/local/store/sqlite/key-storage/index.js.map +1 -1
- package/dist/local/store/sqlite/key-storage/metadata.d.ts +9 -0
- package/dist/local/store/sqlite/key-storage/metadata.d.ts.map +1 -1
- package/dist/local/store/sqlite/key-storage/metadata.js +12 -0
- package/dist/local/store/sqlite/key-storage/metadata.js.map +1 -1
- package/dist/local/store/sqlite/store.d.ts +2 -1
- package/dist/local/store/sqlite/store.d.ts.map +1 -1
- package/dist/local/store/sqlite/store.js +3 -0
- package/dist/local/store/sqlite/store.js.map +1 -1
- package/dist/local/store/web/adapter.d.ts +8 -1
- package/dist/local/store/web/adapter.d.ts.map +1 -1
- package/dist/local/store/web/adapter.js +18 -0
- package/dist/local/store/web/adapter.js.map +1 -1
- package/dist/remote/relay/request-admission.d.ts +49 -0
- package/dist/remote/relay/request-admission.d.ts.map +1 -0
- package/dist/remote/relay/request-admission.js +74 -0
- package/dist/remote/relay/request-admission.js.map +1 -0
- package/dist/types/api.d.ts +77 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/types/errors.d.ts +144 -1
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +146 -1
- package/dist/types/errors.js.map +1 -1
- package/docs/ASSURANCE.md +5 -5
- package/docs/DEVIATIONS.md +34 -4
- package/docs/ERROR_HANDLING.md +134 -7
- package/package.json +1 -1
|
@@ -27,25 +27,29 @@ import { GroupReceiveRefusedError, GroupReceiveUnavailableError, refuseSyncFromO
|
|
|
27
27
|
import { sizedReceiveWork } from '../local/store/receive-work.js';
|
|
28
28
|
import { envelopeCiphertextBytes } from './delivery-error.js';
|
|
29
29
|
import { GroupSenderKeyOperations } from './group-sender-key-operations.js';
|
|
30
|
-
import { checkNewSendTimestamp, withCheckedSendTimestamp, } from './send-timestamp.js';
|
|
30
|
+
import { checkNewSendTimestamp, SEND_TIMESTAMP_ORIGIN, withCheckedSendTimestamp, } from './send-timestamp.js';
|
|
31
|
+
import { intentBinaryAttachment, SEND_BINARY_ATTACHMENT, } from './binary-send.js';
|
|
31
32
|
import { ContentHint } from '../types/messages.js';
|
|
32
33
|
import { createDefaultSignalProtocolContentAdapter, } from './content-adapter.js';
|
|
33
34
|
import * as CryptoUtils from '../internal/crypto/index.js';
|
|
34
|
-
import { completeOutgoingMessageIntent, completeOutgoingSyncPhase, getOutgoingMessageIntent, markOutgoingDeviceSetUnresolved, outgoingMessageIntentResult,
|
|
35
|
+
import { completeOutgoingMessageIntent, completeOutgoingSyncPhase, endOutgoingMessageIntent, getOutgoingMessageIntent, markOutgoingDeviceSetUnresolved, outgoingDestinationProgressKey, outgoingMessageDeadlineAt, outgoingMessageIntentResult, recordOutgoingDestinationProgress, repairOutgoingDeviceSet, getRetryResend, getSentClientMessageIds, reconcileOutgoingDirectDeviceMessages, reconcileOutgoingSyncMessages, replaceOutgoingDirectDeviceMessage, replaceOutgoingGroupPreMessages, retryAttemptClientMessageId, retryNullMessageClientMessageId, retryRequestAttempt, retryResendClientMessageId, storeOutgoingMessageIntent, storeRetryResend, withOutgoingMessageIntentLock, addOutgoingManualResend, endOutgoingManualResend, isOpenManualResend, manualResendMessageId, OUTGOING_POSTING_WINDOW_MS, outgoingManualResends, recordOutgoingManualResendProgress, RELIABILITY_RECORD_TTL_MS, } from '../local/store/reliability.js';
|
|
35
36
|
import { FanOutError, firstItemError } from '../utils/bounded-fan-out.js';
|
|
36
37
|
import { withRetry } from '../utils/retry.js';
|
|
37
38
|
import { acquireUntilStopped, createRelayFanOut, RelayWorkStopped, relaySendsSealedUnderItsBound, rethrowRelayWorkStopped, } from './relay-work.js';
|
|
38
39
|
import { markRelayDeviceRefusal, refusesRemovedDevices, relayDeviceRefusal, } from './relay-device-refusal.js';
|
|
39
|
-
import { aggregateRelayAcceptance, relayOperationRefusal, } from './relay-acceptance.js';
|
|
40
|
+
import { aggregateRelayAcceptance, isConflictAcceptance, relayHoldsMessageId, relayOperationRefusal, sendResultAcceptance, } from './relay-acceptance.js';
|
|
41
|
+
import { attachSendDeadline, isPostingDeadlineReached, provenRefused, recordDeadlineStop, SEND_END_REPORT, manualResendIntent, SendCallEvidence, sendDestinations, storedAcceptance, storedSendEndError, } from './send-deadline.js';
|
|
42
|
+
import { callerBytesMatch } from './send-intent-driver.js';
|
|
43
|
+
import { admitRequestsFor, followedRepeatedRequest, markAfterRepeatedRequest, } from '../remote/relay/request-admission.js';
|
|
40
44
|
import { forDirectSealedRoute, usedGroupRouteFallback } from './relay-sealed-route.js';
|
|
41
45
|
import { comparesDeviceSets, markDeviceSetRefusal } from '../remote/relay/device-set.js';
|
|
42
|
-
import { markRelayProtocolError, runDeviceSetPhase, waitUnlessStopped, syncPostReceipts, uncheckedDeclaredPost, } from './device-set-reconciliation.js';
|
|
46
|
+
import { DeviceSetReconciliationError, markRelayProtocolError, runDeviceSetPhase, waitUnlessStopped, syncPostReceipts, uncheckedDeclaredPost, } from './device-set-reconciliation.js';
|
|
43
47
|
import { prepareGroupSharedMessage } from './group-sealed-sender.js';
|
|
44
48
|
import { attachFailedGroup } from './retry-terminal-recovery.js';
|
|
45
49
|
import { sendGroupWithExactOutbox, } from './group-outbox.js';
|
|
46
50
|
import { groupDeviceKey, listedOwnDeviceChange } from './group-device-set.js';
|
|
47
51
|
import { attachUnsealedEnvelope, reconstructEnvelope, resolveSealedSenderContext as resolveSealedSenderSendContext, SealedRetryRequestReceived, serializeDirectSealedSenderMessage as serializeDirectSealedSenderTransport, unsealMessage, } from './sealed-sender.js';
|
|
48
|
-
import { prepareMediaAttachmentUpload, serializeMediaAttachmentMessage } from '../media/index.js';
|
|
52
|
+
import { parseMediaAttachmentMessage, prepareMediaAttachmentUpload, serializeMediaAttachmentMessage, } from '../media/index.js';
|
|
49
53
|
import { UnidentifiedAccessMode, } from '../profile/contact-state.js';
|
|
50
54
|
/**
|
|
51
55
|
* How long a recipient's relay device list stays current before a send reads
|
|
@@ -61,6 +65,139 @@ export const RECIPIENT_DEVICE_LIST_FRESH_MILLISECONDS = 60_000;
|
|
|
61
65
|
function syncMessageId(clientMessageId, message) {
|
|
62
66
|
return `${clientMessageId}:sync:device:${message.recipientDeviceId}`;
|
|
63
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* The end of a direct or group send at a classification point, or undefined
|
|
70
|
+
* when the send stays open. It reads the stored progress of `intent`, which
|
|
71
|
+
* the caller read under the intent lock. The destinations are the stored
|
|
72
|
+
* pre-messages and device messages. The own device of the sender is no
|
|
73
|
+
* destination of the send.
|
|
74
|
+
*/
|
|
75
|
+
function recipientSendEnd(intent, evidence, userId, deviceId) {
|
|
76
|
+
return evidence.end(recipientDestinations(intent, userId, deviceId), intent.destinationProgress);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The recipient destinations of a direct or group intent, each once: the
|
|
80
|
+
* stored pre-messages and device messages, without the own device of the
|
|
81
|
+
* sender.
|
|
82
|
+
*/
|
|
83
|
+
function recipientDestinations(intent, userId, deviceId) {
|
|
84
|
+
const destinations = sendDestinations(intent.clientMessageId, [...(intent.preMessages ?? []), ...intent.deviceMessages].filter((message) => message.recipientUserId !== userId || message.recipientDeviceId !== deviceId));
|
|
85
|
+
const keys = new Set();
|
|
86
|
+
return destinations.filter(({ device, postMessageId }) => {
|
|
87
|
+
const key = outgoingDestinationProgressKey(postMessageId, device);
|
|
88
|
+
if (keys.has(key))
|
|
89
|
+
return false;
|
|
90
|
+
keys.add(key);
|
|
91
|
+
return true;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The recipient devices of an ended intent that a manual resend posts to:
|
|
96
|
+
* each device with a destination that no post of the intent accepted, and
|
|
97
|
+
* that no earlier manual resend got accepted.
|
|
98
|
+
*/
|
|
99
|
+
function manualResendTargets(intent, userId, deviceId) {
|
|
100
|
+
const deviceKeyOf = (device) => `${device.userId}:${String(device.deviceId)}`;
|
|
101
|
+
const resent = new Set();
|
|
102
|
+
for (const resend of outgoingManualResends(intent)) {
|
|
103
|
+
for (const entry of Object.values(resend.destinationProgress ?? {})) {
|
|
104
|
+
if (entry.state === 'accepted')
|
|
105
|
+
resent.add(deviceKeyOf(entry));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const targets = new Map();
|
|
109
|
+
for (const { device, postMessageId } of recipientDestinations(intent, userId, deviceId)) {
|
|
110
|
+
const entry = intent.destinationProgress?.[outgoingDestinationProgressKey(postMessageId, device)];
|
|
111
|
+
if (entry?.state === 'accepted' || resent.has(deviceKeyOf(device)))
|
|
112
|
+
continue;
|
|
113
|
+
targets.set(deviceKeyOf(device), { userId: device.userId, deviceId: device.deviceId });
|
|
114
|
+
}
|
|
115
|
+
return [...targets.values()];
|
|
116
|
+
}
|
|
117
|
+
/** The key of the order lock that a manual resend of an intent holds. */
|
|
118
|
+
function manualResendOrderKey(intent) {
|
|
119
|
+
return intent.kind === 'group' ? extractGroupId(intent.recipientId) : intent.recipientId;
|
|
120
|
+
}
|
|
121
|
+
/** The stored intent of a manual resend. Throws for a send that is missing or did not end. */
|
|
122
|
+
function endedManualResendIntent(intent) {
|
|
123
|
+
if (!intent)
|
|
124
|
+
throw new Error('No stored send has this clientMessageId');
|
|
125
|
+
if (intent.result || intent.outcome === undefined) {
|
|
126
|
+
throw new Error('Only a send that ended at its posting deadline takes a manual resend');
|
|
127
|
+
}
|
|
128
|
+
return intent;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Check a new manual resend of an ended intent with no open resend, and
|
|
132
|
+
* plan it. The caller holds the intent lock. Nothing is encrypted.
|
|
133
|
+
*/
|
|
134
|
+
async function planManualResend(intent, content, userId, deviceId, withoutGroupContext) {
|
|
135
|
+
if (content === undefined)
|
|
136
|
+
throw new Error('A new manual resend needs the content');
|
|
137
|
+
// The intent digests the caller bytes, without the group context.
|
|
138
|
+
const matches = content.withGroupContext
|
|
139
|
+
? await callerBytesMatch(content.content, withoutGroupContext, intent.plaintextDigest)
|
|
140
|
+
: CryptoUtils.bytesToBase64(await CryptoUtils.sha256(content.content)) ===
|
|
141
|
+
intent.plaintextDigest;
|
|
142
|
+
if (!matches) {
|
|
143
|
+
throw new Error('A clientMessageId cannot identify two different logical sends');
|
|
144
|
+
}
|
|
145
|
+
// The last manual resend posts at most RELIABILITY_RECORD_TTL_MS after the
|
|
146
|
+
// intent, so the drop record of a recipient outlives each copy.
|
|
147
|
+
if (Date.now() >= intent.createdAt + RELIABILITY_RECORD_TTL_MS) {
|
|
148
|
+
throw new Error('Only a send younger than 30 days takes a manual resend');
|
|
149
|
+
}
|
|
150
|
+
const targets = manualResendTargets(intent, userId, deviceId);
|
|
151
|
+
if (targets.length === 0) {
|
|
152
|
+
throw new Error('The Relay accepted each recipient device of this send');
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
intent,
|
|
156
|
+
content,
|
|
157
|
+
targets,
|
|
158
|
+
manualMessageId: manualResendMessageId(intent.clientMessageId, outgoingManualResends(intent).length + 1),
|
|
159
|
+
createdAt: Date.now(),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/** The destinations of a manual resend: one per message, under the manual message ID. */
|
|
163
|
+
function manualResendDestinations(resend) {
|
|
164
|
+
return sendDestinations(resend.manualMessageId, resend.messages.map(({ message }) => message));
|
|
165
|
+
}
|
|
166
|
+
/** The result of a manual resend that the Relay accepted for each of its devices. */
|
|
167
|
+
function manualResendResult(intent, resend, acceptances) {
|
|
168
|
+
const first = sendResultAcceptance(acceptances);
|
|
169
|
+
return {
|
|
170
|
+
clientMessageId: intent.clientMessageId,
|
|
171
|
+
messageId: first?.messageId ?? resend.manualMessageId,
|
|
172
|
+
timestamp: first?.serverTimestamp ?? intent.clientTimestamp,
|
|
173
|
+
recipientDeviceCount: resend.messages.length,
|
|
174
|
+
...aggregateRelayAcceptance(acceptances),
|
|
175
|
+
...(intent.kind === 'group' && { groupId: intent.recipientId }),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/** True when a group post names a list of destinations, as a shared body does. */
|
|
179
|
+
function isDestinationList(destination) {
|
|
180
|
+
return Array.isArray(destination);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* True when the stored progress of `intent` proves that the Relay refused the
|
|
184
|
+
* message of a device, so that a replay does not post it (`provenRefused`).
|
|
185
|
+
*/
|
|
186
|
+
function storedRefusal(intent, message) {
|
|
187
|
+
const [destination] = sendDestinations(intent.clientMessageId, [message]);
|
|
188
|
+
return provenRefused(intent.destinationProgress?.[outgoingDestinationProgressKey(destination.postMessageId, destination.device)]);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The destination of the sync copy of a send to one own device. Its post
|
|
192
|
+
* message ID is the sync ID of the device, also after a repair gave the copy
|
|
193
|
+
* a repair ID, so the stored progress of the copy keeps one key.
|
|
194
|
+
*/
|
|
195
|
+
function syncDestination(clientMessageId, message) {
|
|
196
|
+
return {
|
|
197
|
+
device: { userId: message.recipientUserId, deviceId: message.recipientDeviceId },
|
|
198
|
+
postMessageId: syncMessageId(clientMessageId, message),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
64
201
|
/**
|
|
65
202
|
* How old a recipient's device list can be for a direct send to post before
|
|
66
203
|
* it reads the list again. Only a relay that refuses a removed device's
|
|
@@ -221,6 +358,45 @@ function retryResendAttemptId(resend) {
|
|
|
221
358
|
: retryNullMessageClientMessageId(resend.retryId);
|
|
222
359
|
return retryAttemptClientMessageId(id, resend.attempt);
|
|
223
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* The pointer metadata that a binary send takes from its options. The upload
|
|
363
|
+
* puts each field in the pointer unchanged, and a repeat compares the fields
|
|
364
|
+
* with the stored pointer.
|
|
365
|
+
*/
|
|
366
|
+
function attachmentMetadataFromOptions(options) {
|
|
367
|
+
return {
|
|
368
|
+
contentType: options?.mimeType || 'application/octet-stream',
|
|
369
|
+
blurHash: options?.blurHash,
|
|
370
|
+
thumbnail: options?.thumbnail,
|
|
371
|
+
width: options?.width,
|
|
372
|
+
height: options?.height,
|
|
373
|
+
durationMs: options?.durationMs,
|
|
374
|
+
waveform: options?.waveform,
|
|
375
|
+
fileName: options?.fileName,
|
|
376
|
+
caption: options?.caption,
|
|
377
|
+
isViewOnce: options?.isViewOnce,
|
|
378
|
+
flags: options?.flags,
|
|
379
|
+
clientUuid: options?.clientUuid,
|
|
380
|
+
cdnNumber: options?.cdnNumber,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Whether a stored pointer has the metadata of the options of a repeat. A
|
|
385
|
+
* field that the options omit must be absent from the pointer, except
|
|
386
|
+
* `clientUuid`: the upload generates one when the options give none.
|
|
387
|
+
*/
|
|
388
|
+
function pointerHasAttachmentMetadata(pointer, metadata) {
|
|
389
|
+
const fields = pointer;
|
|
390
|
+
return Object.entries(metadata).every(([key, value]) => (key === 'clientUuid' && value === undefined) ||
|
|
391
|
+
JSON.stringify(fields[key]) === JSON.stringify(value));
|
|
392
|
+
}
|
|
393
|
+
/** The pointer of a serialized attachment message. */
|
|
394
|
+
function attachmentPointerOf(message) {
|
|
395
|
+
const pointer = parseMediaAttachmentMessage(message)?.attachment;
|
|
396
|
+
if (!pointer)
|
|
397
|
+
throw new Error('The attachment message of the send is not valid');
|
|
398
|
+
return pointer;
|
|
399
|
+
}
|
|
224
400
|
/**
|
|
225
401
|
* SignalProtocolServiceCipher - Routes encryption and decryption to appropriate ciphers
|
|
226
402
|
*
|
|
@@ -286,6 +462,10 @@ export class SignalProtocolServiceCipher {
|
|
|
286
462
|
getResolvedContentAdapter() {
|
|
287
463
|
return this.contentAdapter ?? createDefaultSignalProtocolContentAdapter();
|
|
288
464
|
}
|
|
465
|
+
/** The plaintext with no group context, by the resolved content adapter. */
|
|
466
|
+
withoutGroupContext(plaintext) {
|
|
467
|
+
return this.getResolvedContentAdapter().withoutGroupContext(plaintext);
|
|
468
|
+
}
|
|
289
469
|
getDirectConversationId(recipientUserId) {
|
|
290
470
|
const sortedIds = [this.userId, recipientUserId].sort();
|
|
291
471
|
return `dm:${sortedIds[0]}_${sortedIds[1]}`;
|
|
@@ -354,14 +534,20 @@ export class SignalProtocolServiceCipher {
|
|
|
354
534
|
* warning is logged. The post then resolves, so the send completes without
|
|
355
535
|
* the copy.
|
|
356
536
|
*
|
|
537
|
+
* `gate` gives the `beforeRequest` of each copy by its client message ID,
|
|
538
|
+
* or by `undefined` for a copy that has no ID. Without `gate`, each copy
|
|
539
|
+
* uses the `beforeRequest` of `control`.
|
|
540
|
+
*
|
|
541
|
+
* @returns The relay receipt of the copy or of its repaired copy, or
|
|
542
|
+
* undefined when the copy left the intent
|
|
357
543
|
* @throws {EncryptionError} SESSION_ESTABLISHMENT_FAILED when the refresh
|
|
358
544
|
* fails or the rebuild gives the device no copy. The copy stays in the
|
|
359
545
|
* intent, so a replay posts it again.
|
|
360
546
|
*/
|
|
361
|
-
async postSyncMessage(relay, message, control, repair) {
|
|
547
|
+
async postSyncMessage(relay, message, control, repair, gate) {
|
|
548
|
+
const controlOf = (copy) => gate ? { ...control, beforeRequest: gate(copy.clientMessageId) } : control;
|
|
362
549
|
try {
|
|
363
|
-
await this.postSyncCopy(relay, message,
|
|
364
|
-
return;
|
|
550
|
+
return await this.postSyncCopy(relay, message, controlOf(message));
|
|
365
551
|
}
|
|
366
552
|
catch (error) {
|
|
367
553
|
if (!isConclusiveDeviceRejection(error))
|
|
@@ -374,8 +560,7 @@ export class SignalProtocolServiceCipher {
|
|
|
374
560
|
: undefined;
|
|
375
561
|
if (replacement) {
|
|
376
562
|
try {
|
|
377
|
-
await this.postSyncCopy(relay, replacement,
|
|
378
|
-
return;
|
|
563
|
+
return await this.postSyncCopy(relay, replacement, controlOf(replacement));
|
|
379
564
|
}
|
|
380
565
|
catch (error) {
|
|
381
566
|
if (!isConclusiveDeviceRejection(error))
|
|
@@ -392,6 +577,7 @@ export class SignalProtocolServiceCipher {
|
|
|
392
577
|
category: 'E2EE',
|
|
393
578
|
data: { deviceId: refused.recipientDeviceId },
|
|
394
579
|
});
|
|
580
|
+
return undefined;
|
|
395
581
|
}
|
|
396
582
|
/**
|
|
397
583
|
* Refresh the session of an own device that refused a sync copy as stale,
|
|
@@ -426,6 +612,18 @@ export class SignalProtocolServiceCipher {
|
|
|
426
612
|
* @returns The relay receipt of the post
|
|
427
613
|
*/
|
|
428
614
|
async postSyncCopy(relay, message, control) {
|
|
615
|
+
// The transport gates a repeat by the ID that the posted envelope carries.
|
|
616
|
+
const release = control.beforeRequest && message.clientMessageId !== undefined
|
|
617
|
+
? admitRequestsFor(relay, message.clientMessageId, control.beforeRequest)
|
|
618
|
+
: undefined;
|
|
619
|
+
try {
|
|
620
|
+
return await this.postSyncCopyRequest(relay, message, control);
|
|
621
|
+
}
|
|
622
|
+
finally {
|
|
623
|
+
release?.();
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
postSyncCopyRequest(relay, message, control) {
|
|
429
627
|
return this.postToRelay(() => relay.send({
|
|
430
628
|
targetUserId: message.recipientUserId,
|
|
431
629
|
targetDeviceId: message.recipientDeviceId,
|
|
@@ -480,8 +678,10 @@ export class SignalProtocolServiceCipher {
|
|
|
480
678
|
* the same bound, so its sealed post runs without one here.
|
|
481
679
|
*/
|
|
482
680
|
postToRelay(send, sealed, control) {
|
|
483
|
-
const post = () => {
|
|
681
|
+
const post = async () => {
|
|
484
682
|
control.admit?.();
|
|
683
|
+
await control.beforeRequest?.();
|
|
684
|
+
control.onRequest?.();
|
|
485
685
|
return send();
|
|
486
686
|
};
|
|
487
687
|
if (sealed && relaySendsSealedUnderItsBound(this.relay)) {
|
|
@@ -1180,8 +1380,9 @@ export class SignalProtocolServiceCipher {
|
|
|
1180
1380
|
*/
|
|
1181
1381
|
async encrypt(recipientId, content, options, sessions = this.sessionCallbacks, stopSignal) {
|
|
1182
1382
|
const clientMessageId = options?.clientMessageId ?? (await CryptoUtils.generateUuidV4());
|
|
1183
|
-
// The client entry can mark the origin of the timestamp
|
|
1184
|
-
// of the
|
|
1383
|
+
// The client entry can mark the origin of the timestamp and give the end
|
|
1384
|
+
// report of the call. The public type of the options leaves both marks
|
|
1385
|
+
// out, and the spread keeps their symbol keys.
|
|
1185
1386
|
const durableOptions = {
|
|
1186
1387
|
...options,
|
|
1187
1388
|
clientMessageId,
|
|
@@ -1221,14 +1422,15 @@ export class SignalProtocolServiceCipher {
|
|
|
1221
1422
|
* kind of the stored record posts the stored bytes with their epoch
|
|
1222
1423
|
* again, and does not encrypt: that is the sender's own retry of a post
|
|
1223
1424
|
* that did not complete. A call for another request envelope or kind
|
|
1224
|
-
* encrypts
|
|
1225
|
-
* posts it.
|
|
1226
|
-
* OPERATION_EXPIRED
|
|
1227
|
-
*
|
|
1228
|
-
*
|
|
1229
|
-
*
|
|
1230
|
-
*
|
|
1231
|
-
* record before
|
|
1425
|
+
* encrypts once under its own attempt ID, replaces the record in one
|
|
1426
|
+
* write, and posts it. A call whose stored bytes the Relay refuses with
|
|
1427
|
+
* OPERATION_EXPIRED marks the record acceptance-unknown and posts
|
|
1428
|
+
* nothing more under that ID. A later call for that attempt and kind
|
|
1429
|
+
* finds the mark and posts nothing. A RETRY_CONFLICT answer to a post, or a
|
|
1430
|
+
* DELIVERY_ALREADY_ACCEPTED answer under protocol version 2, means that the
|
|
1431
|
+
* Relay holds an earlier encryption under this ID, so the answer is
|
|
1432
|
+
* complete. Nothing deletes the record before
|
|
1433
|
+
* `RELIABILITY_RECORD_TTL_MS`.
|
|
1232
1434
|
*
|
|
1233
1435
|
* @param recipientUserId - The user of the device
|
|
1234
1436
|
* @param recipientDeviceId - The device that gets the message
|
|
@@ -1241,14 +1443,15 @@ export class SignalProtocolServiceCipher {
|
|
|
1241
1443
|
* the content carries that own sender key of the raw group: each
|
|
1242
1444
|
* encryption keeps the key, and when the Relay accepts the bytes, the
|
|
1243
1445
|
* send records a handoff row of the key that they carry. A post that the
|
|
1244
|
-
* Relay answers with RETRY_CONFLICT
|
|
1245
|
-
* holds an
|
|
1446
|
+
* Relay answers with RETRY_CONFLICT, or with DELIVERY_ALREADY_ACCEPTED
|
|
1447
|
+
* under protocol version 2, records no row, because the Relay holds an
|
|
1448
|
+
* earlier encryption
|
|
1246
1449
|
* @param stopSignal - The stop signal of the relay work that sends. When it
|
|
1247
1450
|
* aborts while the send waits for the recipient's lock, the send throws
|
|
1248
1451
|
* RelayWorkStopped
|
|
1249
|
-
* @returns False
|
|
1250
|
-
*
|
|
1251
|
-
*
|
|
1452
|
+
* @returns False when the content is null and no stored bytes posted in
|
|
1453
|
+
* this call. True when the stored bytes posted, or when content exists
|
|
1454
|
+
* and the stored attempt has unknown acceptance. Then nothing posts
|
|
1252
1455
|
* @throws Error when the request envelope ID is not a retry request of
|
|
1253
1456
|
* the retry ID. Nothing is posted
|
|
1254
1457
|
*/
|
|
@@ -1267,11 +1470,11 @@ export class SignalProtocolServiceCipher {
|
|
|
1267
1470
|
await this.postResend(resend, retryResendAttemptId(resend), stopSignal);
|
|
1268
1471
|
}
|
|
1269
1472
|
catch (error) {
|
|
1270
|
-
if (
|
|
1473
|
+
if (!relayHoldsMessageId(error))
|
|
1271
1474
|
throw error;
|
|
1272
|
-
// Only this sender posts this ID
|
|
1273
|
-
//
|
|
1274
|
-
//
|
|
1475
|
+
// Only this sender posts this ID, and it posts one encryption under
|
|
1476
|
+
// each attempt ID. So a conflict means that the Relay holds that
|
|
1477
|
+
// encryption from an earlier post.
|
|
1275
1478
|
this.logger.info('The Relay holds an earlier encryption of a retry resend attempt', {
|
|
1276
1479
|
category: 'E2EE',
|
|
1277
1480
|
data: { retryId: resend.retryId, kind: resend.kind, attempt: resend.attempt },
|
|
@@ -1297,6 +1500,15 @@ export class SignalProtocolServiceCipher {
|
|
|
1297
1500
|
stored.terminal === undefined &&
|
|
1298
1501
|
stored.requestEnvelopeId === target.requestEnvelopeId &&
|
|
1299
1502
|
stored.kind === target.kind) {
|
|
1503
|
+
// The acceptance of the stored attempt is unknown, so nothing
|
|
1504
|
+
// more posts under its ID.
|
|
1505
|
+
if (stored.acceptanceUnknown === true) {
|
|
1506
|
+
this.logger.info('A stored retry resend has unknown acceptance, so nothing posts', {
|
|
1507
|
+
category: 'E2EE',
|
|
1508
|
+
data: { retryId: stored.retryId, kind: stored.kind, attempt: stored.attempt },
|
|
1509
|
+
});
|
|
1510
|
+
return content !== null;
|
|
1511
|
+
}
|
|
1300
1512
|
try {
|
|
1301
1513
|
await post(stored);
|
|
1302
1514
|
return true;
|
|
@@ -1305,18 +1517,21 @@ export class SignalProtocolServiceCipher {
|
|
|
1305
1517
|
if (relayOperationRefusal(error) !== 'OPERATION_EXPIRED')
|
|
1306
1518
|
throw error;
|
|
1307
1519
|
}
|
|
1308
|
-
// The Relay no longer admits or replays the stored operation.
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
}
|
|
1520
|
+
// The Relay no longer admits or replays the stored operation. It
|
|
1521
|
+
// can have accepted an earlier post of these bytes, so the
|
|
1522
|
+
// attempt keeps its ID and gets no new encryption.
|
|
1523
|
+
await storeRetryResend(this.storage, { ...stored, acceptanceUnknown: true });
|
|
1524
|
+
this.logger.info('A stored retry resend expired, and its acceptance is unknown', {
|
|
1525
|
+
category: 'E2EE',
|
|
1526
|
+
data: { retryId: stored.retryId, kind: stored.kind, attempt: stored.attempt },
|
|
1527
|
+
});
|
|
1528
|
+
return content !== null;
|
|
1316
1529
|
}
|
|
1317
1530
|
if (content === null)
|
|
1318
1531
|
return false;
|
|
1319
|
-
//
|
|
1532
|
+
// Only a target with no matching record gets here: a new request
|
|
1533
|
+
// attempt or another kind, so a new ID. Its one encryption replaces
|
|
1534
|
+
// the record before its post.
|
|
1320
1535
|
const resend = {
|
|
1321
1536
|
...target,
|
|
1322
1537
|
...(await this.encryptResend(recipientUserId, recipientDeviceId, content, options)),
|
|
@@ -1326,8 +1541,11 @@ export class SignalProtocolServiceCipher {
|
|
|
1326
1541
|
return true;
|
|
1327
1542
|
}, stopSignal);
|
|
1328
1543
|
}
|
|
1329
|
-
/**
|
|
1330
|
-
|
|
1544
|
+
/**
|
|
1545
|
+
* Post the encrypted bytes of a resend with their operation epoch, under
|
|
1546
|
+
* one client message ID. `control` gives the request checks of the post.
|
|
1547
|
+
*/
|
|
1548
|
+
async postResend(resend, clientMessageId, stopSignal, control = {}) {
|
|
1331
1549
|
const { message } = resend;
|
|
1332
1550
|
if (resend.transportMode !== 'identified' &&
|
|
1333
1551
|
(!message.sealedSenderMessage || !resend.sealedSenderAuth)) {
|
|
@@ -1338,7 +1556,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1338
1556
|
if (auth === null && required) {
|
|
1339
1557
|
throw new EncryptionError('Required group sealed-sender authorization is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: message.recipientUserId });
|
|
1340
1558
|
}
|
|
1341
|
-
|
|
1559
|
+
return this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, resend.contentHint, clientMessageId, auth === null
|
|
1342
1560
|
? undefined
|
|
1343
1561
|
: {
|
|
1344
1562
|
sentMessageBase64: message.sealedSenderMessage,
|
|
@@ -1347,6 +1565,8 @@ export class SignalProtocolServiceCipher {
|
|
|
1347
1565
|
}, {
|
|
1348
1566
|
...(stopSignal && { stopSignal }),
|
|
1349
1567
|
operationEpochMilliseconds: resend.operationEpochMilliseconds,
|
|
1568
|
+
...(control.beforeRequest && { beforeRequest: control.beforeRequest }),
|
|
1569
|
+
...(control.onRequest && { onRequest: control.onRequest }),
|
|
1350
1570
|
});
|
|
1351
1571
|
}
|
|
1352
1572
|
/**
|
|
@@ -1391,13 +1611,14 @@ export class SignalProtocolServiceCipher {
|
|
|
1391
1611
|
}, stopSignal);
|
|
1392
1612
|
}
|
|
1393
1613
|
/**
|
|
1394
|
-
* Encrypt one attempt of a resend, with the
|
|
1395
|
-
* epoch. The resend of a group send's
|
|
1396
|
-
* authorization of a pre-message: the
|
|
1397
|
-
* the group endorsement of the
|
|
1614
|
+
* Encrypt one attempt of a resend, with the epoch of the options or the
|
|
1615
|
+
* current time as its operation epoch. The resend of a group send's
|
|
1616
|
+
* message takes the sealed authorization of a pre-message: the
|
|
1617
|
+
* recipient's access key first, then the group endorsement of the
|
|
1618
|
+
* recipient's account.
|
|
1398
1619
|
*/
|
|
1399
1620
|
async encryptResend(recipientUserId, recipientDeviceId, content, options) {
|
|
1400
|
-
const operationEpochMilliseconds = Date.now();
|
|
1621
|
+
const operationEpochMilliseconds = options.operationEpochMilliseconds ?? Date.now();
|
|
1401
1622
|
const groupId = await this.findSentGroupId(recipientUserId, options.timestamp);
|
|
1402
1623
|
const sealedSender = groupId === undefined
|
|
1403
1624
|
? await this.resolveSealedSenderContext(recipientUserId)
|
|
@@ -1414,7 +1635,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1414
1635
|
// Only a group send resolves an endorsement.
|
|
1415
1636
|
throw new Error('Direct sealed-sender delivery requires access-key authorization');
|
|
1416
1637
|
}
|
|
1417
|
-
const message = await this.sesameManager.sendMessage(recipientUserId, recipientDeviceId, new TextEncoder().encode(content), { clientTimestamp: options.timestamp, includeSyncMessages: false });
|
|
1638
|
+
const message = await this.sesameManager.sendMessage(recipientUserId, recipientDeviceId, typeof content === 'string' ? new TextEncoder().encode(content) : content, { clientTimestamp: options.timestamp, includeSyncMessages: false });
|
|
1418
1639
|
return {
|
|
1419
1640
|
operationEpochMilliseconds,
|
|
1420
1641
|
transportMode: directSealedSender
|
|
@@ -1467,7 +1688,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1467
1688
|
}
|
|
1468
1689
|
/**
|
|
1469
1690
|
* Archive the session with one device, for the session reset of a retry
|
|
1470
|
-
* request that ended as `expired-content`.
|
|
1691
|
+
* request that ended as `expired-content` or `posting-deadline`.
|
|
1471
1692
|
*
|
|
1472
1693
|
* The archive takes the decrypt lock of the device first, so each decrypt
|
|
1473
1694
|
* from the device in progress ends before it, and a decrypt that starts
|
|
@@ -1807,7 +2028,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1807
2028
|
return this.encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal);
|
|
1808
2029
|
}
|
|
1809
2030
|
async encryptToUserWithOutbox(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
|
|
1810
|
-
return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal));
|
|
2031
|
+
return withOutgoingMessageIntentLock(this.storage, options.clientMessageId, () => this.encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal), options[SEND_END_REPORT]);
|
|
1811
2032
|
}
|
|
1812
2033
|
async encryptToUserWithOutboxLocked(recipientUserId, plaintextBytes, options, sessions, stopSignal) {
|
|
1813
2034
|
const plaintextDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(plaintextBytes));
|
|
@@ -1819,13 +2040,19 @@ export class SignalProtocolServiceCipher {
|
|
|
1819
2040
|
existing.contentHint !== options.contentHint) {
|
|
1820
2041
|
throw new Error('A clientMessageId cannot identify two different logical sends');
|
|
1821
2042
|
}
|
|
2043
|
+
// A send that ended at its posting deadline posts nothing again.
|
|
2044
|
+
if (!existing.result && existing.outcome)
|
|
2045
|
+
throw storedSendEndError(existing);
|
|
2046
|
+
const replay = this.sendCallEvidence(existing);
|
|
1822
2047
|
if (this.declaresDeviceSets() && existing.kind === 'direct') {
|
|
1823
|
-
return this.replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal);
|
|
2048
|
+
return this.replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal, replay);
|
|
1824
2049
|
}
|
|
2050
|
+
// An undeclared intent completes with syncPending only when the posting
|
|
2051
|
+
// deadline stopped its sync posts, so a replay posts nothing.
|
|
1825
2052
|
if (existing.result)
|
|
1826
|
-
return existing
|
|
2053
|
+
return outgoingMessageIntentResult(existing);
|
|
1827
2054
|
const reconciled = await this.reconcilePendingDirectIntent(existing, plaintextBytes, sessions);
|
|
1828
|
-
return this.sendStoredDirectIntent(await this.reconcileDirectSyncDevices(reconciled, plaintextBytes, sessions, stopSignal), plaintextBytes, sessions, stopSignal);
|
|
2055
|
+
return this.sendStoredDirectIntent(await this.reconcileDirectSyncDevices(reconciled, plaintextBytes, sessions, stopSignal), plaintextBytes, sessions, stopSignal, replay);
|
|
1829
2056
|
}
|
|
1830
2057
|
// A new send checks the timestamp before the session setup, which can
|
|
1831
2058
|
// post to the Relay. The replays above keep the stored timestamp.
|
|
@@ -1880,29 +2107,571 @@ export class SignalProtocolServiceCipher {
|
|
|
1880
2107
|
throw firstItemError(error);
|
|
1881
2108
|
});
|
|
1882
2109
|
const syncMessages = await Promise.all(batch.syncMessages.map((message) => this.prepareStoredSyncMessage(message, syncMessageId(options.clientMessageId, message))));
|
|
2110
|
+
// One clock read gives the first durable write and its posting deadline.
|
|
2111
|
+
const createdAt = Date.now();
|
|
1883
2112
|
const intent = {
|
|
1884
2113
|
kind: 'direct',
|
|
1885
2114
|
clientMessageId: options.clientMessageId,
|
|
1886
2115
|
recipientId: recipientUserId,
|
|
1887
2116
|
plaintextDigest,
|
|
1888
2117
|
clientTimestamp,
|
|
1889
|
-
createdAt
|
|
2118
|
+
createdAt,
|
|
2119
|
+
deadlineAt: outgoingMessageDeadlineAt({ createdAt, clientTimestamp }),
|
|
1890
2120
|
transportMode,
|
|
1891
2121
|
...(sealedSenderAuth && { sealedSenderAuth }),
|
|
1892
2122
|
...(options.contentHint !== undefined && {
|
|
1893
2123
|
contentHint: options.contentHint,
|
|
1894
2124
|
}),
|
|
2125
|
+
...intentBinaryAttachment(options),
|
|
1895
2126
|
...(sendFirst && { reconcilePending: true }),
|
|
1896
2127
|
deviceMessages,
|
|
1897
2128
|
syncMessages,
|
|
2129
|
+
progressFromStart: true,
|
|
2130
|
+
...(options[SEND_END_REPORT]?.internal && { internal: true }),
|
|
1898
2131
|
};
|
|
2132
|
+
const evidence = this.sendCallEvidence(intent);
|
|
1899
2133
|
await storeOutgoingMessageIntent(this.storage, intent);
|
|
1900
|
-
if (declared)
|
|
1901
|
-
return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
|
|
2134
|
+
if (declared) {
|
|
2135
|
+
return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
|
|
2136
|
+
}
|
|
1902
2137
|
if (sendFirst && sessions) {
|
|
1903
|
-
return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal);
|
|
2138
|
+
return this.sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal, evidence);
|
|
2139
|
+
}
|
|
2140
|
+
return this.sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* The evidence of one `send()` call of a direct or group intent. It starts
|
|
2144
|
+
* from the stored progress of the intent and stores each answer of the
|
|
2145
|
+
* call.
|
|
2146
|
+
*/
|
|
2147
|
+
sendCallEvidence(intent) {
|
|
2148
|
+
return new SendCallEvidence({
|
|
2149
|
+
clientMessageId: intent.clientMessageId,
|
|
2150
|
+
deadlineAt: outgoingMessageDeadlineAt(intent),
|
|
2151
|
+
...(intent.destinationProgress && { progress: intent.destinationProgress }),
|
|
2152
|
+
...(intent.progressFromStart && { progressFromStart: true }),
|
|
2153
|
+
...(intent.transportMode === 'sealed_sender_required' && { sealedSenderRequired: true }),
|
|
2154
|
+
clock: () => Date.now(),
|
|
2155
|
+
refusesDevice: isConclusiveDeviceRejection,
|
|
2156
|
+
recordProgress: (key, update) => recordOutgoingDestinationProgress(this.storage, intent.clientMessageId, key, update),
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
/** A post control whose requests meet the posting deadline of the call. */
|
|
2160
|
+
postingControl(evidence, base) {
|
|
2161
|
+
return { ...base, beforeRequest: evidence.check };
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Post one device message of a direct intent and record its answer in the
|
|
2165
|
+
* evidence of the call. Before each request of the post, the outbox stores
|
|
2166
|
+
* the request of the device, after the checks of `control`. So the stored
|
|
2167
|
+
* progress counts every request that starts.
|
|
2168
|
+
*/
|
|
2169
|
+
postDirectDeviceMessage(intent, message, control, evidence) {
|
|
2170
|
+
const [destination] = sendDestinations(intent.clientMessageId, [message]);
|
|
2171
|
+
const { device, postMessageId } = destination;
|
|
2172
|
+
const key = outgoingDestinationProgressKey(postMessageId, device);
|
|
2173
|
+
const beforeRequest = async () => {
|
|
2174
|
+
await control.beforeRequest?.();
|
|
2175
|
+
await recordOutgoingDestinationProgress(this.storage, intent.clientMessageId, key, {
|
|
2176
|
+
phase: 'recipient',
|
|
2177
|
+
userId: device.userId,
|
|
2178
|
+
deviceId: device.deviceId,
|
|
2179
|
+
postMessageId,
|
|
2180
|
+
request: true,
|
|
2181
|
+
});
|
|
2182
|
+
};
|
|
2183
|
+
return evidence.post(destination, (onRequest) => this.sendStoredDirectDeviceMessage(intent, message, { ...control, beforeRequest, onRequest }));
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* Post one destination of a group send and record its answer in the
|
|
2187
|
+
* evidence of the call. Before each request of the post, the outbox stores
|
|
2188
|
+
* the request of the destination, after the checks of `control`.
|
|
2189
|
+
*/
|
|
2190
|
+
postGroupDestination(clientMessageId, destination, evidence, control, post) {
|
|
2191
|
+
const beforeRequest = this.recordingRequests(clientMessageId, [destination], control);
|
|
2192
|
+
return evidence.post(destination, (onRequest) => post({ ...control, beforeRequest, onRequest }));
|
|
2193
|
+
}
|
|
2194
|
+
/**
|
|
2195
|
+
* The `beforeRequest` of a group post: it runs the checks of `control`,
|
|
2196
|
+
* then stores the request of each destination of the post.
|
|
2197
|
+
*/
|
|
2198
|
+
recordingRequests(clientMessageId, destinations, control) {
|
|
2199
|
+
return async () => {
|
|
2200
|
+
await control.beforeRequest?.();
|
|
2201
|
+
for (const { device, postMessageId } of destinations) {
|
|
2202
|
+
await recordOutgoingDestinationProgress(this.storage, clientMessageId, outgoingDestinationProgressKey(postMessageId, device), {
|
|
2203
|
+
phase: 'recipient',
|
|
2204
|
+
userId: device.userId,
|
|
2205
|
+
deviceId: device.deviceId,
|
|
2206
|
+
postMessageId,
|
|
2207
|
+
request: true,
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Send one relay request of a group post under a slot of the bound. With
|
|
2214
|
+
* one destination, the evidence of the call records the requests and the
|
|
2215
|
+
* answer of the device, and a repeat request that the transport starts for
|
|
2216
|
+
* the device meets the deadline and stores its request first. With a list,
|
|
2217
|
+
* the post is a shared body: each request counts for each destination, and
|
|
2218
|
+
* the one answer is recorded on each destination. A repeat request that the
|
|
2219
|
+
* transport starts for one destination of the body stores the request of
|
|
2220
|
+
* that destination.
|
|
2221
|
+
*/
|
|
2222
|
+
postGroupRelay(send, sealed, control, evidence, clientMessageId, destination) {
|
|
2223
|
+
const ownRepeat = (repeat, { device }) => repeat.userId === device.userId && repeat.deviceId === device.deviceId;
|
|
2224
|
+
if (!isDestinationList(destination)) {
|
|
2225
|
+
const post = send;
|
|
2226
|
+
return this.postGroupDestination(clientMessageId, destination, evidence, control, async (posting) => {
|
|
2227
|
+
// The transport gates a repeat by the ID that the posted envelope
|
|
2228
|
+
// carries. Other posts of the send carry the same ID, so the gate
|
|
2229
|
+
// takes only a repeat of this device.
|
|
2230
|
+
const release = admitRequestsFor(this.relay, clientMessageId, async (repeat) => {
|
|
2231
|
+
if (ownRepeat(repeat, destination))
|
|
2232
|
+
await posting.beforeRequest?.();
|
|
2233
|
+
}, (repeat) => {
|
|
2234
|
+
if (ownRepeat(repeat, destination))
|
|
2235
|
+
posting.onRequest?.(repeat.after);
|
|
2236
|
+
});
|
|
2237
|
+
try {
|
|
2238
|
+
return await this.postToRelay(post, sealed, posting);
|
|
2239
|
+
}
|
|
2240
|
+
finally {
|
|
2241
|
+
release();
|
|
2242
|
+
}
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
const destinations = destination;
|
|
2246
|
+
const shared = send;
|
|
2247
|
+
const beforeRequest = this.recordingRequests(clientMessageId, destinations, control);
|
|
2248
|
+
return evidence.postShared(destinations, async (onRequest) => {
|
|
2249
|
+
// The transport gates a repeat of the body once for each destination
|
|
2250
|
+
// device. Each gate stores the request of its device, and the repeat
|
|
2251
|
+
// counts once, at the first destination.
|
|
2252
|
+
const release = admitRequestsFor(this.relay, clientMessageId, async (repeat) => {
|
|
2253
|
+
const target = destinations.filter((candidate) => ownRepeat(repeat, candidate));
|
|
2254
|
+
await this.recordingRequests(clientMessageId, target, control)();
|
|
2255
|
+
}, (repeat) => {
|
|
2256
|
+
if (destinations[0] && ownRepeat(repeat, destinations[0]))
|
|
2257
|
+
onRequest(repeat.after);
|
|
2258
|
+
});
|
|
2259
|
+
try {
|
|
2260
|
+
return await this.postToRelay(shared, sealed, { ...control, beforeRequest, onRequest });
|
|
2261
|
+
}
|
|
2262
|
+
finally {
|
|
2263
|
+
release();
|
|
2264
|
+
}
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
/**
|
|
2268
|
+
* Decide the recipient phase of a direct or group send that failed. At or
|
|
2269
|
+
* after the posting deadline with an open destination, or when every open
|
|
2270
|
+
* destination got OPERATION_EXPIRED, the send ends: the outbox stores its outcome, and
|
|
2271
|
+
* the error is the class of the end. Before that, the error is thrown with
|
|
2272
|
+
* the deadline, and the intent stays open. A device-set reconciliation
|
|
2273
|
+
* error keeps its own rule.
|
|
2274
|
+
*/
|
|
2275
|
+
async endOrRethrow(intent, evidence, error) {
|
|
2276
|
+
if (error instanceof DeviceSetReconciliationError)
|
|
2277
|
+
throw error;
|
|
2278
|
+
const current = (await getOutgoingMessageIntent(this.storage, intent.clientMessageId)) ?? intent;
|
|
2279
|
+
const end = recipientSendEnd(current, evidence, this.userId, this.deviceId);
|
|
2280
|
+
if (!end)
|
|
2281
|
+
throw attachSendDeadline(error, evidence.deadlineAt);
|
|
2282
|
+
await endOutgoingMessageIntent(this.storage, intent.clientMessageId, {
|
|
2283
|
+
outcome: end.outcome,
|
|
2284
|
+
destinationProgress: end.destinationProgress,
|
|
2285
|
+
});
|
|
2286
|
+
throw end.error;
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* End an open intent whose posting deadline has passed, with the class that
|
|
2290
|
+
* its stored progress gives, and post nothing. The SDK send driver calls it.
|
|
2291
|
+
* Under the intent lock, the call reads the intent again. An intent that is
|
|
2292
|
+
* gone, ended, completed or not yet due stays as it is. Past the deadline,
|
|
2293
|
+
* the stored progress gives no end only when the Relay accepted each
|
|
2294
|
+
* recipient destination: the call then completes the intent from its
|
|
2295
|
+
* stored progress, with `syncPending` when a sync copy is not accepted. With
|
|
2296
|
+
* `report`, the end write or the completion write records the end in it.
|
|
2297
|
+
*/
|
|
2298
|
+
async endPastDeadlineIntent(clientMessageId, report) {
|
|
2299
|
+
await withOutgoingMessageIntentLock(this.storage, clientMessageId, async () => {
|
|
2300
|
+
const current = await getOutgoingMessageIntent(this.storage, clientMessageId);
|
|
2301
|
+
if (!current || current.result || current.outcome !== undefined)
|
|
2302
|
+
return;
|
|
2303
|
+
if (Date.now() < outgoingMessageDeadlineAt(current))
|
|
2304
|
+
return;
|
|
2305
|
+
const end = recipientSendEnd(current, this.sendCallEvidence(current), this.userId, this.deviceId);
|
|
2306
|
+
if (!end) {
|
|
2307
|
+
await this.completeAcceptedIntent(current);
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
await endOutgoingMessageIntent(this.storage, clientMessageId, {
|
|
2311
|
+
outcome: end.outcome,
|
|
2312
|
+
destinationProgress: end.destinationProgress,
|
|
2313
|
+
});
|
|
2314
|
+
}, report);
|
|
2315
|
+
}
|
|
2316
|
+
/**
|
|
2317
|
+
* Complete an open intent whose stored progress records each recipient
|
|
2318
|
+
* destination as accepted, with no post. A process can stop after the last
|
|
2319
|
+
* acceptance and before the completion write, or a sync failure can leave
|
|
2320
|
+
* the intent open after its recipient phase. The result takes its message
|
|
2321
|
+
* ID and time from the stored acceptances, as a send call that found each
|
|
2322
|
+
* destination accepted does. A sync copy with no stored acceptance keeps
|
|
2323
|
+
* the sync phase pending. The caller holds the intent lock.
|
|
2324
|
+
*/
|
|
2325
|
+
async completeAcceptedIntent(intent) {
|
|
2326
|
+
const progress = intent.destinationProgress ?? {};
|
|
2327
|
+
const clock = () => Date.now();
|
|
2328
|
+
const acceptances = recipientDestinations(intent, this.userId, this.deviceId).map(({ device, postMessageId }) => storedAcceptance(progress[outgoingDestinationProgressKey(postMessageId, device)], clock));
|
|
2329
|
+
const first = sendResultAcceptance(acceptances);
|
|
2330
|
+
const group = intent.kind === 'group';
|
|
2331
|
+
const result = {
|
|
2332
|
+
clientMessageId: intent.clientMessageId,
|
|
2333
|
+
messageId: first?.messageId ??
|
|
2334
|
+
(group
|
|
2335
|
+
? `group-${intent.recipientId}-${String(intent.clientTimestamp)}`
|
|
2336
|
+
: `local-${intent.clientTimestamp}`),
|
|
2337
|
+
timestamp: first?.serverTimestamp ?? intent.clientTimestamp,
|
|
2338
|
+
recipientDeviceCount: group
|
|
2339
|
+
? (intent.groupRecipientDeviceCount ?? intent.deviceMessages.length)
|
|
2340
|
+
: intent.deviceMessages.length,
|
|
2341
|
+
...aggregateRelayAcceptance(acceptances),
|
|
2342
|
+
...(group && { groupId: intent.recipientId }),
|
|
2343
|
+
};
|
|
2344
|
+
const syncPending = intent.syncMessages.some((message) => {
|
|
2345
|
+
const { device, postMessageId } = syncDestination(intent.clientMessageId, message);
|
|
2346
|
+
return progress[outgoingDestinationProgressKey(postMessageId, device)]?.state !== 'accepted';
|
|
2347
|
+
});
|
|
2348
|
+
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result, {
|
|
2349
|
+
syncPending,
|
|
2350
|
+
});
|
|
2351
|
+
if (group && intent.contentHint === ContentHint.Resendable) {
|
|
2352
|
+
await this.storage.markSendLogComplete(intent.clientMessageId);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
/**
|
|
2356
|
+
* Post a manual resend of a send that ended at its posting deadline
|
|
2357
|
+
* without acceptance (`resendMessage`). Only an intent with `outcome` and
|
|
2358
|
+
* no `result` takes one.
|
|
2359
|
+
*
|
|
2360
|
+
* - With no open resend, the call stores a new one. Its message ID is
|
|
2361
|
+
* `<clientMessageId>:manual:N`, N from 1. One clock read gives its
|
|
2362
|
+
* `createdAt` and its operation epoch, and its posting deadline is 24
|
|
2363
|
+
* hours later. It encrypts `content` again for each recipient device
|
|
2364
|
+
* that no post of the send or of an earlier resend got accepted, with
|
|
2365
|
+
* the client timestamp of the send in the content. Logged bytes of a
|
|
2366
|
+
* group send carry the group context of the send and post as they are.
|
|
2367
|
+
* Other content of a group intent takes the current group context.
|
|
2368
|
+
* - An open resend posts again under its stored epoch and bytes, and the
|
|
2369
|
+
* call ignores `content`. At or after its deadline, it ends from its
|
|
2370
|
+
* stored progress and posts nothing.
|
|
2371
|
+
*
|
|
2372
|
+
* The resend ends with its result when the Relay accepts each of its
|
|
2373
|
+
* devices, or with its class (contract §3.4) when it is due. A
|
|
2374
|
+
* RETRY_CONFLICT under the manual message ID, or a version 2
|
|
2375
|
+
* DELIVERY_ALREADY_ACCEPTED, is the resend's own earlier post, so it counts
|
|
2376
|
+
* as accepted. The end write fills `report`.
|
|
2377
|
+
*
|
|
2378
|
+
* @throws Error when the send is missing, open, completed, or accepted by
|
|
2379
|
+
* each recipient device. Nothing is posted
|
|
2380
|
+
*/
|
|
2381
|
+
async resendOutgoingMessage(clientMessageId, content, options = {}) {
|
|
2382
|
+
const { stopSignal, report } = options;
|
|
2383
|
+
try {
|
|
2384
|
+
return await this.withManualResendOrderLock(clientMessageId, stopSignal, () => this.resendOutgoingMessageOrdered(clientMessageId, content, stopSignal, report));
|
|
2385
|
+
}
|
|
2386
|
+
catch (error) {
|
|
2387
|
+
throw attachClientMessageId(error, clientMessageId);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Post the open manual resend of an ended intent again for the SDK send
|
|
2392
|
+
* driver, as `resendOutgoingMessage` does with no content. When the intent
|
|
2393
|
+
* has no open resend under the intent lock, for example because a
|
|
2394
|
+
* `resendMessage` call ended it after the driver listed it, the call posts
|
|
2395
|
+
* nothing and fills nothing in `report`.
|
|
2396
|
+
*/
|
|
2397
|
+
async replayManualResend(clientMessageId, options) {
|
|
2398
|
+
const { stopSignal, report } = options;
|
|
2399
|
+
try {
|
|
2400
|
+
await this.withManualResendOrderLock(clientMessageId, stopSignal, () => withOutgoingMessageIntentLock(this.storage, clientMessageId, async () => {
|
|
2401
|
+
const intent = await getOutgoingMessageIntent(this.storage, clientMessageId);
|
|
2402
|
+
const open = intent && outgoingManualResends(intent).find(isOpenManualResend);
|
|
2403
|
+
if (!intent || !open)
|
|
2404
|
+
return;
|
|
2405
|
+
await this.continueManualResend(endedManualResendIntent(intent), open, stopSignal, report);
|
|
2406
|
+
}));
|
|
2407
|
+
}
|
|
2408
|
+
catch (error) {
|
|
2409
|
+
throw attachClientMessageId(error, clientMessageId);
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
* Run `operation` under the order lock of the recipient of a stored send.
|
|
2414
|
+
* A resend keeps the order of the sends to its recipient, as a send does,
|
|
2415
|
+
* and the lock serializes the manual resends of one intent.
|
|
2416
|
+
*/
|
|
2417
|
+
async withManualResendOrderLock(clientMessageId, stopSignal, operation) {
|
|
2418
|
+
if (!this.relay)
|
|
2419
|
+
throw new Error('Relay not configured - cannot resend');
|
|
2420
|
+
const stored = await getOutgoingMessageIntent(this.storage, clientMessageId);
|
|
2421
|
+
if (!stored)
|
|
2422
|
+
throw new Error('No stored send has this clientMessageId');
|
|
2423
|
+
return acquireUntilStopped(this.lock, `encrypt:${manualResendOrderKey(stored)}`, operation, stopSignal);
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Post a manual resend under the order lock. No encrypt lock is taken
|
|
2427
|
+
* while the intent lock is held: a send takes its encrypt lock before the
|
|
2428
|
+
* intent lock, so the other order can deadlock with it.
|
|
2429
|
+
*
|
|
2430
|
+
* 1. Under the intent lock, an open resend posts or ends. With no open
|
|
2431
|
+
* resend, the checks run and the call plans a new resend.
|
|
2432
|
+
* 2. With no intent lock held, the call encrypts the content for each
|
|
2433
|
+
* target device.
|
|
2434
|
+
* 3. Under the intent lock, the call stores the resend, which refuses a
|
|
2435
|
+
* change to the intent since step 1, and posts it.
|
|
2436
|
+
*/
|
|
2437
|
+
async resendOutgoingMessageOrdered(clientMessageId, content, stopSignal, report) {
|
|
2438
|
+
const step = await withOutgoingMessageIntentLock(this.storage, clientMessageId, async () => {
|
|
2439
|
+
const intent = endedManualResendIntent(await getOutgoingMessageIntent(this.storage, clientMessageId));
|
|
2440
|
+
const open = outgoingManualResends(intent).find(isOpenManualResend);
|
|
2441
|
+
if (open)
|
|
2442
|
+
return { done: await this.continueManualResend(intent, open, stopSignal, report) };
|
|
2443
|
+
return {
|
|
2444
|
+
plan: await planManualResend(intent, content, this.userId, this.deviceId, (plaintext) => this.withoutGroupContext(plaintext)),
|
|
2445
|
+
};
|
|
2446
|
+
});
|
|
2447
|
+
if ('done' in step)
|
|
2448
|
+
return step.done;
|
|
2449
|
+
const resend = await this.encryptManualResend(step.plan, stopSignal);
|
|
2450
|
+
return withOutgoingMessageIntentLock(this.storage, clientMessageId, async () => {
|
|
2451
|
+
const intent = await addOutgoingManualResend(this.storage, clientMessageId, resend);
|
|
2452
|
+
return this.continueManualResend(intent, resend, stopSignal, report);
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Post an open manual resend, or end it from its stored progress at or
|
|
2457
|
+
* after its deadline. The caller holds the intent lock.
|
|
2458
|
+
*/
|
|
2459
|
+
async continueManualResend(intent, resend, stopSignal, report) {
|
|
2460
|
+
if (Date.now() >= resend.deadlineAt) {
|
|
2461
|
+
const ended = await this.endStoredManualResend(intent, resend);
|
|
2462
|
+
if (report)
|
|
2463
|
+
report.ended = { intent, resend: ended };
|
|
2464
|
+
if (ended.result)
|
|
2465
|
+
return { ...ended.result };
|
|
2466
|
+
throw storedSendEndError(manualResendIntent(intent, ended));
|
|
2467
|
+
}
|
|
2468
|
+
return this.postManualResend(intent, resend, stopSignal, report);
|
|
2469
|
+
}
|
|
2470
|
+
/**
|
|
2471
|
+
* Encrypt a planned manual resend for each of its target devices. The
|
|
2472
|
+
* caller holds the order lock of the recipient and no intent lock.
|
|
2473
|
+
*/
|
|
2474
|
+
async encryptManualResend(plan, stopSignal) {
|
|
2475
|
+
const { intent, targets, manualMessageId, createdAt } = plan;
|
|
2476
|
+
// A group resend is a direct message to each device, with the group
|
|
2477
|
+
// context of the content that the group send carried. The logged bytes
|
|
2478
|
+
// of the group send carry that context already. The caller bytes of a
|
|
2479
|
+
// message record take the current context once.
|
|
2480
|
+
const bytes = intent.kind === 'group' && !plan.content.withGroupContext
|
|
2481
|
+
? await this.contentWithGroupContext(intent.recipientId, plan.content.content)
|
|
2482
|
+
: plan.content.content;
|
|
2483
|
+
const messages = [];
|
|
2484
|
+
const heldOrderKey = manualResendOrderKey(intent);
|
|
2485
|
+
for (const device of targets) {
|
|
2486
|
+
const encrypt = () => this.encryptResend(device.userId, device.deviceId, bytes, {
|
|
2487
|
+
timestamp: intent.clientTimestamp,
|
|
2488
|
+
...(intent.contentHint !== undefined && { contentHint: intent.contentHint }),
|
|
2489
|
+
operationEpochMilliseconds: createdAt,
|
|
2490
|
+
});
|
|
2491
|
+
// encryptResend takes no lock. As in the retry resend, the encryption
|
|
2492
|
+
// to a user runs under the order lock of that user. The caller holds
|
|
2493
|
+
// that lock for the recipient of a direct send, and the lock is not
|
|
2494
|
+
// reentrant.
|
|
2495
|
+
const encrypted = device.userId === heldOrderKey
|
|
2496
|
+
? await encrypt()
|
|
2497
|
+
: await acquireUntilStopped(this.lock, `encrypt:${device.userId}`, encrypt, stopSignal);
|
|
2498
|
+
messages.push({
|
|
2499
|
+
transportMode: encrypted.transportMode,
|
|
2500
|
+
...(encrypted.sealedSenderAuth && { sealedSenderAuth: encrypted.sealedSenderAuth }),
|
|
2501
|
+
...(encrypted.contentHint !== undefined && { contentHint: encrypted.contentHint }),
|
|
2502
|
+
message: { ...encrypted.message, clientMessageId: manualMessageId },
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
return {
|
|
2506
|
+
manualMessageId,
|
|
2507
|
+
createdAt,
|
|
2508
|
+
operationEpochMilliseconds: createdAt,
|
|
2509
|
+
deadlineAt: createdAt + OUTGOING_POSTING_WINDOW_MS,
|
|
2510
|
+
messages,
|
|
2511
|
+
};
|
|
2512
|
+
}
|
|
2513
|
+
/** The evidence of one call of a manual resend, from its stored progress. */
|
|
2514
|
+
manualResendEvidence(intent, resend) {
|
|
2515
|
+
return new SendCallEvidence({
|
|
2516
|
+
clientMessageId: intent.clientMessageId,
|
|
2517
|
+
deadlineAt: resend.deadlineAt,
|
|
2518
|
+
...(resend.destinationProgress && { progress: resend.destinationProgress }),
|
|
2519
|
+
progressFromStart: true,
|
|
2520
|
+
...(intent.transportMode === 'sealed_sender_required' && { sealedSenderRequired: true }),
|
|
2521
|
+
clock: () => Date.now(),
|
|
2522
|
+
refusesDevice: isConclusiveDeviceRejection,
|
|
2523
|
+
recordProgress: (key, update) => recordOutgoingManualResendProgress(this.storage, intent.clientMessageId, resend.manualMessageId, key, update),
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* Post each device of an open manual resend under its stored epoch, and
|
|
2528
|
+
* end the resend when each device is accepted or when it is due. The
|
|
2529
|
+
* caller holds the intent lock.
|
|
2530
|
+
*/
|
|
2531
|
+
async postManualResend(intent, resend, stopSignal, report) {
|
|
2532
|
+
const { clientMessageId } = intent;
|
|
2533
|
+
const { manualMessageId } = resend;
|
|
2534
|
+
const evidence = this.manualResendEvidence(intent, resend);
|
|
2535
|
+
const destinations = manualResendDestinations(resend);
|
|
2536
|
+
let skippedRefusal = false;
|
|
2537
|
+
let acceptances;
|
|
2538
|
+
try {
|
|
2539
|
+
const posted = await this.sendPhase(resend.messages.map((stored, index) => ({
|
|
2540
|
+
recipientUserId: stored.message.recipientUserId,
|
|
2541
|
+
recipientDeviceId: stored.message.recipientDeviceId,
|
|
2542
|
+
stored,
|
|
2543
|
+
destination: destinations[index],
|
|
2544
|
+
})), async ({ stored, destination }) => {
|
|
2545
|
+
const { device, postMessageId } = destination;
|
|
2546
|
+
const key = outgoingDestinationProgressKey(postMessageId, device);
|
|
2547
|
+
if (provenRefused(resend.destinationProgress?.[key])) {
|
|
2548
|
+
skippedRefusal = true;
|
|
2549
|
+
return undefined;
|
|
2550
|
+
}
|
|
2551
|
+
return evidence.post(destination, (onRequest) => this.postResend({ ...stored, operationEpochMilliseconds: resend.operationEpochMilliseconds }, manualMessageId, stopSignal, {
|
|
2552
|
+
beforeRequest: async () => {
|
|
2553
|
+
await evidence.check();
|
|
2554
|
+
await recordOutgoingManualResendProgress(this.storage, clientMessageId, manualMessageId, key, {
|
|
2555
|
+
phase: 'recipient',
|
|
2556
|
+
userId: device.userId,
|
|
2557
|
+
deviceId: device.deviceId,
|
|
2558
|
+
postMessageId,
|
|
2559
|
+
request: true,
|
|
2560
|
+
});
|
|
2561
|
+
},
|
|
2562
|
+
onRequest,
|
|
2563
|
+
}));
|
|
2564
|
+
}, 'device', stopSignal);
|
|
2565
|
+
acceptances = posted.filter((acceptance) => acceptance !== undefined);
|
|
2566
|
+
}
|
|
2567
|
+
catch (error) {
|
|
2568
|
+
const end = await this.endDueManualResend(intent, resend, evidence, report);
|
|
2569
|
+
if (end)
|
|
2570
|
+
throw end;
|
|
2571
|
+
throw attachSendDeadline(error, resend.deadlineAt);
|
|
1904
2572
|
}
|
|
1905
|
-
|
|
2573
|
+
if (skippedRefusal) {
|
|
2574
|
+
const end = await this.endDueManualResend(intent, resend, evidence, report);
|
|
2575
|
+
if (end)
|
|
2576
|
+
throw end;
|
|
2577
|
+
}
|
|
2578
|
+
const result = manualResendResult(intent, resend, acceptances);
|
|
2579
|
+
const ended = await endOutgoingManualResend(this.storage, clientMessageId, manualMessageId, { result });
|
|
2580
|
+
if (ended && report)
|
|
2581
|
+
report.ended = { intent, resend: ended };
|
|
2582
|
+
return result;
|
|
2583
|
+
}
|
|
2584
|
+
/**
|
|
2585
|
+
* End a manual resend that is due after a failed post (contract §3.4), and
|
|
2586
|
+
* return the error of its end. Undefined when the resend stays open. The
|
|
2587
|
+
* caller holds the intent lock.
|
|
2588
|
+
*/
|
|
2589
|
+
async endDueManualResend(intent, resend, evidence, report) {
|
|
2590
|
+
const current = (await getOutgoingMessageIntent(this.storage, intent.clientMessageId))?.manualResends?.find((candidate) => candidate.manualMessageId === resend.manualMessageId) ?? resend;
|
|
2591
|
+
const end = evidence.end(manualResendDestinations(resend), current.destinationProgress);
|
|
2592
|
+
if (!end)
|
|
2593
|
+
return undefined;
|
|
2594
|
+
const ended = await endOutgoingManualResend(this.storage, intent.clientMessageId, resend.manualMessageId, { outcome: end.outcome, destinationProgress: end.destinationProgress });
|
|
2595
|
+
if (ended && report)
|
|
2596
|
+
report.ended = { intent, resend: ended };
|
|
2597
|
+
return end.error;
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* End an open manual resend from its stored progress, and post nothing:
|
|
2601
|
+
* with its result when the Relay accepted each of its devices, else with
|
|
2602
|
+
* its class. The caller holds the intent lock.
|
|
2603
|
+
*/
|
|
2604
|
+
async endStoredManualResend(intent, resend) {
|
|
2605
|
+
const destinations = manualResendDestinations(resend);
|
|
2606
|
+
const progress = resend.destinationProgress ?? {};
|
|
2607
|
+
const end = this.manualResendEvidence(intent, resend).classify(destinations, progress);
|
|
2608
|
+
const clock = () => Date.now();
|
|
2609
|
+
const ended = await endOutgoingManualResend(this.storage, intent.clientMessageId, resend.manualMessageId, end
|
|
2610
|
+
? { outcome: end.outcome, destinationProgress: end.destinationProgress }
|
|
2611
|
+
: {
|
|
2612
|
+
result: manualResendResult(intent, resend, destinations.map(({ device, postMessageId }) => storedAcceptance(progress[outgoingDestinationProgressKey(postMessageId, device)], clock))),
|
|
2613
|
+
});
|
|
2614
|
+
if (!ended)
|
|
2615
|
+
throw new Error('A manual resend ended in another call');
|
|
2616
|
+
return ended;
|
|
2617
|
+
}
|
|
2618
|
+
/**
|
|
2619
|
+
* End an open manual resend whose posting deadline has passed, from its
|
|
2620
|
+
* stored progress, and post nothing. The SDK send driver calls it. Under
|
|
2621
|
+
* the intent lock, the call reads the intent again.
|
|
2622
|
+
*
|
|
2623
|
+
* @returns The intent and the ended resend, or undefined when the resend
|
|
2624
|
+
* is gone, ended or not yet due
|
|
2625
|
+
*/
|
|
2626
|
+
async endPastDeadlineManualResend(clientMessageId, manualMessageId) {
|
|
2627
|
+
return withOutgoingMessageIntentLock(this.storage, clientMessageId, async () => {
|
|
2628
|
+
const intent = await getOutgoingMessageIntent(this.storage, clientMessageId);
|
|
2629
|
+
const resend = intent?.manualResends?.find((candidate) => candidate.manualMessageId === manualMessageId);
|
|
2630
|
+
if (!intent || !resend || !isOpenManualResend(resend))
|
|
2631
|
+
return undefined;
|
|
2632
|
+
if (Date.now() < resend.deadlineAt)
|
|
2633
|
+
return undefined;
|
|
2634
|
+
return { intent, resend: await this.endStoredManualResend(intent, resend) };
|
|
2635
|
+
});
|
|
2636
|
+
}
|
|
2637
|
+
/**
|
|
2638
|
+
* End a replay whose recipient phase posted no device that a stored
|
|
2639
|
+
* refusal proves refused (`provenRefused`). When every open device has such
|
|
2640
|
+
* a refusal, the send ends now: the outbox stores its outcome, and the end
|
|
2641
|
+
* error is thrown. Otherwise the call returns, and the replay goes on.
|
|
2642
|
+
*/
|
|
2643
|
+
async endRefusedReplay(intent, evidence) {
|
|
2644
|
+
const current = (await getOutgoingMessageIntent(this.storage, intent.clientMessageId)) ?? intent;
|
|
2645
|
+
const end = recipientSendEnd(current, evidence, this.userId, this.deviceId);
|
|
2646
|
+
if (!end)
|
|
2647
|
+
return;
|
|
2648
|
+
await endOutgoingMessageIntent(this.storage, intent.clientMessageId, {
|
|
2649
|
+
outcome: end.outcome,
|
|
2650
|
+
destinationProgress: end.destinationProgress,
|
|
2651
|
+
});
|
|
2652
|
+
throw end.error;
|
|
2653
|
+
}
|
|
2654
|
+
/**
|
|
2655
|
+
* The end of a recipient phase that the device-set reconciliation ended
|
|
2656
|
+
* unresolved: the class of the send at this point (contract §3.4), from
|
|
2657
|
+
* the evidence of the call and the stored progress. Reason `expired` gives
|
|
2658
|
+
* `acceptance-unknown`, because the Relay refused the restart post with
|
|
2659
|
+
* OPERATION_EXPIRED and an earlier post of the operation can have been
|
|
2660
|
+
* accepted. Undefined for an intent that is gone or ended, or whose
|
|
2661
|
+
* recipient destinations are all accepted. The caller holds the intent
|
|
2662
|
+
* lock.
|
|
2663
|
+
*/
|
|
2664
|
+
async unresolvedRecipientEnd(clientMessageId, evidence, unresolved) {
|
|
2665
|
+
const current = await getOutgoingMessageIntent(this.storage, clientMessageId);
|
|
2666
|
+
if (!current || current.result || current.outcome !== undefined)
|
|
2667
|
+
return undefined;
|
|
2668
|
+
const end = evidence.classify(recipientDestinations(current, this.userId, this.deviceId), current.destinationProgress);
|
|
2669
|
+
if (!end)
|
|
2670
|
+
return undefined;
|
|
2671
|
+
return {
|
|
2672
|
+
outcome: unresolved.reason === 'expired' ? 'acceptance-unknown' : end.outcome,
|
|
2673
|
+
destinationProgress: end.destinationProgress,
|
|
2674
|
+
};
|
|
1906
2675
|
}
|
|
1907
2676
|
/**
|
|
1908
2677
|
* Post a direct intent to its known devices while the recipient's device
|
|
@@ -1917,7 +2686,7 @@ export class SignalProtocolServiceCipher {
|
|
|
1917
2686
|
* records, so no message goes to a device after the read that shows its
|
|
1918
2687
|
* removal.
|
|
1919
2688
|
*/
|
|
1920
|
-
async sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal) {
|
|
2689
|
+
async sendDirectIntentBeforeDeviceListRead(intent, plaintextBytes, sessions, stopSignal, evidence) {
|
|
1921
2690
|
const arrived = {};
|
|
1922
2691
|
const read = this.readRecipientDeviceList(intent.recipientId, sessions, true, (listed) => {
|
|
1923
2692
|
arrived.listed = listed;
|
|
@@ -1925,17 +2694,20 @@ export class SignalProtocolServiceCipher {
|
|
|
1925
2694
|
// Every path below awaits the read. This handler only covers the posts.
|
|
1926
2695
|
read.catch(() => undefined);
|
|
1927
2696
|
const posts = { accepted: new Map(), refused: new Map() };
|
|
1928
|
-
const control = {
|
|
2697
|
+
const control = this.postingControl(evidence, {
|
|
1929
2698
|
...(stopSignal && { stopSignal }),
|
|
1930
2699
|
admit: () => {
|
|
1931
2700
|
if (arrived.listed)
|
|
1932
2701
|
throw new DeferredPost();
|
|
1933
2702
|
},
|
|
1934
|
-
};
|
|
2703
|
+
});
|
|
1935
2704
|
try {
|
|
1936
2705
|
await this.sendPhase(intent.deviceMessages, async (message) => {
|
|
2706
|
+
// A stored refusal for good is not posted again.
|
|
2707
|
+
if (storedRefusal(intent, message))
|
|
2708
|
+
return;
|
|
1937
2709
|
try {
|
|
1938
|
-
posts.accepted.set(message.recipientDeviceId, await this.
|
|
2710
|
+
posts.accepted.set(message.recipientDeviceId, await this.postDirectDeviceMessage(intent, message, control, evidence));
|
|
1939
2711
|
}
|
|
1940
2712
|
catch (error) {
|
|
1941
2713
|
if (error instanceof DeferredPost)
|
|
@@ -1949,13 +2721,13 @@ export class SignalProtocolServiceCipher {
|
|
|
1949
2721
|
catch (error) {
|
|
1950
2722
|
// The read commits sessions. It ends before the send fails.
|
|
1951
2723
|
await read.catch(() => undefined);
|
|
1952
|
-
|
|
2724
|
+
return this.endOrRethrow(intent, evidence, error);
|
|
1953
2725
|
}
|
|
1954
2726
|
const list = await read;
|
|
1955
2727
|
const reconciled = list
|
|
1956
2728
|
? await this.reconcileDirectIntent(intent, list, plaintextBytes)
|
|
1957
2729
|
: intent;
|
|
1958
|
-
return this.sendStoredDirectIntent(reconciled, plaintextBytes, sessions, stopSignal, posts);
|
|
2730
|
+
return this.sendStoredDirectIntent(reconciled, plaintextBytes, sessions, stopSignal, evidence, posts);
|
|
1959
2731
|
}
|
|
1960
2732
|
/** A replay whose first attempt posted before its read reads and reconciles first. */
|
|
1961
2733
|
async reconcilePendingDirectIntent(intent, plaintextBytes, sessions) {
|
|
@@ -2072,7 +2844,12 @@ export class SignalProtocolServiceCipher {
|
|
|
2072
2844
|
inRepairTurn(recipientUserId, repair) {
|
|
2073
2845
|
return this.lock.acquire(`session-repair:${recipientUserId}`, repair);
|
|
2074
2846
|
}
|
|
2075
|
-
/**
|
|
2847
|
+
/**
|
|
2848
|
+
* Refresh the session of a rejected device and replace its transmission.
|
|
2849
|
+
*
|
|
2850
|
+
* @returns The new transmission, and the stored progress entry of the
|
|
2851
|
+
* device, which carries the repair mark
|
|
2852
|
+
*/
|
|
2076
2853
|
async repairRejectedDirectDeviceMessage(intent, rejected, plaintextBytes, sessions) {
|
|
2077
2854
|
if (!sessions)
|
|
2078
2855
|
throw new Error('Stale-session refresh is not configured');
|
|
@@ -2085,8 +2862,13 @@ export class SignalProtocolServiceCipher {
|
|
|
2085
2862
|
}
|
|
2086
2863
|
const freshMessage = await this.sesameManager.sendMessage(rejected.recipientUserId, rejected.recipientDeviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
|
|
2087
2864
|
const replacement = await this.prepareStoredDirectDeviceMessage(freshMessage, await this.resolveStoredDirectSealedSender(intent), intent.contentHint);
|
|
2088
|
-
await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
|
|
2089
|
-
|
|
2865
|
+
const stored = await replaceOutgoingDirectDeviceMessage(this.storage, intent.clientMessageId, rejected, replacement);
|
|
2866
|
+
const [destination] = sendDestinations(intent.clientMessageId, [replacement]);
|
|
2867
|
+
const entry = stored.destinationProgress?.[outgoingDestinationProgressKey(destination.postMessageId, destination.device)];
|
|
2868
|
+
// The store writes the entry of the replaced device with its repair mark.
|
|
2869
|
+
if (!entry)
|
|
2870
|
+
throw new Error('A direct outbox repair stored no progress for its device');
|
|
2871
|
+
return { replacement, entry };
|
|
2090
2872
|
}
|
|
2091
2873
|
async sendStoredDirectDeviceMessage(intent, message, control) {
|
|
2092
2874
|
if (intent.transportMode !== 'identified' &&
|
|
@@ -2102,14 +2884,14 @@ export class SignalProtocolServiceCipher {
|
|
|
2102
2884
|
}, control);
|
|
2103
2885
|
}
|
|
2104
2886
|
/** Post one device message, and repair its session once if the device rejects it. */
|
|
2105
|
-
async postStoredDirectDeviceMessage(intent, message, plaintextBytes, sessions, control, refusal) {
|
|
2887
|
+
async postStoredDirectDeviceMessage(intent, message, plaintextBytes, sessions, control, evidence, refusal) {
|
|
2106
2888
|
let rejection;
|
|
2107
2889
|
if (refusal) {
|
|
2108
2890
|
rejection = refusal.error;
|
|
2109
2891
|
}
|
|
2110
2892
|
else {
|
|
2111
2893
|
try {
|
|
2112
|
-
return await this.
|
|
2894
|
+
return await this.postDirectDeviceMessage(intent, message, control, evidence);
|
|
2113
2895
|
}
|
|
2114
2896
|
catch (error) {
|
|
2115
2897
|
rejection = error;
|
|
@@ -2117,15 +2899,21 @@ export class SignalProtocolServiceCipher {
|
|
|
2117
2899
|
}
|
|
2118
2900
|
if (!isConclusiveDeviceRejection(rejection))
|
|
2119
2901
|
throw rejection;
|
|
2120
|
-
const replacement = await this.repairRejectedDirectDeviceMessage(intent, message, plaintextBytes, sessions);
|
|
2121
|
-
|
|
2902
|
+
const { replacement, entry } = await this.repairRejectedDirectDeviceMessage(intent, message, plaintextBytes, sessions);
|
|
2903
|
+
// A RETRY_CONFLICT or DELIVERY_ALREADY_ACCEPTED of the repost then reads
|
|
2904
|
+
// the repair mark.
|
|
2905
|
+
evidence.refreshEntry({ userId: replacement.recipientUserId, deviceId: replacement.recipientDeviceId }, entry);
|
|
2906
|
+
return this.postDirectDeviceMessage(intent, replacement, control, evidence);
|
|
2122
2907
|
}
|
|
2123
2908
|
/**
|
|
2124
2909
|
* Post each device message of a direct intent, then the sync messages, and
|
|
2125
2910
|
* complete the intent. A device that a send-first pass already posted keeps
|
|
2126
|
-
* its result or its refusal.
|
|
2911
|
+
* its result or its refusal. A replay does not post a device that the
|
|
2912
|
+
* stored progress records as accepted or as refused for good
|
|
2913
|
+
* (`provenRefused`), and it does not post an accepted sync copy. When it
|
|
2914
|
+
* skipped a refused device, the send can end before the sync copies.
|
|
2127
2915
|
*/
|
|
2128
|
-
async sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, posts) {
|
|
2916
|
+
async sendStoredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence, posts) {
|
|
2129
2917
|
if (intent.kind !== 'direct')
|
|
2130
2918
|
throw new Error('Expected a direct outbox intent');
|
|
2131
2919
|
if (!this.relay) {
|
|
@@ -2139,33 +2927,61 @@ export class SignalProtocolServiceCipher {
|
|
|
2139
2927
|
return result;
|
|
2140
2928
|
}
|
|
2141
2929
|
const relay = this.relay;
|
|
2142
|
-
|
|
2143
|
-
let
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
this.
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2930
|
+
const control = this.postingControl(evidence, { ...(stopSignal && { stopSignal }) });
|
|
2931
|
+
let results;
|
|
2932
|
+
let skippedRefusal = false;
|
|
2933
|
+
try {
|
|
2934
|
+
const posted = await this.sendPhase(intent.deviceMessages, async (msg) => {
|
|
2935
|
+
const accepted = posts?.accepted.get(msg.recipientDeviceId);
|
|
2936
|
+
if (accepted)
|
|
2937
|
+
return accepted;
|
|
2938
|
+
const refusal = posts?.refused.get(msg.recipientDeviceId);
|
|
2939
|
+
if (!refusal && storedRefusal(intent, msg)) {
|
|
2940
|
+
skippedRefusal = true;
|
|
2941
|
+
return undefined;
|
|
2942
|
+
}
|
|
2943
|
+
return this.postStoredDirectDeviceMessage(intent, msg, plaintextBytes, sessions, control, evidence, refusal);
|
|
2944
|
+
}, 'device', stopSignal);
|
|
2945
|
+
results = posted.filter((acceptance) => acceptance !== undefined);
|
|
2946
|
+
}
|
|
2947
|
+
catch (error) {
|
|
2948
|
+
return this.endOrRethrow(intent, evidence, error);
|
|
2949
|
+
}
|
|
2950
|
+
if (skippedRefusal)
|
|
2951
|
+
await this.endRefusedReplay(intent, evidence);
|
|
2952
|
+
const first = sendResultAcceptance(results);
|
|
2953
|
+
// The sync copies start only after every device post settled. A copy
|
|
2954
|
+
// that the posting deadline stopped stays pending, and the send
|
|
2955
|
+
// completes with syncPending. Every other sync failure fails the send.
|
|
2154
2956
|
const syncRepair = {
|
|
2155
2957
|
sessions,
|
|
2156
2958
|
intentId: intent.clientMessageId,
|
|
2157
2959
|
rebuild: async (deviceId) => (await this.prepareDirectSyncMessages(intent, plaintextBytes, [deviceId]))[0],
|
|
2158
2960
|
};
|
|
2159
|
-
|
|
2961
|
+
let syncPending = false;
|
|
2962
|
+
await this.sendPhase(intent.syncMessages, async (message) => {
|
|
2963
|
+
const stop = recordDeadlineStop(control.beforeRequest);
|
|
2964
|
+
const destination = syncDestination(intent.clientMessageId, message);
|
|
2965
|
+
try {
|
|
2966
|
+
await evidence.postSync(destination, stop.check, (gate) => this.postSyncMessage(relay, message, control, syncRepair, gate));
|
|
2967
|
+
}
|
|
2968
|
+
catch (error) {
|
|
2969
|
+
if (!stop.stopped())
|
|
2970
|
+
throw error;
|
|
2971
|
+
syncPending = true;
|
|
2972
|
+
}
|
|
2973
|
+
}, 'sync', stopSignal);
|
|
2160
2974
|
const result = {
|
|
2161
2975
|
clientMessageId: intent.clientMessageId,
|
|
2162
|
-
messageId
|
|
2163
|
-
timestamp,
|
|
2976
|
+
messageId: first?.messageId ?? `local-${intent.clientTimestamp}`,
|
|
2977
|
+
timestamp: first?.serverTimestamp ?? intent.clientTimestamp,
|
|
2164
2978
|
recipientDeviceCount: intent.deviceMessages.length,
|
|
2165
2979
|
...aggregateRelayAcceptance(results),
|
|
2166
2980
|
};
|
|
2167
|
-
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result
|
|
2168
|
-
|
|
2981
|
+
await completeOutgoingMessageIntent(this.storage, intent.clientMessageId, result, {
|
|
2982
|
+
syncPending,
|
|
2983
|
+
});
|
|
2984
|
+
return syncPending ? { ...result, syncPending: true } : result;
|
|
2169
2985
|
}
|
|
2170
2986
|
/** True when the relay compares declared device sets, so each send declares them. */
|
|
2171
2987
|
declaresDeviceSets() {
|
|
@@ -2291,10 +3107,12 @@ export class SignalProtocolServiceCipher {
|
|
|
2291
3107
|
bundleMissing.push(...repaired.bundleMissing);
|
|
2292
3108
|
for (const device of repaired.ready) {
|
|
2293
3109
|
const message = await run.encrypt(device);
|
|
2294
|
-
if (message)
|
|
3110
|
+
if (message) {
|
|
2295
3111
|
added.push(message);
|
|
2296
|
-
|
|
3112
|
+
}
|
|
3113
|
+
else {
|
|
2297
3114
|
bundleMissing.push(device);
|
|
3115
|
+
}
|
|
2298
3116
|
}
|
|
2299
3117
|
});
|
|
2300
3118
|
}
|
|
@@ -2306,6 +3124,15 @@ export class SignalProtocolServiceCipher {
|
|
|
2306
3124
|
bundleMissing,
|
|
2307
3125
|
...(run.phase === 'recipient' ? { deviceMessages: added } : { syncMessages: added }),
|
|
2308
3126
|
});
|
|
3127
|
+
// The store wrote `repairedFor` on each added device, and
|
|
3128
|
+
// `repaired` on a device that the repair also removed. The hook
|
|
3129
|
+
// takes the entry before the next pass posts the device.
|
|
3130
|
+
for (const message of added) {
|
|
3131
|
+
const [destination] = sendDestinations(run.intentId, [message]);
|
|
3132
|
+
const entry = intent.destinationProgress?.[outgoingDestinationProgressKey(destination.postMessageId, destination.device)];
|
|
3133
|
+
if (entry)
|
|
3134
|
+
run.repaired?.(destination.device, entry);
|
|
3135
|
+
}
|
|
2309
3136
|
messages = postable(run.phase === 'recipient' ? intent.deviceMessages : intent.syncMessages);
|
|
2310
3137
|
}
|
|
2311
3138
|
else {
|
|
@@ -2323,8 +3150,12 @@ export class SignalProtocolServiceCipher {
|
|
|
2323
3150
|
},
|
|
2324
3151
|
unresolve: async (unresolved) => {
|
|
2325
3152
|
if (run.intentId === undefined)
|
|
2326
|
-
return;
|
|
2327
|
-
|
|
3153
|
+
return undefined;
|
|
3154
|
+
const end = run.phase === 'recipient' && run.evidence
|
|
3155
|
+
? await this.unresolvedRecipientEnd(run.intentId, run.evidence, unresolved)
|
|
3156
|
+
: undefined;
|
|
3157
|
+
const stored = await markOutgoingDeviceSetUnresolved(this.storage, run.intentId, storedDeviceSetUnresolved(unresolved), end);
|
|
3158
|
+
return stored.result ? undefined : stored.outcome;
|
|
2328
3159
|
},
|
|
2329
3160
|
wait: (milliseconds) => waitUnlessStopped(milliseconds, run.stopSignal),
|
|
2330
3161
|
logFailure: (device, error) => {
|
|
@@ -2485,7 +3316,8 @@ export class SignalProtocolServiceCipher {
|
|
|
2485
3316
|
}
|
|
2486
3317
|
/**
|
|
2487
3318
|
* Replay a stored direct send on a relay that compares device sets. A
|
|
2488
|
-
*
|
|
3319
|
+
* later `send()` after a recipient-phase end throws the stored-end class
|
|
3320
|
+
* of its outcome and posts nothing. A completed send with a
|
|
2489
3321
|
* pending sync phase posts only its sync messages. It first reads the own
|
|
2490
3322
|
* device list when the send could not read it: the phase has no sync
|
|
2491
3323
|
* message and stores no own device with no bundle. A stored device with no
|
|
@@ -2493,11 +3325,12 @@ export class SignalProtocolServiceCipher {
|
|
|
2493
3325
|
* retries it as the live run does. A send that is not terminal resumes
|
|
2494
3326
|
* with its stored restart counts.
|
|
2495
3327
|
*/
|
|
2496
|
-
async replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal) {
|
|
2497
|
-
const intent =
|
|
3328
|
+
async replayDeclaredDirectIntent(existing, plaintextBytes, sessions, stopSignal, evidence) {
|
|
3329
|
+
const intent = existing;
|
|
2498
3330
|
const stored = outgoingMessageIntentResult(intent);
|
|
2499
|
-
if (!stored)
|
|
2500
|
-
return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal);
|
|
3331
|
+
if (!stored) {
|
|
3332
|
+
return this.sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence);
|
|
3333
|
+
}
|
|
2501
3334
|
if (!intent.syncPending)
|
|
2502
3335
|
return stored;
|
|
2503
3336
|
const { syncPending: _pending, ...result } = stored;
|
|
@@ -2513,7 +3346,7 @@ export class SignalProtocolServiceCipher {
|
|
|
2513
3346
|
return result;
|
|
2514
3347
|
}
|
|
2515
3348
|
}
|
|
2516
|
-
const sync = await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal);
|
|
3349
|
+
const sync = await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal, evidence.check, evidence);
|
|
2517
3350
|
return this.markUncheckedDeclaredPosts(sync.synced ? result : { ...result, syncPending: true }, syncPostReceipts(sync.accepted), current.clientMessageId);
|
|
2518
3351
|
}
|
|
2519
3352
|
/**
|
|
@@ -2548,9 +3381,10 @@ export class SignalProtocolServiceCipher {
|
|
|
2548
3381
|
* `syncPending` and does not fail the send, and the intent keeps the sync
|
|
2549
3382
|
* messages for a replay.
|
|
2550
3383
|
*/
|
|
2551
|
-
async sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal) {
|
|
2552
|
-
const control = { ...(stopSignal && { stopSignal }) };
|
|
3384
|
+
async sendDeclaredDirectIntent(intent, plaintextBytes, sessions, stopSignal, evidence) {
|
|
3385
|
+
const control = this.postingControl(evidence, { ...(stopSignal && { stopSignal }) });
|
|
2553
3386
|
let sealedSender;
|
|
3387
|
+
let skippedRefusal = false;
|
|
2554
3388
|
const recipient = await this.runDeclaredPhase({
|
|
2555
3389
|
phase: 'recipient',
|
|
2556
3390
|
clientMessageId: intent.clientMessageId,
|
|
@@ -2559,7 +3393,17 @@ export class SignalProtocolServiceCipher {
|
|
|
2559
3393
|
messages: intent.deviceMessages,
|
|
2560
3394
|
bundleMissing: intent.deviceSetBundleMissing?.recipient ?? [],
|
|
2561
3395
|
...(intent.recipientId !== this.userId && { requirePostTo: intent.recipientId }),
|
|
2562
|
-
|
|
3396
|
+
// A device with a stored refusal for good stays declared, and is not
|
|
3397
|
+
// posted again.
|
|
3398
|
+
post: async (message, declaredDeviceIds) => {
|
|
3399
|
+
if (storedRefusal(intent, message)) {
|
|
3400
|
+
skippedRefusal = true;
|
|
3401
|
+
return undefined;
|
|
3402
|
+
}
|
|
3403
|
+
return this.postDirectDeviceMessage(intent, message, { ...control, declaredDeviceIds }, evidence);
|
|
3404
|
+
},
|
|
3405
|
+
repaired: (device, entry) => evidence.refreshEntry(device, entry),
|
|
3406
|
+
evidence,
|
|
2563
3407
|
encrypt: async (device) => {
|
|
2564
3408
|
const message = await this.sesameManager.sendMessage(device.userId, device.deviceId, plaintextBytes, { clientTimestamp: intent.clientTimestamp, includeSyncMessages: false });
|
|
2565
3409
|
if (sealedSender === undefined) {
|
|
@@ -2569,31 +3413,28 @@ export class SignalProtocolServiceCipher {
|
|
|
2569
3413
|
},
|
|
2570
3414
|
sessions,
|
|
2571
3415
|
stopSignal,
|
|
2572
|
-
});
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
if (messageId.startsWith('local-')) {
|
|
2578
|
-
messageId = acceptance.messageId;
|
|
2579
|
-
timestamp = acceptance.serverTimestamp;
|
|
2580
|
-
}
|
|
2581
|
-
}
|
|
3416
|
+
}).catch((error) => this.endOrRethrow(intent, evidence, error));
|
|
3417
|
+
if (skippedRefusal)
|
|
3418
|
+
await this.endRefusedReplay(intent, evidence);
|
|
3419
|
+
const accepted = recipient.values.filter((acceptance) => acceptance !== undefined);
|
|
3420
|
+
const first = sendResultAcceptance(accepted);
|
|
2582
3421
|
const result = {
|
|
2583
3422
|
clientMessageId: intent.clientMessageId,
|
|
2584
|
-
messageId
|
|
2585
|
-
timestamp,
|
|
3423
|
+
messageId: first?.messageId ?? `local-${intent.clientTimestamp}`,
|
|
3424
|
+
timestamp: first?.serverTimestamp ?? intent.clientTimestamp,
|
|
2586
3425
|
recipientDeviceCount: recipient.messages.length,
|
|
2587
3426
|
...aggregateRelayAcceptance(accepted),
|
|
2588
3427
|
};
|
|
2589
3428
|
// The sync phase runs when a recipient receipt sets needsSync or the
|
|
2590
3429
|
// send holds an own device record. With needsSync and no own record,
|
|
2591
|
-
// the send reads the own list once.
|
|
2592
|
-
//
|
|
3430
|
+
// the send reads the own list once. A RETRY_CONFLICT or
|
|
3431
|
+
// DELIVERY_ALREADY_ACCEPTED acceptance has no receipt, and the lost receipt can have set needsSync, so it also
|
|
3432
|
+
// starts the read. When that read fails, the sync phase stays pending
|
|
3433
|
+
// with no sync messages, and a replay reads it.
|
|
2593
3434
|
let current = (await getOutgoingMessageIntent(this.storage, intent.clientMessageId)) ?? intent;
|
|
2594
3435
|
let syncUnread = false;
|
|
2595
3436
|
if (current.syncMessages.length === 0 &&
|
|
2596
|
-
accepted.some((acceptance) => acceptance.needsSync === true)) {
|
|
3437
|
+
accepted.some((acceptance) => acceptance.needsSync === true || isConflictAcceptance(acceptance))) {
|
|
2597
3438
|
const added = await this.addDeclaredDirectSync(current, plaintextBytes, sessions, stopSignal);
|
|
2598
3439
|
current = added.intent;
|
|
2599
3440
|
syncUnread = added.unread;
|
|
@@ -2603,7 +3444,7 @@ export class SignalProtocolServiceCipher {
|
|
|
2603
3444
|
syncPending: syncPhase || syncUnread,
|
|
2604
3445
|
});
|
|
2605
3446
|
const sync = syncPhase
|
|
2606
|
-
? await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal)
|
|
3447
|
+
? await this.finishDeclaredSync(current, this.directSyncEncrypt(current, plaintextBytes), sessions, stopSignal, evidence.check, evidence)
|
|
2607
3448
|
: { synced: true, accepted: [] };
|
|
2608
3449
|
const route = intent.transportMode === 'identified' ? 'identified-direct' : 'anonymous-direct';
|
|
2609
3450
|
return this.markUncheckedDeclaredPosts({ ...result, ...((!sync.synced || syncUnread) && { syncPending: true }) }, [
|
|
@@ -2620,11 +3461,17 @@ export class SignalProtocolServiceCipher {
|
|
|
2620
3461
|
* restart count. A failure or an unresolved end is logged and leaves the
|
|
2621
3462
|
* phase pending. The outcome keeps the receipt of each accepted sync post,
|
|
2622
3463
|
* also when the phase fails, so the send reports a receipt without the
|
|
2623
|
-
* `deviceSetChecked` mark.
|
|
3464
|
+
* `deviceSetChecked` mark. A direct send passes its posting deadline
|
|
3465
|
+
* check, so no sync post starts at or after the deadline. It also passes
|
|
3466
|
+
* the evidence of its call: the outbox then stores the progress of each
|
|
3467
|
+
* sync copy, and the phase does not post a copy that the Relay accepted.
|
|
2624
3468
|
*/
|
|
2625
|
-
async finishDeclaredSync(intent, encrypt, sessions, stopSignal) {
|
|
3469
|
+
async finishDeclaredSync(intent, encrypt, sessions, stopSignal, beforeRequest, evidence) {
|
|
2626
3470
|
const relay = this.relay;
|
|
2627
|
-
const control = {
|
|
3471
|
+
const control = {
|
|
3472
|
+
...(stopSignal && { stopSignal }),
|
|
3473
|
+
...(beforeRequest && { beforeRequest }),
|
|
3474
|
+
};
|
|
2628
3475
|
const accepted = [];
|
|
2629
3476
|
try {
|
|
2630
3477
|
await this.runDeclaredPhase({
|
|
@@ -2635,7 +3482,17 @@ export class SignalProtocolServiceCipher {
|
|
|
2635
3482
|
messages: intent.syncMessages,
|
|
2636
3483
|
bundleMissing: intent.deviceSetBundleMissing?.sync ?? [],
|
|
2637
3484
|
post: async (message, declaredDeviceIds) => {
|
|
2638
|
-
|
|
3485
|
+
const copy = { ...control, declaredDeviceIds };
|
|
3486
|
+
if (!evidence) {
|
|
3487
|
+
accepted.push(await this.postSyncCopy(relay, message, copy));
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
const acceptance = await evidence.postSync(syncDestination(intent.clientMessageId, message), beforeRequest ?? (async () => { }), (gate) => this.postSyncCopy(relay, message, {
|
|
3491
|
+
...copy,
|
|
3492
|
+
beforeRequest: gate(message.clientMessageId),
|
|
3493
|
+
}));
|
|
3494
|
+
if (acceptance)
|
|
3495
|
+
accepted.push(acceptance);
|
|
2639
3496
|
},
|
|
2640
3497
|
encrypt,
|
|
2641
3498
|
sessions,
|
|
@@ -2708,11 +3565,27 @@ export class SignalProtocolServiceCipher {
|
|
|
2708
3565
|
}
|
|
2709
3566
|
}
|
|
2710
3567
|
async encryptToGroupWithOutbox(actualGroupId, plaintextBytes, options, sessions, stopSignal) {
|
|
2711
|
-
|
|
3568
|
+
// The outbox binds the evidence of the call once it holds the stored
|
|
3569
|
+
// intent, before any post. Each request of the call meets its deadline.
|
|
3570
|
+
let groupEvidence;
|
|
3571
|
+
const boundGroupEvidence = () => {
|
|
3572
|
+
if (!groupEvidence)
|
|
3573
|
+
throw new Error('group send evidence read before bindEvidence');
|
|
3574
|
+
return groupEvidence;
|
|
3575
|
+
};
|
|
3576
|
+
const control = {
|
|
3577
|
+
...(stopSignal && { stopSignal }),
|
|
3578
|
+
beforeRequest: () => boundGroupEvidence().check(),
|
|
3579
|
+
};
|
|
2712
3580
|
// A send prepared in this attempt keeps its distribution for a repair.
|
|
2713
3581
|
const repair = { ...(sessions && { sessions }) };
|
|
2714
3582
|
const declared = this.declaresDeviceSets();
|
|
2715
3583
|
return sendGroupWithExactOutbox({
|
|
3584
|
+
bindEvidence: (intent) => {
|
|
3585
|
+
groupEvidence = this.sendCallEvidence(intent);
|
|
3586
|
+
},
|
|
3587
|
+
refreshEntry: (device, entry) => boundGroupEvidence().refreshEntry(device, entry),
|
|
3588
|
+
endRecipientPhase: (intent, error) => this.endOrRethrow(intent, boundGroupEvidence(), error),
|
|
2716
3589
|
storage: this.storage,
|
|
2717
3590
|
...(this.relay && { relay: this.relay }),
|
|
2718
3591
|
senderUserId: this.userId,
|
|
@@ -2772,40 +3645,52 @@ export class SignalProtocolServiceCipher {
|
|
|
2772
3645
|
});
|
|
2773
3646
|
return Promise.all(prepared.map((message) => this.prepareStoredSyncMessage(message, syncMessageId(clientMessageId, message))));
|
|
2774
3647
|
},
|
|
2775
|
-
postSyncMessage: (intent, message, rebuild) =>
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
3648
|
+
postSyncMessage: async (intent, message, rebuild) => {
|
|
3649
|
+
// A copy that the posting deadline stopped stays pending.
|
|
3650
|
+
const stop = recordDeadlineStop(control.beforeRequest);
|
|
3651
|
+
try {
|
|
3652
|
+
await boundGroupEvidence().postSync(syncDestination(intent.clientMessageId, message), stop.check, (gate) => this.postSyncMessage(this.relay, message, control, { sessions: repair.sessions, intentId: intent.clientMessageId, rebuild }, gate));
|
|
3653
|
+
}
|
|
3654
|
+
catch (error) {
|
|
3655
|
+
if (!stop.stopped())
|
|
3656
|
+
throw error;
|
|
3657
|
+
return true;
|
|
3658
|
+
}
|
|
3659
|
+
return false;
|
|
3660
|
+
},
|
|
2780
3661
|
resolveGroupAuthorization: (groupId, recipients) => this.resolveGroupSendAuthorization(groupId, recipients),
|
|
2781
3662
|
reportIdentifiedFallback: (recipientUserId) => this.reportIdentifiedFallback(recipientUserId),
|
|
2782
3663
|
refreshPreMessageEndorsements: (groupId, recipientUserIds) => this.refreshPreMessageEndorsements(groupId, recipientUserIds),
|
|
2783
3664
|
authorizePreMessage: (groupId, message, required) => this.authorizePreMessage(groupId, message, required),
|
|
2784
|
-
postPreMessage: (intent, transport, required) => this.postPreMessage(intent, transport, required, repair, control),
|
|
3665
|
+
postPreMessage: (intent, transport, required) => this.postPreMessage(intent, transport, required, repair, control, boundGroupEvidence()),
|
|
2785
3666
|
prepareSenderKeyHandoffs: (intent, listed) => this.prepareIntentSenderKeyHandoffs(intent, listed, repair, repair.sessions, stopSignal),
|
|
2786
3667
|
remoteRegistrationId: (device) => this.sesameManager.getRemoteRegistrationId(device.userId, device.deviceId),
|
|
2787
3668
|
isConclusiveDeviceRejection: (error) => isConclusiveDeviceRejection(error),
|
|
2788
3669
|
repairStaleDevice: (intent, message) => this.repairStaleGroupDevice(intent, message, repair, stopSignal),
|
|
2789
|
-
sendPreparedSealedDevice: (intent, message, auth, declaredDeviceIds) => this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, undefined, intent.clientMessageId, {
|
|
3670
|
+
sendPreparedSealedDevice: (intent, message, auth, declaredDeviceIds) => this.postGroupDestination(intent.clientMessageId, sendDestinations(intent.clientMessageId, [message])[0], boundGroupEvidence(), { ...control, ...(declaredDeviceIds && { declaredDeviceIds }) }, (posting) => this.sendToDevice(message, message.ciphertext, message.messageType, message.recipientRegistrationId, null, undefined, intent.clientMessageId, {
|
|
2790
3671
|
sentMessageBase64: message.sealedSenderMessage,
|
|
2791
3672
|
auth,
|
|
2792
3673
|
deliveryMode: message.sealedSenderDeliveryMode ?? 'preferred',
|
|
2793
|
-
},
|
|
3674
|
+
}, posting)),
|
|
2794
3675
|
prepareEach: (items, task) => this.fanOut.all(items, task).catch((error) => {
|
|
2795
3676
|
throw firstItemError(error);
|
|
2796
3677
|
}),
|
|
2797
3678
|
sendPhase: (messages, task, phase) => this.sendPhase(messages, task, phase, stopSignal),
|
|
2798
|
-
postToRelay: (send, sealed) =>
|
|
3679
|
+
postToRelay: (send, sealed, destination) => destination === undefined
|
|
3680
|
+
? this.postToRelay(send, sealed, control)
|
|
3681
|
+
: this.postGroupRelay(send, sealed, control, boundGroupEvidence(), options.clientMessageId, destination),
|
|
2799
3682
|
...(declared && {
|
|
2800
|
-
deviceSets: this.groupDeviceSetContext(sessions, stopSignal),
|
|
3683
|
+
deviceSets: this.groupDeviceSetContext(sessions, stopSignal, boundGroupEvidence),
|
|
2801
3684
|
}),
|
|
2802
3685
|
}, actualGroupId, plaintextBytes, options);
|
|
2803
3686
|
}
|
|
2804
3687
|
/**
|
|
2805
3688
|
* The declared work of a group send on a relay that compares device sets
|
|
2806
|
-
* (§5.5 of the device-set contract).
|
|
3689
|
+
* (§5.5 of the device-set contract). `readEvidence` gives the evidence of
|
|
3690
|
+
* the call, so each sync copy meets the posting deadline and stores its
|
|
3691
|
+
* progress.
|
|
2807
3692
|
*/
|
|
2808
|
-
groupDeviceSetContext(sessions, stopSignal) {
|
|
3693
|
+
groupDeviceSetContext(sessions, stopSignal, readEvidence) {
|
|
2809
3694
|
return {
|
|
2810
3695
|
repairDevices: (account, postedRegistration, unposted) => {
|
|
2811
3696
|
if (!sessions) {
|
|
@@ -2819,9 +3704,14 @@ export class SignalProtocolServiceCipher {
|
|
|
2819
3704
|
}));
|
|
2820
3705
|
},
|
|
2821
3706
|
readOwnDevices: () => this.readOwnDeviceList(sessions, stopSignal),
|
|
2822
|
-
runSyncPhase: (intent, rebuild) =>
|
|
3707
|
+
runSyncPhase: (intent, rebuild) => {
|
|
3708
|
+
const evidence = readEvidence();
|
|
3709
|
+
return this.finishDeclaredSync(intent, rebuild, sessions, stopSignal, evidence.check, evidence);
|
|
3710
|
+
},
|
|
2823
3711
|
unresolve: async (clientMessageId, unresolved) => {
|
|
2824
|
-
await
|
|
3712
|
+
const end = await this.unresolvedRecipientEnd(clientMessageId, readEvidence(), unresolved);
|
|
3713
|
+
const stored = await markOutgoingDeviceSetUnresolved(this.storage, clientMessageId, storedDeviceSetUnresolved(unresolved), end);
|
|
3714
|
+
return stored.result ? undefined : stored.outcome;
|
|
2825
3715
|
},
|
|
2826
3716
|
wait: (milliseconds) => waitUnlessStopped(milliseconds, stopSignal),
|
|
2827
3717
|
logFailure: (device, error) => {
|
|
@@ -2965,18 +3855,26 @@ export class SignalProtocolServiceCipher {
|
|
|
2965
3855
|
}
|
|
2966
3856
|
await this.restrictUnidentifiedAccessMode(message.recipientUserId);
|
|
2967
3857
|
// The rejected post started, so the next post continues it.
|
|
3858
|
+
// Each request of it still meets the posting deadline and counts for
|
|
3859
|
+
// the device.
|
|
2968
3860
|
const continued = {
|
|
2969
3861
|
...(control.stopSignal && { stopSignal: control.stopSignal }),
|
|
2970
3862
|
...(control.operationEpochMilliseconds !== undefined && {
|
|
2971
3863
|
operationEpochMilliseconds: control.operationEpochMilliseconds,
|
|
2972
3864
|
}),
|
|
3865
|
+
...(control.beforeRequest && { beforeRequest: control.beforeRequest }),
|
|
3866
|
+
...(control.onRequest && { onRequest: control.onRequest }),
|
|
2973
3867
|
};
|
|
2974
3868
|
const endorsement = await this.resolveDistributionEndorsement(message.recipientUserId, intent.recipientId);
|
|
3869
|
+
// When the posting deadline refuses a continued request, the sealed
|
|
3870
|
+
// answer stays the answer of the post.
|
|
2975
3871
|
if (endorsement) {
|
|
2976
3872
|
try {
|
|
2977
3873
|
return await this.postStoredPreMessage(intent, message, endorsement, true, continued);
|
|
2978
3874
|
}
|
|
2979
3875
|
catch (error) {
|
|
3876
|
+
if (isPostingDeadlineReached(error))
|
|
3877
|
+
throw rejection;
|
|
2980
3878
|
if (!(error instanceof SealedSenderAuthError))
|
|
2981
3879
|
throw error;
|
|
2982
3880
|
rejection = error;
|
|
@@ -2985,7 +3883,14 @@ export class SignalProtocolServiceCipher {
|
|
|
2985
3883
|
if (required)
|
|
2986
3884
|
throw rejection;
|
|
2987
3885
|
await this.reportIdentifiedFallback(message.recipientUserId);
|
|
2988
|
-
|
|
3886
|
+
try {
|
|
3887
|
+
return await this.postStoredPreMessage(intent, message, undefined, false, continued);
|
|
3888
|
+
}
|
|
3889
|
+
catch (error) {
|
|
3890
|
+
if (isPostingDeadlineReached(error))
|
|
3891
|
+
throw rejection;
|
|
3892
|
+
throw error;
|
|
3893
|
+
}
|
|
2989
3894
|
}
|
|
2990
3895
|
/**
|
|
2991
3896
|
* The group endorsement of one pre-message recipient, or null when the
|
|
@@ -3023,13 +3928,28 @@ export class SignalProtocolServiceCipher {
|
|
|
3023
3928
|
* refreshes the session and drops the pre-message, because it has no
|
|
3024
3929
|
* distribution of the key of the send. Resolves to the pre-message that the
|
|
3025
3930
|
* relay accepted or that the send dropped, with the outcome.
|
|
3931
|
+
*
|
|
3932
|
+
* A RETRY_CONFLICT answer, or a DELIVERY_ALREADY_ACCEPTED answer under
|
|
3933
|
+
* protocol version 2, means that the Relay holds a message under the ID of
|
|
3934
|
+
* the post. The evidence of the call accepts it only when the stored
|
|
3935
|
+
* entry of the destination has no blocking repair mark: then the Relay
|
|
3936
|
+
* holds the same bytes, and the pre-message counts as accepted. Each other
|
|
3937
|
+
* such answer leaves the destination unknown, and the pre-message counts
|
|
3938
|
+
* as held: it writes no handoff row, so the next send gives the key again.
|
|
3939
|
+
* A repair refreshes the evidence entry of its repaired post before the
|
|
3940
|
+
* post, so the answer to that post reads the repair mark.
|
|
3026
3941
|
*/
|
|
3027
|
-
async postPreMessage(intent, transport, required, repair, control) {
|
|
3942
|
+
async postPreMessage(intent, transport, required, repair, control, evidence) {
|
|
3943
|
+
const post = (sent) => this.postGroupDestination(intent.clientMessageId, sendDestinations(intent.clientMessageId, [sent.message])[0], evidence, control, (posting) => this.sendPreMessage(intent, sent, required, posting));
|
|
3028
3944
|
try {
|
|
3029
|
-
await
|
|
3945
|
+
await post(transport);
|
|
3030
3946
|
return { message: transport.message, outcome: 'accepted' };
|
|
3031
3947
|
}
|
|
3032
3948
|
catch (error) {
|
|
3949
|
+
// The evidence did not accept this answer, so the post rejected.
|
|
3950
|
+
if (relayHoldsMessageId(error)) {
|
|
3951
|
+
return { message: transport.message, outcome: 'held' };
|
|
3952
|
+
}
|
|
3033
3953
|
if (await this.isRemovedDeviceRefusal(error, transport.message, control)) {
|
|
3034
3954
|
return { message: transport.message, outcome: 'removed' };
|
|
3035
3955
|
}
|
|
@@ -3042,15 +3962,22 @@ export class SignalProtocolServiceCipher {
|
|
|
3042
3962
|
const repaired = await this.inRepairTurn(transport.message.recipientUserId, () => this.repairRejectedPreMessageInTurn(intent, transport.message, required, repair, sessions));
|
|
3043
3963
|
if (!repaired)
|
|
3044
3964
|
return { message: transport.message, outcome: 'dropped', refreshed: true };
|
|
3965
|
+
if (repaired.entry) {
|
|
3966
|
+
evidence.refreshEntry({ userId: repaired.entry.userId, deviceId: repaired.entry.deviceId }, repaired.entry);
|
|
3967
|
+
}
|
|
3045
3968
|
try {
|
|
3046
|
-
await
|
|
3969
|
+
await post(repaired.transport);
|
|
3047
3970
|
}
|
|
3048
3971
|
catch (error) {
|
|
3049
|
-
if (
|
|
3972
|
+
if (relayHoldsMessageId(error)) {
|
|
3973
|
+
return { message: repaired.transport.message, outcome: 'held', refreshed: true };
|
|
3974
|
+
}
|
|
3975
|
+
if (!(await this.isRemovedDeviceRefusal(error, repaired.transport.message, control))) {
|
|
3050
3976
|
throw error;
|
|
3051
|
-
|
|
3977
|
+
}
|
|
3978
|
+
return { message: repaired.transport.message, outcome: 'removed' };
|
|
3052
3979
|
}
|
|
3053
|
-
return { message: repaired.message, outcome: 'accepted', refreshed: true };
|
|
3980
|
+
return { message: repaired.transport.message, outcome: 'accepted', refreshed: true };
|
|
3054
3981
|
}
|
|
3055
3982
|
/**
|
|
3056
3983
|
* Delete the sender-key handoff rows of one device in one group, so the
|
|
@@ -3115,8 +4042,10 @@ export class SignalProtocolServiceCipher {
|
|
|
3115
4042
|
/**
|
|
3116
4043
|
* Refresh the session of a device that refused a pre-message, encrypt the
|
|
3117
4044
|
* distribution again, and replace the stored pre-message before its post.
|
|
3118
|
-
* The saved refused ciphertext is never posted again. Resolves to
|
|
3119
|
-
*
|
|
4045
|
+
* The saved refused ciphertext is never posted again. Resolves to the
|
|
4046
|
+
* repaired transport and the stored entry of its post, which carries the
|
|
4047
|
+
* repair mark, or to undefined when a replay has no distribution of the
|
|
4048
|
+
* key of the send.
|
|
3120
4049
|
*/
|
|
3121
4050
|
async repairRejectedPreMessageInTurn(intent, rejected, required, repair, sessions) {
|
|
3122
4051
|
const refreshed = await sessions.refreshStaleSession(rejected.recipientUserId, rejected.recipientDeviceId);
|
|
@@ -3135,10 +4064,14 @@ export class SignalProtocolServiceCipher {
|
|
|
3135
4064
|
if (rejected.senderKeyHandoff)
|
|
3136
4065
|
fresh.senderKeyHandoff = rejected.senderKeyHandoff;
|
|
3137
4066
|
const transport = await this.authorizePreMessage(intent.recipientId, fresh, required);
|
|
3138
|
-
await replaceOutgoingGroupPreMessages(this.storage, intent.clientMessageId, [
|
|
4067
|
+
const stored = await replaceOutgoingGroupPreMessages(this.storage, intent.clientMessageId, [
|
|
3139
4068
|
{ expected: rejected, replacement: transport.message },
|
|
3140
4069
|
]);
|
|
3141
|
-
|
|
4070
|
+
const entry = stored.destinationProgress?.[outgoingDestinationProgressKey(fresh.clientMessageId, {
|
|
4071
|
+
userId: fresh.recipientUserId,
|
|
4072
|
+
deviceId: fresh.recipientDeviceId,
|
|
4073
|
+
})];
|
|
4074
|
+
return { transport, entry };
|
|
3142
4075
|
}
|
|
3143
4076
|
/**
|
|
3144
4077
|
* The distribution of a replayed send. The attempt that prepared the send
|
|
@@ -3417,119 +4350,156 @@ export class SignalProtocolServiceCipher {
|
|
|
3417
4350
|
*/
|
|
3418
4351
|
async sendToDevice(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint, clientMessageId, preparedSealedSender, control = {}) {
|
|
3419
4352
|
const effectiveClientMessageId = msg.clientMessageId ?? clientMessageId;
|
|
4353
|
+
// The transport gates a repeat by the ID that the posted envelope carries.
|
|
4354
|
+
// The devices of one intent share that ID, so only a repeat to this
|
|
4355
|
+
// device counts as a request of this post, and only that repeat runs
|
|
4356
|
+
// the gate of this post.
|
|
4357
|
+
const { beforeRequest, onRequest } = control;
|
|
4358
|
+
const ownRepeat = (repeat) => repeat.userId === msg.recipientUserId && repeat.deviceId === msg.recipientDeviceId;
|
|
4359
|
+
const release = (beforeRequest || onRequest) && effectiveClientMessageId !== undefined
|
|
4360
|
+
? admitRequestsFor(this.relay, effectiveClientMessageId, beforeRequest
|
|
4361
|
+
? (repeat) => (ownRepeat(repeat) ? beforeRequest() : Promise.resolve())
|
|
4362
|
+
: async () => { }, onRequest &&
|
|
4363
|
+
((repeat) => {
|
|
4364
|
+
if (ownRepeat(repeat))
|
|
4365
|
+
onRequest(repeat.after);
|
|
4366
|
+
}))
|
|
4367
|
+
: undefined;
|
|
3420
4368
|
// A fallback continues a post that started, so only the first request is
|
|
3421
|
-
// admitted.
|
|
4369
|
+
// admitted. Each request still meets the posting deadline.
|
|
3422
4370
|
let identifiedControl = control;
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
// Sealed sender path: use the V2 upload format for one recipient. V2 has
|
|
3429
|
-
// no two-recipient minimum; its recipient-count field permits this exact
|
|
3430
|
-
// direct-delivery shape.
|
|
3431
|
-
if ((sealedSender || preparedSealedSender) && this.relay.sendMultiRecipientUnidentified) {
|
|
3432
|
-
// The sealed body names the registration of its device, as the
|
|
3433
|
-
// identified post does.
|
|
3434
|
-
const prepared = preparedSealedSender ??
|
|
3435
|
-
(sealedSender
|
|
3436
|
-
? {
|
|
3437
|
-
sentMessageBase64: await this.serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint),
|
|
3438
|
-
auth: sealedSender.auth,
|
|
3439
|
-
deliveryMode: sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred',
|
|
3440
|
-
}
|
|
3441
|
-
: undefined);
|
|
3442
|
-
if (!prepared)
|
|
3443
|
-
throw new Error('Missing sealed-sender delivery state');
|
|
3444
|
-
// This post has one destination device, so a group endorsement takes
|
|
3445
|
-
// the direct sealed route.
|
|
3446
|
-
const sealedAuth = prepared.auth.type === 'groupSendToken'
|
|
3447
|
-
? forDirectSealedRoute(prepared.auth)
|
|
3448
|
-
: prepared.auth;
|
|
3449
|
-
// The identified fallback declares the same device set as the sealed
|
|
3450
|
-
// post, because both name the same account.
|
|
3451
|
-
identifiedControl = {
|
|
3452
|
-
...(control.stopSignal && { stopSignal: control.stopSignal }),
|
|
3453
|
-
...(control.operationEpochMilliseconds !== undefined && {
|
|
3454
|
-
operationEpochMilliseconds: control.operationEpochMilliseconds,
|
|
3455
|
-
}),
|
|
3456
|
-
...(control.deliveryClass && { deliveryClass: control.deliveryClass }),
|
|
3457
|
-
...(control.declaredDeviceIds && { declaredDeviceIds: control.declaredDeviceIds }),
|
|
3458
|
-
};
|
|
3459
|
-
const declaredDeviceIds = control.declaredDeviceIds;
|
|
3460
|
-
try {
|
|
3461
|
-
const result = await this.postToRelay(() => declaredDeviceIds
|
|
3462
|
-
? this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, control.operationEpochMilliseconds, undefined, [{ userId: msg.recipientUserId, deviceIds: declaredDeviceIds }])
|
|
3463
|
-
: this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, ...(control.operationEpochMilliseconds !== undefined
|
|
3464
|
-
? [control.operationEpochMilliseconds]
|
|
3465
|
-
: [])), true, control);
|
|
3466
|
-
if (result.uuids404.length > 0) {
|
|
3467
|
-
throw new SealedSenderRecipientRejectedError();
|
|
3468
|
-
}
|
|
3469
|
-
if (usedGroupRouteFallback(result)) {
|
|
3470
|
-
// The privacy of the post is the same on both routes. The record
|
|
3471
|
-
// shows that the Relay does not take the endorsement on the
|
|
3472
|
-
// direct route.
|
|
3473
|
-
this.logger.info('The Relay refused the group endorsement on the direct sealed route', {
|
|
3474
|
-
category: 'E2EE',
|
|
3475
|
-
data: {
|
|
3476
|
-
recipientUserId: msg.recipientUserId,
|
|
3477
|
-
recipientDeviceId: msg.recipientDeviceId,
|
|
3478
|
-
behavior: 'GROUP_ROUTE_FALLBACK',
|
|
3479
|
-
},
|
|
3480
|
-
});
|
|
3481
|
-
}
|
|
3482
|
-
// The group-token receipt names each refused destination with its
|
|
3483
|
-
// code. A declared post gets a whole-post refusal for a stale
|
|
3484
|
-
// registration instead. The refused count alone names no device, so
|
|
3485
|
-
// the send infers nothing from it.
|
|
3486
|
-
if (result.refusals?.some((refusal) => refusal.code === 'STALE_DEVICE' &&
|
|
3487
|
-
refusal.userId === msg.recipientUserId &&
|
|
3488
|
-
refusal.deviceId === msg.recipientDeviceId)) {
|
|
3489
|
-
throw markRelayDeviceRefusal(new Error('Recipient device registration changed'), {
|
|
3490
|
-
code: 'STALE_DEVICE',
|
|
3491
|
-
userId: msg.recipientUserId,
|
|
3492
|
-
deviceId: msg.recipientDeviceId,
|
|
3493
|
-
});
|
|
4371
|
+
let fallbackFrom;
|
|
4372
|
+
try {
|
|
4373
|
+
if (preparedSealedSender && !this.relay.sendMultiRecipientUnidentified) {
|
|
4374
|
+
if (preparedSealedSender.deliveryMode === 'required') {
|
|
4375
|
+
throw new EncryptionError('Required sealed-sender relay capability is unavailable', EncryptionErrorCode.SEALED_SENDER_REQUIRED, { recipientUserId: msg.recipientUserId });
|
|
3494
4376
|
}
|
|
3495
|
-
return result;
|
|
3496
4377
|
}
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
4378
|
+
// Sealed sender path: use the V2 upload format for one recipient. V2 has
|
|
4379
|
+
// no two-recipient minimum; its recipient-count field permits this exact
|
|
4380
|
+
// direct-delivery shape.
|
|
4381
|
+
if ((sealedSender || preparedSealedSender) && this.relay.sendMultiRecipientUnidentified) {
|
|
4382
|
+
// The sealed body names the registration of its device, as the
|
|
4383
|
+
// identified post does.
|
|
4384
|
+
const prepared = preparedSealedSender ??
|
|
4385
|
+
(sealedSender
|
|
4386
|
+
? {
|
|
4387
|
+
sentMessageBase64: await this.serializeDirectSealedSenderMessage(msg, ciphertextBase64, messageType, recipientRegistrationId, sealedSender, contentHint),
|
|
4388
|
+
auth: sealedSender.auth,
|
|
4389
|
+
deliveryMode: sealedSender.config.deliveryMode === 'required' ? 'required' : 'preferred',
|
|
4390
|
+
}
|
|
4391
|
+
: undefined);
|
|
4392
|
+
if (!prepared)
|
|
4393
|
+
throw new Error('Missing sealed-sender delivery state');
|
|
4394
|
+
// This post has one destination device, so a group endorsement takes
|
|
4395
|
+
// the direct sealed route.
|
|
4396
|
+
const sealedAuth = prepared.auth.type === 'groupSendToken'
|
|
4397
|
+
? forDirectSealedRoute(prepared.auth)
|
|
4398
|
+
: prepared.auth;
|
|
4399
|
+
// The identified fallback declares the same device set as the sealed
|
|
4400
|
+
// post, because both name the same account.
|
|
4401
|
+
identifiedControl = {
|
|
4402
|
+
...(control.stopSignal && { stopSignal: control.stopSignal }),
|
|
4403
|
+
...(control.operationEpochMilliseconds !== undefined && {
|
|
4404
|
+
operationEpochMilliseconds: control.operationEpochMilliseconds,
|
|
4405
|
+
}),
|
|
4406
|
+
...(control.deliveryClass && { deliveryClass: control.deliveryClass }),
|
|
4407
|
+
...(control.declaredDeviceIds && { declaredDeviceIds: control.declaredDeviceIds }),
|
|
4408
|
+
...(control.beforeRequest && { beforeRequest: control.beforeRequest }),
|
|
4409
|
+
...(control.onRequest && { onRequest: control.onRequest }),
|
|
4410
|
+
};
|
|
4411
|
+
const declaredDeviceIds = control.declaredDeviceIds;
|
|
4412
|
+
try {
|
|
4413
|
+
const result = await this.postToRelay(() => declaredDeviceIds
|
|
4414
|
+
? this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, control.operationEpochMilliseconds, undefined, [{ userId: msg.recipientUserId, deviceIds: declaredDeviceIds }])
|
|
4415
|
+
: this.relay.sendMultiRecipientUnidentified(prepared.sentMessageBase64, sealedAuth, msg.timestamp, control.deliveryClass ?? 'user-visible', [msg.recipientUserId], effectiveClientMessageId, ...(control.operationEpochMilliseconds !== undefined
|
|
4416
|
+
? [control.operationEpochMilliseconds]
|
|
4417
|
+
: [])), true, control);
|
|
4418
|
+
if (result.uuids404.length > 0) {
|
|
4419
|
+
throw new SealedSenderRecipientRejectedError();
|
|
4420
|
+
}
|
|
4421
|
+
if (usedGroupRouteFallback(result)) {
|
|
4422
|
+
// The privacy of the post is the same on both routes. The record
|
|
4423
|
+
// shows that the Relay does not take the endorsement on the
|
|
4424
|
+
// direct route.
|
|
4425
|
+
this.logger.info('The Relay refused the group endorsement on the direct sealed route', {
|
|
4426
|
+
category: 'E2EE',
|
|
4427
|
+
data: {
|
|
4428
|
+
recipientUserId: msg.recipientUserId,
|
|
4429
|
+
recipientDeviceId: msg.recipientDeviceId,
|
|
4430
|
+
behavior: 'GROUP_ROUTE_FALLBACK',
|
|
4431
|
+
},
|
|
4432
|
+
});
|
|
4433
|
+
}
|
|
4434
|
+
// The group-token receipt names each refused destination with its
|
|
4435
|
+
// code. A declared post gets a whole-post refusal for a stale
|
|
4436
|
+
// registration instead. The refused count alone names no device, so
|
|
4437
|
+
// the send infers nothing from it.
|
|
4438
|
+
if (result.refusals?.some((refusal) => refusal.code === 'STALE_DEVICE' &&
|
|
4439
|
+
refusal.userId === msg.recipientUserId &&
|
|
4440
|
+
refusal.deviceId === msg.recipientDeviceId)) {
|
|
4441
|
+
throw markRelayDeviceRefusal(new Error('Recipient device registration changed'), {
|
|
4442
|
+
code: 'STALE_DEVICE',
|
|
4443
|
+
userId: msg.recipientUserId,
|
|
4444
|
+
deviceId: msg.recipientDeviceId,
|
|
4445
|
+
});
|
|
4446
|
+
}
|
|
4447
|
+
return result;
|
|
4448
|
+
}
|
|
4449
|
+
catch (error) {
|
|
4450
|
+
// Fall back to identified delivery only for sealed-sender authorization
|
|
4451
|
+
// failures. Other failures retain their original error semantics.
|
|
4452
|
+
if (error instanceof SealedSenderAuthError) {
|
|
4453
|
+
if (prepared.deliveryMode === 'required') {
|
|
4454
|
+
throw error;
|
|
4455
|
+
}
|
|
4456
|
+
await this.restrictUnidentifiedAccessMode(msg.recipientUserId);
|
|
4457
|
+
await this.reportIdentifiedFallback(msg.recipientUserId);
|
|
4458
|
+
fallbackFrom = error;
|
|
4459
|
+
// Fall through to identified path below
|
|
4460
|
+
}
|
|
4461
|
+
else {
|
|
3502
4462
|
throw error;
|
|
3503
4463
|
}
|
|
3504
|
-
await this.restrictUnidentifiedAccessMode(msg.recipientUserId);
|
|
3505
|
-
await this.reportIdentifiedFallback(msg.recipientUserId);
|
|
3506
|
-
// Fall through to identified path below
|
|
3507
4464
|
}
|
|
3508
|
-
|
|
4465
|
+
}
|
|
4466
|
+
// Identified sender path: standard relay send
|
|
4467
|
+
try {
|
|
4468
|
+
return await this.postToRelay(() => this.relay.send({
|
|
4469
|
+
targetUserId: msg.recipientUserId,
|
|
4470
|
+
targetDeviceId: msg.recipientDeviceId,
|
|
4471
|
+
senderUserId: this.userId,
|
|
4472
|
+
senderDeviceId: this.deviceId,
|
|
4473
|
+
ciphertext: ciphertextBase64,
|
|
4474
|
+
messageType,
|
|
4475
|
+
deliveryClass: identifiedControl.deliveryClass ?? 'user-visible',
|
|
4476
|
+
timestamp: msg.timestamp,
|
|
4477
|
+
...(identifiedControl.operationEpochMilliseconds !== undefined && {
|
|
4478
|
+
operationEpochMilliseconds: identifiedControl.operationEpochMilliseconds,
|
|
4479
|
+
}),
|
|
4480
|
+
clientMessageId: effectiveClientMessageId,
|
|
4481
|
+
recipientRegistrationId,
|
|
4482
|
+
contentHint,
|
|
4483
|
+
...(identifiedControl.declaredDeviceIds && {
|
|
4484
|
+
declaredDeviceIds: identifiedControl.declaredDeviceIds,
|
|
4485
|
+
}),
|
|
4486
|
+
}), false, identifiedControl);
|
|
4487
|
+
}
|
|
4488
|
+
catch (error) {
|
|
4489
|
+
if (fallbackFrom === undefined)
|
|
3509
4490
|
throw error;
|
|
3510
|
-
|
|
4491
|
+
// The posting deadline refused the fallback request, so the sealed
|
|
4492
|
+
// answer stays the answer of the post.
|
|
4493
|
+
if (isPostingDeadlineReached(error))
|
|
4494
|
+
throw fallbackFrom;
|
|
4495
|
+
if (followedRepeatedRequest(fallbackFrom))
|
|
4496
|
+
markAfterRepeatedRequest(error);
|
|
4497
|
+
throw error;
|
|
3511
4498
|
}
|
|
3512
4499
|
}
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
targetDeviceId: msg.recipientDeviceId,
|
|
3517
|
-
senderUserId: this.userId,
|
|
3518
|
-
senderDeviceId: this.deviceId,
|
|
3519
|
-
ciphertext: ciphertextBase64,
|
|
3520
|
-
messageType,
|
|
3521
|
-
deliveryClass: identifiedControl.deliveryClass ?? 'user-visible',
|
|
3522
|
-
timestamp: msg.timestamp,
|
|
3523
|
-
...(identifiedControl.operationEpochMilliseconds !== undefined && {
|
|
3524
|
-
operationEpochMilliseconds: identifiedControl.operationEpochMilliseconds,
|
|
3525
|
-
}),
|
|
3526
|
-
clientMessageId: effectiveClientMessageId,
|
|
3527
|
-
recipientRegistrationId,
|
|
3528
|
-
contentHint,
|
|
3529
|
-
...(identifiedControl.declaredDeviceIds && {
|
|
3530
|
-
declaredDeviceIds: identifiedControl.declaredDeviceIds,
|
|
3531
|
-
}),
|
|
3532
|
-
}), false, identifiedControl);
|
|
4500
|
+
finally {
|
|
4501
|
+
release?.();
|
|
4502
|
+
}
|
|
3533
4503
|
}
|
|
3534
4504
|
/**
|
|
3535
4505
|
* Resolve the group roster to concrete devices via the relay.
|
|
@@ -3793,19 +4763,52 @@ export class SignalProtocolServiceCipher {
|
|
|
3793
4763
|
if (!this.relay) {
|
|
3794
4764
|
throw new EncryptionError('Relay server not configured. Cannot send attachments without server connection.', EncryptionErrorCode.INITIALIZATION_FAILED);
|
|
3795
4765
|
}
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
3808
|
-
|
|
4766
|
+
const fileDigest = CryptoUtils.bytesToBase64(await CryptoUtils.sha256(data));
|
|
4767
|
+
const stored = await getOutgoingMessageIntent(this.storage, options.clientMessageId);
|
|
4768
|
+
let message;
|
|
4769
|
+
let pointer;
|
|
4770
|
+
let sendOptions;
|
|
4771
|
+
if (stored) {
|
|
4772
|
+
// A repeat sends the stored message under the stored timestamp, so the
|
|
4773
|
+
// locked send replays the stored intent and uploads nothing. Another
|
|
4774
|
+
// file, pointer metadata, recipient or timestamp is another logical
|
|
4775
|
+
// send, and the repeat refuses it before any upload.
|
|
4776
|
+
const group = isGroupId(recipientId);
|
|
4777
|
+
const storedPointer = stored.binaryAttachment && attachmentPointerOf(stored.binaryAttachment.message);
|
|
4778
|
+
if (!stored.binaryAttachment ||
|
|
4779
|
+
!storedPointer ||
|
|
4780
|
+
stored.binaryAttachment.fileDigest !== fileDigest ||
|
|
4781
|
+
!pointerHasAttachmentMetadata(storedPointer, attachmentMetadataFromOptions(options)) ||
|
|
4782
|
+
stored.kind !== (group ? 'group' : 'direct') ||
|
|
4783
|
+
stored.recipientId !== (group ? extractGroupId(recipientId) : recipientId) ||
|
|
4784
|
+
(options.timestamp !== undefined && stored.clientTimestamp !== options.timestamp)) {
|
|
4785
|
+
throw new Error('A clientMessageId cannot identify two different logical sends');
|
|
4786
|
+
}
|
|
4787
|
+
message = stored.binaryAttachment.message;
|
|
4788
|
+
pointer = storedPointer;
|
|
4789
|
+
sendOptions = { ...options, timestamp: stored.clientTimestamp };
|
|
4790
|
+
}
|
|
4791
|
+
else {
|
|
4792
|
+
// The upload posts the file, so a new send checks its timestamp first,
|
|
4793
|
+
// once, against one clock reading. Without a caller timestamp, the SDK
|
|
4794
|
+
// reads its clock once, before the upload, and the message and the
|
|
4795
|
+
// intent take that timestamp. The timestamp mark stops the checks of
|
|
4796
|
+
// the send after the upload, which would read a later clock. The
|
|
4797
|
+
// attachment mark puts the message in the intent.
|
|
4798
|
+
const checked = withCheckedSendTimestamp(options);
|
|
4799
|
+
const timestamp = checked.timestamp ?? Date.now();
|
|
4800
|
+
const uploaded = await this.prepareAttachmentUpload(data, checked);
|
|
4801
|
+
message = serializeMediaAttachmentMessage({ attachment: uploaded, timestamp });
|
|
4802
|
+
// The pointer of the result comes from the message, as on a repeat.
|
|
4803
|
+
pointer = attachmentPointerOf(message);
|
|
4804
|
+
sendOptions = {
|
|
4805
|
+
...checked,
|
|
4806
|
+
timestamp,
|
|
4807
|
+
[SEND_TIMESTAMP_ORIGIN]: checked[SEND_TIMESTAMP_ORIGIN] ?? 'sdk-clock',
|
|
4808
|
+
[SEND_BINARY_ATTACHMENT]: { fileDigest, message },
|
|
4809
|
+
};
|
|
4810
|
+
}
|
|
4811
|
+
const attachmentBytes = new TextEncoder().encode(message);
|
|
3809
4812
|
let result;
|
|
3810
4813
|
if (isGroupId(recipientId)) {
|
|
3811
4814
|
result = await this.encryptToGroup(recipientId, attachmentBytes, sendOptions, sessions, stopSignal);
|
|
@@ -3815,11 +4818,11 @@ export class SignalProtocolServiceCipher {
|
|
|
3815
4818
|
}
|
|
3816
4819
|
return {
|
|
3817
4820
|
...result,
|
|
3818
|
-
storageId:
|
|
3819
|
-
aesKey:
|
|
3820
|
-
segmentSize:
|
|
3821
|
-
digest:
|
|
3822
|
-
contentType:
|
|
4821
|
+
storageId: pointer.storageId,
|
|
4822
|
+
aesKey: pointer.key,
|
|
4823
|
+
segmentSize: pointer.segmentSize,
|
|
4824
|
+
digest: pointer.digest,
|
|
4825
|
+
contentType: pointer.contentType,
|
|
3823
4826
|
};
|
|
3824
4827
|
}
|
|
3825
4828
|
async prepareAttachmentUpload(data, options) {
|
|
@@ -3835,19 +4838,7 @@ export class SignalProtocolServiceCipher {
|
|
|
3835
4838
|
onProgress: options?.attachment?.onProgress,
|
|
3836
4839
|
onCheckpoint: options?.attachment?.onCheckpoint,
|
|
3837
4840
|
resume: options?.attachment?.resume,
|
|
3838
|
-
|
|
3839
|
-
blurHash: options?.blurHash,
|
|
3840
|
-
thumbnail: options?.thumbnail,
|
|
3841
|
-
width: options?.width,
|
|
3842
|
-
height: options?.height,
|
|
3843
|
-
durationMs: options?.durationMs,
|
|
3844
|
-
waveform: options?.waveform,
|
|
3845
|
-
fileName: options?.fileName,
|
|
3846
|
-
caption: options?.caption,
|
|
3847
|
-
isViewOnce: options?.isViewOnce,
|
|
3848
|
-
flags: options?.flags,
|
|
3849
|
-
clientUuid: options?.clientUuid,
|
|
3850
|
-
cdnNumber: options?.cdnNumber,
|
|
4841
|
+
...attachmentMetadataFromOptions(options),
|
|
3851
4842
|
});
|
|
3852
4843
|
}
|
|
3853
4844
|
}
|