Better types for WebAPI

This commit is contained in:
Fedor Indutny 2021-09-21 17:58:03 -07:00 committed by GitHub
parent c05d23e628
commit b9d6497cb1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 156 additions and 107 deletions

View file

@ -10,7 +10,8 @@ import PQueue from 'p-queue';
import { omit } from 'lodash';
import EventTarget from './EventTarget';
import { WebAPIType } from './WebAPI';
import type { WebAPIType } from './WebAPI';
import { HTTPError } from './Errors';
import { KeyPairType, CompatSignedPreKeyType } from './Types.d';
import utils from './Helpers';
import ProvisioningCipher from './ProvisioningCipher';
@ -29,6 +30,7 @@ import {
generateSignedPreKey,
generatePreKey,
} from '../Curve';
import { UUID } from '../types/UUID';
import { isMoreRecentThan, isOlderThan } from '../util/timestamp';
import { ourProfileKeyService } from '../services/ourProfileKey';
import { assert, strictAssert } from '../util/assert';
@ -390,8 +392,7 @@ export default class AccountManager extends EventTarget {
log.error('rotateSignedPrekey error:', e && e.stack ? e.stack : e);
if (
e instanceof Error &&
e.name === 'HTTPError' &&
e instanceof HTTPError &&
e.code &&
e.code >= 400 &&
e.code <= 599
@ -589,7 +590,7 @@ export default class AccountManager extends EventTarget {
// update our own identity key, which may have changed
// if we're relinking after a reinstall on the master device
await storage.protocol.saveIdentityWithAttributes(ourUuid, {
await storage.protocol.saveIdentityWithAttributes(new UUID(ourUuid), {
publicKey: identityKeyPair.pubKey,
firstUse: true,
timestamp: Date.now(),

View file

@ -1,7 +1,6 @@
// Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable max-classes-per-file */
import { parseRetryAfter } from '../util/parseRetryAfter';
@ -102,14 +101,14 @@ export class OutgoingIdentityKeyError extends ReplayableError {
export class OutgoingMessageError extends ReplayableError {
identifier: string;
code?: any;
code?: number;
// Note: Data to resend message is no longer captured
constructor(
incomingIdentifier: string,
_m: unknown,
_t: unknown,
httpError?: Error
httpError?: HTTPError
) {
const identifier = incomingIdentifier.split('.')[0];
@ -128,11 +127,13 @@ export class OutgoingMessageError extends ReplayableError {
}
export class SendMessageNetworkError extends ReplayableError {
code: number;
identifier: string;
responseHeaders?: HeaderListType | undefined;
constructor(identifier: string, _m: unknown, httpError: Error) {
constructor(identifier: string, _m: unknown, httpError: HTTPError) {
super({
name: 'SendMessageNetworkError',
message: httpError.message,
@ -152,13 +153,15 @@ export type SendMessageChallengeData = {
};
export class SendMessageChallengeError extends ReplayableError {
public code: number;
public identifier: string;
public readonly data: SendMessageChallengeData | undefined;
public readonly retryAfter: number;
constructor(identifier: string, httpError: Error) {
constructor(identifier: string, httpError: HTTPError) {
super({
name: 'SendMessageChallengeError',
message: httpError.message,
@ -166,7 +169,7 @@ export class SendMessageChallengeError extends ReplayableError {
[this.identifier] = identifier.split('.');
this.code = httpError.code;
this.data = httpError.response;
this.data = httpError.response as SendMessageChallengeData;
const headers = httpError.responseHeaders || {};
@ -241,9 +244,9 @@ export class SignedPreKeyRotationError extends ReplayableError {
}
export class MessageError extends ReplayableError {
code?: any;
code: number;
constructor(_m: unknown, httpError: Error) {
constructor(_m: unknown, httpError: HTTPError) {
super({
name: 'MessageError',
message: httpError.message,
@ -258,9 +261,9 @@ export class MessageError extends ReplayableError {
export class UnregisteredUserError extends Error {
identifier: string;
code?: any;
code: number;
constructor(identifier: string, httpError: Error) {
constructor(identifier: string, httpError: HTTPError) {
const { message } = httpError;
super(message);
@ -282,3 +285,5 @@ export class UnregisteredUserError extends Error {
}
export class ConnectTimeoutError extends Error {}
export class WarnOnlyError extends Error {}

View file

@ -63,6 +63,7 @@ import { IncomingWebSocketRequest } from './WebsocketResources';
import { ContactBuffer, GroupBuffer } from './ContactsParser';
import type { WebAPIType } from './WebAPI';
import type { Storage } from './Storage';
import { WarnOnlyError } from './Errors';
import * as Bytes from '../Bytes';
import {
ProcessedDataMessage,
@ -922,7 +923,7 @@ export default class MessageReceiver
':',
Errors.toLogFormat(error),
];
if (error.warn) {
if (error instanceof WarnOnlyError) {
log.warn(...args);
} else {
log.error(...args);

View file

@ -21,7 +21,7 @@ import {
UnidentifiedSenderMessageContent,
} from '@signalapp/signal-client';
import { WebAPIType } from './WebAPI';
import type { WebAPIType } from './WebAPI';
import { SendMetadataType, SendOptionsType } from './SendMessage';
import {
OutgoingIdentityKeyError,
@ -29,6 +29,7 @@ import {
SendMessageNetworkError,
SendMessageChallengeError,
UnregisteredUserError,
HTTPError,
} from './Errors';
import { CallbackResultType, CustomError } from './Types.d';
import { isValidNumber } from '../types/PhoneNumber';
@ -221,7 +222,7 @@ export default class OutgoingMessage {
): void {
let error = providedError;
if (!error || (error.name === 'HTTPError' && error.code !== 404)) {
if (!error || (error instanceof HTTPError && error.code !== 404)) {
if (error && error.code === 428) {
error = new SendMessageChallengeError(identifier, error);
} else {
@ -313,7 +314,7 @@ export default class OutgoingMessage {
}
return promise.catch(e => {
if (e.name === 'HTTPError' && e.code !== 409 && e.code !== 410) {
if (e instanceof HTTPError && e.code !== 409 && e.code !== 410) {
// 409 and 410 should bubble and be handled by doSendMessage
// 404 should throw UnregisteredUserError
// 428 should throw SendMessageChallengeError
@ -517,7 +518,10 @@ export default class OutgoingMessage {
}
},
async (error: Error) => {
if (error.code === 401 || error.code === 403) {
if (
error instanceof HTTPError &&
(error.code === 401 || error.code === 403)
) {
if (this.failoverIdentifiers.indexOf(identifier) === -1) {
this.failoverIdentifiers.push(identifier);
}
@ -556,8 +560,7 @@ export default class OutgoingMessage {
})
.catch(async error => {
if (
error instanceof Error &&
error.name === 'HTTPError' &&
error instanceof HTTPError &&
(error.code === 410 || error.code === 409)
) {
if (!recurse) {
@ -569,15 +572,20 @@ export default class OutgoingMessage {
return undefined;
}
const response = error.response as {
extraDevices?: Array<number>;
staleDevices?: Array<number>;
missingDevices?: Array<number>;
};
let p: Promise<any> = Promise.resolve();
if (error.code === 409) {
p = this.removeDeviceIdsForIdentifier(
identifier,
error.response.extraDevices || []
response.extraDevices || []
);
} else {
p = Promise.all(
error.response.staleDevices.map(async (deviceId: number) => {
(response.staleDevices || []).map(async (deviceId: number) => {
await window.textsecure.storage.protocol.archiveSession(
new QualifiedAddress(
ourUuid,
@ -591,8 +599,8 @@ export default class OutgoingMessage {
return p.then(async () => {
const resetDevices =
error.code === 410
? error.response.staleDevices
: error.response.missingDevices;
? response.staleDevices
: response.missingDevices;
return this.getKeysForIdentifier(identifier, resetDevices).then(
// We continue to retry as long as the error code was 409; the assumption is
// that we'll request new device info and the next request will succeed.
@ -678,7 +686,10 @@ export default class OutgoingMessage {
if (!uuid) {
throw new UnregisteredUserError(
identifier,
new Error('User is not registered')
new HTTPError('User is not registered', {
code: -1,
headers: {},
})
);
}
identifier = uuid;

View file

@ -9,6 +9,7 @@
/* eslint-disable max-classes-per-file */
import { Dictionary } from 'lodash';
import Long from 'long';
import PQueue from 'p-queue';
import {
PlaintextContent,
@ -54,6 +55,7 @@ import {
MessageError,
SignedPreKeyRotationError,
SendMessageProtoError,
HTTPError,
} from './Errors';
import { BodyRangesType } from '../types/Util';
import {
@ -526,7 +528,7 @@ export default class MessageSender {
const id = await this.server.putAttachment(result.ciphertext);
const proto = new Proto.AttachmentPointer();
proto.cdnId = id;
proto.cdnId = Long.fromString(id);
proto.contentType = attachment.contentType;
proto.key = new FIXMEU8(key);
proto.size = attachment.size;
@ -563,7 +565,7 @@ export default class MessageSender {
message.attachmentPointers = attachmentPointers;
})
.catch(error => {
if (error instanceof Error && error.name === 'HTTPError') {
if (error instanceof HTTPError) {
throw new MessageError(message, error);
} else {
throw error;
@ -584,7 +586,7 @@ export default class MessageSender {
// eslint-disable-next-line no-param-reassign
message.preview = preview;
} catch (error) {
if (error instanceof Error && error.name === 'HTTPError') {
if (error instanceof HTTPError) {
throw new MessageError(message, error);
} else {
throw error;
@ -609,7 +611,7 @@ export default class MessageSender {
attachmentPointer: await this.makeAttachmentPointer(sticker.data),
};
} catch (error) {
if (error instanceof Error && error.name === 'HTTPError') {
if (error instanceof HTTPError) {
throw new MessageError(message, error);
} else {
throw error;
@ -637,7 +639,7 @@ export default class MessageSender {
});
})
).catch(error => {
if (error instanceof Error && error.name === 'HTTPError') {
if (error instanceof HTTPError) {
throw new MessageError(message, error);
} else {
throw error;

View file

@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
import * as log from '../logging/log';
import { HTTPError } from './Errors';
export async function handleStatusCode(status: number): Promise<void> {
if (status === 499) {
@ -11,7 +12,7 @@ export async function handleStatusCode(status: number): Promise<void> {
}
}
export function translateError(error: Error): Error | undefined {
export function translateError(error: HTTPError): HTTPError | undefined {
const { code } = error;
if (code === 200) {
// Happens sometimes when we get no response. Might be nice to get 204 instead.

View file

@ -598,7 +598,7 @@ async function _retryAjax(
const limit = providedLimit || 3;
return _promiseAjax(url, options).catch(async (e: Error) => {
if (e.name === 'HTTPError' && e.code === -1 && count < limit) {
if (e instanceof HTTPError && e.code === -1 && count < limit) {
return new Promise(resolve => {
setTimeout(() => {
resolve(_retryAjax(url, options, limit, count));
@ -615,17 +615,6 @@ async function _outerAjax(url: string | null, options: PromiseAjaxOptionsType) {
return _retryAjax(url, options);
}
declare global {
// We want to extend `Error`, so we need an interface.
// eslint-disable-next-line no-restricted-syntax
interface Error {
code?: number | string;
response?: any;
responseHeaders?: HeaderListType;
warn?: boolean;
}
}
function makeHTTPError(
message: string,
providedCode: number,
@ -722,7 +711,7 @@ type InitializeOptionsType = {
version: string;
};
type MessageType = any;
type MessageType = unknown;
type AjaxOptionsType = {
accessKey?: string;
@ -737,7 +726,7 @@ type AjaxOptionsType = {
password?: string;
redactUrl?: RedactUrl;
responseType?: 'json' | 'arraybuffer' | 'arraybufferwithdetails';
schema?: any;
schema?: unknown;
timeout?: number;
unauthenticated?: boolean;
urlParameters?: string;
@ -768,7 +757,7 @@ export type CapabilitiesUploadType = {
changeNumber: true;
};
type StickerPackManifestType = any;
type StickerPackManifestType = ArrayBuffer;
export type GroupCredentialType = {
credential: string;
@ -808,6 +797,20 @@ const uploadAvatarHeadersZod = z
.passthrough();
export type UploadAvatarHeadersType = z.infer<typeof uploadAvatarHeadersZod>;
export type ProfileType = Readonly<{
identityKey?: string;
name?: string;
about?: string;
aboutEmoji?: string;
avatar?: string;
unidentifiedAccess?: string;
unrestrictedUnidentifiedAccess?: string;
username?: string;
uuid?: string;
credential?: string;
capabilities?: unknown;
}>;
export type WebAPIType = {
confirmCode: (
number: string,
@ -816,14 +819,21 @@ export type WebAPIType = {
registrationId: number,
deviceName?: string | null,
options?: { accessKey?: ArrayBuffer; uuid?: string }
) => Promise<any>;
) => Promise<{ uuid?: string; deviceId: number }>;
createGroup: (
group: Proto.IGroup,
options: GroupCredentialsType
) => Promise<void>;
getAttachment: (cdnKey: string, cdnNumber?: number) => Promise<any>;
getAvatar: (path: string) => Promise<any>;
getDevices: () => Promise<any>;
getAttachment: (cdnKey: string, cdnNumber?: number) => Promise<ArrayBuffer>;
getAvatar: (path: string) => Promise<ArrayBuffer>;
getDevices: () => Promise<
Array<{
id: number;
name: string;
lastSeen: number;
created: number;
}>
>;
getGroup: (options: GroupCredentialsType) => Promise<Proto.Group>;
getGroupFromLink: (
inviteLinkPassword: string,
@ -841,7 +851,11 @@ export type WebAPIType = {
startVersion: number,
options: GroupCredentialsType
) => Promise<GroupLogResponseType>;
getIceServers: () => Promise<any>;
getIceServers: () => Promise<{
username: string;
password: string;
urls: Array<string>;
}>;
getKeysForIdentifier: (
identifier: string,
deviceId?: number
@ -858,7 +872,7 @@ export type WebAPIType = {
profileKeyVersion?: string;
profileKeyCredentialRequest?: string;
}
) => Promise<any>;
) => Promise<ProfileType>;
getProfileUnauth: (
identifier: string,
options: {
@ -866,7 +880,7 @@ export type WebAPIType = {
profileKeyVersion?: string;
profileKeyCredentialRequest?: string;
}
) => Promise<any>;
) => Promise<ProfileType>;
getProvisioningResource: (
handler: IRequestHandler
) => Promise<WebSocketResource>;
@ -892,7 +906,13 @@ export type WebAPIType = {
makeProxiedRequest: (
targetUrl: string,
options?: ProxiedRequestOptionsType
) => Promise<any>;
) => Promise<
| ArrayBufferWithDetailsType
| {
result: ArrayBufferWithDetailsType;
totalSize: number;
}
>;
makeSfuRequest: (
targetUrl: string,
type: HTTPCodeType,
@ -905,7 +925,7 @@ export type WebAPIType = {
inviteLinkBase64?: string
) => Promise<Proto.IGroupChange>;
modifyStorageRecords: MessageSender['modifyStorageRecords'];
putAttachment: (encryptedBin: ArrayBuffer) => Promise<any>;
putAttachment: (encryptedBin: ArrayBuffer) => Promise<string>;
putProfile: (
jsonData: ProfileRequestDataType
) => Promise<UploadAvatarHeadersType | undefined>;
@ -916,10 +936,10 @@ export type WebAPIType = {
onProgress?: () => void
) => Promise<string>;
registerKeys: (genKeys: KeysType) => Promise<void>;
registerSupportForUnauthenticatedDelivery: () => Promise<any>;
registerSupportForUnauthenticatedDelivery: () => Promise<void>;
reportMessage: (senderE164: string, serverGuid: string) => Promise<void>;
requestVerificationSMS: (number: string) => Promise<any>;
requestVerificationVoice: (number: string) => Promise<any>;
requestVerificationSMS: (number: string) => Promise<void>;
requestVerificationVoice: (number: string) => Promise<void>;
sendMessages: (
destination: string,
messageArray: Array<MessageType>,
@ -949,8 +969,11 @@ export type WebAPIType = {
avatarData: Uint8Array,
options: GroupCredentialsType
) => Promise<string>;
whoami: () => Promise<any>;
sendChallengeResponse: (challengeResponse: ChallengeType) => Promise<any>;
whoami: () => Promise<{
uuid?: string;
number?: string;
}>;
sendChallengeResponse: (challengeResponse: ChallengeType) => Promise<void>;
getConfig: () => Promise<
Array<{ name: string; enabled: boolean; value: string | null }>
>;
@ -1188,6 +1211,9 @@ export function initialize({
unauthenticated: param.unauthenticated,
accessKey: param.accessKey,
}).catch((e: Error) => {
if (!(e instanceof HTTPError)) {
throw e;
}
const translatedError = translateError(e);
if (translatedError) {
throw translatedError;
@ -1458,7 +1484,7 @@ export function initialize({
async function getAvatar(path: string) {
// 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.
return _outerAjax(`${cdnUrlObject['0']}/${path}`, {
return (await _outerAjax(`${cdnUrlObject['0']}/${path}`, {
certificateAuthority,
contentType: 'application/octet-stream',
proxyUrl,
@ -1470,7 +1496,7 @@ export function initialize({
return href.replace(pattern, `[REDACTED]${path.slice(-3)}`);
},
version,
});
})) as ArrayBuffer;
}
async function reportMessage(
@ -1571,6 +1597,7 @@ export function initialize({
return _ajax({
call: 'getIceServers',
httpType: 'GET',
responseType: 'json',
});
}
@ -1832,7 +1859,7 @@ export function initialize({
if (!isPackIdValid(packId)) {
throw new Error('getSticker: pack ID was invalid');
}
return _outerAjax(
return (await _outerAjax(
`${cdnUrlObject['0']}/stickers/${packId}/full/${stickerId}`,
{
certificateAuthority,
@ -1842,14 +1869,14 @@ export function initialize({
redactUrl: redactStickerUrl,
version,
}
);
)) as ArrayBuffer;
}
async function getStickerPackManifest(packId: string) {
if (!isPackIdValid(packId)) {
throw new Error('getStickerPackManifest: pack ID was invalid');
}
return _outerAjax(
return (await _outerAjax(
`${cdnUrlObject['0']}/stickers/${packId}/manifest.proto`,
{
certificateAuthority,
@ -1859,7 +1886,7 @@ export function initialize({
redactUrl: redactStickerUrl,
version,
}
);
)) as ArrayBuffer;
}
type ServerAttachmentType = {
@ -1989,7 +2016,7 @@ export function initialize({
? cdnUrlObject[cdnNumber] || cdnUrlObject['0']
: cdnUrlObject['0'];
// This is going to the CDN, not the service, so we use _outerAjax
return _outerAjax(`${cdnUrl}/attachments/${cdnKey}`, {
return (await _outerAjax(`${cdnUrl}/attachments/${cdnKey}`, {
certificateAuthority,
proxyUrl,
responseType: 'arraybuffer',
@ -1997,7 +2024,7 @@ export function initialize({
type: 'GET',
redactUrl: _createRedactor(cdnKey),
version,
});
})) as ArrayBuffer;
}
async function putAttachment(encryptedBin: ArrayBuffer) {
@ -2066,7 +2093,7 @@ export function initialize({
headers.Range = `bytes=${start}-${end}`;
}
const result = await _outerAjax(targetUrl, {
const result = (await _outerAjax(targetUrl, {
responseType: returnArrayBuffer ? 'arraybufferwithdetails' : undefined,
proxyUrl: contentProxyUrl,
type: 'GET',
@ -2074,7 +2101,7 @@ export function initialize({
redactUrl: () => '[REDACTED_URL]',
headers,
version,
});
})) as ArrayBufferWithDetailsType;
if (!returnArrayBuffer) {
return result;

View file

@ -8,7 +8,7 @@ import {
PublicKey,
} from '@signalapp/signal-client';
import { UnregisteredUserError } from './Errors';
import { UnregisteredUserError, HTTPError } from './Errors';
import { Sessions, IdentityKeys } from '../LibSignalStores';
import { Address } from '../types/Address';
import { QualifiedAddress } from '../types/QualifiedAddress';
@ -35,7 +35,7 @@ export async function getKeysForIdentifier(
accessKeyFailed,
};
} catch (error) {
if (error.name === 'HTTPError' && error.code === 404) {
if (error instanceof HTTPError && error.code === 404) {
const theirUuid = UUID.lookup(identifier);
if (theirUuid) {

View file

@ -23,6 +23,7 @@ import {
ProcessedReaction,
ProcessedDelete,
} from './Types.d';
import { WarnOnlyError } from './Errors';
// TODO: remove once we move away from ArrayBuffers
const FIXMEU8 = Uint8Array;
@ -335,11 +336,9 @@ export async function processDataMessage(
// Cleaned up in `processGroupContext`
break;
default: {
const err = new Error(
throw new WarnOnlyError(
`Unknown group message type: ${result.group.type}`
);
err.warn = true;
throw err;
}
}
}