session-desktop/libtextsecure/outgoing_message.js

449 lines
14 KiB
JavaScript
Raw Normal View History

2018-11-01 01:08:41 +01:00
/* global
textsecure,
libsignal,
window,
ConversationController,
libloki,
StringView,
dcodeIO,
log,
*/
2018-07-21 23:51:20 +02:00
/* eslint-disable more/no-then */
2018-05-02 18:51:22 +02:00
function OutgoingMessage(
server,
timestamp,
numbers,
message,
silent,
callback
) {
if (message instanceof textsecure.protobuf.DataMessage) {
2018-07-21 23:51:20 +02:00
const content = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
content.dataMessage = message;
2018-07-21 23:51:20 +02:00
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
message = content;
}
this.server = server;
this.timestamp = timestamp;
this.numbers = numbers;
this.message = message; // ContentMessage proto
this.callback = callback;
this.silent = silent;
2018-11-01 01:08:41 +01:00
this.lokiserver = window.LokiAPI.connect();
2018-05-02 18:51:22 +02:00
this.numbersCompleted = 0;
this.errors = [];
this.successfulNumbers = [];
this.fallBackEncryption = false;
}
OutgoingMessage.prototype = {
2018-05-02 18:51:22 +02:00
constructor: OutgoingMessage,
2018-07-21 23:51:20 +02:00
numberCompleted() {
this.numbersCompleted += 1;
2018-05-02 18:51:22 +02:00
if (this.numbersCompleted >= this.numbers.length) {
this.callback({
successfulNumbers: this.successfulNumbers,
errors: this.errors,
});
}
},
2018-07-21 23:51:20 +02:00
registerError(number, reason, error) {
2018-05-02 18:51:22 +02:00
if (!error || (error.name === 'HTTPError' && error.code !== 404)) {
2018-07-21 23:51:20 +02:00
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
error = new textsecure.OutgoingMessageError(
number,
this.message.toArrayBuffer(),
this.timestamp,
error
);
}
2018-07-21 23:51:20 +02:00
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
error.number = number;
2018-07-21 23:51:20 +02:00
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
error.reason = reason;
this.errors[this.errors.length] = error;
this.numberCompleted();
},
2018-07-21 23:51:20 +02:00
reloadDevicesAndSend(number, recurse) {
return () =>
textsecure.storage.protocol.getDeviceIds(number).then(deviceIds => {
if (deviceIds.length === 0) {
2018-11-01 01:08:41 +01:00
// eslint-disable-next-line no-param-reassign
deviceIds = [1];
// return this.registerError(
// number,
// 'Got empty device list when loading device keys',
// null
// );
2018-07-21 23:51:20 +02:00
}
return this.doSendMessage(number, deviceIds, recurse);
});
},
getKeysForNumber(number, updateDevices) {
const handleResult = response =>
Promise.all(
response.devices.map(device => {
// eslint-disable-next-line no-param-reassign
device.identityKey = response.identityKey;
if (
updateDevices === undefined ||
updateDevices.indexOf(device.deviceId) > -1
) {
const address = new libsignal.SignalProtocolAddress(
2018-05-02 18:51:22 +02:00
number,
2018-07-21 23:51:20 +02:00
device.deviceId
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
const builder = new libsignal.SessionBuilder(
textsecure.storage.protocol,
address
);
if (device.registrationId === 0) {
window.log.info('device registrationId 0!');
}
return builder.processPreKey(device).catch(error => {
if (error.message === 'Identity key changed') {
// eslint-disable-next-line no-param-reassign
error.timestamp = this.timestamp;
// eslint-disable-next-line no-param-reassign
error.originalMessage = this.message.toArrayBuffer();
// eslint-disable-next-line no-param-reassign
error.identityKey = device.identityKey;
}
throw error;
});
2018-05-02 18:51:22 +02:00
}
return true;
2018-07-21 23:51:20 +02:00
})
2018-05-02 18:51:22 +02:00
);
// TODO: check if still applicable
2018-05-02 18:51:22 +02:00
if (updateDevices === undefined) {
return this.server.getKeysForNumber(number).then(handleResult);
2018-07-21 23:51:20 +02:00
}
let promise = Promise.resolve(true);
2018-07-21 23:51:20 +02:00
updateDevices.forEach(device => {
promise = promise.then(() =>
Promise.all([
textsecure.storage.protocol.loadContactPreKey(number),
2018-11-01 01:08:41 +01:00
textsecure.storage.protocol.loadContactSignedPreKey(number),
])
.then(keys => {
const [preKey, signedPreKey] = keys;
if (preKey === undefined || signedPreKey === undefined) {
return false;
}
const identityKey = StringView.hexToArrayBuffer(number);
2018-11-01 01:08:41 +01:00
return handleResult({
identityKey,
devices: [
{ deviceId: device, preKey, signedPreKey, registrationId: 0 },
],
});
})
2018-07-21 23:51:20 +02:00
.catch(e => {
if (e.name === 'HTTPError' && e.code === 404) {
if (device !== 1) {
return this.removeDeviceIdsForNumber(number, [device]);
}
throw new textsecure.UnregisteredUserError(number, e);
} else {
throw e;
}
})
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
});
2018-05-02 18:51:22 +02:00
2018-07-21 23:51:20 +02:00
return promise;
2018-05-02 18:51:22 +02:00
},
// Default ttl to 24 hours if no value provided
async transmitMessage(number, data, timestamp, ttl = 24 * 60 * 60) {
const pubKey = number;
try {
2018-11-01 01:08:41 +01:00
const [response] = await this.lokiserver.sendMessage(pubKey, data, ttl);
return response;
2018-11-01 01:08:41 +01:00
} catch (e) {
if (e.name === 'HTTPError' && (e.code !== 409 && e.code !== 410)) {
// 409 and 410 should bubble and be handled by doSendMessage
// 404 should throw UnregisteredUserError
// all other network errors can be retried later.
if (e.code === 404) {
throw new textsecure.UnregisteredUserError(number, e);
}
2018-11-01 01:08:41 +01:00
throw new textsecure.SendMessageNetworkError(number, '', e, timestamp);
}
throw e;
}
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
getPaddedMessageLength(messageLength) {
const messageLengthWithTerminator = messageLength + 1;
let messagePartCount = Math.floor(messageLengthWithTerminator / 160);
2018-05-02 18:51:22 +02:00
if (messageLengthWithTerminator % 160 !== 0) {
2018-07-21 23:51:20 +02:00
messagePartCount += 1;
2018-05-02 18:51:22 +02:00
}
2018-05-02 18:51:22 +02:00
return messagePartCount * 160;
},
2018-07-21 23:51:20 +02:00
getPlaintext() {
2018-05-02 18:51:22 +02:00
if (!this.plaintext) {
2018-07-21 23:51:20 +02:00
const messageBuffer = this.message.toArrayBuffer();
this.plaintext = new Uint8Array(messageBuffer.byteLength);
// TODO: figure out why we needed padding in the first place
// this.plaintext = new Uint8Array(
// this.getPaddedMessageLength(messageBuffer.byteLength + 1) - 1
// );
2018-05-02 18:51:22 +02:00
this.plaintext.set(new Uint8Array(messageBuffer));
2018-11-01 01:08:41 +01:00
// this.plaintext[messageBuffer.byteLength] = 0x80;
2018-05-02 18:51:22 +02:00
}
return this.plaintext;
},
async wrapInWebsocketMessage(outgoingObject) {
const messageEnvelope = new textsecure.protobuf.Envelope({
type: outgoingObject.type,
source: outgoingObject.address.getName(),
sourceDevice: outgoingObject.address.getDeviceId(),
timestamp: this.timestamp,
content: outgoingObject.content,
});
const requestMessage = new textsecure.protobuf.WebSocketRequestMessage({
2018-11-01 01:08:41 +01:00
id: new Uint8Array(libsignal.crypto.getRandomBytes(1))[0], // random ID for now
verb: 'PUT',
path: '/api/v1/message',
body: messageEnvelope.encode().toArrayBuffer(),
});
2018-10-08 06:03:32 +02:00
const websocketMessage = new textsecure.protobuf.WebSocketMessage({
type: textsecure.protobuf.WebSocketMessage.Type.REQUEST,
2018-11-01 01:08:41 +01:00
request: requestMessage,
});
2018-11-01 01:08:41 +01:00
const bytes = new Uint8Array(websocketMessage.encode().toArrayBuffer());
log.info(bytes.toString()); // print bytes for debugging purposes: can be injected in mock socket server
return bytes;
},
2018-07-21 23:51:20 +02:00
doSendMessage(number, deviceIds, recurse) {
const ciphers = {};
const plaintext = this.getPlaintext();
2018-05-02 18:51:22 +02:00
return Promise.all(
deviceIds.map(async deviceId => {
2018-07-21 23:51:20 +02:00
const address = new libsignal.SignalProtocolAddress(number, deviceId);
2018-07-21 23:51:20 +02:00
const ourNumber = textsecure.storage.user.getNumber();
const options = {};
2018-05-02 18:51:22 +02:00
2018-07-21 23:51:20 +02:00
// No limit on message keys if we're communicating with our other devices
if (ourNumber === number) {
options.messageKeysLimit = false;
}
2018-05-02 18:51:22 +02:00
let sessionCipher;
if (this.fallBackEncryption) {
2018-11-01 01:08:41 +01:00
sessionCipher = new libloki.FallBackSessionCipher(address);
} else {
sessionCipher = new libsignal.SessionCipher(
textsecure.storage.protocol,
address,
options
);
}
2018-07-21 23:51:20 +02:00
ciphers[address.getDeviceId()] = sessionCipher;
2018-11-01 01:08:41 +01:00
return sessionCipher
.encrypt(plaintext)
.then(ciphertext => {
if (!this.fallBackEncryption)
// eslint-disable-next-line no-param-reassign
ciphertext.body = new Uint8Array(
dcodeIO.ByteBuffer.wrap(
ciphertext.body,
'binary'
).toArrayBuffer()
);
return ciphertext;
})
.then(ciphertext => ({
type: ciphertext.type,
address,
destinationDeviceId: address.getDeviceId(),
destinationRegistrationId: ciphertext.registrationId,
content: ciphertext.body,
}));
2018-07-21 23:51:20 +02:00
})
2018-05-02 18:51:22 +02:00
)
.then(async outgoingObjects => {
// TODO: handle multiple devices/messages per transmit
const outgoingObject = outgoingObjects[0];
const socketMessage = await this.wrapInWebsocketMessage(outgoingObject);
let ttl;
// TODO: Allow user to set ttl manually
2018-11-01 01:08:41 +01:00
if (
outgoingObject.type ===
textsecure.protobuf.Envelope.Type.FRIEND_REQUEST
) {
ttl = 4 * 24 * 60 * 60; // 4 days for friend request message
} else {
ttl = 24 * 60 * 60; // 1 day default for any other message
}
await this.transmitMessage(number, socketMessage, this.timestamp, ttl);
this.successfulNumbers[this.successfulNumbers.length] = number;
this.numberCompleted();
2018-11-01 01:08:41 +01:00
})
2018-07-21 23:51:20 +02:00
.catch(error => {
if (
error instanceof Error &&
error.name === 'HTTPError' &&
(error.code === 410 || error.code === 409)
) {
if (!recurse)
return this.registerError(
number,
'Hit retry limit attempting to reload device list',
error
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
let p;
if (error.code === 409) {
p = this.removeDeviceIdsForNumber(
2018-05-02 18:51:22 +02:00
number,
2018-07-21 23:51:20 +02:00
error.response.extraDevices
2018-05-02 18:51:22 +02:00
);
} else {
2018-07-21 23:51:20 +02:00
p = Promise.all(
error.response.staleDevices.map(deviceId =>
ciphers[deviceId].closeOpenSessionForDevice()
)
2018-05-02 18:51:22 +02:00
);
}
2018-07-21 23:51:20 +02:00
return p.then(() => {
const resetDevices =
error.code === 410
? error.response.staleDevices
: error.response.missingDevices;
return this.getKeysForNumber(number, resetDevices).then(
this.reloadDevicesAndSend(number, error.code === 409)
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
});
} else if (error.message === 'Identity key changed') {
// eslint-disable-next-line no-param-reassign
error.timestamp = this.timestamp;
// eslint-disable-next-line no-param-reassign
error.originalMessage = this.message.toArrayBuffer();
window.log.error(
'Got "key changed" error from encrypt - no identityKey for application layer',
number,
deviceIds
);
throw error;
} else {
this.registerError(number, 'Failed to create or send message', error);
}
return null;
2018-05-02 18:51:22 +02:00
});
},
2018-07-21 23:51:20 +02:00
getStaleDeviceIdsForNumber(number) {
return textsecure.storage.protocol.getDeviceIds(number).then(deviceIds => {
if (deviceIds.length === 0) {
return [1];
}
const updateDevices = [];
return Promise.all(
deviceIds.map(deviceId => {
const address = new libsignal.SignalProtocolAddress(number, deviceId);
const sessionCipher = new libsignal.SessionCipher(
textsecure.storage.protocol,
address
);
return sessionCipher.hasOpenSession().then(hasSession => {
if (!hasSession) {
updateDevices.push(deviceId);
}
});
})
).then(() => updateDevices);
});
},
removeDeviceIdsForNumber(number, deviceIdsToRemove) {
let promise = Promise.resolve();
// eslint-disable-next-line no-restricted-syntax, guard-for-in
for (const j in deviceIdsToRemove) {
promise = promise.then(() => {
const encodedNumber = `${number}.${deviceIdsToRemove[j]}`;
2018-05-02 18:51:22 +02:00
return textsecure.storage.protocol.removeSession(encodedNumber);
});
}
2018-05-02 18:51:22 +02:00
return promise;
},
2018-07-21 23:51:20 +02:00
sendToNumber(number) {
let conversation;
try {
conversation = ConversationController.get(number);
2018-11-01 01:08:41 +01:00
} catch (e) {
// do nothing
}
return this.getStaleDeviceIdsForNumber(number).then(updateDevices =>
this.getKeysForNumber(number, updateDevices)
2018-11-01 01:08:41 +01:00
.then(async keysFound => {
let attachPrekeys = false;
2018-11-01 01:08:41 +01:00
if (!keysFound) {
log.info('Fallback encryption enabled');
this.fallBackEncryption = true;
attachPrekeys = true;
} else if (conversation) {
try {
attachPrekeys = !conversation.isKeyExchangeCompleted();
2018-11-01 01:08:41 +01:00
} catch (e) {
// do nothing
}
}
2018-11-01 01:08:41 +01:00
if (attachPrekeys) {
log.info('attaching prekeys to outgoing message');
2018-11-01 01:08:41 +01:00
this.message.preKeyBundleMessage = await libloki.getPreKeyBundleForNumber(
number
);
}
2018-11-01 01:08:41 +01:00
})
.then(this.reloadDevicesAndSend(number, true))
.then(() => {
if (this.fallBackEncryption && conversation) {
conversation.onFriendRequestSent();
}
})
.catch(error => {
if (error.message === 'Identity key changed') {
// eslint-disable-next-line no-param-reassign
error = new textsecure.OutgoingIdentityKeyError(
number,
error.originalMessage,
error.timestamp,
error.identityKey
);
this.registerError(number, 'Identity key changed', error);
} else {
this.registerError(
number,
`Failed to retrieve new device keys for number ${number}`,
error
);
}
})
);
2018-05-02 18:51:22 +02:00
},
};
window.textsecure = window.textsecure || {};
window.textsecure.OutgoingMessage = OutgoingMessage;