signal-desktop/ts/textsecure/OutgoingMessage.ts

736 lines
21 KiB
TypeScript
Raw Normal View History

// Copyright 2020-2022 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable more/no-then */
/* eslint-disable no-param-reassign */
import { reject } from 'lodash';
2021-05-25 22:40:04 +00:00
import { z } from 'zod';
import type {
2021-05-28 19:11:19 +00:00
CiphertextMessage,
PlaintextContent,
} from '@signalapp/libsignal-client';
import {
CiphertextMessageType,
ProtocolAddress,
2021-05-28 19:11:19 +00:00
sealedSenderEncrypt,
SenderCertificate,
signalEncrypt,
2021-05-28 19:11:19 +00:00
UnidentifiedSenderMessageContent,
} from '@signalapp/libsignal-client';
2021-09-28 23:38:55 +00:00
import type { WebAPIType, MessageType } from './WebAPI';
import type { SendMetadataType, SendOptionsType } from './SendMessage';
import {
OutgoingIdentityKeyError,
OutgoingMessageError,
SendMessageNetworkError,
SendMessageChallengeError,
UnregisteredUserError,
2021-09-22 00:58:03 +00:00
HTTPError,
} from './Errors';
import type { CallbackResultType, CustomError } from './Types.d';
2020-09-04 01:25:19 +00:00
import { isValidNumber } from '../types/PhoneNumber';
import { Address } from '../types/Address';
import { QualifiedAddress } from '../types/QualifiedAddress';
2021-10-26 22:59:08 +00:00
import { UUID, isValidUuid } from '../types/UUID';
import { Sessions, IdentityKeys } from '../LibSignalStores';
import { updateConversationsWithUuidLookup } from '../updateConversationsWithUuidLookup';
2021-05-25 22:40:04 +00:00
import { getKeysForIdentifier } from './getKeysForIdentifier';
2021-07-09 19:36:10 +00:00
import { SignalService as Proto } from '../protobuf';
import * as log from '../logging/log';
export const enum SenderCertificateMode {
WithE164,
WithoutE164,
}
export type SendLogCallbackType = (options: {
identifier: string;
deviceIds: Array<number>;
}) => Promise<void>;
export const serializedCertificateSchema = z.object({
expires: z.number().optional(),
serialized: z.instanceof(Uint8Array),
});
export type SerializedCertificateType = z.infer<
typeof serializedCertificateSchema
>;
type OutgoingMessageOptionsType = SendOptionsType & {
online?: boolean;
};
function ciphertextMessageTypeToEnvelopeType(type: number) {
if (type === CiphertextMessageType.PreKey) {
2021-07-09 19:36:10 +00:00
return Proto.Envelope.Type.PREKEY_BUNDLE;
}
if (type === CiphertextMessageType.Whisper) {
2021-07-09 19:36:10 +00:00
return Proto.Envelope.Type.CIPHERTEXT;
}
2021-05-28 19:11:19 +00:00
if (type === CiphertextMessageType.Plaintext) {
2021-07-09 19:36:10 +00:00
return Proto.Envelope.Type.PLAINTEXT_CONTENT;
2021-05-28 19:11:19 +00:00
}
throw new Error(
`ciphertextMessageTypeToEnvelopeType: Unrecognized type ${type}`
);
}
2021-05-25 22:40:04 +00:00
function getPaddedMessageLength(messageLength: number): number {
const messageLengthWithTerminator = messageLength + 1;
let messagePartCount = Math.floor(messageLengthWithTerminator / 160);
if (messageLengthWithTerminator % 160 !== 0) {
messagePartCount += 1;
}
return messagePartCount * 160;
}
2021-07-09 19:36:10 +00:00
export function padMessage(messageBuffer: Uint8Array): Uint8Array {
2021-05-25 22:40:04 +00:00
const plaintext = new Uint8Array(
getPaddedMessageLength(messageBuffer.byteLength + 1) - 1
);
2021-07-09 19:36:10 +00:00
plaintext.set(messageBuffer);
2021-05-25 22:40:04 +00:00
plaintext[messageBuffer.byteLength] = 0x80;
return plaintext;
}
export default class OutgoingMessage {
server: WebAPIType;
timestamp: number;
identifiers: ReadonlyArray<string>;
2021-07-09 19:36:10 +00:00
message: Proto.Content | PlaintextContent;
callback: (result: CallbackResultType) => void;
plaintext?: Uint8Array;
identifiersCompleted: number;
errors: Array<CustomError>;
successfulIdentifiers: Array<string>;
failoverIdentifiers: Array<string>;
unidentifiedDeliveries: Array<string>;
sendMetadata?: SendMetadataType;
online?: boolean;
2021-05-28 19:11:19 +00:00
groupId?: string;
contentHint: number;
urgent: boolean;
recipients: Record<string, Array<number>>;
sendLogCallback?: SendLogCallbackType;
constructor({
callback,
contentHint,
groupId,
identifiers,
message,
options,
sendLogCallback,
server,
timestamp,
urgent,
}: {
callback: (result: CallbackResultType) => void;
contentHint: number;
groupId: string | undefined;
identifiers: ReadonlyArray<string>;
message: Proto.Content | Proto.DataMessage | PlaintextContent;
options?: OutgoingMessageOptionsType;
sendLogCallback?: SendLogCallbackType;
server: WebAPIType;
timestamp: number;
urgent: boolean;
}) {
2021-07-09 19:36:10 +00:00
if (message instanceof Proto.DataMessage) {
const content = new Proto.Content();
content.dataMessage = message;
this.message = content;
} else {
this.message = message;
}
this.server = server;
this.timestamp = timestamp;
this.identifiers = identifiers;
2021-05-28 19:11:19 +00:00
this.contentHint = contentHint;
this.groupId = groupId;
this.callback = callback;
this.urgent = urgent;
this.identifiersCompleted = 0;
this.errors = [];
this.successfulIdentifiers = [];
this.failoverIdentifiers = [];
this.unidentifiedDeliveries = [];
this.recipients = {};
this.sendLogCallback = sendLogCallback;
this.sendMetadata = options?.sendMetadata;
this.online = options?.online;
}
numberCompleted(): void {
this.identifiersCompleted += 1;
if (this.identifiersCompleted >= this.identifiers.length) {
const proto = this.message;
const contentProto = this.getContentProtoBytes();
const { timestamp, contentHint, recipients, urgent } = this;
let dataMessage: Uint8Array | undefined;
2022-08-15 21:53:33 +00:00
let hasPniSignatureMessage = false;
2022-08-15 21:53:33 +00:00
if (proto instanceof Proto.Content) {
if (proto.dataMessage) {
dataMessage = Proto.DataMessage.encode(proto.dataMessage).finish();
}
hasPniSignatureMessage = Boolean(proto.pniSignatureMessage);
} else if (proto instanceof Proto.DataMessage) {
dataMessage = Proto.DataMessage.encode(proto).finish();
}
2018-05-02 16:51:22 +00:00
this.callback({
successfulIdentifiers: this.successfulIdentifiers,
failoverIdentifiers: this.failoverIdentifiers,
2018-05-02 16:51:22 +00:00
errors: this.errors,
unidentifiedDeliveries: this.unidentifiedDeliveries,
contentHint,
dataMessage,
recipients,
contentProto,
timestamp,
urgent,
2022-08-15 21:53:33 +00:00
hasPniSignatureMessage,
2018-05-02 16:51:22 +00:00
});
}
}
registerError(
identifier: string,
reason: string,
providedError?: Error
): void {
let error = providedError;
2021-09-22 00:58:03 +00:00
if (!error || (error instanceof HTTPError && error.code !== 404)) {
if (error && error.code === 428) {
error = new SendMessageChallengeError(identifier, error);
} else {
2021-05-28 19:11:19 +00:00
error = new OutgoingMessageError(identifier, null, null, error);
}
2018-05-02 16:51:22 +00:00
}
2018-05-02 16:51:22 +00:00
error.reason = reason;
error.stackForLog = providedError ? providedError.stack : undefined;
2018-05-02 16:51:22 +00:00
this.errors[this.errors.length] = error;
this.numberCompleted();
}
reloadDevicesAndSend(
identifier: string,
recurse?: boolean
): () => Promise<void> {
2021-05-25 22:40:04 +00:00
return async () => {
const ourUuid = window.textsecure.storage.user.getCheckedUuid();
const deviceIds = await window.textsecure.storage.protocol.getDeviceIds({
ourUuid,
identifier,
});
2021-05-25 22:40:04 +00:00
if (deviceIds.length === 0) {
this.registerError(
identifier,
'reloadDevicesAndSend: Got empty device list when loading device keys',
undefined
);
return undefined;
}
return this.doSendMessage(identifier, deviceIds, recurse);
};
}
2018-07-21 21:51:20 +00:00
async getKeysForIdentifier(
identifier: string,
2021-05-25 22:40:04 +00:00
updateDevices?: Array<number>
): Promise<void | Array<void | null>> {
const { sendMetadata } = this;
const info =
sendMetadata && sendMetadata[identifier]
? sendMetadata[identifier]
: { accessKey: undefined };
const { accessKey } = info;
2021-05-25 22:40:04 +00:00
try {
const { accessKeyFailed } = await getKeysForIdentifier(
identifier,
this.server,
updateDevices,
accessKey
);
if (accessKeyFailed && !this.failoverIdentifiers.includes(identifier)) {
this.failoverIdentifiers.push(identifier);
}
2021-05-25 22:40:04 +00:00
} catch (error) {
if (error?.message?.includes('untrusted identity for address')) {
error.timestamp = this.timestamp;
}
throw error;
2018-07-21 21:51:20 +00:00
}
}
async transmitMessage(
identifier: string,
2021-09-28 23:38:55 +00:00
jsonData: ReadonlyArray<MessageType>,
timestamp: number,
{ accessKey }: { accessKey?: string } = {}
): Promise<void> {
let promise;
if (accessKey) {
promise = this.server.sendMessagesUnauth(
identifier,
jsonData,
timestamp,
{ accessKey, online: this.online, urgent: this.urgent }
);
} else {
promise = this.server.sendMessages(identifier, jsonData, timestamp, {
online: this.online,
urgent: this.urgent,
});
}
return promise.catch(e => {
2021-09-22 00:58:03 +00:00
if (e instanceof HTTPError && e.code !== 409 && e.code !== 410) {
// 409 and 410 should bubble and be handled by doSendMessage
// 404 should throw UnregisteredUserError
// 428 should throw SendMessageChallengeError
// all other network errors can be retried later.
if (e.code === 404) {
throw new UnregisteredUserError(identifier, e);
}
if (e.code === 428) {
throw new SendMessageChallengeError(identifier, e);
}
throw new SendMessageNetworkError(identifier, jsonData, e);
}
throw e;
});
}
2021-09-24 00:49:05 +00:00
getPlaintext(): Uint8Array {
2018-05-02 16:51:22 +00:00
if (!this.plaintext) {
2021-05-28 19:11:19 +00:00
const { message } = this;
2021-07-09 19:36:10 +00:00
if (message instanceof Proto.Content) {
this.plaintext = padMessage(Proto.Content.encode(message).finish());
2021-05-28 19:11:19 +00:00
} else {
this.plaintext = message.serialize();
}
2018-05-02 16:51:22 +00:00
}
2021-09-24 00:49:05 +00:00
return this.plaintext;
}
getContentProtoBytes(): Uint8Array | undefined {
if (this.message instanceof Proto.Content) {
return new Uint8Array(Proto.Content.encode(this.message).finish());
}
return undefined;
}
2021-05-28 19:11:19 +00:00
async getCiphertextMessage({
identityKeyStore,
protocolAddress,
sessionStore,
}: {
identityKeyStore: IdentityKeys;
protocolAddress: ProtocolAddress;
sessionStore: Sessions;
}): Promise<CiphertextMessage> {
const { message } = this;
2021-07-09 19:36:10 +00:00
if (message instanceof Proto.Content) {
2021-05-28 19:11:19 +00:00
return signalEncrypt(
Buffer.from(this.getPlaintext()),
protocolAddress,
sessionStore,
identityKeyStore
);
}
return message.asCiphertextMessage();
}
async doSendMessage(
identifier: string,
deviceIds: Array<number>,
recurse?: boolean
): Promise<void> {
const { sendMetadata } = this;
const { accessKey, senderCertificate } = sendMetadata?.[identifier] || {};
if (accessKey && !senderCertificate) {
log.warn(
'OutgoingMessage.doSendMessage: accessKey was provided, but senderCertificate was not'
);
}
2018-10-31 23:58:14 +00:00
const sealedSender = Boolean(accessKey && senderCertificate);
// We don't send to ourselves unless sealedSender is enabled
const ourNumber = window.textsecure.storage.user.getNumber();
const ourUuid = window.textsecure.storage.user.getCheckedUuid();
const ourDeviceId = window.textsecure.storage.user.getDeviceId();
if (
(identifier === ourNumber || identifier === ourUuid.toString()) &&
!sealedSender
) {
deviceIds = reject(
deviceIds,
deviceId =>
// because we store our own device ID as a string at least sometimes
deviceId === ourDeviceId ||
(typeof ourDeviceId === 'string' &&
deviceId === parseInt(ourDeviceId, 10))
);
}
const sessionStore = new Sessions({ ourUuid });
const identityKeyStore = new IdentityKeys({ ourUuid });
2018-05-02 16:51:22 +00:00
return Promise.all(
deviceIds.map(async destinationDeviceId => {
const theirUuid = UUID.checkedLookup(identifier);
const address = new QualifiedAddress(
ourUuid,
new Address(theirUuid, destinationDeviceId)
);
2021-09-28 23:38:55 +00:00
return window.textsecure.storage.protocol.enqueueSessionJob<MessageType>(
address,
async () => {
const protocolAddress = ProtocolAddress.new(
theirUuid.toString(),
destinationDeviceId
);
2018-05-02 16:51:22 +00:00
const activeSession = await sessionStore.getSession(
protocolAddress
);
if (!activeSession) {
throw new Error(
2022-02-09 20:33:19 +00:00
'OutgoingMessage.doSendMessage: No active session!'
);
}
2021-11-11 22:43:05 +00:00
const destinationRegistrationId =
activeSession.remoteRegistrationId();
if (sealedSender && senderCertificate) {
2021-05-28 19:11:19 +00:00
const ciphertextMessage = await this.getCiphertextMessage({
identityKeyStore,
protocolAddress,
sessionStore,
});
const certificate = SenderCertificate.deserialize(
Buffer.from(senderCertificate.serialized)
);
2021-05-28 19:11:19 +00:00
const groupIdBuffer = this.groupId
? Buffer.from(this.groupId, 'base64')
: null;
2021-05-28 19:11:19 +00:00
const content = UnidentifiedSenderMessageContent.new(
ciphertextMessage,
certificate,
2021-05-28 19:11:19 +00:00
this.contentHint,
groupIdBuffer
);
const buffer = await sealedSenderEncrypt(
content,
protocolAddress,
identityKeyStore
);
return {
2021-07-09 19:36:10 +00:00
type: Proto.Envelope.Type.UNIDENTIFIED_SENDER,
destinationDeviceId,
destinationRegistrationId,
content: buffer.toString('base64'),
};
}
2021-05-28 19:11:19 +00:00
const ciphertextMessage = await this.getCiphertextMessage({
identityKeyStore,
protocolAddress,
sessionStore,
2021-05-28 19:11:19 +00:00
});
const type = ciphertextMessageTypeToEnvelopeType(
ciphertextMessage.type()
);
const content = ciphertextMessage.serialize().toString('base64');
return {
type,
destinationDeviceId,
destinationRegistrationId,
content,
};
}
);
2018-07-21 21:51:20 +00:00
})
2018-05-02 16:51:22 +00:00
)
2021-09-28 23:38:55 +00:00
.then(async (jsonData: Array<MessageType>) => {
if (sealedSender) {
return this.transmitMessage(identifier, jsonData, this.timestamp, {
accessKey,
}).then(
() => {
this.recipients[identifier] = deviceIds;
this.unidentifiedDeliveries.push(identifier);
this.successfulIdentifiers.push(identifier);
this.numberCompleted();
if (this.sendLogCallback) {
this.sendLogCallback({
identifier,
deviceIds,
});
} else if (this.successfulIdentifiers.length > 1) {
log.warn(
`OutgoingMessage.doSendMessage: no sendLogCallback provided for message ${this.timestamp}, but multiple recipients`
);
}
},
async (error: Error) => {
2021-09-22 00:58:03 +00:00
if (
error instanceof HTTPError &&
(error.code === 401 || error.code === 403)
) {
if (this.failoverIdentifiers.indexOf(identifier) === -1) {
this.failoverIdentifiers.push(identifier);
}
// This ensures that we don't hit this codepath the next time through
if (sendMetadata) {
delete sendMetadata[identifier];
}
return this.doSendMessage(identifier, deviceIds, recurse);
}
throw error;
}
);
}
return this.transmitMessage(identifier, jsonData, this.timestamp).then(
() => {
this.successfulIdentifiers.push(identifier);
this.recipients[identifier] = deviceIds;
this.numberCompleted();
if (this.sendLogCallback) {
this.sendLogCallback({
identifier,
deviceIds,
});
} else if (this.successfulIdentifiers.length > 1) {
log.warn(
`OutgoingMessage.doSendMessage: no sendLogCallback provided for message ${this.timestamp}, but multiple recipients`
);
}
}
);
})
.catch(async error => {
2018-07-21 21:51:20 +00:00
if (
2021-09-22 00:58:03 +00:00
error instanceof HTTPError &&
2018-07-21 21:51:20 +00:00
(error.code === 410 || error.code === 409)
) {
if (!recurse) {
this.registerError(
identifier,
2018-07-21 21:51:20 +00:00
'Hit retry limit attempting to reload device list',
error
2018-05-02 16:51:22 +00:00
);
return undefined;
}
2018-07-21 21:51:20 +00:00
2021-09-22 00:58:03 +00:00
const response = error.response as {
extraDevices?: Array<number>;
staleDevices?: Array<number>;
missingDevices?: Array<number>;
};
let p: Promise<any> = Promise.resolve();
2018-07-21 21:51:20 +00:00
if (error.code === 409) {
p = this.removeDeviceIdsForIdentifier(
identifier,
2021-09-22 00:58:03 +00:00
response.extraDevices || []
2018-05-02 16:51:22 +00:00
);
} else {
2018-07-21 21:51:20 +00:00
p = Promise.all(
2021-09-22 00:58:03 +00:00
(response.staleDevices || []).map(async (deviceId: number) => {
await window.textsecure.storage.protocol.archiveSession(
new QualifiedAddress(
ourUuid,
new Address(UUID.checkedLookup(identifier), deviceId)
)
);
})
2018-05-02 16:51:22 +00:00
);
}
return p.then(async () => {
2018-07-21 21:51:20 +00:00
const resetDevices =
error.code === 410
2021-09-22 00:58:03 +00:00
? response.staleDevices
: response.missingDevices;
return this.getKeysForIdentifier(identifier, resetDevices).then(
2018-10-31 23:58:14 +00:00
// We continue to retry as long as the error code was 409; the assumption is
// that we'll request new device info and the next request will succeed.
this.reloadDevicesAndSend(identifier, error.code === 409)
2018-05-02 16:51:22 +00:00
);
2018-07-21 21:51:20 +00:00
});
}
if (error?.message?.includes('untrusted identity for address')) {
2018-07-21 21:51:20 +00:00
error.timestamp = this.timestamp;
log.error(
2018-07-21 21:51:20 +00:00
'Got "key changed" error from encrypt - no identityKey for application layer',
identifier,
2018-07-21 21:51:20 +00:00
deviceIds
);
log.info('closing all sessions for', identifier);
window.textsecure.storage.protocol
.archiveAllSessions(UUID.checkedLookup(identifier))
.then(
() => {
throw error;
},
innerError => {
log.error(
`doSendMessage: Error closing sessions: ${innerError.stack}`
);
throw error;
}
);
2018-07-21 21:51:20 +00:00
}
this.registerError(
identifier,
'Failed to create or send message',
error
);
return undefined;
2018-05-02 16:51:22 +00:00
});
}
2018-05-02 16:51:22 +00:00
async removeDeviceIdsForIdentifier(
identifier: string,
deviceIdsToRemove: Array<number>
): Promise<void> {
const ourUuid = window.textsecure.storage.user.getCheckedUuid();
const theirUuid = UUID.checkedLookup(identifier);
await Promise.all(
deviceIdsToRemove.map(async deviceId => {
await window.textsecure.storage.protocol.archiveSession(
new QualifiedAddress(ourUuid, new Address(theirUuid, deviceId))
);
})
);
}
2018-05-02 16:51:22 +00:00
async sendToIdentifier(providedIdentifier: string): Promise<void> {
2020-09-04 01:25:19 +00:00
let identifier = providedIdentifier;
try {
2021-10-26 22:59:08 +00:00
if (isValidUuid(identifier)) {
2021-04-26 18:15:00 +00:00
// We're good!
} else if (isValidNumber(identifier)) {
if (!window.textsecure.server) {
2021-04-26 18:15:00 +00:00
throw new Error(
'sendToIdentifier: window.textsecure.server is not available!'
2021-04-26 18:15:00 +00:00
);
}
2021-04-26 18:15:00 +00:00
try {
await updateConversationsWithUuidLookup({
conversationController: window.ConversationController,
conversations: [
window.ConversationController.getOrCreate(identifier, 'private'),
],
server: window.textsecure.server,
});
2021-04-26 18:15:00 +00:00
2021-11-11 22:43:05 +00:00
const uuid =
window.ConversationController.get(identifier)?.get('uuid');
if (!uuid) {
2021-04-26 18:15:00 +00:00
throw new UnregisteredUserError(
identifier,
2021-09-22 00:58:03 +00:00
new HTTPError('User is not registered', {
code: -1,
headers: {},
})
2020-09-09 02:25:05 +00:00
);
}
identifier = uuid;
2021-04-26 18:15:00 +00:00
} catch (error) {
log.error(
2021-05-04 16:44:17 +00:00
`sendToIdentifier: Failed to fetch UUID for identifier ${identifier}`,
2021-04-26 18:15:00 +00:00
error && error.stack ? error.stack : error
2020-09-04 01:25:19 +00:00
);
}
2021-04-26 18:15:00 +00:00
} else {
throw new Error(
`sendToIdentifier: identifier ${identifier} was neither a UUID or E164`
);
2020-09-04 01:25:19 +00:00
}
const ourUuid = window.textsecure.storage.user.getCheckedUuid();
const deviceIds = await window.textsecure.storage.protocol.getDeviceIds({
ourUuid,
identifier,
});
2021-05-25 22:40:04 +00:00
if (deviceIds.length === 0) {
await this.getKeysForIdentifier(identifier);
}
await this.reloadDevicesAndSend(identifier, true)();
} catch (error) {
if (error?.message?.includes('untrusted identity for address')) {
const newError = new OutgoingIdentityKeyError(identifier);
this.registerError(identifier, 'Untrusted identity', newError);
} else {
this.registerError(
identifier,
2020-09-04 01:25:19 +00:00
`Failed to retrieve new device keys for identifier ${identifier}`,
error
);
}
}
}
}