2021-01-14 18:07:05 +00:00
|
|
|
// Copyright 2020-2021 Signal Messenger, LLC
|
2020-10-30 20:34:04 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
/* eslint-disable no-param-reassign */
|
|
|
|
/* eslint-disable more/no-then */
|
|
|
|
/* eslint-disable no-bitwise */
|
|
|
|
/* eslint-disable guard-for-in */
|
|
|
|
/* eslint-disable no-restricted-syntax */
|
|
|
|
/* eslint-disable no-nested-ternary */
|
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
import fetch, { Response } from 'node-fetch';
|
|
|
|
import ProxyAgent from 'proxy-agent';
|
2021-06-09 22:28:54 +00:00
|
|
|
import { Agent, RequestOptions } from 'https';
|
2020-09-04 01:25:19 +00:00
|
|
|
import pProps from 'p-props';
|
|
|
|
import {
|
|
|
|
compact,
|
|
|
|
Dictionary,
|
|
|
|
escapeRegExp,
|
2021-06-17 17:15:10 +00:00
|
|
|
isNumber,
|
2020-09-04 01:25:19 +00:00
|
|
|
mapValues,
|
|
|
|
zipObject,
|
|
|
|
} from 'lodash';
|
|
|
|
import { createVerify } from 'crypto';
|
|
|
|
import { pki } from 'node-forge';
|
2020-03-31 20:03:38 +00:00
|
|
|
import is from '@sindresorhus/is';
|
2020-09-24 21:53:21 +00:00
|
|
|
import PQueue from 'p-queue';
|
|
|
|
import { v4 as getGuid } from 'uuid';
|
2021-06-09 22:28:54 +00:00
|
|
|
import { client as WebSocketClient, connection as WebSocket } from 'websocket';
|
2021-05-25 22:40:04 +00:00
|
|
|
import { z } from 'zod';
|
2020-09-24 21:53:21 +00:00
|
|
|
|
|
|
|
import { Long } from '../window.d';
|
2021-06-09 22:28:54 +00:00
|
|
|
import { assert } from '../util/assert';
|
2020-09-24 21:53:21 +00:00
|
|
|
import { getUserAgent } from '../util/getUserAgent';
|
2021-01-29 22:16:48 +00:00
|
|
|
import { toWebSafeBase64 } from '../util/webSafeBase64';
|
2020-08-31 16:29:22 +00:00
|
|
|
import { isPackIdValid, redactPackId } from '../../js/modules/stickers';
|
2020-09-04 01:25:19 +00:00
|
|
|
import {
|
|
|
|
arrayBufferToBase64,
|
|
|
|
base64ToArrayBuffer,
|
|
|
|
bytesFromHexString,
|
|
|
|
bytesFromString,
|
|
|
|
concatenateBytes,
|
|
|
|
constantTimeEqual,
|
|
|
|
decryptAesGcm,
|
2021-04-16 23:13:13 +00:00
|
|
|
deriveSecrets,
|
2020-09-04 01:25:19 +00:00
|
|
|
encryptCdsDiscoveryRequest,
|
|
|
|
getBytes,
|
|
|
|
getRandomValue,
|
|
|
|
splitUuids,
|
|
|
|
} from '../Crypto';
|
2021-04-16 23:13:13 +00:00
|
|
|
import { calculateAgreement, generateKeyPair } from '../Curve';
|
2020-09-28 23:46:31 +00:00
|
|
|
import * as linkPreviewFetch from '../linkPreviews/linkPreviewFetch';
|
|
|
|
|
2020-07-07 00:56:56 +00:00
|
|
|
import {
|
2020-09-09 02:25:05 +00:00
|
|
|
AvatarUploadAttributesClass,
|
|
|
|
GroupChangeClass,
|
|
|
|
GroupChangesClass,
|
|
|
|
GroupClass,
|
2021-01-29 22:16:48 +00:00
|
|
|
GroupJoinInfoClass,
|
2020-11-13 19:57:55 +00:00
|
|
|
GroupExternalCredentialClass,
|
2020-07-07 00:56:56 +00:00
|
|
|
StorageServiceCallOptionsType,
|
|
|
|
StorageServiceCredentials,
|
|
|
|
} from '../textsecure.d';
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
import MessageSender from './SendMessage';
|
|
|
|
|
2021-01-29 22:16:48 +00:00
|
|
|
// Note: this will break some code that expects to be able to use err.response when a
|
|
|
|
// web request fails, because it will force it to text. But it is very useful for
|
|
|
|
// debugging failed requests.
|
|
|
|
const DEBUG = false;
|
|
|
|
|
2020-09-04 01:25:19 +00:00
|
|
|
type SgxConstantsType = {
|
|
|
|
SGX_FLAGS_INITTED: Long;
|
|
|
|
SGX_FLAGS_DEBUG: Long;
|
|
|
|
SGX_FLAGS_MODE64BIT: Long;
|
|
|
|
SGX_FLAGS_PROVISION_KEY: Long;
|
|
|
|
SGX_FLAGS_EINITTOKEN_KEY: Long;
|
|
|
|
SGX_FLAGS_RESERVED: Long;
|
|
|
|
SGX_XFRM_LEGACY: Long;
|
|
|
|
SGX_XFRM_AVX: Long;
|
|
|
|
SGX_XFRM_RESERVED: Long;
|
|
|
|
};
|
|
|
|
|
|
|
|
let sgxConstantCache: SgxConstantsType | null = null;
|
|
|
|
|
|
|
|
function makeLong(value: string): Long {
|
|
|
|
return window.dcodeIO.Long.fromString(value);
|
|
|
|
}
|
|
|
|
function getSgxConstants() {
|
|
|
|
if (sgxConstantCache) {
|
|
|
|
return sgxConstantCache;
|
|
|
|
}
|
|
|
|
|
|
|
|
sgxConstantCache = {
|
|
|
|
SGX_FLAGS_INITTED: makeLong('x0000000000000001L'),
|
|
|
|
SGX_FLAGS_DEBUG: makeLong('x0000000000000002L'),
|
|
|
|
SGX_FLAGS_MODE64BIT: makeLong('x0000000000000004L'),
|
|
|
|
SGX_FLAGS_PROVISION_KEY: makeLong('x0000000000000004L'),
|
|
|
|
SGX_FLAGS_EINITTOKEN_KEY: makeLong('x0000000000000004L'),
|
|
|
|
SGX_FLAGS_RESERVED: makeLong('xFFFFFFFFFFFFFFC8L'),
|
|
|
|
SGX_XFRM_LEGACY: makeLong('x0000000000000003L'),
|
|
|
|
SGX_XFRM_AVX: makeLong('x0000000000000006L'),
|
|
|
|
SGX_XFRM_RESERVED: makeLong('xFFFFFFFFFFFFFFF8L'),
|
|
|
|
};
|
|
|
|
|
|
|
|
return sgxConstantCache;
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _btoa(str: any) {
|
2018-05-26 01:01:56 +00:00
|
|
|
let buffer;
|
|
|
|
|
|
|
|
if (str instanceof Buffer) {
|
|
|
|
buffer = str;
|
|
|
|
} else {
|
|
|
|
buffer = Buffer.from(str.toString(), 'binary');
|
|
|
|
}
|
|
|
|
|
|
|
|
return buffer.toString('base64');
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
const _call = (object: any) => Object.prototype.toString.call(object);
|
2018-05-26 01:01:56 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
const ArrayBufferToString = _call(new ArrayBuffer(0));
|
2018-05-26 01:01:56 +00:00
|
|
|
const Uint8ArrayToString = _call(new Uint8Array());
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _getString(thing: any): string {
|
2018-05-26 01:01:56 +00:00
|
|
|
if (typeof thing !== 'string') {
|
2020-03-31 20:03:38 +00:00
|
|
|
if (_call(thing) === Uint8ArrayToString) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return String.fromCharCode.apply(null, thing);
|
2020-03-31 20:03:38 +00:00
|
|
|
}
|
|
|
|
if (_call(thing) === ArrayBufferToString) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _getString(new Uint8Array(thing));
|
2020-03-31 20:03:38 +00:00
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return thing;
|
|
|
|
}
|
|
|
|
|
2020-01-08 17:44:54 +00:00
|
|
|
// prettier-ignore
|
2020-03-31 20:03:38 +00:00
|
|
|
function _b64ToUint6(nChr: number) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return nChr > 64 && nChr < 91
|
|
|
|
? nChr - 65
|
|
|
|
: nChr > 96 && nChr < 123
|
|
|
|
? nChr - 71
|
|
|
|
: nChr > 47 && nChr < 58
|
|
|
|
? nChr + 4
|
|
|
|
: nChr === 43
|
|
|
|
? 62
|
|
|
|
: nChr === 47
|
|
|
|
? 63
|
|
|
|
: 0;
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _getStringable(thing: any) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return (
|
|
|
|
typeof thing === 'string' ||
|
|
|
|
typeof thing === 'number' ||
|
|
|
|
typeof thing === 'boolean' ||
|
|
|
|
(thing === Object(thing) &&
|
|
|
|
(_call(thing) === ArrayBufferToString ||
|
|
|
|
_call(thing) === Uint8ArrayToString))
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _ensureStringed(thing: any): any {
|
2018-05-26 01:01:56 +00:00
|
|
|
if (_getStringable(thing)) {
|
|
|
|
return _getString(thing);
|
2020-09-24 21:53:21 +00:00
|
|
|
}
|
|
|
|
if (thing instanceof Array) {
|
2018-05-26 01:01:56 +00:00
|
|
|
const res = [];
|
|
|
|
for (let i = 0; i < thing.length; i += 1) {
|
|
|
|
res[i] = _ensureStringed(thing[i]);
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return res;
|
2020-09-24 21:53:21 +00:00
|
|
|
}
|
|
|
|
if (thing === Object(thing)) {
|
2020-03-31 20:03:38 +00:00
|
|
|
const res: any = {};
|
2018-05-26 01:01:56 +00:00
|
|
|
for (const key in thing) {
|
|
|
|
res[key] = _ensureStringed(thing[key]);
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return res;
|
2020-09-24 21:53:21 +00:00
|
|
|
}
|
|
|
|
if (thing === null) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return null;
|
2020-09-24 21:53:21 +00:00
|
|
|
}
|
|
|
|
if (thing === undefined) {
|
2018-10-18 01:01:21 +00:00
|
|
|
return undefined;
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
throw new Error(`unsure of how to jsonify object of type ${typeof thing}`);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _jsonThing(thing: any) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return JSON.stringify(_ensureStringed(thing));
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _base64ToBytes(sBase64: string, nBlocksSize?: number) {
|
2018-05-26 01:01:56 +00:00
|
|
|
const sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, '');
|
|
|
|
const nInLen = sB64Enc.length;
|
|
|
|
const nOutLen = nBlocksSize
|
|
|
|
? Math.ceil(((nInLen * 3 + 1) >> 2) / nBlocksSize) * nBlocksSize
|
|
|
|
: (nInLen * 3 + 1) >> 2;
|
|
|
|
const aBBytes = new ArrayBuffer(nOutLen);
|
|
|
|
const taBytes = new Uint8Array(aBBytes);
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
let nMod3 = 0;
|
|
|
|
let nMod4 = 0;
|
|
|
|
let nUint24 = 0;
|
|
|
|
let nOutIdx = 0;
|
|
|
|
|
|
|
|
for (let nInIdx = 0; nInIdx < nInLen; nInIdx += 1) {
|
2018-05-26 01:01:56 +00:00
|
|
|
nMod4 = nInIdx & 3;
|
|
|
|
nUint24 |= _b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << (18 - 6 * nMod4);
|
|
|
|
if (nMod4 === 3 || nInLen - nInIdx === 1) {
|
|
|
|
for (
|
|
|
|
nMod3 = 0;
|
|
|
|
nMod3 < 3 && nOutIdx < nOutLen;
|
|
|
|
nMod3 += 1, nOutIdx += 1
|
|
|
|
) {
|
|
|
|
taBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255;
|
|
|
|
}
|
|
|
|
nUint24 = 0;
|
|
|
|
}
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return aBBytes;
|
|
|
|
}
|
|
|
|
|
2020-08-20 22:15:50 +00:00
|
|
|
function _createRedactor(
|
|
|
|
...toReplace: ReadonlyArray<string | undefined>
|
|
|
|
): RedactUrl {
|
|
|
|
// NOTE: It would be nice to remove this cast, but TypeScript doesn't support
|
|
|
|
// it. However, there is [an issue][0] that discusses this in more detail.
|
|
|
|
// [0]: https://github.com/Microsoft/TypeScript/issues/16069
|
|
|
|
const stringsToReplace = toReplace.filter(Boolean) as Array<string>;
|
|
|
|
return href =>
|
|
|
|
stringsToReplace.reduce((result: string, stringToReplace: string) => {
|
|
|
|
const pattern = RegExp(escapeRegExp(stringToReplace), 'g');
|
|
|
|
const replacement = `[REDACTED]${stringToReplace.slice(-3)}`;
|
|
|
|
return result.replace(pattern, replacement);
|
|
|
|
}, href);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function _validateResponse(response: any, schema: any) {
|
2018-05-26 01:01:56 +00:00
|
|
|
try {
|
|
|
|
for (const i in schema) {
|
|
|
|
switch (schema[i]) {
|
|
|
|
case 'object':
|
|
|
|
case 'string':
|
|
|
|
case 'number':
|
|
|
|
if (typeof response[i] !== schema[i]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (ex) {
|
|
|
|
return false;
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
export type ConnectSocketOptions = Readonly<{
|
|
|
|
certificateAuthority: string;
|
|
|
|
proxyUrl?: string;
|
|
|
|
version: string;
|
|
|
|
timeout?: number;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
const TEN_SECONDS = 1000 * 10;
|
|
|
|
|
|
|
|
async function _connectSocket(
|
2020-03-31 20:03:38 +00:00
|
|
|
url: string,
|
|
|
|
{
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
2020-09-09 22:50:44 +00:00
|
|
|
version,
|
2021-06-09 22:28:54 +00:00
|
|
|
timeout = TEN_SECONDS,
|
|
|
|
}: ConnectSocketOptions
|
|
|
|
): Promise<WebSocket> {
|
|
|
|
let tlsOptions: RequestOptions = {
|
|
|
|
ca: certificateAuthority,
|
|
|
|
};
|
2018-05-26 01:01:56 +00:00
|
|
|
if (proxyUrl) {
|
2021-06-09 22:28:54 +00:00
|
|
|
tlsOptions = {
|
|
|
|
...tlsOptions,
|
2018-05-26 01:01:56 +00:00
|
|
|
agent: new ProxyAgent(proxyUrl),
|
|
|
|
};
|
|
|
|
}
|
2021-06-09 22:28:54 +00:00
|
|
|
|
2020-09-09 22:50:44 +00:00
|
|
|
const headers = {
|
|
|
|
'User-Agent': getUserAgent(version),
|
|
|
|
};
|
2021-06-09 22:28:54 +00:00
|
|
|
const client = new WebSocketClient({
|
|
|
|
tlsOptions,
|
2020-07-20 23:51:12 +00:00
|
|
|
maxReceivedFrameSize: 0x210000,
|
|
|
|
});
|
2021-06-09 22:28:54 +00:00
|
|
|
|
|
|
|
client.connect(url, undefined, undefined, headers);
|
|
|
|
|
|
|
|
const { stack } = new Error();
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const timer = setTimeout(() => {
|
2021-06-21 19:06:06 +00:00
|
|
|
reject(
|
|
|
|
makeHTTPError(
|
|
|
|
'_connectSocket: Connection timed out',
|
|
|
|
-1,
|
|
|
|
{},
|
|
|
|
'Connection timed out',
|
|
|
|
stack
|
|
|
|
)
|
|
|
|
);
|
2021-06-09 22:28:54 +00:00
|
|
|
|
|
|
|
client.abort();
|
|
|
|
}, timeout);
|
|
|
|
|
|
|
|
client.on('connect', socket => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
resolve(socket);
|
|
|
|
});
|
|
|
|
|
|
|
|
client.on('httpResponse', async response => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
|
|
|
|
const statusCode = response.statusCode || -1;
|
|
|
|
await _handleStatusCode(statusCode);
|
|
|
|
|
|
|
|
const error = makeHTTPError(
|
2021-06-21 19:06:06 +00:00
|
|
|
'_connectSocket: invalid websocket response',
|
2021-06-09 22:28:54 +00:00
|
|
|
statusCode || -1,
|
|
|
|
{}, // headers
|
|
|
|
undefined,
|
|
|
|
stack
|
|
|
|
);
|
|
|
|
|
|
|
|
const translatedError = _translateError(error);
|
|
|
|
assert(
|
|
|
|
translatedError,
|
|
|
|
'`httpResponse` event cannot be emitted with 200 status code'
|
|
|
|
);
|
|
|
|
|
|
|
|
reject(translatedError);
|
|
|
|
});
|
2021-06-15 00:12:58 +00:00
|
|
|
client.on('connectFailed', e => {
|
2021-06-09 22:28:54 +00:00
|
|
|
clearTimeout(timer);
|
2021-06-15 00:12:58 +00:00
|
|
|
|
|
|
|
reject(
|
|
|
|
makeHTTPError(
|
2021-06-21 19:06:06 +00:00
|
|
|
'_connectSocket: connectFailed',
|
|
|
|
-1,
|
2021-06-15 00:12:58 +00:00
|
|
|
{},
|
|
|
|
e.toString(),
|
|
|
|
stack
|
|
|
|
)
|
|
|
|
);
|
2021-06-09 22:28:54 +00:00
|
|
|
});
|
|
|
|
});
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
|
2018-11-09 01:23:07 +00:00
|
|
|
const FIVE_MINUTES = 1000 * 60 * 5;
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
type AgentCacheType = {
|
|
|
|
[name: string]: {
|
|
|
|
timestamp: number;
|
|
|
|
agent: ProxyAgent | Agent;
|
|
|
|
};
|
2018-11-07 19:20:43 +00:00
|
|
|
};
|
2020-03-31 20:03:38 +00:00
|
|
|
const agents: AgentCacheType = {};
|
2018-11-07 19:20:43 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function getContentType(response: Response) {
|
2019-01-16 03:03:56 +00:00
|
|
|
if (response.headers && response.headers.get) {
|
|
|
|
return response.headers.get('content-type');
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2021-05-06 00:09:29 +00:00
|
|
|
type FetchHeaderListType = { [name: string]: string };
|
|
|
|
type HeaderListType = { [name: string]: string | ReadonlyArray<string> };
|
2020-07-07 00:56:56 +00:00
|
|
|
type HTTPCodeType = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2020-08-20 22:15:50 +00:00
|
|
|
type RedactUrl = (url: string) => string;
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type PromiseAjaxOptionsType = {
|
|
|
|
accessKey?: string;
|
2020-09-09 02:25:05 +00:00
|
|
|
basicAuth?: string;
|
2020-03-31 20:03:38 +00:00
|
|
|
certificateAuthority?: string;
|
|
|
|
contentType?: string;
|
|
|
|
data?: ArrayBuffer | Buffer | string;
|
|
|
|
headers?: HeaderListType;
|
|
|
|
host?: string;
|
|
|
|
password?: string;
|
|
|
|
path?: string;
|
|
|
|
proxyUrl?: string;
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl?: RedactUrl;
|
2020-03-31 20:03:38 +00:00
|
|
|
redirect?: 'error' | 'follow' | 'manual';
|
2020-09-04 01:25:19 +00:00
|
|
|
responseType?:
|
|
|
|
| 'json'
|
|
|
|
| 'jsonwithdetails'
|
|
|
|
| 'arraybuffer'
|
|
|
|
| 'arraybufferwithdetails';
|
2021-05-17 18:29:37 +00:00
|
|
|
serverUrl?: string;
|
2020-03-31 20:03:38 +00:00
|
|
|
stack?: string;
|
|
|
|
timeout?: number;
|
2020-07-07 00:56:56 +00:00
|
|
|
type: HTTPCodeType;
|
2020-03-31 20:03:38 +00:00
|
|
|
unauthenticated?: boolean;
|
|
|
|
user?: string;
|
|
|
|
validateResponse?: any;
|
|
|
|
version: string;
|
|
|
|
};
|
|
|
|
|
2020-09-04 01:25:19 +00:00
|
|
|
type JSONWithDetailsType = {
|
|
|
|
data: any;
|
2020-09-09 02:25:05 +00:00
|
|
|
contentType: string | null;
|
|
|
|
response: Response;
|
|
|
|
};
|
|
|
|
type ArrayBufferWithDetailsType = {
|
|
|
|
data: ArrayBuffer;
|
|
|
|
contentType: string | null;
|
2020-09-04 01:25:19 +00:00
|
|
|
response: Response;
|
|
|
|
};
|
|
|
|
|
2021-05-25 22:40:04 +00:00
|
|
|
export const multiRecipient200ResponseSchema = z
|
|
|
|
.object({
|
|
|
|
uuids404: z.array(z.string()).optional(),
|
|
|
|
needsSync: z.boolean().optional(),
|
|
|
|
})
|
|
|
|
.passthrough();
|
|
|
|
export type MultiRecipient200ResponseType = z.infer<
|
|
|
|
typeof multiRecipient200ResponseSchema
|
|
|
|
>;
|
|
|
|
|
|
|
|
export const multiRecipient409ResponseSchema = z.array(
|
|
|
|
z
|
|
|
|
.object({
|
|
|
|
uuid: z.string(),
|
|
|
|
devices: z
|
|
|
|
.object({
|
|
|
|
missingDevices: z.array(z.number()).optional(),
|
|
|
|
extraDevices: z.array(z.number()).optional(),
|
|
|
|
})
|
|
|
|
.passthrough(),
|
|
|
|
})
|
|
|
|
.passthrough()
|
|
|
|
);
|
|
|
|
export type MultiRecipient409ResponseType = z.infer<
|
|
|
|
typeof multiRecipient409ResponseSchema
|
|
|
|
>;
|
|
|
|
|
|
|
|
export const multiRecipient410ResponseSchema = z.array(
|
|
|
|
z
|
|
|
|
.object({
|
|
|
|
uuid: z.string(),
|
|
|
|
devices: z
|
|
|
|
.object({
|
|
|
|
staleDevices: z.array(z.number()).optional(),
|
|
|
|
})
|
|
|
|
.passthrough(),
|
|
|
|
})
|
|
|
|
.passthrough()
|
|
|
|
);
|
|
|
|
export type MultiRecipient410ResponseType = z.infer<
|
|
|
|
typeof multiRecipient410ResponseSchema
|
|
|
|
>;
|
|
|
|
|
2021-01-29 22:16:48 +00:00
|
|
|
function isSuccess(status: number): boolean {
|
|
|
|
return status >= 0 && status < 400;
|
|
|
|
}
|
|
|
|
|
2021-05-17 18:29:37 +00:00
|
|
|
function getHostname(url: string): string {
|
|
|
|
const urlObject = new URL(url);
|
|
|
|
return urlObject.hostname;
|
|
|
|
}
|
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
async function _handleStatusCode(
|
|
|
|
status: number,
|
|
|
|
unauthenticated = false
|
|
|
|
): Promise<void> {
|
|
|
|
if (status === 499) {
|
|
|
|
window.log.error('Got 499 from Signal Server. Build is expired.');
|
|
|
|
await window.storage.put('remoteBuildExpiration', Date.now());
|
|
|
|
window.reduxActions.expiration.hydrateExpirationStatus(true);
|
|
|
|
}
|
|
|
|
if (!unauthenticated && status === 401) {
|
|
|
|
window.log.error('Got 401 from Signal Server. We might be unlinked.');
|
|
|
|
window.Whisper.events.trigger('mightBeUnlinked');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function _translateError(error: Error): Error | undefined {
|
|
|
|
const { code } = error;
|
|
|
|
if (code === 200) {
|
|
|
|
// Happens sometimes when we get no response. Might be nice to get 204 instead.
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
let message: string;
|
|
|
|
switch (code) {
|
|
|
|
case -1:
|
|
|
|
message =
|
|
|
|
'Failed to connect to the server, please check your network connection.';
|
|
|
|
break;
|
|
|
|
case 413:
|
|
|
|
message = 'Rate limit exceeded, please try again later.';
|
|
|
|
break;
|
|
|
|
case 403:
|
|
|
|
message = 'Invalid code, please try again.';
|
|
|
|
break;
|
|
|
|
case 417:
|
|
|
|
message = 'Number already registered.';
|
|
|
|
break;
|
|
|
|
case 401:
|
|
|
|
message =
|
|
|
|
'Invalid authentication, most likely someone re-registered and invalidated our registration.';
|
|
|
|
break;
|
|
|
|
case 404:
|
|
|
|
message = 'Number is not registered.';
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
message = 'The server rejected our query, please file a bug report.';
|
|
|
|
}
|
|
|
|
error.message = `${message} (original: ${error.message})`;
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function _promiseAjax(
|
|
|
|
providedUrl: string | null,
|
|
|
|
options: PromiseAjaxOptionsType
|
|
|
|
): Promise<any> {
|
2018-05-26 01:01:56 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const url = providedUrl || `${options.host}/${options.path}`;
|
2019-05-16 22:32:11 +00:00
|
|
|
|
|
|
|
const unauthLabel = options.unauthenticated ? ' (unauth)' : '';
|
|
|
|
if (options.redactUrl) {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(
|
|
|
|
`${options.type} ${options.redactUrl(url)}${unauthLabel}`
|
|
|
|
);
|
2019-01-16 03:03:56 +00:00
|
|
|
} else {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(`${options.type} ${url}${unauthLabel}`);
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
2019-02-20 22:40:32 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
const timeout =
|
2020-03-31 20:03:38 +00:00
|
|
|
typeof options.timeout === 'number' ? options.timeout : 10000;
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
const { proxyUrl } = options;
|
2018-11-09 01:23:07 +00:00
|
|
|
const agentType = options.unauthenticated ? 'unauth' : 'auth';
|
2019-02-20 22:40:32 +00:00
|
|
|
const cacheKey = `${proxyUrl}-${agentType}`;
|
2018-11-07 19:20:43 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
const { timestamp } = agents[cacheKey] || { timestamp: null };
|
2018-11-09 01:23:07 +00:00
|
|
|
if (!timestamp || timestamp + FIVE_MINUTES < Date.now()) {
|
|
|
|
if (timestamp) {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(`Cycling agent for type ${cacheKey}`);
|
2018-11-07 19:20:43 +00:00
|
|
|
}
|
2019-02-20 22:40:32 +00:00
|
|
|
agents[cacheKey] = {
|
2018-11-09 01:23:07 +00:00
|
|
|
agent: proxyUrl
|
|
|
|
? new ProxyAgent(proxyUrl)
|
|
|
|
: new Agent({ keepAlive: true }),
|
|
|
|
timestamp: Date.now(),
|
|
|
|
};
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
2019-02-20 22:40:32 +00:00
|
|
|
const { agent } = agents[cacheKey];
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
const fetchOptions = {
|
|
|
|
method: options.type,
|
2020-03-31 20:03:38 +00:00
|
|
|
body: options.data,
|
2019-01-16 03:03:56 +00:00
|
|
|
headers: {
|
2020-09-09 22:50:44 +00:00
|
|
|
'User-Agent': getUserAgent(options.version),
|
2019-01-16 03:03:56 +00:00
|
|
|
'X-Signal-Agent': 'OWD',
|
|
|
|
...options.headers,
|
2021-05-06 00:09:29 +00:00
|
|
|
} as FetchHeaderListType,
|
2019-01-16 03:03:56 +00:00
|
|
|
redirect: options.redirect,
|
2018-05-26 01:01:56 +00:00
|
|
|
agent,
|
|
|
|
ca: options.certificateAuthority,
|
|
|
|
timeout,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (fetchOptions.body instanceof ArrayBuffer) {
|
|
|
|
// node-fetch doesn't support ArrayBuffer, only node Buffer
|
|
|
|
const contentLength = fetchOptions.body.byteLength;
|
|
|
|
fetchOptions.body = Buffer.from(fetchOptions.body);
|
|
|
|
|
|
|
|
// node-fetch doesn't set content-length like S3 requires
|
2020-03-31 20:03:38 +00:00
|
|
|
fetchOptions.headers['Content-Length'] = contentLength.toString();
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
const { accessKey, basicAuth, unauthenticated } = options;
|
|
|
|
if (basicAuth) {
|
|
|
|
fetchOptions.headers.Authorization = `Basic ${basicAuth}`;
|
|
|
|
} else if (unauthenticated) {
|
2018-10-18 01:01:21 +00:00
|
|
|
if (!accessKey) {
|
|
|
|
throw new Error(
|
2020-11-16 20:05:10 +00:00
|
|
|
'_promiseAjax: mode is unauthenticated, but accessKey was not provided'
|
2018-10-18 01:01:21 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
// Access key is already a Base64 string
|
|
|
|
fetchOptions.headers['Unidentified-Access-Key'] = accessKey;
|
|
|
|
} else if (options.user && options.password) {
|
2018-05-26 01:01:56 +00:00
|
|
|
const user = _getString(options.user);
|
|
|
|
const password = _getString(options.password);
|
|
|
|
const auth = _btoa(`${user}:${password}`);
|
|
|
|
fetchOptions.headers.Authorization = `Basic ${auth}`;
|
|
|
|
}
|
2018-10-18 01:01:21 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
if (options.contentType) {
|
|
|
|
fetchOptions.headers['Content-Type'] = options.contentType;
|
|
|
|
}
|
2018-10-18 01:01:21 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
fetch(url, fetchOptions)
|
2020-03-31 20:03:38 +00:00
|
|
|
.then(async response => {
|
2021-06-09 22:28:54 +00:00
|
|
|
if (
|
|
|
|
options.serverUrl &&
|
|
|
|
getHostname(options.serverUrl) === getHostname(url)
|
|
|
|
) {
|
|
|
|
await _handleStatusCode(response.status, unauthenticated);
|
2020-09-09 22:50:44 +00:00
|
|
|
}
|
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
let resultPromise;
|
2021-01-29 22:16:48 +00:00
|
|
|
if (DEBUG && !isSuccess(response.status)) {
|
|
|
|
resultPromise = response.text();
|
|
|
|
} else if (
|
2020-09-04 01:25:19 +00:00
|
|
|
(options.responseType === 'json' ||
|
|
|
|
options.responseType === 'jsonwithdetails') &&
|
2021-03-15 23:45:42 +00:00
|
|
|
/^application\/json(;.*)?$/.test(
|
|
|
|
response.headers.get('Content-Type') || ''
|
|
|
|
)
|
2018-05-26 01:01:56 +00:00
|
|
|
) {
|
|
|
|
resultPromise = response.json();
|
2019-01-16 03:03:56 +00:00
|
|
|
} else if (
|
|
|
|
options.responseType === 'arraybuffer' ||
|
|
|
|
options.responseType === 'arraybufferwithdetails'
|
|
|
|
) {
|
2018-05-26 01:01:56 +00:00
|
|
|
resultPromise = response.buffer();
|
|
|
|
} else {
|
2020-08-11 21:23:37 +00:00
|
|
|
resultPromise = response.textConverted();
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
2019-01-16 03:03:56 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return resultPromise.then(result => {
|
2021-01-29 22:16:48 +00:00
|
|
|
if (isSuccess(response.status)) {
|
|
|
|
if (
|
|
|
|
options.responseType === 'arraybuffer' ||
|
|
|
|
options.responseType === 'arraybufferwithdetails'
|
|
|
|
) {
|
|
|
|
result = result.buffer.slice(
|
|
|
|
result.byteOffset,
|
|
|
|
result.byteOffset + result.byteLength
|
|
|
|
);
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
options.responseType === 'json' ||
|
|
|
|
options.responseType === 'jsonwithdetails'
|
|
|
|
) {
|
|
|
|
if (options.validateResponse) {
|
|
|
|
if (!_validateResponse(result, options.validateResponse)) {
|
|
|
|
if (options.redactUrl) {
|
|
|
|
window.log.info(
|
|
|
|
options.type,
|
|
|
|
options.redactUrl(url),
|
|
|
|
response.status,
|
|
|
|
'Error'
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
window.log.error(
|
|
|
|
options.type,
|
|
|
|
url,
|
|
|
|
response.status,
|
|
|
|
'Error'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
reject(
|
|
|
|
makeHTTPError(
|
|
|
|
'promiseAjax: invalid response',
|
|
|
|
response.status,
|
2021-05-06 00:09:29 +00:00
|
|
|
response.headers.raw(),
|
2021-01-29 22:16:48 +00:00
|
|
|
result,
|
|
|
|
options.stack
|
|
|
|
)
|
2019-01-16 03:03:56 +00:00
|
|
|
);
|
2021-01-29 22:16:48 +00:00
|
|
|
|
|
|
|
return;
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
}
|
2021-01-29 22:16:48 +00:00
|
|
|
|
2019-05-16 22:32:11 +00:00
|
|
|
if (options.redactUrl) {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(
|
2019-01-16 03:03:56 +00:00
|
|
|
options.type,
|
2019-05-16 22:32:11 +00:00
|
|
|
options.redactUrl(url),
|
2019-01-16 03:03:56 +00:00
|
|
|
response.status,
|
|
|
|
'Success'
|
|
|
|
);
|
|
|
|
} else {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(options.type, url, response.status, 'Success');
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
2020-09-09 02:25:05 +00:00
|
|
|
if (options.responseType === 'arraybufferwithdetails') {
|
|
|
|
const fullResult: ArrayBufferWithDetailsType = {
|
|
|
|
data: result,
|
|
|
|
contentType: getContentType(response),
|
|
|
|
response,
|
|
|
|
};
|
|
|
|
|
|
|
|
resolve(fullResult);
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (options.responseType === 'jsonwithdetails') {
|
|
|
|
const fullResult: JSONWithDetailsType = {
|
2019-01-16 03:03:56 +00:00
|
|
|
data: result,
|
|
|
|
contentType: getContentType(response),
|
|
|
|
response,
|
2020-09-09 02:25:05 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
resolve(fullResult);
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
return;
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
2020-09-09 02:25:05 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
resolve(result);
|
|
|
|
|
|
|
|
return;
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2019-05-16 22:32:11 +00:00
|
|
|
if (options.redactUrl) {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info(
|
2019-05-16 22:32:11 +00:00
|
|
|
options.type,
|
|
|
|
options.redactUrl(url),
|
|
|
|
response.status,
|
|
|
|
'Error'
|
|
|
|
);
|
2018-05-26 01:01:56 +00:00
|
|
|
} else {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.error(options.type, url, response.status, 'Error');
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
reject(
|
|
|
|
makeHTTPError(
|
2019-01-16 03:03:56 +00:00
|
|
|
'promiseAjax: error response',
|
|
|
|
response.status,
|
2021-05-06 00:09:29 +00:00
|
|
|
response.headers.raw(),
|
2019-01-16 03:03:56 +00:00
|
|
|
result,
|
|
|
|
options.stack
|
|
|
|
)
|
|
|
|
);
|
2018-05-26 01:01:56 +00:00
|
|
|
});
|
|
|
|
})
|
|
|
|
.catch(e => {
|
2019-05-16 22:32:11 +00:00
|
|
|
if (options.redactUrl) {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.error(options.type, options.redactUrl(url), 0, 'Error');
|
2019-01-16 03:03:56 +00:00
|
|
|
} else {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.error(options.type, url, 0, 'Error');
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
const stack = `${e.stack}\nInitial stack:\n${options.stack}`;
|
2021-05-06 00:09:29 +00:00
|
|
|
reject(makeHTTPError('promiseAjax catch', 0, {}, e.toString(), stack));
|
2018-05-26 01:01:56 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function _retryAjax(
|
|
|
|
url: string | null,
|
|
|
|
options: PromiseAjaxOptionsType,
|
|
|
|
providedLimit?: number,
|
|
|
|
providedCount?: number
|
|
|
|
) {
|
2018-05-26 01:01:56 +00:00
|
|
|
const count = (providedCount || 0) + 1;
|
|
|
|
const limit = providedLimit || 3;
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
return _promiseAjax(url, options).catch(async (e: Error) => {
|
2018-05-26 01:01:56 +00:00
|
|
|
if (e.name === 'HTTPError' && e.code === -1 && count < limit) {
|
|
|
|
return new Promise(resolve => {
|
|
|
|
setTimeout(() => {
|
|
|
|
resolve(_retryAjax(url, options, limit, count));
|
|
|
|
}, 1000);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function _outerAjax(url: string | null, options: PromiseAjaxOptionsType) {
|
2018-05-26 01:01:56 +00:00
|
|
|
options.stack = new Error().stack; // just in case, save stack here.
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return _retryAjax(url, options);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
declare global {
|
2021-01-14 18:07:05 +00:00
|
|
|
// We want to extend `Error`, so we need an interface.
|
|
|
|
// eslint-disable-next-line no-restricted-syntax
|
2020-03-31 20:03:38 +00:00
|
|
|
interface Error {
|
|
|
|
code?: number | string;
|
|
|
|
response?: any;
|
2021-05-06 00:09:29 +00:00
|
|
|
responseHeaders?: HeaderListType;
|
2020-04-13 17:37:29 +00:00
|
|
|
warn?: boolean;
|
2020-03-31 20:03:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function makeHTTPError(
|
|
|
|
message: string,
|
|
|
|
providedCode: number,
|
2021-05-06 00:09:29 +00:00
|
|
|
headers: HeaderListType,
|
2020-03-31 20:03:38 +00:00
|
|
|
response: any,
|
|
|
|
stack?: string
|
|
|
|
) {
|
2018-05-26 01:01:56 +00:00
|
|
|
const code = providedCode > 999 || providedCode < 100 ? -1 : providedCode;
|
|
|
|
const e = new Error(`${message}; code: ${code}`);
|
|
|
|
e.name = 'HTTPError';
|
|
|
|
e.code = code;
|
2021-05-06 00:09:29 +00:00
|
|
|
e.responseHeaders = headers;
|
2021-01-29 22:16:48 +00:00
|
|
|
if (DEBUG && response) {
|
|
|
|
e.stack += `\nresponse: ${response}`;
|
|
|
|
}
|
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
e.stack += `\nOriginal stack:\n${stack}`;
|
|
|
|
if (response) {
|
|
|
|
e.response = response;
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return e;
|
|
|
|
}
|
|
|
|
|
|
|
|
const URL_CALLS = {
|
|
|
|
accounts: 'v1/accounts',
|
2019-05-08 20:14:52 +00:00
|
|
|
attachmentId: 'v2/attachments/form/upload',
|
2020-09-09 02:25:05 +00:00
|
|
|
attestation: 'v1/attestation',
|
|
|
|
config: 'v1/config',
|
2018-10-18 01:01:21 +00:00
|
|
|
deliveryCert: 'v1/certificate/delivery',
|
2018-05-26 01:01:56 +00:00
|
|
|
devices: 'v1/devices',
|
2020-09-09 02:25:05 +00:00
|
|
|
directoryAuth: 'v1/directory/auth',
|
|
|
|
discovery: 'v1/discovery',
|
2020-11-20 17:30:45 +00:00
|
|
|
getGroupAvatarUpload: 'v1/groups/avatar/form',
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroupCredentials: 'v1/certificate/group',
|
|
|
|
getIceServers: 'v1/accounts/turn',
|
|
|
|
getStickerPackUpload: 'v1/sticker/pack/form',
|
|
|
|
groupLog: 'v1/groups/logs',
|
|
|
|
groups: 'v1/groups',
|
2021-01-29 22:16:48 +00:00
|
|
|
groupsViaLink: 'v1/groups/join',
|
2020-11-13 19:57:55 +00:00
|
|
|
groupToken: 'v1/groups/token',
|
2018-05-26 01:01:56 +00:00
|
|
|
keys: 'v2/keys',
|
|
|
|
messages: 'v1/messages',
|
2021-05-25 22:40:04 +00:00
|
|
|
multiRecipient: 'v1/messages/multi_recipient',
|
2018-05-26 01:01:56 +00:00
|
|
|
profile: 'v1/profile',
|
2020-07-07 00:56:56 +00:00
|
|
|
registerCapabilities: 'v1/devices/capabilities',
|
2020-09-09 02:25:05 +00:00
|
|
|
removeSignalingKey: 'v1/accounts/signaling_key',
|
2021-05-27 20:17:05 +00:00
|
|
|
reportMessage: 'v1/messages/report',
|
2018-10-18 01:01:21 +00:00
|
|
|
signed: 'v2/keys/signed',
|
2020-07-07 00:56:56 +00:00
|
|
|
storageManifest: 'v1/storage/manifest',
|
|
|
|
storageModify: 'v1/storage/',
|
|
|
|
storageRead: 'v1/storage/read',
|
|
|
|
storageToken: 'v1/storage/auth',
|
|
|
|
supportUnauthenticatedDelivery: 'v1/devices/unauthenticated_delivery',
|
2020-09-09 02:25:05 +00:00
|
|
|
updateDeviceName: 'v1/accounts/name',
|
2020-03-05 21:14:58 +00:00
|
|
|
whoami: 'v1/accounts/whoami',
|
2021-05-06 00:09:29 +00:00
|
|
|
challenge: 'v1/challenge',
|
2018-05-26 01:01:56 +00:00
|
|
|
};
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type InitializeOptionsType = {
|
|
|
|
url: string;
|
2020-07-07 00:56:56 +00:00
|
|
|
storageUrl: string;
|
2020-09-04 01:25:19 +00:00
|
|
|
directoryEnclaveId: string;
|
|
|
|
directoryTrustAnchor: string;
|
|
|
|
directoryUrl: string;
|
2020-04-17 22:51:39 +00:00
|
|
|
cdnUrlObject: {
|
|
|
|
readonly '0': string;
|
|
|
|
readonly [propName: string]: string;
|
|
|
|
};
|
2020-03-31 20:03:38 +00:00
|
|
|
certificateAuthority: string;
|
|
|
|
contentProxyUrl: string;
|
|
|
|
proxyUrl: string;
|
|
|
|
version: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
type ConnectParametersType = {
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
type MessageType = any;
|
|
|
|
|
|
|
|
type AjaxOptionsType = {
|
|
|
|
accessKey?: string;
|
2020-09-09 02:25:05 +00:00
|
|
|
basicAuth?: string;
|
2020-03-31 20:03:38 +00:00
|
|
|
call: keyof typeof URL_CALLS;
|
2020-07-07 00:56:56 +00:00
|
|
|
contentType?: string;
|
|
|
|
data?: ArrayBuffer | Buffer | string;
|
2021-05-25 22:40:04 +00:00
|
|
|
headers?: HeaderListType;
|
2020-07-07 00:56:56 +00:00
|
|
|
host?: string;
|
|
|
|
httpType: HTTPCodeType;
|
2020-03-31 20:03:38 +00:00
|
|
|
jsonData?: any;
|
2020-07-07 00:56:56 +00:00
|
|
|
password?: string;
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl?: RedactUrl;
|
2020-03-31 20:03:38 +00:00
|
|
|
responseType?: 'json' | 'arraybuffer' | 'arraybufferwithdetails';
|
2020-07-07 00:56:56 +00:00
|
|
|
schema?: any;
|
2020-03-31 20:03:38 +00:00
|
|
|
timeout?: number;
|
|
|
|
unauthenticated?: boolean;
|
|
|
|
urlParameters?: string;
|
2020-07-07 00:56:56 +00:00
|
|
|
username?: string;
|
2020-03-31 20:03:38 +00:00
|
|
|
validateResponse?: any;
|
|
|
|
};
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
export type WebAPIConnectType = {
|
|
|
|
connect: (options: ConnectParametersType) => WebAPIType;
|
|
|
|
};
|
|
|
|
|
2020-11-20 17:30:45 +00:00
|
|
|
export type CapabilitiesType = {
|
|
|
|
gv2: boolean;
|
|
|
|
'gv1-migration': boolean;
|
2021-05-25 22:40:04 +00:00
|
|
|
senderKey: boolean;
|
2020-11-20 17:30:45 +00:00
|
|
|
};
|
|
|
|
export type CapabilitiesUploadType = {
|
|
|
|
'gv2-3': boolean;
|
|
|
|
'gv1-migration': boolean;
|
2021-05-25 22:40:04 +00:00
|
|
|
senderKey: boolean;
|
2020-11-20 17:30:45 +00:00
|
|
|
};
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
type StickerPackManifestType = any;
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
export type GroupCredentialType = {
|
|
|
|
credential: string;
|
|
|
|
redemptionTime: number;
|
|
|
|
};
|
|
|
|
export type GroupCredentialsType = {
|
|
|
|
groupPublicParamsHex: string;
|
|
|
|
authCredentialPresentationHex: string;
|
|
|
|
};
|
|
|
|
export type GroupLogResponseType = {
|
|
|
|
currentRevision?: number;
|
|
|
|
start?: number;
|
|
|
|
end?: number;
|
|
|
|
changes: GroupChangesClass;
|
|
|
|
};
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
export type WebAPIType = {
|
|
|
|
confirmCode: (
|
|
|
|
number: string,
|
|
|
|
code: string,
|
|
|
|
newPassword: string,
|
|
|
|
registrationId: number,
|
|
|
|
deviceName?: string | null,
|
|
|
|
options?: { accessKey?: ArrayBuffer }
|
|
|
|
) => Promise<any>;
|
2020-09-09 02:25:05 +00:00
|
|
|
createGroup: (
|
|
|
|
group: GroupClass,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
) => Promise<void>;
|
2021-06-17 17:15:10 +00:00
|
|
|
getAttachment: (cdnKey: string, cdnNumber?: number) => Promise<any>;
|
2020-04-13 17:37:29 +00:00
|
|
|
getAvatar: (path: string) => Promise<any>;
|
|
|
|
getDevices: () => Promise<any>;
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroup: (options: GroupCredentialsType) => Promise<GroupClass>;
|
2021-01-29 22:16:48 +00:00
|
|
|
getGroupFromLink: (
|
|
|
|
inviteLinkPassword: string,
|
|
|
|
auth: GroupCredentialsType
|
|
|
|
) => Promise<GroupJoinInfoClass>;
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroupAvatar: (key: string) => Promise<ArrayBuffer>;
|
|
|
|
getGroupCredentials: (
|
|
|
|
startDay: number,
|
|
|
|
endDay: number
|
|
|
|
) => Promise<Array<GroupCredentialType>>;
|
2020-11-13 19:57:55 +00:00
|
|
|
getGroupExternalCredential: (
|
|
|
|
options: GroupCredentialsType
|
|
|
|
) => Promise<GroupExternalCredentialClass>;
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroupLog: (
|
|
|
|
startVersion: number,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
) => Promise<GroupLogResponseType>;
|
2020-06-04 18:16:19 +00:00
|
|
|
getIceServers: () => Promise<any>;
|
2020-04-13 17:37:29 +00:00
|
|
|
getKeysForIdentifier: (
|
|
|
|
identifier: string,
|
|
|
|
deviceId?: number
|
|
|
|
) => Promise<ServerKeysType>;
|
|
|
|
getKeysForIdentifierUnauth: (
|
|
|
|
identifier: string,
|
|
|
|
deviceId?: number,
|
|
|
|
options?: { accessKey?: string }
|
|
|
|
) => Promise<ServerKeysType>;
|
2021-06-09 22:28:54 +00:00
|
|
|
getMessageSocket: () => Promise<WebSocket>;
|
2020-04-13 17:37:29 +00:00
|
|
|
getMyKeys: () => Promise<number>;
|
2020-04-15 23:12:28 +00:00
|
|
|
getProfile: (
|
|
|
|
identifier: string,
|
|
|
|
options?: {
|
|
|
|
profileKeyVersion?: string;
|
|
|
|
profileKeyCredentialRequest?: string;
|
|
|
|
}
|
|
|
|
) => Promise<any>;
|
2020-04-13 17:37:29 +00:00
|
|
|
getProfileUnauth: (
|
|
|
|
identifier: string,
|
2020-04-15 23:12:28 +00:00
|
|
|
options: {
|
|
|
|
accessKey: string;
|
|
|
|
profileKeyVersion?: string;
|
|
|
|
profileKeyCredentialRequest?: string;
|
|
|
|
}
|
2020-04-13 17:37:29 +00:00
|
|
|
) => Promise<any>;
|
2021-06-09 22:28:54 +00:00
|
|
|
getProvisioningSocket: () => Promise<WebSocket>;
|
2021-04-08 16:24:21 +00:00
|
|
|
getSenderCertificate: (
|
|
|
|
withUuid?: boolean
|
|
|
|
) => Promise<{ certificate: string }>;
|
2020-09-24 21:53:21 +00:00
|
|
|
getSticker: (packId: string, stickerId: number) => Promise<any>;
|
2020-04-13 17:37:29 +00:00
|
|
|
getStickerPackManifest: (packId: string) => Promise<StickerPackManifestType>;
|
2020-07-10 18:28:49 +00:00
|
|
|
getStorageCredentials: MessageSender['getStorageCredentials'];
|
|
|
|
getStorageManifest: MessageSender['getStorageManifest'];
|
|
|
|
getStorageRecords: MessageSender['getStorageRecords'];
|
2020-09-04 01:25:19 +00:00
|
|
|
getUuidsForE164s: (
|
|
|
|
e164s: ReadonlyArray<string>
|
|
|
|
) => Promise<Dictionary<string | null>>;
|
2020-09-28 23:46:31 +00:00
|
|
|
fetchLinkPreviewMetadata: (
|
|
|
|
href: string,
|
|
|
|
abortSignal: AbortSignal
|
|
|
|
) => Promise<null | linkPreviewFetch.LinkPreviewMetadata>;
|
|
|
|
fetchLinkPreviewImage: (
|
|
|
|
href: string,
|
|
|
|
abortSignal: AbortSignal
|
|
|
|
) => Promise<null | linkPreviewFetch.LinkPreviewImage>;
|
2020-04-13 17:37:29 +00:00
|
|
|
makeProxiedRequest: (
|
|
|
|
targetUrl: string,
|
|
|
|
options?: ProxiedRequestOptionsType
|
|
|
|
) => Promise<any>;
|
2020-11-13 19:57:55 +00:00
|
|
|
makeSfuRequest: (
|
|
|
|
targetUrl: string,
|
|
|
|
type: HTTPCodeType,
|
|
|
|
headers: HeaderListType,
|
|
|
|
body: ArrayBuffer | undefined
|
|
|
|
) => Promise<ArrayBufferWithDetailsType>;
|
2020-09-09 02:25:05 +00:00
|
|
|
modifyGroup: (
|
|
|
|
changes: GroupChangeClass.Actions,
|
2021-01-29 22:16:48 +00:00
|
|
|
options: GroupCredentialsType,
|
|
|
|
inviteLinkBase64?: string
|
2020-09-09 02:25:05 +00:00
|
|
|
) => Promise<GroupChangeClass>;
|
2020-09-09 00:56:23 +00:00
|
|
|
modifyStorageRecords: MessageSender['modifyStorageRecords'];
|
2020-04-13 17:37:29 +00:00
|
|
|
putAttachment: (encryptedBin: ArrayBuffer) => Promise<any>;
|
2020-11-20 17:30:45 +00:00
|
|
|
registerCapabilities: (capabilities: CapabilitiesUploadType) => Promise<void>;
|
2020-04-13 17:37:29 +00:00
|
|
|
putStickers: (
|
|
|
|
encryptedManifest: ArrayBuffer,
|
|
|
|
encryptedStickers: Array<ArrayBuffer>,
|
|
|
|
onProgress?: () => void
|
|
|
|
) => Promise<string>;
|
|
|
|
registerKeys: (genKeys: KeysType) => Promise<void>;
|
|
|
|
registerSupportForUnauthenticatedDelivery: () => Promise<any>;
|
|
|
|
removeSignalingKey: () => Promise<void>;
|
2021-05-27 20:17:05 +00:00
|
|
|
reportMessage: (senderE164: string, serverGuid: string) => Promise<void>;
|
2020-04-13 17:37:29 +00:00
|
|
|
requestVerificationSMS: (number: string) => Promise<any>;
|
|
|
|
requestVerificationVoice: (number: string) => Promise<any>;
|
|
|
|
sendMessages: (
|
|
|
|
destination: string,
|
|
|
|
messageArray: Array<MessageType>,
|
|
|
|
timestamp: number,
|
|
|
|
online?: boolean
|
|
|
|
) => Promise<void>;
|
|
|
|
sendMessagesUnauth: (
|
|
|
|
destination: string,
|
|
|
|
messageArray: Array<MessageType>,
|
|
|
|
timestamp: number,
|
|
|
|
online?: boolean,
|
|
|
|
options?: { accessKey?: string }
|
|
|
|
) => Promise<void>;
|
2021-05-25 22:40:04 +00:00
|
|
|
sendWithSenderKey: (
|
|
|
|
payload: ArrayBuffer,
|
|
|
|
accessKeys: ArrayBuffer,
|
|
|
|
timestamp: number,
|
|
|
|
online?: boolean
|
|
|
|
) => Promise<MultiRecipient200ResponseType>;
|
2020-04-13 17:37:29 +00:00
|
|
|
setSignedPreKey: (signedPreKey: SignedPreKeyType) => Promise<void>;
|
|
|
|
updateDeviceName: (deviceName: string) => Promise<void>;
|
2020-09-09 02:25:05 +00:00
|
|
|
uploadGroupAvatar: (
|
|
|
|
avatarData: ArrayBuffer,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
) => Promise<string>;
|
2020-04-13 17:37:29 +00:00
|
|
|
whoami: () => Promise<any>;
|
2021-05-06 00:09:29 +00:00
|
|
|
sendChallengeResponse: (challengeResponse: ChallengeType) => Promise<any>;
|
2020-09-09 22:50:44 +00:00
|
|
|
getConfig: () => Promise<
|
|
|
|
Array<{ name: string; enabled: boolean; value: string | null }>
|
|
|
|
>;
|
2020-04-13 17:37:29 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export type SignedPreKeyType = {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: ArrayBuffer;
|
|
|
|
signature: ArrayBuffer;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type KeysType = {
|
|
|
|
identityKey: ArrayBuffer;
|
|
|
|
signedPreKey: SignedPreKeyType;
|
|
|
|
preKeys: Array<{
|
|
|
|
keyId: number;
|
|
|
|
publicKey: ArrayBuffer;
|
|
|
|
}>;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type ServerKeysType = {
|
|
|
|
devices: Array<{
|
|
|
|
deviceId: number;
|
|
|
|
registrationId: number;
|
|
|
|
signedPreKey: {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: ArrayBuffer;
|
|
|
|
signature: ArrayBuffer;
|
|
|
|
};
|
|
|
|
preKey?: {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: ArrayBuffer;
|
|
|
|
};
|
|
|
|
}>;
|
|
|
|
identityKey: ArrayBuffer;
|
|
|
|
};
|
|
|
|
|
2021-05-06 00:09:29 +00:00
|
|
|
export type ChallengeType = {
|
|
|
|
readonly type: 'recaptcha';
|
|
|
|
readonly token: string;
|
|
|
|
readonly captcha: string;
|
|
|
|
};
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
export type ProxiedRequestOptionsType = {
|
|
|
|
returnArrayBuffer?: boolean;
|
|
|
|
start?: number;
|
|
|
|
end?: number;
|
|
|
|
};
|
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
// We first set up the data that won't change during this session of the app
|
2020-04-13 17:37:29 +00:00
|
|
|
export function initialize({
|
2019-01-16 03:03:56 +00:00
|
|
|
url,
|
2020-07-07 00:56:56 +00:00
|
|
|
storageUrl,
|
2020-09-04 01:25:19 +00:00
|
|
|
directoryEnclaveId,
|
|
|
|
directoryTrustAnchor,
|
|
|
|
directoryUrl,
|
2020-04-17 22:51:39 +00:00
|
|
|
cdnUrlObject,
|
2019-01-16 03:03:56 +00:00
|
|
|
certificateAuthority,
|
|
|
|
contentProxyUrl,
|
|
|
|
proxyUrl,
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2020-04-13 17:37:29 +00:00
|
|
|
}: InitializeOptionsType): WebAPIConnectType {
|
2018-05-26 01:01:56 +00:00
|
|
|
if (!is.string(url)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid server url');
|
|
|
|
}
|
2020-07-07 00:56:56 +00:00
|
|
|
if (!is.string(storageUrl)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid storageUrl');
|
|
|
|
}
|
2020-09-04 01:25:19 +00:00
|
|
|
if (!is.string(directoryEnclaveId)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid directory enclave id');
|
|
|
|
}
|
|
|
|
if (!is.string(directoryTrustAnchor)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid directory enclave id');
|
|
|
|
}
|
|
|
|
if (!is.string(directoryUrl)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid directory url');
|
|
|
|
}
|
2020-04-17 22:51:39 +00:00
|
|
|
if (!is.object(cdnUrlObject)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid cdnUrlObject');
|
|
|
|
}
|
|
|
|
if (!is.string(cdnUrlObject['0'])) {
|
|
|
|
throw new Error('WebAPI.initialize: Missing CDN 0 configuration');
|
|
|
|
}
|
|
|
|
if (!is.string(cdnUrlObject['2'])) {
|
|
|
|
throw new Error('WebAPI.initialize: Missing CDN 2 configuration');
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
if (!is.string(certificateAuthority)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid certificateAuthority');
|
|
|
|
}
|
2019-01-16 03:03:56 +00:00
|
|
|
if (!is.string(contentProxyUrl)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid contentProxyUrl');
|
|
|
|
}
|
2020-10-12 22:08:43 +00:00
|
|
|
if (proxyUrl && !is.string(proxyUrl)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid proxyUrl');
|
|
|
|
}
|
2020-01-17 00:53:35 +00:00
|
|
|
if (!is.string(version)) {
|
|
|
|
throw new Error('WebAPI.initialize: Invalid version');
|
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
// Thanks to function-hoisting, we can put this return statement before all of the
|
|
|
|
// below function definitions.
|
|
|
|
return {
|
|
|
|
connect,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Then we connect to the server with user-specific information. This is the only API
|
|
|
|
// exposed to the browser context, ensuring that it can't connect to arbitrary
|
|
|
|
// locations.
|
2020-03-31 20:03:38 +00:00
|
|
|
function connect({
|
|
|
|
username: initialUsername,
|
|
|
|
password: initialPassword,
|
|
|
|
}: ConnectParametersType) {
|
2018-05-26 01:01:56 +00:00
|
|
|
let username = initialUsername;
|
|
|
|
let password = initialPassword;
|
2019-05-16 22:32:11 +00:00
|
|
|
const PARSE_RANGE_HEADER = /\/(\d+)$/;
|
2020-09-09 02:25:05 +00:00
|
|
|
const PARSE_GROUP_LOG_RANGE_HEADER = /$versions (\d{1,10})-(\d{1,10})\/(d{1,10})/;
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
// Thanks, function hoisting!
|
|
|
|
return {
|
|
|
|
confirmCode,
|
2020-09-09 02:25:05 +00:00
|
|
|
createGroup,
|
2021-01-29 22:16:48 +00:00
|
|
|
fetchLinkPreviewImage,
|
|
|
|
fetchLinkPreviewMetadata,
|
2018-05-26 01:01:56 +00:00
|
|
|
getAttachment,
|
|
|
|
getAvatar,
|
2020-09-09 02:25:05 +00:00
|
|
|
getConfig,
|
2018-05-26 01:01:56 +00:00
|
|
|
getDevices,
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroup,
|
|
|
|
getGroupAvatar,
|
|
|
|
getGroupCredentials,
|
2020-11-13 19:57:55 +00:00
|
|
|
getGroupExternalCredential,
|
2021-01-29 22:16:48 +00:00
|
|
|
getGroupFromLink,
|
2020-09-09 02:25:05 +00:00
|
|
|
getGroupLog,
|
2020-06-04 18:16:19 +00:00
|
|
|
getIceServers,
|
2020-03-05 21:14:58 +00:00
|
|
|
getKeysForIdentifier,
|
|
|
|
getKeysForIdentifierUnauth,
|
2018-05-26 01:01:56 +00:00
|
|
|
getMessageSocket,
|
|
|
|
getMyKeys,
|
|
|
|
getProfile,
|
2018-10-18 01:01:21 +00:00
|
|
|
getProfileUnauth,
|
2018-05-26 01:01:56 +00:00
|
|
|
getProvisioningSocket,
|
2019-01-16 03:03:56 +00:00
|
|
|
getSenderCertificate,
|
2019-05-16 22:32:11 +00:00
|
|
|
getSticker,
|
|
|
|
getStickerPackManifest,
|
2020-07-07 00:56:56 +00:00
|
|
|
getStorageCredentials,
|
|
|
|
getStorageManifest,
|
|
|
|
getStorageRecords,
|
2020-09-04 01:25:19 +00:00
|
|
|
getUuidsForE164s,
|
2019-01-16 03:03:56 +00:00
|
|
|
makeProxiedRequest,
|
2020-11-13 19:57:55 +00:00
|
|
|
makeSfuRequest,
|
2020-09-09 02:25:05 +00:00
|
|
|
modifyGroup,
|
2020-09-09 00:56:23 +00:00
|
|
|
modifyStorageRecords,
|
2018-05-26 01:01:56 +00:00
|
|
|
putAttachment,
|
2019-12-17 20:25:57 +00:00
|
|
|
putStickers,
|
2020-09-09 02:25:05 +00:00
|
|
|
registerCapabilities,
|
2018-05-26 01:01:56 +00:00
|
|
|
registerKeys,
|
2019-01-16 03:03:56 +00:00
|
|
|
registerSupportForUnauthenticatedDelivery,
|
|
|
|
removeSignalingKey,
|
2021-05-27 20:17:05 +00:00
|
|
|
reportMessage,
|
2018-05-26 01:01:56 +00:00
|
|
|
requestVerificationSMS,
|
|
|
|
requestVerificationVoice,
|
|
|
|
sendMessages,
|
2018-10-18 01:01:21 +00:00
|
|
|
sendMessagesUnauth,
|
2021-05-25 22:40:04 +00:00
|
|
|
sendWithSenderKey,
|
2018-05-26 01:01:56 +00:00
|
|
|
setSignedPreKey,
|
2018-12-13 19:12:33 +00:00
|
|
|
updateDeviceName,
|
2020-09-09 02:25:05 +00:00
|
|
|
uploadGroupAvatar,
|
2020-03-05 21:14:58 +00:00
|
|
|
whoami,
|
2021-05-06 00:09:29 +00:00
|
|
|
sendChallengeResponse,
|
2018-05-26 01:01:56 +00:00
|
|
|
};
|
|
|
|
|
2020-05-27 21:37:06 +00:00
|
|
|
async function _ajax(param: AjaxOptionsType): Promise<any> {
|
2018-05-26 01:01:56 +00:00
|
|
|
if (!param.urlParameters) {
|
|
|
|
param.urlParameters = '';
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return _outerAjax(null, {
|
2020-09-09 02:25:05 +00:00
|
|
|
basicAuth: param.basicAuth,
|
2018-05-26 01:01:56 +00:00
|
|
|
certificateAuthority,
|
2020-07-07 00:56:56 +00:00
|
|
|
contentType: param.contentType || 'application/json; charset=utf-8',
|
|
|
|
data: param.data || (param.jsonData && _jsonThing(param.jsonData)),
|
2021-05-25 22:40:04 +00:00
|
|
|
headers: param.headers,
|
2020-07-07 00:56:56 +00:00
|
|
|
host: param.host || url,
|
|
|
|
password: param.password || password,
|
2018-05-26 01:01:56 +00:00
|
|
|
path: URL_CALLS[param.call] + param.urlParameters,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: param.responseType,
|
|
|
|
timeout: param.timeout,
|
|
|
|
type: param.httpType,
|
2020-07-07 00:56:56 +00:00
|
|
|
user: param.username || username,
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl: param.redactUrl,
|
2021-05-17 18:29:37 +00:00
|
|
|
serverUrl: url,
|
2018-05-26 01:01:56 +00:00
|
|
|
validateResponse: param.validateResponse,
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2018-10-18 01:01:21 +00:00
|
|
|
unauthenticated: param.unauthenticated,
|
|
|
|
accessKey: param.accessKey,
|
2020-03-31 20:03:38 +00:00
|
|
|
}).catch((e: Error) => {
|
2021-06-09 22:28:54 +00:00
|
|
|
const translatedError = _translateError(e);
|
|
|
|
if (translatedError) {
|
|
|
|
throw translatedError;
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function whoami() {
|
2020-03-05 21:14:58 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'whoami',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-06 00:09:29 +00:00
|
|
|
async function sendChallengeResponse(challengeResponse: ChallengeType) {
|
|
|
|
return _ajax({
|
|
|
|
call: 'challenge',
|
|
|
|
httpType: 'PUT',
|
|
|
|
jsonData: challengeResponse,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-05-27 21:37:06 +00:00
|
|
|
async function getConfig() {
|
|
|
|
type ResType = {
|
2020-09-09 22:50:44 +00:00
|
|
|
config: Array<{ name: string; enabled: boolean; value: string | null }>;
|
2020-05-27 21:37:06 +00:00
|
|
|
};
|
|
|
|
const res: ResType = await _ajax({
|
|
|
|
call: 'config',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
|
2020-12-01 16:42:35 +00:00
|
|
|
return res.config.filter(
|
|
|
|
({ name }: { name: string }) =>
|
|
|
|
name.startsWith('desktop.') || name.startsWith('global.')
|
2020-05-27 21:37:06 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-12-09 22:26:37 +00:00
|
|
|
async function getSenderCertificate(omitE164?: boolean) {
|
2018-10-18 01:01:21 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'deliveryCert',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
2020-03-31 20:03:38 +00:00
|
|
|
validateResponse: { certificate: 'string' },
|
2021-01-27 17:10:00 +00:00
|
|
|
...(omitE164 ? { urlParameters: '?includeE164=false' } : {}),
|
2018-10-18 01:01:21 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-07-07 00:56:56 +00:00
|
|
|
async function getStorageCredentials(): Promise<StorageServiceCredentials> {
|
|
|
|
return _ajax({
|
|
|
|
call: 'storageToken',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
schema: { username: 'string', password: 'string' },
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getStorageManifest(
|
|
|
|
options: StorageServiceCallOptionsType = {}
|
|
|
|
): Promise<ArrayBuffer> {
|
|
|
|
const { credentials, greaterThanVersion } = options;
|
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'storageManifest',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
host: storageUrl,
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
urlParameters: greaterThanVersion
|
|
|
|
? `/version/${greaterThanVersion}`
|
|
|
|
: '',
|
|
|
|
...credentials,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getStorageRecords(
|
|
|
|
data: ArrayBuffer,
|
|
|
|
options: StorageServiceCallOptionsType = {}
|
|
|
|
): Promise<ArrayBuffer> {
|
|
|
|
const { credentials } = options;
|
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'storageRead',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
data,
|
|
|
|
host: storageUrl,
|
|
|
|
httpType: 'PUT',
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
...credentials,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-09-09 00:56:23 +00:00
|
|
|
async function modifyStorageRecords(
|
|
|
|
data: ArrayBuffer,
|
|
|
|
options: StorageServiceCallOptionsType = {}
|
|
|
|
): Promise<ArrayBuffer> {
|
|
|
|
const { credentials } = options;
|
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'storageModify',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
data,
|
|
|
|
host: storageUrl,
|
|
|
|
httpType: 'PUT',
|
|
|
|
// If we run into a conflict, the current manifest is returned -
|
|
|
|
// it will will be an ArrayBuffer at the response key on the Error
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
...credentials,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function registerSupportForUnauthenticatedDelivery() {
|
2018-10-18 01:01:21 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'supportUnauthenticatedDelivery',
|
|
|
|
httpType: 'PUT',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-11-20 17:30:45 +00:00
|
|
|
async function registerCapabilities(capabilities: CapabilitiesUploadType) {
|
2020-03-05 21:14:58 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'registerCapabilities',
|
|
|
|
httpType: 'PUT',
|
2020-09-10 22:03:17 +00:00
|
|
|
jsonData: capabilities,
|
2020-03-05 21:14:58 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-04-15 23:12:28 +00:00
|
|
|
function getProfileUrl(
|
|
|
|
identifier: string,
|
|
|
|
profileKeyVersion?: string,
|
|
|
|
profileKeyCredentialRequest?: string
|
|
|
|
) {
|
2020-08-10 19:39:06 +00:00
|
|
|
let profileUrl = `/${identifier}`;
|
|
|
|
|
|
|
|
if (profileKeyVersion) {
|
|
|
|
profileUrl += `/${profileKeyVersion}`;
|
|
|
|
}
|
2020-04-15 23:12:28 +00:00
|
|
|
if (profileKeyVersion && profileKeyCredentialRequest) {
|
2020-08-10 19:39:06 +00:00
|
|
|
profileUrl += `/${profileKeyCredentialRequest}`;
|
2020-04-15 23:12:28 +00:00
|
|
|
}
|
|
|
|
|
2020-08-10 19:39:06 +00:00
|
|
|
return profileUrl;
|
2020-04-15 23:12:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function getProfile(
|
|
|
|
identifier: string,
|
|
|
|
options: {
|
|
|
|
profileKeyVersion?: string;
|
|
|
|
profileKeyCredentialRequest?: string;
|
|
|
|
} = {}
|
|
|
|
) {
|
|
|
|
const { profileKeyVersion, profileKeyCredentialRequest } = options;
|
|
|
|
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'profile',
|
|
|
|
httpType: 'GET',
|
2020-04-15 23:12:28 +00:00
|
|
|
urlParameters: getProfileUrl(
|
|
|
|
identifier,
|
|
|
|
profileKeyVersion,
|
|
|
|
profileKeyCredentialRequest
|
|
|
|
),
|
2018-05-26 01:01:56 +00:00
|
|
|
responseType: 'json',
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl: _createRedactor(
|
|
|
|
identifier,
|
|
|
|
profileKeyVersion,
|
|
|
|
profileKeyCredentialRequest
|
|
|
|
),
|
2018-05-26 01:01:56 +00:00
|
|
|
});
|
|
|
|
}
|
2020-04-15 23:12:28 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function getProfileUnauth(
|
|
|
|
identifier: string,
|
2020-04-15 23:12:28 +00:00
|
|
|
options: {
|
|
|
|
accessKey: string;
|
|
|
|
profileKeyVersion?: string;
|
|
|
|
profileKeyCredentialRequest?: string;
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
) {
|
2020-04-15 23:12:28 +00:00
|
|
|
const {
|
|
|
|
accessKey,
|
|
|
|
profileKeyVersion,
|
|
|
|
profileKeyCredentialRequest,
|
|
|
|
} = options;
|
|
|
|
|
2018-10-18 01:01:21 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'profile',
|
|
|
|
httpType: 'GET',
|
2020-04-15 23:12:28 +00:00
|
|
|
urlParameters: getProfileUrl(
|
|
|
|
identifier,
|
|
|
|
profileKeyVersion,
|
|
|
|
profileKeyCredentialRequest
|
|
|
|
),
|
2018-10-18 01:01:21 +00:00
|
|
|
responseType: 'json',
|
|
|
|
unauthenticated: true,
|
|
|
|
accessKey,
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl: _createRedactor(
|
|
|
|
identifier,
|
|
|
|
profileKeyVersion,
|
|
|
|
profileKeyCredentialRequest
|
|
|
|
),
|
2018-10-18 01:01:21 +00:00
|
|
|
});
|
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function getAvatar(path: string) {
|
2018-05-26 01:01:56 +00:00
|
|
|
// Using _outerAJAX, since it's not hardcoded to the Signal Server. Unlike our
|
|
|
|
// attachment CDN, it uses our self-signed certificate, so we pass it in.
|
2020-04-17 22:51:39 +00:00
|
|
|
return _outerAjax(`${cdnUrlObject['0']}/${path}`, {
|
2018-05-26 01:01:56 +00:00
|
|
|
certificateAuthority,
|
|
|
|
contentType: 'application/octet-stream',
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
timeout: 0,
|
|
|
|
type: 'GET',
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl: (href: string) => {
|
|
|
|
const pattern = RegExp(escapeRegExp(path), 'g');
|
|
|
|
return href.replace(pattern, `[REDACTED]${path.slice(-3)}`);
|
|
|
|
},
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2018-05-26 01:01:56 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-27 20:17:05 +00:00
|
|
|
async function reportMessage(
|
|
|
|
senderE164: string,
|
|
|
|
serverGuid: string
|
|
|
|
): Promise<void> {
|
|
|
|
await _ajax({
|
|
|
|
call: 'reportMessage',
|
|
|
|
httpType: 'POST',
|
|
|
|
urlParameters: `/${senderE164}/${serverGuid}`,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function requestVerificationSMS(number: string) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'accounts',
|
|
|
|
httpType: 'GET',
|
|
|
|
urlParameters: `/sms/code/${number}`,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function requestVerificationVoice(number: string) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'accounts',
|
|
|
|
httpType: 'GET',
|
|
|
|
urlParameters: `/voice/code/${number}`,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function confirmCode(
|
2020-03-31 20:03:38 +00:00
|
|
|
number: string,
|
|
|
|
code: string,
|
|
|
|
newPassword: string,
|
2020-04-13 17:37:29 +00:00
|
|
|
registrationId: number,
|
|
|
|
deviceName?: string | null,
|
|
|
|
options: { accessKey?: ArrayBuffer } = {}
|
2018-05-26 01:01:56 +00:00
|
|
|
) {
|
2020-11-20 17:30:45 +00:00
|
|
|
const capabilities: CapabilitiesUploadType = {
|
|
|
|
'gv2-3': true,
|
|
|
|
'gv1-migration': true,
|
2021-06-01 19:40:09 +00:00
|
|
|
senderKey: false,
|
2020-11-20 17:30:45 +00:00
|
|
|
};
|
|
|
|
|
2018-10-18 01:01:21 +00:00
|
|
|
const { accessKey } = options;
|
2020-03-31 20:03:38 +00:00
|
|
|
const jsonData: any = {
|
2020-11-20 17:30:45 +00:00
|
|
|
capabilities,
|
2018-05-26 01:01:56 +00:00
|
|
|
fetchesMessages: true,
|
2020-09-24 21:53:21 +00:00
|
|
|
name: deviceName || undefined,
|
2018-05-26 01:01:56 +00:00
|
|
|
registrationId,
|
2020-05-05 19:46:42 +00:00
|
|
|
supportsSms: false,
|
2018-10-18 01:01:21 +00:00
|
|
|
unidentifiedAccessKey: accessKey
|
|
|
|
? _btoa(_getString(accessKey))
|
|
|
|
: undefined,
|
|
|
|
unrestrictedUnidentifiedAccess: false,
|
2018-05-26 01:01:56 +00:00
|
|
|
};
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
const call = deviceName ? 'devices' : 'accounts';
|
|
|
|
const urlPrefix = deviceName ? '/' : '/code/';
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
// We update our saved username and password, since we're creating a new account
|
|
|
|
username = number;
|
|
|
|
password = newPassword;
|
|
|
|
|
|
|
|
const response = await _ajax({
|
|
|
|
call,
|
|
|
|
httpType: 'PUT',
|
2020-03-05 21:14:58 +00:00
|
|
|
responseType: 'json',
|
2018-05-26 01:01:56 +00:00
|
|
|
urlParameters: urlPrefix + code,
|
|
|
|
jsonData,
|
|
|
|
});
|
|
|
|
|
2020-03-05 21:14:58 +00:00
|
|
|
// From here on out, our username will be our UUID or E164 combined with device
|
|
|
|
username = `${response.uuid || number}.${response.deviceId || 1}`;
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function updateDeviceName(deviceName: string) {
|
2018-12-13 19:12:33 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'updateDeviceName',
|
|
|
|
httpType: 'PUT',
|
|
|
|
jsonData: {
|
|
|
|
deviceName,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-06-04 18:16:19 +00:00
|
|
|
async function getIceServers() {
|
|
|
|
return _ajax({
|
|
|
|
call: 'getIceServers',
|
|
|
|
httpType: 'GET',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function removeSignalingKey() {
|
2019-01-11 16:53:35 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'removeSignalingKey',
|
|
|
|
httpType: 'DELETE',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function getDevices() {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'devices',
|
|
|
|
httpType: 'GET',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type JSONSignedPreKeyType = {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: string;
|
|
|
|
signature: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
type JSONKeysType = {
|
|
|
|
identityKey: string;
|
|
|
|
signedPreKey: JSONSignedPreKeyType;
|
|
|
|
preKeys: Array<{
|
|
|
|
keyId: number;
|
|
|
|
publicKey: string;
|
|
|
|
}>;
|
|
|
|
lastResortKey: {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: string;
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
async function registerKeys(genKeys: KeysType) {
|
|
|
|
const preKeys = genKeys.preKeys.map(key => ({
|
|
|
|
keyId: key.keyId,
|
|
|
|
publicKey: _btoa(_getString(key.publicKey)),
|
|
|
|
}));
|
|
|
|
|
|
|
|
const keys: JSONKeysType = {
|
|
|
|
identityKey: _btoa(_getString(genKeys.identityKey)),
|
|
|
|
signedPreKey: {
|
|
|
|
keyId: genKeys.signedPreKey.keyId,
|
|
|
|
publicKey: _btoa(_getString(genKeys.signedPreKey.publicKey)),
|
|
|
|
signature: _btoa(_getString(genKeys.signedPreKey.signature)),
|
|
|
|
},
|
|
|
|
preKeys,
|
|
|
|
// This is just to make the server happy (v2 clients should choke on publicKey)
|
|
|
|
lastResortKey: {
|
|
|
|
keyId: 0x7fffffff,
|
|
|
|
publicKey: _btoa('42'),
|
|
|
|
},
|
|
|
|
};
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'keys',
|
|
|
|
httpType: 'PUT',
|
|
|
|
jsonData: keys,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function setSignedPreKey(signedPreKey: SignedPreKeyType) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'signed',
|
|
|
|
httpType: 'PUT',
|
|
|
|
jsonData: {
|
|
|
|
keyId: signedPreKey.keyId,
|
|
|
|
publicKey: _btoa(_getString(signedPreKey.publicKey)),
|
|
|
|
signature: _btoa(_getString(signedPreKey.signature)),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type ServerKeyCountType = {
|
|
|
|
count: number;
|
|
|
|
};
|
|
|
|
|
|
|
|
async function getMyKeys(): Promise<number> {
|
|
|
|
const result: ServerKeyCountType = await _ajax({
|
2018-05-26 01:01:56 +00:00
|
|
|
call: 'keys',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
validateResponse: { count: 'number' },
|
2020-03-31 20:03:38 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return result.count;
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type ServerKeyResponseType = {
|
|
|
|
devices: Array<{
|
|
|
|
deviceId: number;
|
|
|
|
registrationId: number;
|
|
|
|
signedPreKey: {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: string;
|
|
|
|
signature: string;
|
|
|
|
};
|
|
|
|
preKey?: {
|
|
|
|
keyId: number;
|
|
|
|
publicKey: string;
|
|
|
|
};
|
|
|
|
}>;
|
|
|
|
identityKey: string;
|
|
|
|
};
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
function handleKeys(res: ServerKeyResponseType): ServerKeysType {
|
2018-10-18 01:01:21 +00:00
|
|
|
if (!Array.isArray(res.devices)) {
|
|
|
|
throw new Error('Invalid response');
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
const devices = res.devices.map(device => {
|
2018-10-18 01:01:21 +00:00
|
|
|
if (
|
|
|
|
!_validateResponse(device, { signedPreKey: 'object' }) ||
|
|
|
|
!_validateResponse(device.signedPreKey, {
|
|
|
|
publicKey: 'string',
|
|
|
|
signature: 'string',
|
|
|
|
})
|
|
|
|
) {
|
|
|
|
throw new Error('Invalid signedPreKey');
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
let preKey;
|
2018-10-18 01:01:21 +00:00
|
|
|
if (device.preKey) {
|
|
|
|
if (
|
|
|
|
!_validateResponse(device, { preKey: 'object' }) ||
|
|
|
|
!_validateResponse(device.preKey, { publicKey: 'string' })
|
|
|
|
) {
|
|
|
|
throw new Error('Invalid preKey');
|
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
preKey = {
|
|
|
|
keyId: device.preKey.keyId,
|
|
|
|
publicKey: _base64ToBytes(device.preKey.publicKey),
|
|
|
|
};
|
2018-10-18 01:01:21 +00:00
|
|
|
}
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
deviceId: device.deviceId,
|
|
|
|
registrationId: device.registrationId,
|
|
|
|
preKey,
|
|
|
|
signedPreKey: {
|
|
|
|
keyId: device.signedPreKey.keyId,
|
|
|
|
publicKey: _base64ToBytes(device.signedPreKey.publicKey),
|
|
|
|
signature: _base64ToBytes(device.signedPreKey.signature),
|
|
|
|
},
|
|
|
|
};
|
2018-10-18 01:01:21 +00:00
|
|
|
});
|
2020-03-31 20:03:38 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
devices,
|
|
|
|
identityKey: _base64ToBytes(res.identityKey),
|
|
|
|
};
|
2018-10-18 01:01:21 +00:00
|
|
|
}
|
|
|
|
|
2020-04-13 17:37:29 +00:00
|
|
|
async function getKeysForIdentifier(identifier: string, deviceId?: number) {
|
2018-05-26 01:01:56 +00:00
|
|
|
return _ajax({
|
|
|
|
call: 'keys',
|
|
|
|
httpType: 'GET',
|
2020-04-13 17:37:29 +00:00
|
|
|
urlParameters: `/${identifier}/${deviceId || '*'}`,
|
2018-05-26 01:01:56 +00:00
|
|
|
responseType: 'json',
|
|
|
|
validateResponse: { identityKey: 'string', devices: 'object' },
|
2018-10-18 01:01:21 +00:00
|
|
|
}).then(handleKeys);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function getKeysForIdentifierUnauth(
|
|
|
|
identifier: string,
|
2020-04-13 17:37:29 +00:00
|
|
|
deviceId?: number,
|
2020-03-31 20:03:38 +00:00
|
|
|
{ accessKey }: { accessKey?: string } = {}
|
2018-10-18 01:01:21 +00:00
|
|
|
) {
|
|
|
|
return _ajax({
|
|
|
|
call: 'keys',
|
|
|
|
httpType: 'GET',
|
2020-04-13 17:37:29 +00:00
|
|
|
urlParameters: `/${identifier}/${deviceId || '*'}`,
|
2018-10-18 01:01:21 +00:00
|
|
|
responseType: 'json',
|
|
|
|
validateResponse: { identityKey: 'string', devices: 'object' },
|
|
|
|
unauthenticated: true,
|
|
|
|
accessKey,
|
|
|
|
}).then(handleKeys);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function sendMessagesUnauth(
|
|
|
|
destination: string,
|
|
|
|
messageArray: Array<MessageType>,
|
|
|
|
timestamp: number,
|
2020-04-13 17:37:29 +00:00
|
|
|
online?: boolean,
|
2020-03-31 20:03:38 +00:00
|
|
|
{ accessKey }: { accessKey?: string } = {}
|
2018-10-18 01:01:21 +00:00
|
|
|
) {
|
2020-03-31 20:03:38 +00:00
|
|
|
const jsonData: any = { messages: messageArray, timestamp };
|
2018-10-18 01:01:21 +00:00
|
|
|
|
2018-11-14 19:10:32 +00:00
|
|
|
if (online) {
|
|
|
|
jsonData.online = true;
|
|
|
|
}
|
2018-10-18 01:01:21 +00:00
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'messages',
|
|
|
|
httpType: 'PUT',
|
|
|
|
urlParameters: `/${destination}`,
|
|
|
|
jsonData,
|
|
|
|
responseType: 'json',
|
|
|
|
unauthenticated: true,
|
|
|
|
accessKey,
|
2018-05-26 01:01:56 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function sendMessages(
|
|
|
|
destination: string,
|
|
|
|
messageArray: Array<MessageType>,
|
|
|
|
timestamp: number,
|
2020-04-13 17:37:29 +00:00
|
|
|
online?: boolean
|
2018-11-14 19:10:32 +00:00
|
|
|
) {
|
2020-03-31 20:03:38 +00:00
|
|
|
const jsonData: any = { messages: messageArray, timestamp };
|
2018-05-26 01:01:56 +00:00
|
|
|
|
2018-11-14 19:10:32 +00:00
|
|
|
if (online) {
|
|
|
|
jsonData.online = true;
|
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
|
|
|
|
return _ajax({
|
|
|
|
call: 'messages',
|
|
|
|
httpType: 'PUT',
|
|
|
|
urlParameters: `/${destination}`,
|
|
|
|
jsonData,
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-25 22:40:04 +00:00
|
|
|
async function sendWithSenderKey(
|
|
|
|
data: ArrayBuffer,
|
|
|
|
accessKeys: ArrayBuffer,
|
|
|
|
timestamp: number,
|
|
|
|
online?: boolean
|
|
|
|
): Promise<MultiRecipient200ResponseType> {
|
|
|
|
return _ajax({
|
|
|
|
call: 'multiRecipient',
|
|
|
|
httpType: 'PUT',
|
|
|
|
contentType: 'application/vnd.signal-messenger.mrm',
|
|
|
|
data,
|
|
|
|
urlParameters: `?ts=${timestamp}&online=${online ? 'true' : 'false'}`,
|
|
|
|
responseType: 'json',
|
|
|
|
headers: {
|
|
|
|
'Unidentified-Access-Key': arrayBufferToBase64(accessKeys),
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
function redactStickerUrl(stickerUrl: string) {
|
2019-05-16 22:32:11 +00:00
|
|
|
return stickerUrl.replace(
|
|
|
|
/(\/stickers\/)([^/]+)(\/)/,
|
2020-03-31 20:03:38 +00:00
|
|
|
(_, begin: string, packId: string, end: string) =>
|
|
|
|
`${begin}${redactPackId(packId)}${end}`
|
2019-05-16 22:32:11 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-09-24 21:53:21 +00:00
|
|
|
async function getSticker(packId: string, stickerId: number) {
|
2020-08-31 16:29:22 +00:00
|
|
|
if (!isPackIdValid(packId)) {
|
|
|
|
throw new Error('getSticker: pack ID was invalid');
|
|
|
|
}
|
2020-04-17 22:51:39 +00:00
|
|
|
return _outerAjax(
|
|
|
|
`${cdnUrlObject['0']}/stickers/${packId}/full/${stickerId}`,
|
|
|
|
{
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
type: 'GET',
|
|
|
|
redactUrl: redactStickerUrl,
|
|
|
|
version,
|
|
|
|
}
|
|
|
|
);
|
2019-05-16 22:32:11 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function getStickerPackManifest(packId: string) {
|
2020-08-31 16:29:22 +00:00
|
|
|
if (!isPackIdValid(packId)) {
|
|
|
|
throw new Error('getStickerPackManifest: pack ID was invalid');
|
|
|
|
}
|
2020-04-17 22:51:39 +00:00
|
|
|
return _outerAjax(
|
|
|
|
`${cdnUrlObject['0']}/stickers/${packId}/manifest.proto`,
|
|
|
|
{
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
type: 'GET',
|
|
|
|
redactUrl: redactStickerUrl,
|
|
|
|
version,
|
|
|
|
}
|
|
|
|
);
|
2019-05-16 22:32:11 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
type ServerAttachmentType = {
|
|
|
|
key: string;
|
|
|
|
credential: string;
|
|
|
|
acl: string;
|
|
|
|
algorithm: string;
|
|
|
|
date: string;
|
|
|
|
policy: string;
|
|
|
|
signature: string;
|
|
|
|
};
|
|
|
|
|
2019-12-17 20:25:57 +00:00
|
|
|
function makePutParams(
|
2020-03-31 20:03:38 +00:00
|
|
|
{
|
|
|
|
key,
|
|
|
|
credential,
|
|
|
|
acl,
|
|
|
|
algorithm,
|
|
|
|
date,
|
|
|
|
policy,
|
|
|
|
signature,
|
|
|
|
}: ServerAttachmentType,
|
|
|
|
encryptedBin: ArrayBuffer
|
2019-12-17 20:25:57 +00:00
|
|
|
) {
|
2019-05-08 20:14:52 +00:00
|
|
|
// Note: when using the boundary string in the POST body, it needs to be prefixed by
|
|
|
|
// an extra --, and the final boundary string at the end gets a -- prefix and a --
|
|
|
|
// suffix.
|
|
|
|
const boundaryString = `----------------${getGuid().replace(/-/g, '')}`;
|
|
|
|
const CRLF = '\r\n';
|
2020-03-31 20:03:38 +00:00
|
|
|
const getSection = (name: string, value: string) =>
|
2019-05-08 20:14:52 +00:00
|
|
|
[
|
|
|
|
`--${boundaryString}`,
|
|
|
|
`Content-Disposition: form-data; name="${name}"${CRLF}`,
|
|
|
|
value,
|
|
|
|
].join(CRLF);
|
|
|
|
|
|
|
|
const start = [
|
|
|
|
getSection('key', key),
|
|
|
|
getSection('x-amz-credential', credential),
|
|
|
|
getSection('acl', acl),
|
|
|
|
getSection('x-amz-algorithm', algorithm),
|
|
|
|
getSection('x-amz-date', date),
|
|
|
|
getSection('policy', policy),
|
|
|
|
getSection('x-amz-signature', signature),
|
|
|
|
getSection('Content-Type', 'application/octet-stream'),
|
|
|
|
`--${boundaryString}`,
|
|
|
|
'Content-Disposition: form-data; name="file"',
|
|
|
|
`Content-Type: application/octet-stream${CRLF}${CRLF}`,
|
|
|
|
].join(CRLF);
|
|
|
|
const end = `${CRLF}--${boundaryString}--${CRLF}`;
|
|
|
|
|
|
|
|
const startBuffer = Buffer.from(start, 'utf8');
|
|
|
|
const attachmentBuffer = Buffer.from(encryptedBin);
|
|
|
|
const endBuffer = Buffer.from(end, 'utf8');
|
|
|
|
|
|
|
|
const contentLength =
|
|
|
|
startBuffer.length + attachmentBuffer.length + endBuffer.length;
|
|
|
|
const data = Buffer.concat(
|
|
|
|
[startBuffer, attachmentBuffer, endBuffer],
|
|
|
|
contentLength
|
2018-05-26 01:01:56 +00:00
|
|
|
);
|
2019-05-08 20:14:52 +00:00
|
|
|
|
2019-12-17 20:25:57 +00:00
|
|
|
return {
|
|
|
|
data,
|
|
|
|
contentType: `multipart/form-data; boundary=${boundaryString}`,
|
|
|
|
headers: {
|
2020-03-31 20:03:38 +00:00
|
|
|
'Content-Length': contentLength.toString(),
|
2019-12-17 20:25:57 +00:00
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function putStickers(
|
2020-03-31 20:03:38 +00:00
|
|
|
encryptedManifest: ArrayBuffer,
|
|
|
|
encryptedStickers: Array<ArrayBuffer>,
|
|
|
|
onProgress?: () => void
|
2019-12-17 20:25:57 +00:00
|
|
|
) {
|
|
|
|
// Get manifest and sticker upload parameters
|
|
|
|
const { packId, manifest, stickers } = await _ajax({
|
|
|
|
call: 'getStickerPackUpload',
|
|
|
|
responseType: 'json',
|
2020-03-31 20:03:38 +00:00
|
|
|
httpType: 'GET',
|
2019-12-17 20:25:57 +00:00
|
|
|
urlParameters: `/${encryptedStickers.length}`,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Upload manifest
|
|
|
|
const manifestParams = makePutParams(manifest, encryptedManifest);
|
|
|
|
// This is going to the CDN, not the service, so we use _outerAjax
|
2020-04-17 22:51:39 +00:00
|
|
|
await _outerAjax(`${cdnUrlObject['0']}/`, {
|
2019-12-17 20:25:57 +00:00
|
|
|
...manifestParams,
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
timeout: 0,
|
|
|
|
type: 'POST',
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2019-12-17 20:25:57 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// Upload stickers
|
2020-09-18 20:40:41 +00:00
|
|
|
const queue = new PQueue({ concurrency: 3, timeout: 1000 * 60 * 2 });
|
2019-12-17 20:25:57 +00:00
|
|
|
await Promise.all(
|
2020-03-31 20:03:38 +00:00
|
|
|
stickers.map(async (sticker: ServerAttachmentType, index: number) => {
|
|
|
|
const stickerParams = makePutParams(
|
|
|
|
sticker,
|
|
|
|
encryptedStickers[index]
|
|
|
|
);
|
2019-12-19 23:27:02 +00:00
|
|
|
await queue.add(async () =>
|
2020-04-17 22:51:39 +00:00
|
|
|
_outerAjax(`${cdnUrlObject['0']}/`, {
|
2019-12-19 23:27:02 +00:00
|
|
|
...stickerParams,
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
timeout: 0,
|
|
|
|
type: 'POST',
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2019-12-19 23:27:02 +00:00
|
|
|
})
|
|
|
|
);
|
2019-12-17 20:25:57 +00:00
|
|
|
if (onProgress) {
|
|
|
|
onProgress();
|
|
|
|
}
|
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
// Done!
|
|
|
|
return packId;
|
|
|
|
}
|
|
|
|
|
2021-06-17 17:15:10 +00:00
|
|
|
async function getAttachment(cdnKey: string, cdnNumber?: number) {
|
|
|
|
const cdnUrl = isNumber(cdnNumber)
|
|
|
|
? cdnUrlObject[cdnNumber] || cdnUrlObject['0']
|
|
|
|
: cdnUrlObject['0'];
|
2019-12-17 20:25:57 +00:00
|
|
|
// This is going to the CDN, not the service, so we use _outerAjax
|
2020-04-17 22:51:39 +00:00
|
|
|
return _outerAjax(`${cdnUrl}/attachments/${cdnKey}`, {
|
2019-12-17 20:25:57 +00:00
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
timeout: 0,
|
|
|
|
type: 'GET',
|
2020-08-20 22:15:50 +00:00
|
|
|
redactUrl: _createRedactor(cdnKey),
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2019-12-17 20:25:57 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function putAttachment(encryptedBin: ArrayBuffer) {
|
2019-12-17 20:25:57 +00:00
|
|
|
const response = await _ajax({
|
|
|
|
call: 'attachmentId',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
|
|
|
|
const { attachmentIdString } = response;
|
|
|
|
|
|
|
|
const params = makePutParams(response, encryptedBin);
|
|
|
|
|
2019-05-08 20:14:52 +00:00
|
|
|
// This is going to the CDN, not the service, so we use _outerAjax
|
2020-04-17 22:51:39 +00:00
|
|
|
await _outerAjax(`${cdnUrlObject['0']}/attachments/`, {
|
2019-12-17 20:25:57 +00:00
|
|
|
...params,
|
2019-05-08 20:14:52 +00:00
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
timeout: 0,
|
|
|
|
type: 'POST',
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2019-05-08 20:14:52 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return attachmentIdString;
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
|
2019-05-16 22:32:11 +00:00
|
|
|
function getHeaderPadding() {
|
2020-03-31 20:03:38 +00:00
|
|
|
const max = getRandomValue(1, 64);
|
2019-05-16 22:32:11 +00:00
|
|
|
let characters = '';
|
2019-01-16 03:03:56 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
for (let i = 0; i < max; i += 1) {
|
|
|
|
characters += String.fromCharCode(getRandomValue(65, 122));
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2019-05-16 22:32:11 +00:00
|
|
|
return characters;
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2020-09-28 23:46:31 +00:00
|
|
|
async function fetchLinkPreviewMetadata(
|
|
|
|
href: string,
|
|
|
|
abortSignal: AbortSignal
|
|
|
|
) {
|
|
|
|
return linkPreviewFetch.fetchLinkPreviewMetadata(
|
|
|
|
fetch,
|
|
|
|
href,
|
|
|
|
abortSignal
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchLinkPreviewImage(
|
|
|
|
href: string,
|
|
|
|
abortSignal: AbortSignal
|
|
|
|
) {
|
|
|
|
return linkPreviewFetch.fetchLinkPreviewImage(fetch, href, abortSignal);
|
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
async function makeProxiedRequest(
|
|
|
|
targetUrl: string,
|
|
|
|
options: ProxiedRequestOptionsType = {}
|
|
|
|
) {
|
2019-01-16 03:03:56 +00:00
|
|
|
const { returnArrayBuffer, start, end } = options;
|
2020-03-31 20:03:38 +00:00
|
|
|
const headers: HeaderListType = {
|
2019-05-16 22:32:11 +00:00
|
|
|
'X-SignalPadding': getHeaderPadding(),
|
|
|
|
};
|
2019-01-16 03:03:56 +00:00
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
if (is.number(start) && is.number(end)) {
|
2019-05-16 22:32:11 +00:00
|
|
|
headers.Range = `bytes=${start}-${end}`;
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2020-03-31 20:03:38 +00:00
|
|
|
const result = await _outerAjax(targetUrl, {
|
|
|
|
responseType: returnArrayBuffer ? 'arraybufferwithdetails' : undefined,
|
2019-01-16 03:03:56 +00:00
|
|
|
proxyUrl: contentProxyUrl,
|
|
|
|
type: 'GET',
|
|
|
|
redirect: 'follow',
|
2019-05-16 22:32:11 +00:00
|
|
|
redactUrl: () => '[REDACTED_URL]',
|
2019-01-16 03:03:56 +00:00
|
|
|
headers,
|
2020-01-17 00:53:35 +00:00
|
|
|
version,
|
2019-01-16 03:03:56 +00:00
|
|
|
});
|
2019-05-16 22:32:11 +00:00
|
|
|
|
|
|
|
if (!returnArrayBuffer) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
const { response } = result as ArrayBufferWithDetailsType;
|
2019-05-16 22:32:11 +00:00
|
|
|
if (!response.headers || !response.headers.get) {
|
|
|
|
throw new Error('makeProxiedRequest: Problem retrieving header value');
|
|
|
|
}
|
|
|
|
|
|
|
|
const range = response.headers.get('content-range');
|
2020-09-09 02:25:05 +00:00
|
|
|
const match = PARSE_RANGE_HEADER.exec(range || '');
|
2019-05-16 22:32:11 +00:00
|
|
|
|
|
|
|
if (!match || !match[1]) {
|
|
|
|
throw new Error(
|
|
|
|
`makeProxiedRequest: Unable to parse total size from ${range}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const totalSize = parseInt(match[1], 10);
|
|
|
|
|
|
|
|
return {
|
|
|
|
totalSize,
|
|
|
|
result,
|
|
|
|
};
|
2019-01-16 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2020-11-13 19:57:55 +00:00
|
|
|
async function makeSfuRequest(
|
|
|
|
targetUrl: string,
|
|
|
|
type: HTTPCodeType,
|
|
|
|
headers: HeaderListType,
|
|
|
|
body: ArrayBuffer | undefined
|
|
|
|
): Promise<ArrayBufferWithDetailsType> {
|
|
|
|
return _outerAjax(targetUrl, {
|
|
|
|
certificateAuthority,
|
|
|
|
data: body,
|
|
|
|
headers,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybufferwithdetails',
|
|
|
|
timeout: 0,
|
|
|
|
type,
|
|
|
|
version,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
// Groups
|
|
|
|
|
|
|
|
function generateGroupAuth(
|
|
|
|
groupPublicParamsHex: string,
|
|
|
|
authCredentialPresentationHex: string
|
|
|
|
) {
|
|
|
|
return _btoa(`${groupPublicParamsHex}:${authCredentialPresentationHex}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
type CredentialResponseType = {
|
|
|
|
credentials: Array<GroupCredentialType>;
|
|
|
|
};
|
|
|
|
|
|
|
|
async function getGroupCredentials(
|
|
|
|
startDay: number,
|
|
|
|
endDay: number
|
|
|
|
): Promise<Array<GroupCredentialType>> {
|
|
|
|
const response: CredentialResponseType = await _ajax({
|
|
|
|
call: 'getGroupCredentials',
|
|
|
|
urlParameters: `/${startDay}/${endDay}`,
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
|
|
|
|
return response.credentials;
|
|
|
|
}
|
|
|
|
|
2020-11-13 19:57:55 +00:00
|
|
|
async function getGroupExternalCredential(
|
|
|
|
options: GroupCredentialsType
|
|
|
|
): Promise<GroupExternalCredentialClass> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
|
|
|
|
const response: ArrayBuffer = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groupToken',
|
|
|
|
httpType: 'GET',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
host: storageUrl,
|
|
|
|
});
|
|
|
|
|
|
|
|
return window.textsecure.protobuf.GroupExternalCredential.decode(
|
|
|
|
response
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
function verifyAttributes(attributes: AvatarUploadAttributesClass) {
|
|
|
|
const {
|
|
|
|
key,
|
|
|
|
credential,
|
|
|
|
acl,
|
|
|
|
algorithm,
|
|
|
|
date,
|
|
|
|
policy,
|
|
|
|
signature,
|
|
|
|
} = attributes;
|
|
|
|
|
|
|
|
if (
|
|
|
|
!key ||
|
|
|
|
!credential ||
|
|
|
|
!acl ||
|
|
|
|
!algorithm ||
|
|
|
|
!date ||
|
|
|
|
!policy ||
|
|
|
|
!signature
|
|
|
|
) {
|
|
|
|
throw new Error(
|
|
|
|
'verifyAttributes: Missing value from AvatarUploadAttributes'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
key,
|
|
|
|
credential,
|
|
|
|
acl,
|
|
|
|
algorithm,
|
|
|
|
date,
|
|
|
|
policy,
|
|
|
|
signature,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function uploadGroupAvatar(
|
|
|
|
avatarData: ArrayBuffer,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
): Promise<string> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
|
|
|
|
const response: ArrayBuffer = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'getGroupAvatarUpload',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
host: storageUrl,
|
|
|
|
});
|
|
|
|
const attributes = window.textsecure.protobuf.AvatarUploadAttributes.decode(
|
|
|
|
response
|
|
|
|
);
|
|
|
|
|
|
|
|
const verified = verifyAttributes(attributes);
|
|
|
|
const { key } = verified;
|
|
|
|
|
|
|
|
const manifestParams = makePutParams(verified, avatarData);
|
|
|
|
|
|
|
|
await _outerAjax(`${cdnUrlObject['0']}/`, {
|
|
|
|
...manifestParams,
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
timeout: 0,
|
|
|
|
type: 'POST',
|
|
|
|
version,
|
|
|
|
});
|
|
|
|
|
|
|
|
return key;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getGroupAvatar(key: string): Promise<ArrayBuffer> {
|
|
|
|
return _outerAjax(`${cdnUrlObject['0']}/${key}`, {
|
|
|
|
certificateAuthority,
|
|
|
|
proxyUrl,
|
|
|
|
responseType: 'arraybuffer',
|
|
|
|
timeout: 0,
|
|
|
|
type: 'GET',
|
|
|
|
version,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function createGroup(
|
|
|
|
group: GroupClass,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
): Promise<void> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
const data = group.toArrayBuffer();
|
|
|
|
|
|
|
|
await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groups',
|
2020-11-20 17:30:45 +00:00
|
|
|
contentType: 'application/x-protobuf',
|
2020-09-09 02:25:05 +00:00
|
|
|
data,
|
|
|
|
host: storageUrl,
|
2020-11-20 17:30:45 +00:00
|
|
|
httpType: 'PUT',
|
2020-09-09 02:25:05 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getGroup(
|
|
|
|
options: GroupCredentialsType
|
|
|
|
): Promise<GroupClass> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
|
|
|
|
const response: ArrayBuffer = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groups',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
host: storageUrl,
|
2020-11-20 17:30:45 +00:00
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'arraybuffer',
|
2020-09-09 02:25:05 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return window.textsecure.protobuf.Group.decode(response);
|
|
|
|
}
|
|
|
|
|
2021-01-29 22:16:48 +00:00
|
|
|
async function getGroupFromLink(
|
|
|
|
inviteLinkPassword: string,
|
|
|
|
auth: GroupCredentialsType
|
|
|
|
): Promise<GroupJoinInfoClass> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
auth.groupPublicParamsHex,
|
|
|
|
auth.authCredentialPresentationHex
|
|
|
|
);
|
2021-05-06 19:06:20 +00:00
|
|
|
const safeInviteLinkPassword = toWebSafeBase64(inviteLinkPassword);
|
2021-01-29 22:16:48 +00:00
|
|
|
|
|
|
|
const response: ArrayBuffer = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groupsViaLink',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
host: storageUrl,
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'arraybuffer',
|
2021-05-06 19:06:20 +00:00
|
|
|
urlParameters: `/${safeInviteLinkPassword}`,
|
|
|
|
redactUrl: _createRedactor(safeInviteLinkPassword),
|
2021-01-29 22:16:48 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return window.textsecure.protobuf.GroupJoinInfo.decode(response);
|
|
|
|
}
|
|
|
|
|
2020-09-09 02:25:05 +00:00
|
|
|
async function modifyGroup(
|
|
|
|
changes: GroupChangeClass.Actions,
|
2021-01-29 22:16:48 +00:00
|
|
|
options: GroupCredentialsType,
|
|
|
|
inviteLinkBase64?: string
|
2020-09-09 02:25:05 +00:00
|
|
|
): Promise<GroupChangeClass> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
const data = changes.toArrayBuffer();
|
2021-05-06 19:06:20 +00:00
|
|
|
const safeInviteLinkPassword = inviteLinkBase64
|
|
|
|
? toWebSafeBase64(inviteLinkBase64)
|
|
|
|
: undefined;
|
2020-09-09 02:25:05 +00:00
|
|
|
|
|
|
|
const response: ArrayBuffer = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groups',
|
|
|
|
contentType: 'application/x-protobuf',
|
2020-11-20 17:30:45 +00:00
|
|
|
data,
|
2020-09-09 02:25:05 +00:00
|
|
|
host: storageUrl,
|
2020-11-20 17:30:45 +00:00
|
|
|
httpType: 'PATCH',
|
|
|
|
responseType: 'arraybuffer',
|
2021-05-06 19:06:20 +00:00
|
|
|
urlParameters: safeInviteLinkPassword
|
|
|
|
? `?inviteLinkPassword=${safeInviteLinkPassword}`
|
|
|
|
: undefined,
|
|
|
|
redactUrl: safeInviteLinkPassword
|
|
|
|
? _createRedactor(safeInviteLinkPassword)
|
2021-01-29 22:16:48 +00:00
|
|
|
: undefined,
|
2020-09-09 02:25:05 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return window.textsecure.protobuf.GroupChange.decode(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getGroupLog(
|
|
|
|
startVersion: number,
|
|
|
|
options: GroupCredentialsType
|
|
|
|
): Promise<GroupLogResponseType> {
|
|
|
|
const basicAuth = generateGroupAuth(
|
|
|
|
options.groupPublicParamsHex,
|
|
|
|
options.authCredentialPresentationHex
|
|
|
|
);
|
|
|
|
|
|
|
|
const withDetails: ArrayBufferWithDetailsType = await _ajax({
|
|
|
|
basicAuth,
|
|
|
|
call: 'groupLog',
|
|
|
|
contentType: 'application/x-protobuf',
|
|
|
|
host: storageUrl,
|
2020-11-20 17:30:45 +00:00
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'arraybufferwithdetails',
|
|
|
|
urlParameters: `/${startVersion}`,
|
2020-09-09 02:25:05 +00:00
|
|
|
});
|
|
|
|
const { data, response } = withDetails;
|
|
|
|
const changes = window.textsecure.protobuf.GroupChanges.decode(data);
|
|
|
|
|
|
|
|
if (response && response.status === 206) {
|
|
|
|
const range = response.headers.get('Content-Range');
|
|
|
|
const match = PARSE_GROUP_LOG_RANGE_HEADER.exec(range || '');
|
|
|
|
|
|
|
|
const start = match ? parseInt(match[0], 10) : undefined;
|
|
|
|
const end = match ? parseInt(match[1], 10) : undefined;
|
|
|
|
const currentRevision = match ? parseInt(match[2], 10) : undefined;
|
|
|
|
|
|
|
|
if (
|
|
|
|
match &&
|
|
|
|
is.number(start) &&
|
|
|
|
is.number(end) &&
|
|
|
|
is.number(currentRevision)
|
|
|
|
) {
|
|
|
|
return {
|
|
|
|
changes,
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
currentRevision,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
changes,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
function getMessageSocket(): Promise<WebSocket> {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info('opening message socket', url);
|
2018-05-26 01:01:56 +00:00
|
|
|
const fixedScheme = url
|
|
|
|
.replace('https://', 'wss://')
|
|
|
|
.replace('http://', 'ws://');
|
|
|
|
const login = encodeURIComponent(username);
|
|
|
|
const pass = encodeURIComponent(password);
|
2020-01-17 00:53:35 +00:00
|
|
|
const clientVersion = encodeURIComponent(version);
|
2018-05-26 01:01:56 +00:00
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
return _connectSocket(
|
2020-01-17 00:53:35 +00:00
|
|
|
`${fixedScheme}/v1/websocket/?login=${login}&password=${pass}&agent=OWD&version=${clientVersion}`,
|
2020-09-09 22:50:44 +00:00
|
|
|
{ certificateAuthority, proxyUrl, version }
|
2018-05-26 01:01:56 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
function getProvisioningSocket(): Promise<WebSocket> {
|
2020-03-31 20:03:38 +00:00
|
|
|
window.log.info('opening provisioning socket', url);
|
2018-05-26 01:01:56 +00:00
|
|
|
const fixedScheme = url
|
|
|
|
.replace('https://', 'wss://')
|
|
|
|
.replace('http://', 'ws://');
|
2020-01-17 00:53:35 +00:00
|
|
|
const clientVersion = encodeURIComponent(version);
|
2018-05-26 01:01:56 +00:00
|
|
|
|
2021-06-09 22:28:54 +00:00
|
|
|
return _connectSocket(
|
2020-01-17 00:53:35 +00:00
|
|
|
`${fixedScheme}/v1/websocket/provisioning/?agent=OWD&version=${clientVersion}`,
|
2020-09-09 22:50:44 +00:00
|
|
|
{ certificateAuthority, proxyUrl, version }
|
2018-05-26 01:01:56 +00:00
|
|
|
);
|
|
|
|
}
|
2020-09-04 01:25:19 +00:00
|
|
|
|
|
|
|
async function getDirectoryAuth(): Promise<{
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
}> {
|
|
|
|
return _ajax({
|
|
|
|
call: 'directoryAuth',
|
|
|
|
httpType: 'GET',
|
|
|
|
responseType: 'json',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function validateAttestationQuote({
|
|
|
|
serverStaticPublic,
|
|
|
|
quote,
|
|
|
|
}: {
|
|
|
|
serverStaticPublic: ArrayBuffer;
|
|
|
|
quote: ArrayBuffer;
|
|
|
|
}) {
|
|
|
|
const SGX_CONSTANTS = getSgxConstants();
|
|
|
|
const byteBuffer = window.dcodeIO.ByteBuffer.wrap(
|
|
|
|
quote,
|
|
|
|
'binary',
|
|
|
|
window.dcodeIO.ByteBuffer.LITTLE_ENDIAN
|
|
|
|
);
|
|
|
|
|
|
|
|
const quoteVersion = byteBuffer.readShort(0) & 0xffff;
|
|
|
|
if (quoteVersion < 0 || quoteVersion > 2) {
|
|
|
|
throw new Error(`Unknown version ${quoteVersion}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const miscSelect = new Uint8Array(getBytes(quote, 64, 4));
|
|
|
|
if (!miscSelect.every(byte => byte === 0)) {
|
|
|
|
throw new Error('Quote miscSelect invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const reserved1 = new Uint8Array(getBytes(quote, 68, 28));
|
|
|
|
if (!reserved1.every(byte => byte === 0)) {
|
|
|
|
throw new Error('Quote reserved1 invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const flags = byteBuffer.readLong(96);
|
|
|
|
if (
|
|
|
|
flags.and(SGX_CONSTANTS.SGX_FLAGS_RESERVED).notEquals(0) ||
|
|
|
|
flags.and(SGX_CONSTANTS.SGX_FLAGS_INITTED).equals(0) ||
|
|
|
|
flags.and(SGX_CONSTANTS.SGX_FLAGS_MODE64BIT).equals(0)
|
|
|
|
) {
|
|
|
|
throw new Error(`Quote flags invalid ${flags.toString()}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const xfrm = byteBuffer.readLong(104);
|
|
|
|
if (xfrm.and(SGX_CONSTANTS.SGX_XFRM_RESERVED).notEquals(0)) {
|
|
|
|
throw new Error(`Quote xfrm invalid ${xfrm}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const mrenclave = new Uint8Array(getBytes(quote, 112, 32));
|
|
|
|
const enclaveIdBytes = new Uint8Array(
|
|
|
|
bytesFromHexString(directoryEnclaveId)
|
|
|
|
);
|
|
|
|
if (!mrenclave.every((byte, index) => byte === enclaveIdBytes[index])) {
|
|
|
|
throw new Error('Quote mrenclave invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const reserved2 = new Uint8Array(getBytes(quote, 144, 32));
|
|
|
|
if (!reserved2.every(byte => byte === 0)) {
|
|
|
|
throw new Error('Quote reserved2 invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const reportData = new Uint8Array(getBytes(quote, 368, 64));
|
|
|
|
const serverStaticPublicBytes = new Uint8Array(serverStaticPublic);
|
|
|
|
if (
|
|
|
|
!reportData.every((byte, index) => {
|
|
|
|
if (index >= 32) {
|
|
|
|
return byte === 0;
|
|
|
|
}
|
|
|
|
return byte === serverStaticPublicBytes[index];
|
|
|
|
})
|
|
|
|
) {
|
|
|
|
throw new Error('Quote report_data invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const reserved3 = new Uint8Array(getBytes(quote, 208, 96));
|
|
|
|
if (!reserved3.every(byte => byte === 0)) {
|
|
|
|
throw new Error('Quote reserved3 invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const reserved4 = new Uint8Array(getBytes(quote, 308, 60));
|
|
|
|
if (!reserved4.every(byte => byte === 0)) {
|
|
|
|
throw new Error('Quote reserved4 invalid!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const signatureLength = byteBuffer.readInt(432) & 0xffff_ffff;
|
|
|
|
if (signatureLength !== quote.byteLength - 436) {
|
|
|
|
throw new Error(`Bad signatureLength ${signatureLength}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// const signature = Uint8Array.from(getBytes(quote, 436, signatureLength));
|
|
|
|
}
|
|
|
|
|
|
|
|
function validateAttestationSignatureBody(
|
|
|
|
signatureBody: {
|
|
|
|
timestamp: string;
|
|
|
|
version: number;
|
|
|
|
isvEnclaveQuoteBody: string;
|
|
|
|
isvEnclaveQuoteStatus: string;
|
|
|
|
},
|
|
|
|
encodedQuote: string
|
|
|
|
) {
|
|
|
|
// Parse timestamp as UTC
|
|
|
|
const { timestamp } = signatureBody;
|
|
|
|
const utcTimestamp = timestamp.endsWith('Z')
|
|
|
|
? timestamp
|
|
|
|
: `${timestamp}Z`;
|
|
|
|
const signatureTime = new Date(utcTimestamp).getTime();
|
|
|
|
|
|
|
|
const now = Date.now();
|
|
|
|
if (signatureBody.version !== 3) {
|
|
|
|
throw new Error('Attestation signature invalid version!');
|
|
|
|
}
|
|
|
|
if (!encodedQuote.startsWith(signatureBody.isvEnclaveQuoteBody)) {
|
|
|
|
throw new Error('Attestion signature mismatches quote!');
|
|
|
|
}
|
|
|
|
if (signatureBody.isvEnclaveQuoteStatus !== 'OK') {
|
|
|
|
throw new Error('Attestation signature status not "OK"!');
|
|
|
|
}
|
|
|
|
if (signatureTime < now - 24 * 60 * 60 * 1000) {
|
|
|
|
throw new Error('Attestation signature timestamp older than 24 hours!');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function validateAttestationSignature(
|
|
|
|
signature: ArrayBuffer,
|
|
|
|
signatureBody: string,
|
|
|
|
certificates: string
|
|
|
|
) {
|
|
|
|
const CERT_PREFIX = '-----BEGIN CERTIFICATE-----';
|
|
|
|
const pem = compact(
|
|
|
|
certificates.split(CERT_PREFIX).map(match => {
|
|
|
|
if (!match) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return `${CERT_PREFIX}${match}`;
|
|
|
|
})
|
|
|
|
);
|
|
|
|
if (pem.length < 2) {
|
|
|
|
throw new Error(
|
|
|
|
`validateAttestationSignature: Expect two or more entries; got ${pem.length}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const verify = createVerify('RSA-SHA256');
|
|
|
|
verify.update(Buffer.from(bytesFromString(signatureBody)));
|
|
|
|
const isValid = verify.verify(pem[0], Buffer.from(signature));
|
|
|
|
if (!isValid) {
|
|
|
|
throw new Error('Validation of signature across signatureBody failed!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const caStore = pki.createCaStore([directoryTrustAnchor]);
|
|
|
|
const chain = compact(pem.map(cert => pki.certificateFromPem(cert)));
|
|
|
|
const isChainValid = pki.verifyCertificateChain(caStore, chain);
|
|
|
|
if (!isChainValid) {
|
|
|
|
throw new Error('Validation of certificate chain failed!');
|
|
|
|
}
|
|
|
|
|
|
|
|
const leafCert = chain[0];
|
|
|
|
const fieldCN = leafCert.subject.getField('CN');
|
|
|
|
if (
|
|
|
|
!fieldCN ||
|
|
|
|
fieldCN.value !== 'Intel SGX Attestation Report Signing'
|
|
|
|
) {
|
|
|
|
throw new Error('Leaf cert CN field had unexpected value');
|
|
|
|
}
|
|
|
|
const fieldO = leafCert.subject.getField('O');
|
|
|
|
if (!fieldO || fieldO.value !== 'Intel Corporation') {
|
|
|
|
throw new Error('Leaf cert O field had unexpected value');
|
|
|
|
}
|
|
|
|
const fieldL = leafCert.subject.getField('L');
|
|
|
|
if (!fieldL || fieldL.value !== 'Santa Clara') {
|
|
|
|
throw new Error('Leaf cert L field had unexpected value');
|
|
|
|
}
|
|
|
|
const fieldST = leafCert.subject.getField('ST');
|
|
|
|
if (!fieldST || fieldST.value !== 'CA') {
|
|
|
|
throw new Error('Leaf cert ST field had unexpected value');
|
|
|
|
}
|
|
|
|
const fieldC = leafCert.subject.getField('C');
|
|
|
|
if (!fieldC || fieldC.value !== 'US') {
|
|
|
|
throw new Error('Leaf cert C field had unexpected value');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function putRemoteAttestation(auth: {
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
}) {
|
2021-04-16 23:13:13 +00:00
|
|
|
const keyPair = generateKeyPair();
|
2020-09-04 01:25:19 +00:00
|
|
|
const { privKey, pubKey } = keyPair;
|
|
|
|
// Remove first "key type" byte from public key
|
|
|
|
const slicedPubKey = pubKey.slice(1);
|
|
|
|
const pubKeyBase64 = arrayBufferToBase64(slicedPubKey);
|
|
|
|
// Do request
|
|
|
|
const data = JSON.stringify({ clientPublic: pubKeyBase64 });
|
|
|
|
const result: JSONWithDetailsType = await _outerAjax(null, {
|
|
|
|
certificateAuthority,
|
|
|
|
type: 'PUT',
|
|
|
|
contentType: 'application/json; charset=utf-8',
|
|
|
|
host: directoryUrl,
|
|
|
|
path: `${URL_CALLS.attestation}/${directoryEnclaveId}`,
|
|
|
|
user: auth.username,
|
|
|
|
password: auth.password,
|
|
|
|
responseType: 'jsonwithdetails',
|
|
|
|
data,
|
2021-01-11 21:59:46 +00:00
|
|
|
timeout: 30000,
|
2020-09-04 01:25:19 +00:00
|
|
|
version,
|
|
|
|
});
|
|
|
|
|
|
|
|
const { data: responseBody, response } = result;
|
|
|
|
|
|
|
|
const attestationsLength = Object.keys(responseBody.attestations).length;
|
|
|
|
if (attestationsLength > 3) {
|
|
|
|
throw new Error(
|
|
|
|
'Got more than three attestations from the Contact Discovery Service'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
if (attestationsLength < 1) {
|
|
|
|
throw new Error(
|
|
|
|
'Got no attestations from the Contact Discovery Service'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const cookie = response.headers.get('set-cookie');
|
|
|
|
|
|
|
|
// Decode response
|
|
|
|
return {
|
|
|
|
cookie,
|
|
|
|
attestations: await pProps(
|
|
|
|
responseBody.attestations,
|
|
|
|
async attestation => {
|
|
|
|
const decoded = { ...attestation };
|
|
|
|
|
|
|
|
[
|
|
|
|
'ciphertext',
|
|
|
|
'iv',
|
|
|
|
'quote',
|
|
|
|
'serverEphemeralPublic',
|
|
|
|
'serverStaticPublic',
|
|
|
|
'signature',
|
|
|
|
'tag',
|
|
|
|
].forEach(prop => {
|
|
|
|
decoded[prop] = base64ToArrayBuffer(decoded[prop]);
|
|
|
|
});
|
|
|
|
|
|
|
|
// Validate response
|
|
|
|
validateAttestationQuote(decoded);
|
|
|
|
validateAttestationSignatureBody(
|
|
|
|
JSON.parse(decoded.signatureBody),
|
|
|
|
attestation.quote
|
|
|
|
);
|
|
|
|
await validateAttestationSignature(
|
|
|
|
decoded.signature,
|
|
|
|
decoded.signatureBody,
|
|
|
|
decoded.certificates
|
|
|
|
);
|
|
|
|
|
|
|
|
// Derive key
|
2021-04-16 23:13:13 +00:00
|
|
|
const ephemeralToEphemeral = calculateAgreement(
|
2020-09-04 01:25:19 +00:00
|
|
|
decoded.serverEphemeralPublic,
|
|
|
|
privKey
|
|
|
|
);
|
2021-04-16 23:13:13 +00:00
|
|
|
const ephemeralToStatic = calculateAgreement(
|
2020-09-04 01:25:19 +00:00
|
|
|
decoded.serverStaticPublic,
|
|
|
|
privKey
|
|
|
|
);
|
|
|
|
const masterSecret = concatenateBytes(
|
|
|
|
ephemeralToEphemeral,
|
|
|
|
ephemeralToStatic
|
|
|
|
);
|
|
|
|
const publicKeys = concatenateBytes(
|
|
|
|
slicedPubKey,
|
|
|
|
decoded.serverEphemeralPublic,
|
|
|
|
decoded.serverStaticPublic
|
|
|
|
);
|
2021-04-16 23:13:13 +00:00
|
|
|
const [clientKey, serverKey] = await deriveSecrets(
|
2020-09-04 01:25:19 +00:00
|
|
|
masterSecret,
|
2021-03-11 19:21:49 +00:00
|
|
|
publicKeys,
|
|
|
|
new ArrayBuffer(0)
|
2020-09-04 01:25:19 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
// Decrypt ciphertext into requestId
|
|
|
|
const requestId = await decryptAesGcm(
|
|
|
|
serverKey,
|
|
|
|
decoded.iv,
|
|
|
|
concatenateBytes(decoded.ciphertext, decoded.tag)
|
|
|
|
);
|
|
|
|
|
|
|
|
return { clientKey, serverKey, requestId };
|
|
|
|
}
|
|
|
|
),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getUuidsForE164s(
|
|
|
|
e164s: ReadonlyArray<string>
|
|
|
|
): Promise<Dictionary<string | null>> {
|
|
|
|
const directoryAuth = await getDirectoryAuth();
|
|
|
|
const attestationResult = await putRemoteAttestation(directoryAuth);
|
|
|
|
|
|
|
|
// Encrypt data for discovery
|
|
|
|
const data = await encryptCdsDiscoveryRequest(
|
|
|
|
attestationResult.attestations,
|
|
|
|
e164s
|
|
|
|
);
|
|
|
|
const { cookie } = attestationResult;
|
|
|
|
|
|
|
|
// Send discovery request
|
|
|
|
const discoveryResponse: {
|
|
|
|
requestId: string;
|
|
|
|
iv: string;
|
|
|
|
data: string;
|
|
|
|
mac: string;
|
|
|
|
} = await _outerAjax(null, {
|
|
|
|
certificateAuthority,
|
|
|
|
type: 'PUT',
|
|
|
|
headers: cookie
|
|
|
|
? {
|
|
|
|
cookie,
|
|
|
|
}
|
|
|
|
: undefined,
|
|
|
|
contentType: 'application/json; charset=utf-8',
|
|
|
|
host: directoryUrl,
|
|
|
|
path: `${URL_CALLS.discovery}/${directoryEnclaveId}`,
|
|
|
|
user: directoryAuth.username,
|
|
|
|
password: directoryAuth.password,
|
|
|
|
responseType: 'json',
|
2021-01-11 21:59:46 +00:00
|
|
|
timeout: 30000,
|
2020-09-04 01:25:19 +00:00
|
|
|
data: JSON.stringify(data),
|
|
|
|
version,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Decode discovery request response
|
|
|
|
const decodedDiscoveryResponse: {
|
|
|
|
[K in keyof typeof discoveryResponse]: ArrayBuffer;
|
|
|
|
} = mapValues(discoveryResponse, value => {
|
|
|
|
return base64ToArrayBuffer(value);
|
|
|
|
}) as any;
|
|
|
|
|
|
|
|
const returnedAttestation = Object.values(
|
|
|
|
attestationResult.attestations
|
|
|
|
).find(at =>
|
|
|
|
constantTimeEqual(at.requestId, decodedDiscoveryResponse.requestId)
|
|
|
|
);
|
|
|
|
if (!returnedAttestation) {
|
|
|
|
throw new Error('No known attestations returned from CDS');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decrypt discovery response
|
|
|
|
const decryptedDiscoveryData = await decryptAesGcm(
|
|
|
|
returnedAttestation.serverKey,
|
|
|
|
decodedDiscoveryResponse.iv,
|
|
|
|
concatenateBytes(
|
|
|
|
decodedDiscoveryResponse.data,
|
|
|
|
decodedDiscoveryResponse.mac
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
// Process and return result
|
|
|
|
const uuids = splitUuids(decryptedDiscoveryData);
|
|
|
|
|
|
|
|
if (uuids.length !== e164s.length) {
|
|
|
|
throw new Error(
|
|
|
|
'Returned set of UUIDs did not match returned set of e164s!'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return zipObject(e164s, uuids);
|
|
|
|
}
|
2018-05-26 01:01:56 +00:00
|
|
|
}
|
|
|
|
}
|