session-desktop/libtextsecure/sendmessage.js

1119 lines
31 KiB
JavaScript
Raw Normal View History

/* global _, textsecure, WebAPI, libsignal, OutgoingMessage, window */
2018-07-21 23:51:20 +02:00
/* eslint-disable more/no-then, no-bitwise */
function stringToArrayBuffer(str) {
2018-05-02 18:51:22 +02:00
if (typeof str !== 'string') {
throw new Error('Passed non-string to stringToArrayBuffer');
}
2018-07-21 23:51:20 +02:00
const res = new ArrayBuffer(str.length);
const uint = new Uint8Array(res);
for (let i = 0; i < str.length; i += 1) {
2018-05-02 18:51:22 +02:00
uint[i] = str.charCodeAt(i);
}
return res;
}
function Message(options) {
2018-05-02 18:51:22 +02:00
this.body = options.body;
this.attachments = options.attachments || [];
this.quote = options.quote;
2019-01-16 04:03:56 +01:00
this.preview = options.preview;
2018-05-02 18:51:22 +02:00
this.group = options.group;
this.flags = options.flags;
this.recipients = options.recipients;
this.timestamp = options.timestamp;
this.needsSync = options.needsSync;
this.expireTimer = options.expireTimer;
this.profileKey = options.profileKey;
if (!(this.recipients instanceof Array) || this.recipients.length < 1) {
throw new Error('Invalid recipient list');
}
if (!this.group && this.recipients.length > 1) {
throw new Error('Invalid recipient list for non-group');
}
if (typeof this.timestamp !== 'number') {
throw new Error('Invalid timestamp');
}
if (this.expireTimer !== undefined && this.expireTimer !== null) {
if (typeof this.expireTimer !== 'number' || !(this.expireTimer >= 0)) {
throw new Error('Invalid expireTimer');
}
2018-05-02 18:51:22 +02:00
}
2018-05-02 18:51:22 +02:00
if (this.attachments) {
if (!(this.attachments instanceof Array)) {
throw new Error('Invalid message attachments');
}
2018-05-02 18:51:22 +02:00
}
if (this.flags !== undefined) {
if (typeof this.flags !== 'number') {
throw new Error('Invalid message flags');
2016-09-29 01:54:05 +02:00
}
2018-05-02 18:51:22 +02:00
}
if (this.isEndSession()) {
if (
this.body !== null ||
this.group !== null ||
this.attachments.length !== 0
) {
throw new Error('Invalid end session message');
}
2018-05-02 18:51:22 +02:00
} else {
if (
typeof this.timestamp !== 'number' ||
(this.body && typeof this.body !== 'string')
) {
throw new Error('Invalid message body');
}
2018-05-02 18:51:22 +02:00
if (this.group) {
if (
typeof this.group.id !== 'string' ||
typeof this.group.type !== 'number'
) {
throw new Error('Invalid group context');
}
}
2018-05-02 18:51:22 +02:00
}
}
Message.prototype = {
2018-05-02 18:51:22 +02:00
constructor: Message,
2018-07-21 23:51:20 +02:00
isEndSession() {
2018-05-02 18:51:22 +02:00
return this.flags & textsecure.protobuf.DataMessage.Flags.END_SESSION;
},
2018-07-21 23:51:20 +02:00
toProto() {
2018-05-02 18:51:22 +02:00
if (this.dataMessage instanceof textsecure.protobuf.DataMessage) {
return this.dataMessage;
}
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
if (this.body) {
proto.body = this.body;
}
proto.attachments = this.attachmentPointers;
if (this.flags) {
proto.flags = this.flags;
}
if (this.group) {
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(this.group.id);
proto.group.type = this.group.type;
}
2019-01-16 04:03:56 +01:00
if (Array.isArray(this.preview)) {
proto.preview = this.preview.map(preview => {
const item = new textsecure.protobuf.DataMessage.Preview();
item.title = preview.title;
item.url = preview.url;
item.image = preview.image || null;
2019-01-16 04:03:56 +01:00
return item;
});
}
2018-05-02 18:51:22 +02:00
if (this.quote) {
2018-07-21 23:51:20 +02:00
const { QuotedAttachment } = textsecure.protobuf.DataMessage.Quote;
const { Quote } = textsecure.protobuf.DataMessage;
2018-05-02 18:51:22 +02:00
proto.quote = new Quote();
2018-07-21 23:51:20 +02:00
const { quote } = proto;
2018-05-02 18:51:22 +02:00
quote.id = this.quote.id;
quote.author = this.quote.author;
quote.text = this.quote.text;
2018-07-21 23:51:20 +02:00
quote.attachments = (this.quote.attachments || []).map(attachment => {
const quotedAttachment = new QuotedAttachment();
2018-05-02 18:51:22 +02:00
quotedAttachment.contentType = attachment.contentType;
quotedAttachment.fileName = attachment.fileName;
if (attachment.attachmentPointer) {
quotedAttachment.thumbnail = attachment.attachmentPointer;
2016-09-29 01:54:05 +02:00
}
2018-05-02 18:51:22 +02:00
return quotedAttachment;
});
}
if (this.expireTimer) {
proto.expireTimer = this.expireTimer;
}
Profiles (#1453) * Add AES-GCM encryption for profiles With tests. * Add profileKey to DataMessage protobuf // FREEBIE * Decrypt and save profile names // FREEBIE * Save incoming profile keys * Move pad/unpad to crypto module // FREEBIE * Support fetching avatars from the cdn // FREEBIE * Translate failed authentication errors When AES-GCM authentication fails, webcrypto returns a very generic error. The same error is thrown for invalid length inputs, but our earlier checks in decryptProfile should rule out those failure modes and leave us safe to assume that we either had bad ciphertext or the wrong key. // FREEBIE * Handle profile avatars (wip) and log decrypt errors // FREEBIE * Display profile avatars Synced contact avatars will still override profile avatars. * Display profile names in convo list Only if we don't have a synced contact name. // FREEBIE * Make cdn url an environment config Use different ones for staging and production // FREEBIE * Display profile name in conversation header * Display profile name in group messages * Update conversation header if profile avatar changes // FREEBIE * Style profile names small with ~ * Save profileKeys from contact sync messages // FREEBIE * Save profile keys from provisioning messages For standalone accounts, generate a random profile key. // FREEBIE * Special case for one-time sync of our profile key Android will use a contact sync message to sync a profile key from Android clients who have just upgraded and generated their profile key. Normally we should receive this data in a provisioning message. // FREEBIE * Infer profile sharing from synced data messages * Populate profile keys on outgoing messages Requires that `profileSharing` be set on the conversation. // FREEBIE * Support for the profile key update flag When receiving a message with this flag, don't init a message record, just process the profile key and move on. // FREEBIE * Display profile names in group member list * Refresh contact's profile on profile key changes // FREEBIE * Catch errors on profile save // FREEBIE * Save our own synced contact info Don't return early if we get a contact sync for our own number // FREEBIE
2017-09-11 18:50:35 +02:00
2018-05-02 18:51:22 +02:00
if (this.profileKey) {
proto.profileKey = this.profileKey;
}
2018-05-02 18:51:22 +02:00
this.dataMessage = proto;
return proto;
},
2018-07-21 23:51:20 +02:00
toArrayBuffer() {
2018-05-02 18:51:22 +02:00
return this.toProto().toArrayBuffer();
},
};
function MessageSender(username, password) {
this.server = WebAPI.connect({ username, password });
2018-05-02 18:51:22 +02:00
this.pendingMessages = {};
}
MessageSender.prototype = {
2018-05-02 18:51:22 +02:00
constructor: MessageSender,
2018-05-02 18:51:22 +02:00
// makeAttachmentPointer :: Attachment -> Promise AttachmentPointerProto
2018-07-21 23:51:20 +02:00
makeAttachmentPointer(attachment) {
2018-05-02 18:51:22 +02:00
if (typeof attachment !== 'object' || attachment == null) {
return Promise.resolve(undefined);
}
2018-05-02 18:51:22 +02:00
if (
!(attachment.data instanceof ArrayBuffer) &&
!ArrayBuffer.isView(attachment.data)
) {
return Promise.reject(
new TypeError(
2018-07-21 23:51:20 +02:00
`\`attachment.data\` must be an \`ArrayBuffer\` or \`ArrayBufferView\`; got: ${typeof attachment.data}`
2018-05-02 18:51:22 +02:00
)
);
}
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.AttachmentPointer();
2018-05-02 18:51:22 +02:00
proto.key = libsignal.crypto.getRandomBytes(64);
2018-07-21 23:51:20 +02:00
const iv = libsignal.crypto.getRandomBytes(16);
2018-05-02 18:51:22 +02:00
return textsecure.crypto
.encryptAttachment(attachment.data, proto.key, iv)
2018-07-21 23:51:20 +02:00
.then(result =>
this.server.putAttachment(result.ciphertext).then(id => {
proto.id = id;
proto.contentType = attachment.contentType;
proto.digest = result.digest;
2018-07-21 23:51:20 +02:00
if (attachment.size) {
proto.size = attachment.size;
}
if (attachment.fileName) {
proto.fileName = attachment.fileName;
}
2018-07-21 23:51:20 +02:00
if (attachment.flags) {
proto.flags = attachment.flags;
}
if (attachment.width) {
proto.width = attachment.width;
}
if (attachment.height) {
proto.height = attachment.height;
}
if (attachment.caption) {
proto.caption = attachment.caption;
}
2018-07-21 23:51:20 +02:00
return proto;
})
2018-05-02 18:51:22 +02:00
);
},
2018-07-21 23:51:20 +02:00
queueJobForNumber(number, runJob) {
const taskWithTimeout = textsecure.createTaskWithTimeout(
2018-05-02 18:51:22 +02:00
runJob,
2018-07-21 23:51:20 +02:00
`queueJobForNumber ${number}`
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
const runPrevious = this.pendingMessages[number] || Promise.resolve();
this.pendingMessages[number] = runPrevious.then(
2018-05-02 18:51:22 +02:00
taskWithTimeout,
taskWithTimeout
);
2018-07-21 23:51:20 +02:00
const runCurrent = this.pendingMessages[number];
runCurrent.then(() => {
if (this.pendingMessages[number] === runCurrent) {
delete this.pendingMessages[number];
}
});
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
uploadAttachments(message) {
2018-05-02 18:51:22 +02:00
return Promise.all(
message.attachments.map(this.makeAttachmentPointer.bind(this))
)
2018-07-21 23:51:20 +02:00
.then(attachmentPointers => {
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
message.attachmentPointers = attachmentPointers;
})
2018-07-21 23:51:20 +02:00
.catch(error => {
2018-05-02 18:51:22 +02:00
if (error instanceof Error && error.name === 'HTTPError') {
throw new textsecure.MessageError(message, error);
} else {
throw error;
}
2018-05-02 18:51:22 +02:00
});
},
2019-01-16 04:03:56 +01:00
async uploadLinkPreviews(message) {
try {
const preview = await Promise.all(
(message.preview || []).map(async item => ({
...item,
image: await this.makeAttachmentPointer(item.image),
}))
);
// eslint-disable-next-line no-param-reassign
message.preview = preview;
} catch (error) {
if (error instanceof Error && error.name === 'HTTPError') {
throw new textsecure.MessageError(message, error);
} else {
throw error;
}
}
},
2018-07-21 23:51:20 +02:00
uploadThumbnails(message) {
const makePointer = this.makeAttachmentPointer.bind(this);
const { quote } = message;
2018-05-02 18:51:22 +02:00
if (!quote || !quote.attachments || quote.attachments.length === 0) {
return Promise.resolve();
}
2018-05-02 18:51:22 +02:00
return Promise.all(
2018-07-21 23:51:20 +02:00
quote.attachments.map(attachment => {
const { thumbnail } = attachment;
2018-05-02 18:51:22 +02:00
if (!thumbnail) {
2018-07-21 23:51:20 +02:00
return null;
2018-05-02 18:51:22 +02:00
}
2018-07-21 23:51:20 +02:00
return makePointer(thumbnail).then(pointer => {
// eslint-disable-next-line no-param-reassign
2018-05-02 18:51:22 +02:00
attachment.attachmentPointer = pointer;
});
})
2018-07-21 23:51:20 +02:00
).catch(error => {
2018-05-02 18:51:22 +02:00
if (error instanceof Error && error.name === 'HTTPError') {
throw new textsecure.MessageError(message, error);
} else {
throw error;
}
});
},
sendMessage(attrs, options) {
2018-07-21 23:51:20 +02:00
const message = new Message(attrs);
const silent = false;
2018-05-02 18:51:22 +02:00
return Promise.all([
this.uploadAttachments(message),
this.uploadThumbnails(message),
2019-01-16 04:03:56 +01:00
this.uploadLinkPreviews(message),
2018-05-02 18:51:22 +02:00
]).then(
2018-07-21 23:51:20 +02:00
() =>
new Promise((resolve, reject) => {
this.sendMessageProto(
message.timestamp,
message.recipients,
message.toProto(),
res => {
res.dataMessage = message.toArrayBuffer();
if (res.errors.length > 0) {
reject(res);
} else {
resolve(res);
2018-05-02 18:51:22 +02:00
}
},
silent,
options
2018-07-21 23:51:20 +02:00
);
})
2018-05-02 18:51:22 +02:00
);
},
sendMessageProto(
timestamp,
numbers,
message,
callback,
silent,
options = {}
) {
2018-07-21 23:51:20 +02:00
const rejections = textsecure.storage.get('signedKeyRotationRejected', 0);
2018-05-02 18:51:22 +02:00
if (rejections > 5) {
throw new textsecure.SignedPreKeyRotationError(
numbers,
message.toArrayBuffer(),
timestamp
);
}
2018-07-21 23:51:20 +02:00
const outgoing = new OutgoingMessage(
2018-05-02 18:51:22 +02:00
this.server,
timestamp,
numbers,
message,
silent,
callback,
options
2018-05-02 18:51:22 +02:00
);
2018-07-21 23:51:20 +02:00
numbers.forEach(number => {
this.queueJobForNumber(number, () => outgoing.sendToNumber(number));
});
2018-05-02 18:51:22 +02:00
},
2018-11-14 20:10:32 +01:00
sendMessageProtoAndWait(timestamp, numbers, message, silent, options = {}) {
return new Promise((resolve, reject) => {
const callback = result => {
if (result && result.errors && result.errors.length > 0) {
return reject(result);
}
return resolve(result);
};
this.sendMessageProto(
timestamp,
numbers,
message,
callback,
silent,
options
);
});
},
sendIndividualProto(number, proto, timestamp, silent, options = {}) {
2018-07-21 23:51:20 +02:00
return new Promise((resolve, reject) => {
const callback = res => {
2018-11-14 20:10:32 +01:00
if (res && res.errors && res.errors.length > 0) {
2018-07-21 23:51:20 +02:00
reject(res);
} else {
resolve(res);
}
};
this.sendMessageProto(
timestamp,
[number],
proto,
callback,
silent,
options
);
2018-07-21 23:51:20 +02:00
});
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
createSyncMessage() {
const syncMessage = new textsecure.protobuf.SyncMessage();
2018-05-02 18:51:22 +02:00
// Generate a random int from 1 and 512
2018-07-21 23:51:20 +02:00
const buffer = libsignal.crypto.getRandomBytes(1);
const paddingLength = (new Uint8Array(buffer)[0] & 0x1ff) + 1;
2018-05-02 18:51:22 +02:00
// Generate a random padding buffer of the chosen size
syncMessage.padding = libsignal.crypto.getRandomBytes(paddingLength);
return syncMessage;
},
2018-07-21 23:51:20 +02:00
sendSyncMessage(
2018-05-02 18:51:22 +02:00
encodedDataMessage,
timestamp,
destination,
expirationStartTimestamp,
sentTo = [],
unidentifiedDeliveries = [],
options
2018-05-02 18:51:22 +02:00
) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myDevice === 1 || myDevice === '1') {
2018-05-02 18:51:22 +02:00
return Promise.resolve();
}
2018-07-21 23:51:20 +02:00
const dataMessage = textsecure.protobuf.DataMessage.decode(
2018-05-02 18:51:22 +02:00
encodedDataMessage
);
2018-07-21 23:51:20 +02:00
const sentMessage = new textsecure.protobuf.SyncMessage.Sent();
2018-05-02 18:51:22 +02:00
sentMessage.timestamp = timestamp;
sentMessage.message = dataMessage;
if (destination) {
sentMessage.destination = destination;
}
if (expirationStartTimestamp) {
sentMessage.expirationStartTimestamp = expirationStartTimestamp;
}
const unidentifiedLookup = unidentifiedDeliveries.reduce(
(accumulator, item) => {
// eslint-disable-next-line no-param-reassign
accumulator[item] = true;
return accumulator;
},
Object.create(null)
);
// Though this field has 'unidenified' in the name, it should have entries for each
// number we sent to.
if (sentTo && sentTo.length) {
sentMessage.unidentifiedStatus = sentTo.map(number => {
const status = new textsecure.protobuf.SyncMessage.Sent.UnidentifiedDeliveryStatus();
status.destination = number;
status.unidentified = Boolean(unidentifiedLookup[number]);
return status;
});
}
2018-07-21 23:51:20 +02:00
const syncMessage = this.createSyncMessage();
2018-05-02 18:51:22 +02:00
syncMessage.sent = sentMessage;
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.syncMessage = syncMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
2018-05-02 18:51:22 +02:00
return this.sendIndividualProto(
myNumber,
contentMessage,
Date.now(),
silent,
options
2018-05-02 18:51:22 +02:00
);
},
async getProfile(number, { accessKey } = {}) {
if (accessKey) {
return this.server.getProfileUnauth(number, { accessKey });
}
2018-05-02 18:51:22 +02:00
return this.server.getProfile(number);
},
2018-07-21 23:51:20 +02:00
getAvatar(path) {
2018-05-02 18:51:22 +02:00
return this.server.getAvatar(path);
},
sendRequestConfigurationSyncMessage(options) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myDevice !== 1 && myDevice !== '1') {
const request = new textsecure.protobuf.SyncMessage.Request();
2018-05-02 18:51:22 +02:00
request.type = textsecure.protobuf.SyncMessage.Request.Type.CONFIGURATION;
2018-07-21 23:51:20 +02:00
const syncMessage = this.createSyncMessage();
2018-05-02 18:51:22 +02:00
syncMessage.request = request;
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.syncMessage = syncMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
2018-05-02 18:51:22 +02:00
return this.sendIndividualProto(
myNumber,
contentMessage,
Date.now(),
silent,
options
2018-05-02 18:51:22 +02:00
);
}
2018-05-02 18:51:22 +02:00
return Promise.resolve();
},
2018-11-14 20:10:32 +01:00
sendRequestGroupSyncMessage(options) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myDevice !== 1 && myDevice !== '1') {
const request = new textsecure.protobuf.SyncMessage.Request();
2018-05-02 18:51:22 +02:00
request.type = textsecure.protobuf.SyncMessage.Request.Type.GROUPS;
2018-07-21 23:51:20 +02:00
const syncMessage = this.createSyncMessage();
2018-05-02 18:51:22 +02:00
syncMessage.request = request;
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.syncMessage = syncMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
2018-05-02 18:51:22 +02:00
return this.sendIndividualProto(
myNumber,
contentMessage,
Date.now(),
silent,
options
2018-05-02 18:51:22 +02:00
);
}
2018-05-02 18:51:22 +02:00
return Promise.resolve();
},
sendRequestContactSyncMessage(options) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myDevice !== 1 && myDevice !== '1') {
const request = new textsecure.protobuf.SyncMessage.Request();
2018-05-02 18:51:22 +02:00
request.type = textsecure.protobuf.SyncMessage.Request.Type.CONTACTS;
2018-07-21 23:51:20 +02:00
const syncMessage = this.createSyncMessage();
2018-05-02 18:51:22 +02:00
syncMessage.request = request;
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.syncMessage = syncMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
2018-05-02 18:51:22 +02:00
return this.sendIndividualProto(
myNumber,
contentMessage,
Date.now(),
silent,
options
2018-05-02 18:51:22 +02:00
);
}
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-05 00:28:43 +02:00
2018-05-02 18:51:22 +02:00
return Promise.resolve();
},
2018-11-14 20:10:32 +01:00
async sendTypingMessage(options = {}, sendOptions = {}) {
const ACTION_ENUM = textsecure.protobuf.TypingMessage.Action;
const { recipientId, groupId, groupNumbers, isTyping, timestamp } = options;
2018-11-14 20:10:32 +01:00
// We don't want to send typing messages to our other devices, but we will
// in the group case.
const myNumber = textsecure.storage.user.getNumber();
if (recipientId && myNumber === recipientId) {
return null;
}
if (!recipientId && !groupId) {
throw new Error('Need to provide either recipientId or groupId!');
}
const recipients = groupId
? _.without(groupNumbers, myNumber)
2018-11-14 20:10:32 +01:00
: [recipientId];
const groupIdBuffer = groupId
? window.Signal.Crypto.fromEncodedBinaryToArrayBuffer(groupId)
: null;
const action = isTyping ? ACTION_ENUM.STARTED : ACTION_ENUM.STOPPED;
const finalTimestamp = timestamp || Date.now();
const typingMessage = new textsecure.protobuf.TypingMessage();
typingMessage.groupId = groupIdBuffer;
typingMessage.action = action;
typingMessage.timestamp = finalTimestamp;
const contentMessage = new textsecure.protobuf.Content();
contentMessage.typingMessage = typingMessage;
const silent = true;
const online = true;
return this.sendMessageProtoAndWait(
finalTimestamp,
recipients,
contentMessage,
silent,
{
...sendOptions,
online,
}
);
},
sendDeliveryReceipt(recipientId, timestamp, options) {
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myNumber === recipientId && (myDevice === 1 || myDevice === '1')) {
return Promise.resolve();
}
const receiptMessage = new textsecure.protobuf.ReceiptMessage();
receiptMessage.type = textsecure.protobuf.ReceiptMessage.Type.DELIVERY;
receiptMessage.timestamp = [timestamp];
const contentMessage = new textsecure.protobuf.Content();
contentMessage.receiptMessage = receiptMessage;
const silent = true;
return this.sendIndividualProto(
recipientId,
contentMessage,
Date.now(),
silent,
options
);
},
2018-11-14 20:10:32 +01:00
sendReadReceipts(sender, timestamps, options) {
2018-07-21 23:51:20 +02:00
const receiptMessage = new textsecure.protobuf.ReceiptMessage();
2018-05-02 18:51:22 +02:00
receiptMessage.type = textsecure.protobuf.ReceiptMessage.Type.READ;
receiptMessage.timestamp = timestamps;
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.receiptMessage = receiptMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
return this.sendIndividualProto(
sender,
contentMessage,
Date.now(),
silent,
options
);
2018-05-02 18:51:22 +02:00
},
syncReadMessages(reads, options) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
if (myDevice !== 1 && myDevice !== '1') {
const syncMessage = this.createSyncMessage();
2018-05-02 18:51:22 +02:00
syncMessage.read = [];
2018-07-21 23:51:20 +02:00
for (let i = 0; i < reads.length; i += 1) {
const read = new textsecure.protobuf.SyncMessage.Read();
2018-05-02 18:51:22 +02:00
read.timestamp = reads[i].timestamp;
read.sender = reads[i].sender;
syncMessage.read.push(read);
}
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.syncMessage = syncMessage;
2018-07-21 23:51:20 +02:00
const silent = true;
2018-05-02 18:51:22 +02:00
return this.sendIndividualProto(
myNumber,
contentMessage,
Date.now(),
silent,
options
2018-05-02 18:51:22 +02:00
);
}
2018-05-02 18:51:22 +02:00
return Promise.resolve();
},
syncVerification(destination, state, identityKey, options) {
2018-07-21 23:51:20 +02:00
const myNumber = textsecure.storage.user.getNumber();
const myDevice = textsecure.storage.user.getDeviceId();
const now = Date.now();
2018-07-21 23:51:20 +02:00
if (myDevice === 1 || myDevice === '1') {
2018-05-02 18:51:22 +02:00
return Promise.resolve();
}
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-05 00:28:43 +02:00
2018-05-02 18:51:22 +02:00
// First send a null message to mask the sync message.
2018-07-21 23:51:20 +02:00
const nullMessage = new textsecure.protobuf.NullMessage();
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-05 00:28:43 +02:00
2018-05-02 18:51:22 +02:00
// Generate a random int from 1 and 512
2018-07-21 23:51:20 +02:00
const buffer = libsignal.crypto.getRandomBytes(1);
const paddingLength = (new Uint8Array(buffer)[0] & 0x1ff) + 1;
2018-05-02 18:51:22 +02:00
// Generate a random padding buffer of the chosen size
nullMessage.padding = libsignal.crypto.getRandomBytes(paddingLength);
2018-07-21 23:51:20 +02:00
const contentMessage = new textsecure.protobuf.Content();
2018-05-02 18:51:22 +02:00
contentMessage.nullMessage = nullMessage;
2018-05-02 18:51:22 +02:00
// We want the NullMessage to look like a normal outgoing message; not silent
const silent = false;
const promise = this.sendIndividualProto(
destination,
contentMessage,
now,
silent,
options
);
2018-07-21 23:51:20 +02:00
return promise.then(() => {
const verified = new textsecure.protobuf.Verified();
verified.state = state;
verified.destination = destination;
verified.identityKey = identityKey;
verified.nullMessage = nullMessage.padding;
2018-07-21 23:51:20 +02:00
const syncMessage = this.createSyncMessage();
syncMessage.verified = verified;
2018-07-21 23:51:20 +02:00
const secondMessage = new textsecure.protobuf.Content();
secondMessage.syncMessage = syncMessage;
const innerSilent = true;
return this.sendIndividualProto(
myNumber,
secondMessage,
now,
innerSilent,
options
);
2018-07-21 23:51:20 +02:00
});
2018-05-02 18:51:22 +02:00
},
sendGroupProto(providedNumbers, proto, timestamp = Date.now(), options = {}) {
2018-07-21 23:51:20 +02:00
const me = textsecure.storage.user.getNumber();
const numbers = providedNumbers.filter(number => number !== me);
2018-05-02 18:51:22 +02:00
if (numbers.length === 0) {
return Promise.resolve({
successfulNumbers: [],
failoverNumbers: [],
errors: [],
unidentifiedDeliveries: [],
});
2018-05-02 18:51:22 +02:00
}
2018-07-21 23:51:20 +02:00
return new Promise((resolve, reject) => {
const silent = true;
const callback = res => {
res.dataMessage = proto.toArrayBuffer();
if (res.errors.length > 0) {
reject(res);
} else {
resolve(res);
}
};
2018-05-02 18:51:22 +02:00
this.sendMessageProto(
timestamp,
numbers,
proto,
callback,
silent,
options
);
2018-07-21 23:51:20 +02:00
});
2018-05-02 18:51:22 +02:00
},
2019-01-31 02:45:58 +01:00
async getMessageProto(
number,
body,
attachments,
quote,
preview,
timestamp,
expireTimer,
profileKey
) {
const attributes = {
recipients: [number],
body,
timestamp,
attachments,
quote,
preview,
expireTimer,
profileKey,
};
const message = new Message(attributes);
await Promise.all([
this.uploadAttachments(message),
this.uploadThumbnails(message),
this.uploadLinkPreviews(message),
]);
return message.toArrayBuffer();
},
2018-07-21 23:51:20 +02:00
sendMessageToNumber(
2018-05-02 18:51:22 +02:00
number,
messageText,
attachments,
quote,
2019-01-16 04:03:56 +01:00
preview,
2018-05-02 18:51:22 +02:00
timestamp,
expireTimer,
profileKey,
options
2018-05-02 18:51:22 +02:00
) {
return this.sendMessage(
{
recipients: [number],
body: messageText,
timestamp,
attachments,
quote,
2019-01-16 04:03:56 +01:00
preview,
needsSync: true,
expireTimer,
profileKey,
},
options
);
2018-05-02 18:51:22 +02:00
},
resetSession(number, timestamp, options) {
window.log.info('resetting secure session');
const silent = false;
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.body = 'TERMINATE';
proto.flags = textsecure.protobuf.DataMessage.Flags.END_SESSION;
2018-07-21 23:51:20 +02:00
const logError = prefix => error => {
window.log.error(prefix, error && error.stack ? error.stack : error);
throw error;
2018-05-02 18:51:22 +02:00
};
2018-07-21 23:51:20 +02:00
const deleteAllSessions = targetNumber =>
textsecure.storage.protocol.getDeviceIds(targetNumber).then(deviceIds =>
Promise.all(
deviceIds.map(deviceId => {
const address = new libsignal.SignalProtocolAddress(
targetNumber,
deviceId
);
window.log.info('deleting sessions for', address.toString());
const sessionCipher = new libsignal.SessionCipher(
textsecure.storage.protocol,
address
);
return sessionCipher.deleteAllSessionsForDevice();
})
)
);
2018-05-02 18:51:22 +02:00
const sendToContactPromise = deleteAllSessions(number)
2018-05-02 18:51:22 +02:00
.catch(logError('resetSession/deleteAllSessions1 error:'))
2018-07-21 23:51:20 +02:00
.then(() => {
window.log.info(
'finished closing local sessions, now sending to contact'
2018-05-02 18:51:22 +02:00
);
return this.sendIndividualProto(
number,
proto,
timestamp,
silent,
options
).catch(logError('resetSession/sendToContact error:'));
2018-07-21 23:51:20 +02:00
})
.then(() =>
deleteAllSessions(number).catch(
logError('resetSession/deleteAllSessions2 error:')
)
);
2018-05-02 18:51:22 +02:00
const myNumber = textsecure.storage.user.getNumber();
// We already sent the reset session to our other devices in the code above!
if (number === myNumber) {
return sendToContactPromise;
}
2018-07-21 23:51:20 +02:00
const buffer = proto.toArrayBuffer();
const sendSyncPromise = this.sendSyncMessage(
buffer,
timestamp,
number,
null,
[],
[],
options
).catch(logError('resetSession/sendSync error:'));
2018-05-02 18:51:22 +02:00
return Promise.all([sendToContactPromise, sendSyncPromise]);
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
sendMessageToGroup(
2018-05-02 18:51:22 +02:00
groupId,
groupNumbers,
2018-05-02 18:51:22 +02:00
messageText,
attachments,
quote,
2019-01-16 04:03:56 +01:00
preview,
2018-05-02 18:51:22 +02:00
timestamp,
expireTimer,
profileKey,
options
2018-05-02 18:51:22 +02:00
) {
const me = textsecure.storage.user.getNumber();
const numbers = groupNumbers.filter(number => number !== me);
if (numbers.length === 0) {
return Promise.reject(new Error('No other members in the group'));
}
return this.sendMessage(
{
recipients: numbers,
body: messageText,
timestamp,
attachments,
quote,
preview,
needsSync: true,
expireTimer,
profileKey,
group: {
id: groupId,
type: textsecure.protobuf.GroupContext.Type.DELIVER,
2018-07-21 23:51:20 +02:00
},
},
options
);
2018-05-02 18:51:22 +02:00
},
createGroup(targetNumbers, id, name, avatar, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(id);
proto.group.type = textsecure.protobuf.GroupContext.Type.UPDATE;
proto.group.members = targetNumbers;
proto.group.name = name;
return this.makeAttachmentPointer(avatar).then(attachment => {
proto.group.avatar = attachment;
return this.sendGroupProto(
targetNumbers,
proto,
Date.now(),
options
).then(() => proto.group.id);
});
2018-05-02 18:51:22 +02:00
},
updateGroup(groupId, name, avatar, targetNumbers, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(groupId);
proto.group.type = textsecure.protobuf.GroupContext.Type.UPDATE;
proto.group.name = name;
proto.group.members = targetNumbers;
2018-05-02 18:51:22 +02:00
return this.makeAttachmentPointer(avatar).then(attachment => {
proto.group.avatar = attachment;
return this.sendGroupProto(
targetNumbers,
proto,
Date.now(),
options
).then(() => proto.group.id);
});
2018-05-02 18:51:22 +02:00
},
addNumberToGroup(groupId, newNumbers, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(groupId);
proto.group.type = textsecure.protobuf.GroupContext.Type.UPDATE;
proto.group.members = newNumbers;
return this.sendGroupProto(newNumbers, proto, Date.now(), options);
2018-05-02 18:51:22 +02:00
},
setGroupName(groupId, name, groupNumbers, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(groupId);
proto.group.type = textsecure.protobuf.GroupContext.Type.UPDATE;
proto.group.name = name;
proto.group.members = groupNumbers;
2018-05-02 18:51:22 +02:00
return this.sendGroupProto(groupNumbers, proto, Date.now(), options);
2018-05-02 18:51:22 +02:00
},
setGroupAvatar(groupId, avatar, groupNumbers, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(groupId);
proto.group.type = textsecure.protobuf.GroupContext.Type.UPDATE;
proto.group.members = groupNumbers;
2018-05-02 18:51:22 +02:00
return this.makeAttachmentPointer(avatar).then(attachment => {
proto.group.avatar = attachment;
return this.sendGroupProto(groupNumbers, proto, Date.now(), options);
2018-07-21 23:51:20 +02:00
});
2018-05-02 18:51:22 +02:00
},
leaveGroup(groupId, groupNumbers, options) {
2018-07-21 23:51:20 +02:00
const proto = new textsecure.protobuf.DataMessage();
2018-05-02 18:51:22 +02:00
proto.group = new textsecure.protobuf.GroupContext();
proto.group.id = stringToArrayBuffer(groupId);
proto.group.type = textsecure.protobuf.GroupContext.Type.QUIT;
return this.sendGroupProto(groupNumbers, proto, Date.now(), options);
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
sendExpirationTimerUpdateToGroup(
2018-05-02 18:51:22 +02:00
groupId,
groupNumbers,
2018-05-02 18:51:22 +02:00
expireTimer,
timestamp,
profileKey,
options
2018-05-02 18:51:22 +02:00
) {
const me = textsecure.storage.user.getNumber();
const numbers = groupNumbers.filter(number => number !== me);
if (numbers.length === 0) {
return Promise.reject(new Error('No other members in the group'));
}
return this.sendMessage(
{
recipients: numbers,
timestamp,
needsSync: true,
expireTimer,
profileKey,
flags: textsecure.protobuf.DataMessage.Flags.EXPIRATION_TIMER_UPDATE,
group: {
id: groupId,
type: textsecure.protobuf.GroupContext.Type.DELIVER,
2018-07-21 23:51:20 +02:00
},
},
options
);
2018-05-02 18:51:22 +02:00
},
2018-07-21 23:51:20 +02:00
sendExpirationTimerUpdateToNumber(
2018-05-02 18:51:22 +02:00
number,
expireTimer,
timestamp,
profileKey,
options
2018-05-02 18:51:22 +02:00
) {
return this.sendMessage(
{
recipients: [number],
timestamp,
needsSync: true,
expireTimer,
profileKey,
flags: textsecure.protobuf.DataMessage.Flags.EXPIRATION_TIMER_UPDATE,
},
options
);
2018-05-02 18:51:22 +02:00
},
2019-01-16 04:03:56 +01:00
makeProxiedRequest(url, options) {
return this.server.makeProxiedRequest(url, options);
},
getProxiedSize(url) {
return this.server.getProxiedSize(url);
},
};
window.textsecure = window.textsecure || {};
2018-07-21 23:51:20 +02:00
textsecure.MessageSender = function MessageSenderWrapper(
url,
username,
password,
cdnUrl
) {
const sender = new MessageSender(url, username, password, cdnUrl);
2018-05-02 18:51:22 +02:00
this.sendExpirationTimerUpdateToNumber = sender.sendExpirationTimerUpdateToNumber.bind(
sender
);
this.sendExpirationTimerUpdateToGroup = sender.sendExpirationTimerUpdateToGroup.bind(
sender
);
this.sendRequestGroupSyncMessage = sender.sendRequestGroupSyncMessage.bind(
sender
);
this.sendRequestContactSyncMessage = sender.sendRequestContactSyncMessage.bind(
sender
);
this.sendRequestConfigurationSyncMessage = sender.sendRequestConfigurationSyncMessage.bind(
sender
);
this.sendMessageToNumber = sender.sendMessageToNumber.bind(sender);
this.sendMessage = sender.sendMessage.bind(sender);
2018-05-02 18:51:22 +02:00
this.resetSession = sender.resetSession.bind(sender);
this.sendMessageToGroup = sender.sendMessageToGroup.bind(sender);
2018-11-14 20:10:32 +01:00
this.sendTypingMessage = sender.sendTypingMessage.bind(sender);
2018-05-02 18:51:22 +02:00
this.createGroup = sender.createGroup.bind(sender);
this.updateGroup = sender.updateGroup.bind(sender);
this.addNumberToGroup = sender.addNumberToGroup.bind(sender);
this.setGroupName = sender.setGroupName.bind(sender);
this.setGroupAvatar = sender.setGroupAvatar.bind(sender);
this.leaveGroup = sender.leaveGroup.bind(sender);
this.sendSyncMessage = sender.sendSyncMessage.bind(sender);
this.getProfile = sender.getProfile.bind(sender);
this.getAvatar = sender.getAvatar.bind(sender);
this.syncReadMessages = sender.syncReadMessages.bind(sender);
this.syncVerification = sender.syncVerification.bind(sender);
this.sendDeliveryReceipt = sender.sendDeliveryReceipt.bind(sender);
2018-05-02 18:51:22 +02:00
this.sendReadReceipts = sender.sendReadReceipts.bind(sender);
2019-01-16 04:03:56 +01:00
this.makeProxiedRequest = sender.makeProxiedRequest.bind(sender);
this.getProxiedSize = sender.getProxiedSize.bind(sender);
2019-01-31 02:45:58 +01:00
this.getMessageProto = sender.getMessageProto.bind(sender);
};
2014-12-25 00:45:51 +01:00
2015-10-03 00:02:25 +02:00
textsecure.MessageSender.prototype = {
2018-05-02 18:51:22 +02:00
constructor: textsecure.MessageSender,
};