2021-07-28 21:37:09 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
import URL from 'url';
|
|
|
|
import ProxyAgent from 'proxy-agent';
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { RequestInit } from 'node-fetch';
|
|
|
|
import { Response, Headers } from 'node-fetch';
|
2021-11-08 23:32:31 +00:00
|
|
|
import type { connection as WebSocket } from 'websocket';
|
2021-07-28 21:37:09 +00:00
|
|
|
import qs from 'querystring';
|
|
|
|
import EventListener from 'events';
|
|
|
|
|
2021-11-08 23:32:31 +00:00
|
|
|
import type { AbortableProcess } from '../util/AbortableProcess';
|
2021-07-28 21:37:09 +00:00
|
|
|
import { strictAssert } from '../util/assert';
|
|
|
|
import { BackOff, FIBONACCI_TIMEOUTS } from '../util/BackOff';
|
2021-08-26 14:10:58 +00:00
|
|
|
import * as durations from '../util/durations';
|
2021-07-28 21:37:09 +00:00
|
|
|
import { sleep } from '../util/sleep';
|
|
|
|
import { SocketStatus } from '../types/SocketStatus';
|
|
|
|
import * as Errors from '../types/errors';
|
|
|
|
import * as Bytes from '../Bytes';
|
2021-09-17 18:27:53 +00:00
|
|
|
import * as log from '../logging/log';
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-10-26 19:15:33 +00:00
|
|
|
import type {
|
2021-07-28 21:37:09 +00:00
|
|
|
WebSocketResourceOptions,
|
|
|
|
IncomingWebSocketRequest,
|
|
|
|
} from './WebsocketResources';
|
2021-10-26 19:15:33 +00:00
|
|
|
import WebSocketResource from './WebsocketResources';
|
2021-11-08 23:32:31 +00:00
|
|
|
import { HTTPError } from './Errors';
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { WebAPICredentials, IRequestHandler } from './Types.d';
|
2021-11-08 23:32:31 +00:00
|
|
|
import { connect as connectWebSocket } from './WebSocket';
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-08-26 14:10:58 +00:00
|
|
|
const FIVE_MINUTES = 5 * durations.MINUTE;
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-09-28 22:12:43 +00:00
|
|
|
const JITTER = 5 * durations.SECOND;
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
export type SocketManagerOptions = Readonly<{
|
|
|
|
url: string;
|
2023-02-27 22:34:43 +00:00
|
|
|
artCreatorUrl: string;
|
2021-07-28 21:37:09 +00:00
|
|
|
certificateAuthority: string;
|
|
|
|
version: string;
|
|
|
|
proxyUrl?: string;
|
2022-10-05 00:48:25 +00:00
|
|
|
hasStoriesDisabled: boolean;
|
2021-07-28 21:37:09 +00:00
|
|
|
}>;
|
|
|
|
|
2021-08-24 15:58:40 +00:00
|
|
|
// This class manages two websocket resources:
|
2021-07-28 21:37:09 +00:00
|
|
|
//
|
|
|
|
// - Authenticated WebSocketResource which uses supplied WebAPICredentials and
|
|
|
|
// automatically reconnects on closed socket (using back off)
|
2021-08-24 15:58:40 +00:00
|
|
|
// - Unauthenticated WebSocketResource that is created on the first outgoing
|
|
|
|
// unauthenticated request and is periodically rotated (5 minutes since first
|
|
|
|
// activity on the socket).
|
2021-07-28 21:37:09 +00:00
|
|
|
//
|
|
|
|
// Incoming requests on authenticated resource are funneled into the registered
|
|
|
|
// request handlers (`registerRequestHandler`) or queued internally until at
|
|
|
|
// least one such request handler becomes available.
|
|
|
|
//
|
|
|
|
// Incoming requests on unauthenticated resource are not currently supported.
|
|
|
|
// WebSocketResource is responsible for their immediate termination.
|
|
|
|
export class SocketManager extends EventListener {
|
2021-09-28 22:12:43 +00:00
|
|
|
private backOff = new BackOff(FIBONACCI_TIMEOUTS, {
|
|
|
|
jitter: JITTER,
|
|
|
|
});
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
private authenticated?: AbortableProcess<WebSocketResource>;
|
|
|
|
|
|
|
|
private unauthenticated?: AbortableProcess<WebSocketResource>;
|
|
|
|
|
2021-08-24 15:58:40 +00:00
|
|
|
private unauthenticatedExpirationTimer?: NodeJS.Timeout;
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
private credentials?: WebAPICredentials;
|
|
|
|
|
2021-10-06 16:25:22 +00:00
|
|
|
private readonly proxyAgent?: ReturnType<typeof ProxyAgent>;
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
private status = SocketStatus.CLOSED;
|
|
|
|
|
|
|
|
private requestHandlers = new Set<IRequestHandler>();
|
|
|
|
|
|
|
|
private incomingRequestQueue = new Array<IncomingWebSocketRequest>();
|
|
|
|
|
|
|
|
private isOffline = false;
|
|
|
|
|
2022-10-05 00:48:25 +00:00
|
|
|
private hasStoriesDisabled: boolean;
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
constructor(private readonly options: SocketManagerOptions) {
|
|
|
|
super();
|
|
|
|
|
|
|
|
if (options.proxyUrl) {
|
|
|
|
this.proxyAgent = new ProxyAgent(options.proxyUrl);
|
|
|
|
}
|
2022-10-05 00:48:25 +00:00
|
|
|
|
|
|
|
this.hasStoriesDisabled = options.hasStoriesDisabled;
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public getStatus(): SocketStatus {
|
|
|
|
return this.status;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update WebAPICredentials and reconnect authenticated resource if
|
|
|
|
// credentials changed
|
|
|
|
public async authenticate(credentials: WebAPICredentials): Promise<void> {
|
|
|
|
if (this.isOffline) {
|
|
|
|
throw new HTTPError('SocketManager offline', {
|
|
|
|
code: 0,
|
|
|
|
headers: {},
|
|
|
|
stack: new Error().stack,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const { username, password } = credentials;
|
|
|
|
if (!username && !password) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn('SocketManager authenticate was called without credentials');
|
2021-07-28 21:37:09 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
this.credentials &&
|
|
|
|
this.credentials.username === username &&
|
|
|
|
this.credentials.password === password &&
|
|
|
|
this.authenticated
|
|
|
|
) {
|
|
|
|
try {
|
|
|
|
await this.authenticated.getResult();
|
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: failed to wait for existing authenticated socket ' +
|
|
|
|
` due to error: ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.credentials = credentials;
|
|
|
|
|
2022-10-05 00:48:25 +00:00
|
|
|
log.info(
|
|
|
|
'SocketManager: connecting authenticated socket ' +
|
|
|
|
`(hasStoriesDisabled=${this.hasStoriesDisabled})`
|
|
|
|
);
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-09-16 20:18:42 +00:00
|
|
|
this.setStatus(SocketStatus.CONNECTING);
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
const process = this.connectResource({
|
2021-12-01 18:55:17 +00:00
|
|
|
name: 'authenticated',
|
2021-07-28 21:37:09 +00:00
|
|
|
path: '/v1/websocket/',
|
|
|
|
query: { login: username, password },
|
|
|
|
resourceOptions: {
|
2023-06-07 00:36:38 +00:00
|
|
|
name: 'authenticated',
|
2021-07-28 21:37:09 +00:00
|
|
|
keepalive: { path: '/v1/keepalive' },
|
|
|
|
handleRequest: (req: IncomingWebSocketRequest): void => {
|
|
|
|
this.queueOrHandleRequest(req);
|
|
|
|
},
|
|
|
|
},
|
2022-10-05 00:48:25 +00:00
|
|
|
extraHeaders: {
|
|
|
|
'X-Signal-Receive-Stories': String(!this.hasStoriesDisabled),
|
|
|
|
},
|
2021-07-28 21:37:09 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// Cancel previous connect attempt or close socket
|
|
|
|
this.authenticated?.abort();
|
|
|
|
|
|
|
|
this.authenticated = process;
|
|
|
|
|
|
|
|
const reconnect = async (): Promise<void> => {
|
|
|
|
const timeout = this.backOff.getAndIncrement();
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: reconnecting authenticated socket ' +
|
|
|
|
`after ${timeout}ms`
|
|
|
|
);
|
|
|
|
|
|
|
|
await sleep(timeout);
|
|
|
|
if (this.isOffline) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager: cancelled reconnect because we are offline');
|
2021-07-28 21:37:09 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.authenticated) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager: authenticated socket already reconnected');
|
2021-07-28 21:37:09 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
strictAssert(this.credentials !== undefined, 'Missing credentials');
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.authenticate(this.credentials);
|
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2022-02-09 20:33:19 +00:00
|
|
|
'SocketManager: authenticated socket failed to reconnect ' +
|
2021-07-28 21:37:09 +00:00
|
|
|
`due to error ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
return reconnect();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let authenticated: WebSocketResource;
|
|
|
|
try {
|
|
|
|
authenticated = await process.getResult();
|
2021-09-16 20:18:42 +00:00
|
|
|
this.setStatus(SocketStatus.OPEN);
|
2021-07-28 21:37:09 +00:00
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: authenticated socket connection failed with ' +
|
|
|
|
`error: ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
|
2021-09-15 18:44:27 +00:00
|
|
|
// The socket was deliberately closed, don't follow up
|
|
|
|
if (this.authenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.dropAuthenticated(process);
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
if (error instanceof HTTPError) {
|
|
|
|
const { code } = error;
|
|
|
|
|
|
|
|
if (code === 401 || code === 403) {
|
|
|
|
this.emit('authError', error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-28 22:12:43 +00:00
|
|
|
if (!(code >= 500 && code <= 599) && code !== -1) {
|
2021-07-28 21:37:09 +00:00
|
|
|
// No reconnect attempt should be made
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-21 18:41:48 +00:00
|
|
|
void reconnect();
|
2021-07-28 21:37:09 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager: connected authenticated socket');
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-08-03 17:05:20 +00:00
|
|
|
window.logAuthenticatedConnect?.();
|
2021-07-28 21:37:09 +00:00
|
|
|
this.backOff.reset();
|
|
|
|
|
|
|
|
authenticated.addEventListener('close', ({ code, reason }): void => {
|
|
|
|
if (this.authenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: authenticated socket closed ' +
|
|
|
|
`with code=${code} and reason=${reason}`
|
|
|
|
);
|
|
|
|
this.dropAuthenticated(process);
|
|
|
|
|
|
|
|
if (code === 3000) {
|
|
|
|
// Intentional disconnect
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-12-21 18:41:48 +00:00
|
|
|
void reconnect();
|
2021-07-28 21:37:09 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Either returns currently connecting/active authenticated
|
|
|
|
// WebSocketResource or connects a fresh one.
|
|
|
|
public async getAuthenticatedResource(): Promise<WebSocketResource> {
|
|
|
|
if (!this.authenticated) {
|
|
|
|
strictAssert(this.credentials !== undefined, 'Missing credentials');
|
|
|
|
await this.authenticate(this.credentials);
|
|
|
|
}
|
|
|
|
|
|
|
|
strictAssert(this.authenticated !== undefined, 'Authentication failed');
|
|
|
|
return this.authenticated.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Creates new WebSocketResource for AccountManager's provisioning
|
|
|
|
public async getProvisioningResource(
|
|
|
|
handler: IRequestHandler
|
|
|
|
): Promise<WebSocketResource> {
|
|
|
|
return this.connectResource({
|
2021-12-01 18:55:17 +00:00
|
|
|
name: 'provisioning',
|
2021-07-28 21:37:09 +00:00
|
|
|
path: '/v1/websocket/provisioning/',
|
|
|
|
resourceOptions: {
|
2023-06-07 00:36:38 +00:00
|
|
|
name: 'provisioning',
|
2021-07-28 21:37:09 +00:00
|
|
|
handleRequest: (req: IncomingWebSocketRequest): void => {
|
|
|
|
handler.handleRequest(req);
|
|
|
|
},
|
|
|
|
keepalive: { path: '/v1/keepalive/provisioning' },
|
|
|
|
},
|
|
|
|
}).getResult();
|
|
|
|
}
|
|
|
|
|
2023-02-27 22:34:43 +00:00
|
|
|
// Creates new WebSocket for Art Creator provisioning
|
|
|
|
public async connectExternalSocket({
|
|
|
|
url,
|
|
|
|
extraHeaders,
|
|
|
|
}: {
|
|
|
|
url: string;
|
|
|
|
extraHeaders?: Record<string, string>;
|
|
|
|
}): Promise<WebSocket> {
|
|
|
|
return connectWebSocket({
|
|
|
|
name: 'art-creator-provisioning',
|
|
|
|
url,
|
|
|
|
version: this.options.version,
|
|
|
|
proxyAgent: this.proxyAgent,
|
|
|
|
extraHeaders,
|
|
|
|
|
|
|
|
createResource(socket: WebSocket): WebSocket {
|
|
|
|
return socket;
|
|
|
|
},
|
|
|
|
}).getResult();
|
|
|
|
}
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
// Fetch-compatible wrapper around underlying unauthenticated/authenticated
|
|
|
|
// websocket resources. This wrapper supports only limited number of features
|
|
|
|
// of node-fetch despite being API compatible.
|
|
|
|
public async fetch(url: string, init: RequestInit): Promise<Response> {
|
|
|
|
const headers = new Headers(init.headers);
|
|
|
|
|
|
|
|
let resource: WebSocketResource;
|
2021-08-04 00:37:17 +00:00
|
|
|
if (this.isAuthenticated(headers)) {
|
2021-07-28 21:37:09 +00:00
|
|
|
resource = await this.getAuthenticatedResource();
|
|
|
|
} else {
|
|
|
|
resource = await this.getUnauthenticatedResource();
|
2021-08-24 15:58:40 +00:00
|
|
|
await this.startUnauthenticatedExpirationTimer(resource);
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const { path } = URL.parse(url);
|
|
|
|
strictAssert(path, "Fetch can't have empty path");
|
|
|
|
|
|
|
|
const { method = 'GET', body, timeout } = init;
|
|
|
|
|
|
|
|
let bodyBytes: Uint8Array | undefined;
|
|
|
|
if (body === undefined) {
|
|
|
|
bodyBytes = undefined;
|
|
|
|
} else if (body instanceof Uint8Array) {
|
|
|
|
bodyBytes = body;
|
|
|
|
} else if (body instanceof ArrayBuffer) {
|
2021-09-24 00:49:05 +00:00
|
|
|
throw new Error('Unsupported body type: ArrayBuffer');
|
2021-07-28 21:37:09 +00:00
|
|
|
} else if (typeof body === 'string') {
|
|
|
|
bodyBytes = Bytes.fromString(body);
|
|
|
|
} else {
|
|
|
|
throw new Error(`Unsupported body type: ${typeof body}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const {
|
|
|
|
status,
|
|
|
|
message: statusText,
|
|
|
|
response,
|
|
|
|
headers: flatResponseHeaders,
|
|
|
|
} = await resource.sendRequest({
|
|
|
|
verb: method,
|
|
|
|
path,
|
|
|
|
body: bodyBytes,
|
|
|
|
headers: Array.from(headers.entries()).map(([key, value]) => {
|
|
|
|
return `${key}:${value}`;
|
|
|
|
}),
|
|
|
|
timeout,
|
|
|
|
});
|
|
|
|
|
|
|
|
const responseHeaders: Array<[string, string]> = flatResponseHeaders.map(
|
|
|
|
header => {
|
|
|
|
const [key, value] = header.split(':', 2);
|
|
|
|
strictAssert(value !== undefined, 'Invalid header!');
|
|
|
|
return [key, value];
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
return new Response(response, {
|
|
|
|
status,
|
|
|
|
statusText,
|
|
|
|
headers: responseHeaders,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public registerRequestHandler(handler: IRequestHandler): void {
|
|
|
|
this.requestHandlers.add(handler);
|
|
|
|
|
|
|
|
const queue = this.incomingRequestQueue;
|
|
|
|
if (queue.length === 0) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-07-28 21:37:09 +00:00
|
|
|
`SocketManager: processing ${queue.length} queued incoming requests`
|
|
|
|
);
|
|
|
|
this.incomingRequestQueue = [];
|
|
|
|
for (const req of queue) {
|
|
|
|
this.queueOrHandleRequest(req);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public unregisterRequestHandler(handler: IRequestHandler): void {
|
|
|
|
this.requestHandlers.delete(handler);
|
|
|
|
}
|
|
|
|
|
2022-10-05 00:48:25 +00:00
|
|
|
public async onHasStoriesDisabledChange(newValue: boolean): Promise<void> {
|
|
|
|
if (this.hasStoriesDisabled === newValue) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.hasStoriesDisabled = newValue;
|
|
|
|
log.info(
|
|
|
|
`SocketManager: reconnecting after setting hasStoriesDisabled=${newValue}`
|
|
|
|
);
|
|
|
|
await this.reconnect();
|
|
|
|
}
|
|
|
|
|
|
|
|
public async reconnect(): Promise<void> {
|
|
|
|
log.info('SocketManager.reconnect: starting...');
|
|
|
|
this.onOffline();
|
|
|
|
await this.onOnline();
|
|
|
|
log.info('SocketManager.reconnect: complete.');
|
|
|
|
}
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
// Force keep-alive checks on WebSocketResources
|
|
|
|
public async check(): Promise<void> {
|
|
|
|
if (this.isOffline) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager.check');
|
2021-07-28 21:37:09 +00:00
|
|
|
await Promise.all([
|
|
|
|
SocketManager.checkResource(this.authenticated),
|
|
|
|
SocketManager.checkResource(this.unauthenticated),
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Puts SocketManager into "online" state and reconnects the authenticated
|
|
|
|
// WebSocketResource (if there are valid credentials)
|
|
|
|
public async onOnline(): Promise<void> {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager.onOnline');
|
2021-07-28 21:37:09 +00:00
|
|
|
this.isOffline = false;
|
|
|
|
|
|
|
|
if (this.credentials) {
|
|
|
|
await this.authenticate(this.credentials);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Puts SocketManager into "offline" state and gracefully disconnects both
|
|
|
|
// unauthenticated and authenticated resources.
|
2022-10-05 00:48:25 +00:00
|
|
|
public onOffline(): void {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager.onOffline');
|
2021-07-28 21:37:09 +00:00
|
|
|
this.isOffline = true;
|
|
|
|
|
2021-08-24 15:58:40 +00:00
|
|
|
const { authenticated, unauthenticated } = this;
|
|
|
|
if (authenticated) {
|
|
|
|
authenticated.abort();
|
|
|
|
this.dropAuthenticated(authenticated);
|
|
|
|
}
|
|
|
|
if (unauthenticated) {
|
|
|
|
unauthenticated.abort();
|
|
|
|
this.dropUnauthenticated(unauthenticated);
|
|
|
|
}
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
2021-09-15 18:44:27 +00:00
|
|
|
public async logout(): Promise<void> {
|
|
|
|
const { authenticated } = this;
|
|
|
|
if (authenticated) {
|
|
|
|
authenticated.abort();
|
|
|
|
this.dropAuthenticated(authenticated);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.credentials = undefined;
|
|
|
|
}
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
//
|
|
|
|
// Private
|
|
|
|
//
|
|
|
|
|
2021-09-16 20:18:42 +00:00
|
|
|
private setStatus(status: SocketStatus): void {
|
|
|
|
if (this.status === status) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.status = status;
|
|
|
|
this.emit('statusChange');
|
|
|
|
}
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
private async getUnauthenticatedResource(): Promise<WebSocketResource> {
|
|
|
|
if (this.isOffline) {
|
|
|
|
throw new HTTPError('SocketManager offline', {
|
|
|
|
code: 0,
|
|
|
|
headers: {},
|
|
|
|
stack: new Error().stack,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.unauthenticated) {
|
|
|
|
return this.unauthenticated.getResult();
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager: connecting unauthenticated socket');
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
const process = this.connectResource({
|
2021-12-01 18:55:17 +00:00
|
|
|
name: 'unauthenticated',
|
2021-07-28 21:37:09 +00:00
|
|
|
path: '/v1/websocket/',
|
|
|
|
resourceOptions: {
|
2023-06-07 00:36:38 +00:00
|
|
|
name: 'unauthenticated',
|
2021-07-28 21:37:09 +00:00
|
|
|
keepalive: { path: '/v1/keepalive' },
|
|
|
|
},
|
|
|
|
});
|
|
|
|
this.unauthenticated = process;
|
|
|
|
|
2021-07-29 16:25:21 +00:00
|
|
|
let unauthenticated: WebSocketResource;
|
|
|
|
try {
|
|
|
|
unauthenticated = await this.unauthenticated.getResult();
|
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-07-29 16:25:21 +00:00
|
|
|
'SocketManager: failed to connect unauthenticated socket ' +
|
|
|
|
` due to error: ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
this.dropUnauthenticated(process);
|
|
|
|
throw error;
|
|
|
|
}
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info('SocketManager: connected unauthenticated socket');
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
unauthenticated.addEventListener('close', ({ code, reason }): void => {
|
|
|
|
if (this.unauthenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: unauthenticated socket closed ' +
|
|
|
|
`with code=${code} and reason=${reason}`
|
|
|
|
);
|
|
|
|
|
|
|
|
this.dropUnauthenticated(process);
|
|
|
|
});
|
|
|
|
|
|
|
|
return this.unauthenticated.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
private connectResource({
|
2021-12-01 18:55:17 +00:00
|
|
|
name,
|
2021-07-28 21:37:09 +00:00
|
|
|
path,
|
|
|
|
resourceOptions,
|
|
|
|
query = {},
|
2022-10-05 00:48:25 +00:00
|
|
|
extraHeaders = {},
|
2021-07-28 21:37:09 +00:00
|
|
|
}: {
|
2021-12-01 18:55:17 +00:00
|
|
|
name: string;
|
2021-07-28 21:37:09 +00:00
|
|
|
path: string;
|
|
|
|
resourceOptions: WebSocketResourceOptions;
|
|
|
|
query?: Record<string, string>;
|
2022-10-05 00:48:25 +00:00
|
|
|
extraHeaders?: Record<string, string>;
|
2021-07-28 21:37:09 +00:00
|
|
|
}): AbortableProcess<WebSocketResource> {
|
|
|
|
const queryWithDefaults = {
|
|
|
|
agent: 'OWD',
|
|
|
|
version: this.options.version,
|
|
|
|
...query,
|
|
|
|
};
|
|
|
|
|
2021-11-08 23:32:31 +00:00
|
|
|
const url = `${this.options.url}${path}?${qs.encode(queryWithDefaults)}`;
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-11-08 23:32:31 +00:00
|
|
|
return connectWebSocket({
|
2021-12-01 18:55:17 +00:00
|
|
|
name,
|
2021-11-08 23:32:31 +00:00
|
|
|
url,
|
|
|
|
certificateAuthority: this.options.certificateAuthority,
|
|
|
|
version: this.options.version,
|
|
|
|
proxyAgent: this.proxyAgent,
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2022-10-05 00:48:25 +00:00
|
|
|
extraHeaders,
|
|
|
|
|
2021-11-08 23:32:31 +00:00
|
|
|
createResource(socket: WebSocket): WebSocketResource {
|
|
|
|
return new WebSocketResource(socket, resourceOptions);
|
2021-07-28 21:37:09 +00:00
|
|
|
},
|
2021-11-08 23:32:31 +00:00
|
|
|
});
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private static async checkResource(
|
|
|
|
process?: AbortableProcess<WebSocketResource>
|
|
|
|
): Promise<void> {
|
|
|
|
if (!process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const resource = await process.getResult();
|
|
|
|
resource.forceKeepAlive();
|
|
|
|
}
|
|
|
|
|
|
|
|
private dropAuthenticated(
|
|
|
|
process: AbortableProcess<WebSocketResource>
|
|
|
|
): void {
|
2021-08-24 15:58:40 +00:00
|
|
|
if (this.authenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
this.incomingRequestQueue = [];
|
|
|
|
this.authenticated = undefined;
|
2021-09-16 20:18:42 +00:00
|
|
|
this.setStatus(SocketStatus.CLOSED);
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private dropUnauthenticated(
|
|
|
|
process: AbortableProcess<WebSocketResource>
|
|
|
|
): void {
|
2021-08-24 15:58:40 +00:00
|
|
|
if (this.unauthenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.unauthenticated = undefined;
|
|
|
|
if (!this.unauthenticatedExpirationTimer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
clearTimeout(this.unauthenticatedExpirationTimer);
|
|
|
|
this.unauthenticatedExpirationTimer = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async startUnauthenticatedExpirationTimer(
|
|
|
|
expected: WebSocketResource
|
|
|
|
): Promise<void> {
|
|
|
|
const process = this.unauthenticated;
|
2021-07-28 21:37:09 +00:00
|
|
|
strictAssert(
|
2021-08-24 15:58:40 +00:00
|
|
|
process !== undefined,
|
|
|
|
'Unauthenticated socket must be connected'
|
2021-07-28 21:37:09 +00:00
|
|
|
);
|
2021-08-24 15:58:40 +00:00
|
|
|
|
|
|
|
const unauthenticated = await process.getResult();
|
|
|
|
strictAssert(
|
|
|
|
unauthenticated === expected,
|
|
|
|
'Unauthenticated resource should be the same'
|
|
|
|
);
|
|
|
|
|
|
|
|
if (this.unauthenticatedExpirationTimer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-08-24 15:58:40 +00:00
|
|
|
'SocketManager: starting expiration timer for unauthenticated socket'
|
|
|
|
);
|
|
|
|
this.unauthenticatedExpirationTimer = setTimeout(async () => {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-08-24 15:58:40 +00:00
|
|
|
'SocketManager: shutting down unauthenticated socket after timeout'
|
|
|
|
);
|
|
|
|
unauthenticated.shutdown();
|
|
|
|
|
|
|
|
// The socket is either deliberately closed or reconnected already
|
|
|
|
if (this.unauthenticated !== process) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.dropUnauthenticated(process);
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this.getUnauthenticatedResource();
|
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-08-24 15:58:40 +00:00
|
|
|
'SocketManager: failed to reconnect unauthenticated socket ' +
|
|
|
|
`due to error: ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}, FIVE_MINUTES);
|
2021-07-28 21:37:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private queueOrHandleRequest(req: IncomingWebSocketRequest): void {
|
|
|
|
if (this.requestHandlers.size === 0) {
|
|
|
|
this.incomingRequestQueue.push(req);
|
2021-09-17 18:27:53 +00:00
|
|
|
log.info(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: request handler unavailable, ' +
|
|
|
|
`queued request. Queue size: ${this.incomingRequestQueue.length}`
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
for (const handlers of this.requestHandlers) {
|
|
|
|
try {
|
|
|
|
handlers.handleRequest(req);
|
|
|
|
} catch (error) {
|
2021-09-17 18:27:53 +00:00
|
|
|
log.warn(
|
2021-07-28 21:37:09 +00:00
|
|
|
'SocketManager: got exception while handling incoming request, ' +
|
|
|
|
`error: ${Errors.toLogFormat(error)}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-04 00:37:17 +00:00
|
|
|
private isAuthenticated(headers: Headers): boolean {
|
|
|
|
if (!this.credentials) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const authorization = headers.get('Authorization');
|
|
|
|
if (!authorization) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const [basic, base64] = authorization.split(/\s+/, 2);
|
|
|
|
|
|
|
|
if (basic.toLowerCase() !== 'basic' || !base64) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const [username, password] = Bytes.toString(Bytes.fromBase64(base64)).split(
|
|
|
|
':',
|
|
|
|
2
|
|
|
|
);
|
|
|
|
|
|
|
|
return (
|
|
|
|
username === this.credentials.username &&
|
|
|
|
password === this.credentials.password
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-07-28 21:37:09 +00:00
|
|
|
// EventEmitter types
|
|
|
|
|
2021-11-12 23:44:20 +00:00
|
|
|
public override on(
|
|
|
|
type: 'authError',
|
|
|
|
callback: (error: HTTPError) => void
|
|
|
|
): this;
|
|
|
|
public override on(type: 'statusChange', callback: () => void): this;
|
2021-07-28 21:37:09 +00:00
|
|
|
|
2021-11-12 23:44:20 +00:00
|
|
|
public override on(
|
2021-07-28 21:37:09 +00:00
|
|
|
type: string | symbol,
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
listener: (...args: Array<any>) => void
|
|
|
|
): this {
|
|
|
|
return super.on(type, listener);
|
|
|
|
}
|
|
|
|
|
2021-11-12 23:44:20 +00:00
|
|
|
public override emit(type: 'authError', error: HTTPError): boolean;
|
|
|
|
public override emit(type: 'statusChange'): boolean;
|
2021-07-28 21:37:09 +00:00
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2021-11-12 23:44:20 +00:00
|
|
|
public override emit(type: string | symbol, ...args: Array<any>): boolean {
|
2021-07-28 21:37:09 +00:00
|
|
|
return super.emit(type, ...args);
|
|
|
|
}
|
|
|
|
}
|