signal-desktop/libtextsecure/outgoing_message.js

245 lines
10 KiB
JavaScript
Raw Normal View History

/*
* vim: ts=4:sw=4:expandtab
*/
Feature: Blue check marks for read messages if opted in (#1489) * Refactor delivery receipt event handler * Rename the delivery receipt event For less ambiguity with read receipts. * Rename synced read event For less ambiguity with read receipts from other Signal users. * Add support for incoming receipt messages Handle ReceiptMessages, which may include encrypted delivery receipts or read receipts from recipients of our sent messages. // FREEBIE * Rename ReadReceipts to ReadSyncs * Render read messages with blue double checks * Send read receipts to senders of incoming messages // FREEBIE * Move ReadSyncs to their own file // FREEBIE * Fixup old comments on read receipts (now read syncs) And some variable renaming for extra clarity. // FREEBIE * Add global setting for read receipts Don't send read receipt messages unless the setting is enabled. Don't process read receipts if the setting is disabled. // FREEBIE * Sync read receipt setting from mobile Toggling this setting on your mobile device should sync it to Desktop. When linking, use the setting in the provisioning message. // FREEBIE * Send receipt messages silently Avoid generating phantom messages on ios // FREEBIE * Save recipients on the outgoing message models For accurate tracking and display of sent/delivered/read state, even if group membership changes later. // FREEBIE * Fix conversation type in profile key update handling // FREEBIE * Set recipients on synced sent messages * Render saved recipients in message detail if available For older messages, where we did not save the intended set of recipients at the time of sending, fall back to the current group membership. // FREEBIE * Record who has been successfully sent to // FREEBIE * Record who a message has been delivered to * Invert the not-clickable class * Fix readReceipt setting sync when linking * Render per recipient sent/delivered/read status In the message detail view for outgoing messages, render each recipient's individual sent/delivered/read status with respect to this message, as long as there are no errors associated with the recipient (ie, safety number changes, user not registered, etc...) since the error icon is displayed in that case. *Messages sent before this change may not have per-recipient status lists and will simply show no status icon. // FREEBIE * Add configuration sync request Send these requests in a one-off fashion when: 1. We have just setup from a chrome app import 2. We have just upgraded to read-receipt support // FREEBIE * Expose sendRequestConfigurationSyncMessage // FREEBIE * Fix handling of incoming delivery receipts - union with array FREEBIE
2017-10-04 22:28:43 +00:00
function OutgoingMessage(server, timestamp, numbers, message, silent, callback) {
2017-02-21 03:51:43 +00:00
if (message instanceof textsecure.protobuf.DataMessage) {
var content = new textsecure.protobuf.Content();
content.dataMessage = message;
message = content;
}
this.server = server;
this.timestamp = timestamp;
this.numbers = numbers;
2017-02-21 03:51:43 +00:00
this.message = message; // ContentMessage proto
this.callback = callback;
Feature: Blue check marks for read messages if opted in (#1489) * Refactor delivery receipt event handler * Rename the delivery receipt event For less ambiguity with read receipts. * Rename synced read event For less ambiguity with read receipts from other Signal users. * Add support for incoming receipt messages Handle ReceiptMessages, which may include encrypted delivery receipts or read receipts from recipients of our sent messages. // FREEBIE * Rename ReadReceipts to ReadSyncs * Render read messages with blue double checks * Send read receipts to senders of incoming messages // FREEBIE * Move ReadSyncs to their own file // FREEBIE * Fixup old comments on read receipts (now read syncs) And some variable renaming for extra clarity. // FREEBIE * Add global setting for read receipts Don't send read receipt messages unless the setting is enabled. Don't process read receipts if the setting is disabled. // FREEBIE * Sync read receipt setting from mobile Toggling this setting on your mobile device should sync it to Desktop. When linking, use the setting in the provisioning message. // FREEBIE * Send receipt messages silently Avoid generating phantom messages on ios // FREEBIE * Save recipients on the outgoing message models For accurate tracking and display of sent/delivered/read state, even if group membership changes later. // FREEBIE * Fix conversation type in profile key update handling // FREEBIE * Set recipients on synced sent messages * Render saved recipients in message detail if available For older messages, where we did not save the intended set of recipients at the time of sending, fall back to the current group membership. // FREEBIE * Record who has been successfully sent to // FREEBIE * Record who a message has been delivered to * Invert the not-clickable class * Fix readReceipt setting sync when linking * Render per recipient sent/delivered/read status In the message detail view for outgoing messages, render each recipient's individual sent/delivered/read status with respect to this message, as long as there are no errors associated with the recipient (ie, safety number changes, user not registered, etc...) since the error icon is displayed in that case. *Messages sent before this change may not have per-recipient status lists and will simply show no status icon. // FREEBIE * Add configuration sync request Send these requests in a one-off fashion when: 1. We have just setup from a chrome app import 2. We have just upgraded to read-receipt support // FREEBIE * Expose sendRequestConfigurationSyncMessage // FREEBIE * Fix handling of incoming delivery receipts - union with array FREEBIE
2017-10-04 22:28:43 +00:00
this.silent = silent;
2017-02-21 03:51:43 +00:00
this.numbersCompleted = 0;
this.errors = [];
this.successfulNumbers = [];
}
OutgoingMessage.prototype = {
constructor: OutgoingMessage,
numberCompleted: function() {
this.numbersCompleted++;
if (this.numbersCompleted >= this.numbers.length) {
this.callback({successfulNumbers: this.successfulNumbers, errors: this.errors});
}
},
registerError: function(number, reason, error) {
if (!error || error.name === 'HTTPError' && error.code !== 404) {
error = new textsecure.OutgoingMessageError(number, this.message.toArrayBuffer(), this.timestamp, error);
}
error.number = number;
error.reason = reason;
this.errors[this.errors.length] = error;
this.numberCompleted();
},
reloadDevicesAndSend: function(number, recurse) {
return function() {
return textsecure.storage.protocol.getDeviceIds(number).then(function(deviceIds) {
if (deviceIds.length == 0) {
return this.registerError(number, "Got empty device list when loading device keys", null);
}
return this.doSendMessage(number, deviceIds, recurse);
}.bind(this));
}.bind(this);
},
getKeysForNumber: function(number, updateDevices) {
var handleResult = function(response) {
return Promise.all(response.devices.map(function(device) {
device.identityKey = response.identityKey;
if (updateDevices === undefined || updateDevices.indexOf(device.deviceId) > -1) {
var address = new libsignal.SignalProtocolAddress(number, device.deviceId);
var builder = new libsignal.SessionBuilder(textsecure.storage.protocol, address);
if (device.registrationId === 0) {
console.log("device registrationId 0!");
}
return builder.processPreKey(device).catch(function(error) {
if (error.message === "Identity key changed") {
error.timestamp = this.timestamp;
error.originalMessage = this.message.toArrayBuffer();
error.identityKey = device.identityKey;
}
throw error;
}.bind(this));
}
}.bind(this)));
}.bind(this);
if (updateDevices === undefined) {
return this.server.getKeysForNumber(number).then(handleResult);
} else {
var promise = Promise.resolve();
updateDevices.forEach(function(device) {
promise = promise.then(function() {
2016-06-02 01:41:51 +00:00
return this.server.getKeysForNumber(number, device).then(handleResult).catch(function(e) {
if (e.name === 'HTTPError' && e.code === 404) {
if (device !== 1) {
return this.removeDeviceIdsForNumber(number, [device]);
} else {
throw new textsecure.UnregisteredUserError(number, e);
}
2016-06-02 01:41:51 +00:00
} else {
throw e;
}
}.bind(this));
}.bind(this));
}.bind(this));
return promise;
}
},
transmitMessage: function(number, jsonData, timestamp) {
Feature: Blue check marks for read messages if opted in (#1489) * Refactor delivery receipt event handler * Rename the delivery receipt event For less ambiguity with read receipts. * Rename synced read event For less ambiguity with read receipts from other Signal users. * Add support for incoming receipt messages Handle ReceiptMessages, which may include encrypted delivery receipts or read receipts from recipients of our sent messages. // FREEBIE * Rename ReadReceipts to ReadSyncs * Render read messages with blue double checks * Send read receipts to senders of incoming messages // FREEBIE * Move ReadSyncs to their own file // FREEBIE * Fixup old comments on read receipts (now read syncs) And some variable renaming for extra clarity. // FREEBIE * Add global setting for read receipts Don't send read receipt messages unless the setting is enabled. Don't process read receipts if the setting is disabled. // FREEBIE * Sync read receipt setting from mobile Toggling this setting on your mobile device should sync it to Desktop. When linking, use the setting in the provisioning message. // FREEBIE * Send receipt messages silently Avoid generating phantom messages on ios // FREEBIE * Save recipients on the outgoing message models For accurate tracking and display of sent/delivered/read state, even if group membership changes later. // FREEBIE * Fix conversation type in profile key update handling // FREEBIE * Set recipients on synced sent messages * Render saved recipients in message detail if available For older messages, where we did not save the intended set of recipients at the time of sending, fall back to the current group membership. // FREEBIE * Record who has been successfully sent to // FREEBIE * Record who a message has been delivered to * Invert the not-clickable class * Fix readReceipt setting sync when linking * Render per recipient sent/delivered/read status In the message detail view for outgoing messages, render each recipient's individual sent/delivered/read status with respect to this message, as long as there are no errors associated with the recipient (ie, safety number changes, user not registered, etc...) since the error icon is displayed in that case. *Messages sent before this change may not have per-recipient status lists and will simply show no status icon. // FREEBIE * Add configuration sync request Send these requests in a one-off fashion when: 1. We have just setup from a chrome app import 2. We have just upgraded to read-receipt support // FREEBIE * Expose sendRequestConfigurationSyncMessage // FREEBIE * Fix handling of incoming delivery receipts - union with array FREEBIE
2017-10-04 22:28:43 +00:00
return this.server.sendMessages(number, jsonData, timestamp, this.silent).catch(function(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);
}
throw new textsecure.SendMessageNetworkError(number, jsonData, e, timestamp);
}
throw e;
});
},
getPaddedMessageLength: function(messageLength) {
var messageLengthWithTerminator = messageLength + 1;
var messagePartCount = Math.floor(messageLengthWithTerminator / 160);
if (messageLengthWithTerminator % 160 !== 0) {
messagePartCount++;
}
return messagePartCount * 160;
},
getPlaintext: function() {
if (!this.plaintext) {
var messageBuffer = this.message.toArrayBuffer();
this.plaintext = new Uint8Array(
this.getPaddedMessageLength(messageBuffer.byteLength + 1) - 1
);
this.plaintext.set(new Uint8Array(messageBuffer));
this.plaintext[messageBuffer.byteLength] = 0x80;
}
return this.plaintext;
},
doSendMessage: function(number, deviceIds, recurse) {
var ciphers = {};
var plaintext = this.getPlaintext();
return Promise.all(deviceIds.map(function(deviceId) {
var address = new libsignal.SignalProtocolAddress(number, deviceId);
var ourNumber = textsecure.storage.user.getNumber();
var options = {};
// No limit on message keys if we're communicating with our other devices
if (ourNumber === number) {
options.messageKeysLimit = false;
}
var sessionCipher = new libsignal.SessionCipher(textsecure.storage.protocol, address, options);
ciphers[address.getDeviceId()] = sessionCipher;
return sessionCipher.encrypt(plaintext).then(function(ciphertext) {
return {
type : ciphertext.type,
destinationDeviceId : address.getDeviceId(),
destinationRegistrationId : ciphertext.registrationId,
content : btoa(ciphertext.body)
};
});
}.bind(this))).then(function(jsonData) {
return this.transmitMessage(number, jsonData, this.timestamp).then(function() {
this.successfulNumbers[this.successfulNumbers.length] = number;
this.numberCompleted();
}.bind(this));
}.bind(this)).catch(function(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);
var p;
if (error.code == 409) {
p = this.removeDeviceIdsForNumber(number, error.response.extraDevices);
} else {
p = Promise.all(error.response.staleDevices.map(function(deviceId) {
return ciphers[deviceId].closeOpenSessionForDevice();
}));
}
return p.then(function() {
var resetDevices = ((error.code == 410) ? error.response.staleDevices : error.response.missingDevices);
return this.getKeysForNumber(number, resetDevices)
.then(this.reloadDevicesAndSend(number, error.code == 409));
}.bind(this));
} else if (error.message === "Identity key changed") {
error.timestamp = this.timestamp;
error.originalMessage = this.message.toArrayBuffer();
console.log('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);
}
}.bind(this));
},
getStaleDeviceIdsForNumber: function(number) {
return textsecure.storage.protocol.getDeviceIds(number).then(function(deviceIds) {
if (deviceIds.length === 0) {
return [1];
}
var updateDevices = [];
return Promise.all(deviceIds.map(function(deviceId) {
var address = new libsignal.SignalProtocolAddress(number, deviceId);
2016-10-05 12:15:58 +00:00
var sessionCipher = new libsignal.SessionCipher(textsecure.storage.protocol, address);
return sessionCipher.hasOpenSession().then(function(hasSession) {
if (!hasSession) {
updateDevices.push(deviceId);
}
});
})).then(function() {
return updateDevices;
});
});
},
removeDeviceIdsForNumber: function(number, deviceIdsToRemove) {
var promise = Promise.resolve();
for (var j in deviceIdsToRemove) {
promise = promise.then(function() {
var encodedNumber = number + "." + deviceIdsToRemove[j];
return textsecure.storage.protocol.removeSession(encodedNumber);
});
}
return promise;
},
sendToNumber: function(number) {
return this.getStaleDeviceIdsForNumber(number).then(function(updateDevices) {
return this.getKeysForNumber(number, updateDevices)
.then(this.reloadDevicesAndSend(number, true))
.catch(function(error) {
if (error.message === "Identity key changed") {
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
);
}
}.bind(this));
}.bind(this));
}
};