185 lines
6.4 KiB
TypeScript
185 lines
6.4 KiB
TypeScript
/**
|
|
* Copyright (c) Microsoft Corporation.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
import { WebSocketServer as wsServer } from 'ws';
|
|
import { computeAllowedHosts, hostnameFromHostHeader, urlHostFromAddress } from './httpServer';
|
|
import { createHttpServer } from './network';
|
|
import { debugLogger } from './debugLogger';
|
|
|
|
import type { WebSocket, WebSocketServer } from 'ws';
|
|
import type http from 'http';
|
|
import type stream from 'stream';
|
|
|
|
|
|
let lastConnectionId = 0;
|
|
const kConnectionSymbol = Symbol('kConnection');
|
|
|
|
export const perMessageDeflate = {
|
|
serverNoContextTakeover: true,
|
|
zlibDeflateOptions: {
|
|
level: 3,
|
|
},
|
|
zlibInflateOptions: {
|
|
chunkSize: 10 * 1024
|
|
},
|
|
threshold: 10 * 1024,
|
|
};
|
|
|
|
export type WSConnection = {
|
|
close: () => Promise<void>;
|
|
};
|
|
|
|
export type WSServerDelegate = {
|
|
onRequest: (request: http.IncomingMessage, response: http.ServerResponse) => void;
|
|
onHeaders: (headers: string[]) => void;
|
|
onUpgrade: (request: http.IncomingMessage, socket: stream.Duplex) => { error: string } | undefined;
|
|
onConnection: (request: http.IncomingMessage, url: URL, ws: WebSocket, id: string) => WSConnection;
|
|
};
|
|
|
|
export class WSServer {
|
|
private _wsServer: WebSocketServer | undefined;
|
|
server: http.Server | undefined;
|
|
private _delegate: WSServerDelegate;
|
|
// Allowed Host headers for HTTP requests. null disables the check (server bound to a public address).
|
|
private _allowedHosts: Set<string> | null = null;
|
|
|
|
constructor(delegate: WSServerDelegate) {
|
|
this._delegate = delegate;
|
|
}
|
|
|
|
async listen(port: number = 0, hostname: string | undefined, path: string): Promise<string> {
|
|
debugLogger.log('server', `Server started at ${new Date()}`);
|
|
|
|
// Default to loopback so the WebSocket RPC is not exposed to the network unless
|
|
// the caller explicitly opts in by passing a host (e.g. '0.0.0.0').
|
|
hostname ??= 'localhost';
|
|
|
|
const server = createHttpServer((request, response) => this._onRequest(request, response));
|
|
server.on('error', error => debugLogger.log('server', String(error)));
|
|
this.server = server;
|
|
|
|
const wsEndpoint = await new Promise<string>((resolve, reject) => {
|
|
server.listen(port, hostname, () => {
|
|
const address = server.address();
|
|
if (!address) {
|
|
reject(new Error('Could not bind server socket'));
|
|
return;
|
|
}
|
|
if (typeof address === 'string') {
|
|
resolve(`${address}${path}`);
|
|
return;
|
|
}
|
|
// Advertise the bound IP literal in the wsEndpoint so the client connects to
|
|
// the same address family the server bound to. Otherwise the client and
|
|
// server resolvers can disagree on what 'localhost' means (see #40605).
|
|
this._allowedHosts = computeAllowedHosts(hostname, address.address);
|
|
resolve(`ws://${urlHostFromAddress(address)}:${address.port}${path}`);
|
|
}).on('error', reject);
|
|
});
|
|
|
|
debugLogger.log('server', 'Listening at ' + wsEndpoint);
|
|
|
|
this._wsServer = new wsServer({
|
|
noServer: true,
|
|
perMessageDeflate,
|
|
});
|
|
|
|
this._wsServer.on('headers', headers => this._delegate.onHeaders(headers));
|
|
|
|
server.on('upgrade', (request, socket, head) => {
|
|
const pathname = new URL('http://localhost' + request.url!).pathname;
|
|
if (pathname !== path) {
|
|
socket.write(`HTTP/${request.httpVersion} 400 Bad Request\r\n\r\n`);
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
if (this._allowedHosts && !this._isAllowedOrigin(request.headers.origin)) {
|
|
socket.write(`HTTP/${request.httpVersion} 403 Forbidden\r\n\r\n`);
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
const upgradeResult = this._delegate.onUpgrade(request, socket);
|
|
if (upgradeResult) {
|
|
socket.write(upgradeResult.error);
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
this._wsServer!.handleUpgrade(request, socket, head, ws => this._wsServer!.emit('connection', ws, request));
|
|
});
|
|
|
|
this._wsServer.on('connection', (ws, request) => {
|
|
debugLogger.log('server', 'Connected client ws.extension=' + ws.extensions);
|
|
const url = new URL('http://localhost' + (request.url || ''));
|
|
const id = String(++lastConnectionId);
|
|
debugLogger.log('server', `[${id}] serving connection: ${request.url}`);
|
|
const connection = this._delegate.onConnection(request, url, ws, id);
|
|
(ws as any)[kConnectionSymbol] = connection;
|
|
});
|
|
|
|
return wsEndpoint;
|
|
}
|
|
|
|
private _onRequest(request: http.IncomingMessage, response: http.ServerResponse) {
|
|
if (this._allowedHosts) {
|
|
const host = request.headers.host?.toLowerCase();
|
|
const hostname = host ? hostnameFromHostHeader(host) : undefined;
|
|
if (!hostname || !this._allowedHosts.has(hostname)) {
|
|
response.statusCode = 403;
|
|
response.end();
|
|
return;
|
|
}
|
|
}
|
|
this._delegate.onRequest(request, response);
|
|
}
|
|
|
|
private _isAllowedOrigin(origin: string | undefined): boolean {
|
|
if (!origin)
|
|
return true;
|
|
try {
|
|
const hostname = new URL(origin).hostname.toLowerCase();
|
|
const bracketed = hostname.includes(':') ? `[${hostname}]` : hostname;
|
|
return this._allowedHosts!.has(hostname) || this._allowedHosts!.has(bracketed);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async close() {
|
|
const server = this._wsServer;
|
|
if (!server)
|
|
return;
|
|
debugLogger.log('server', 'closing websocket server');
|
|
const waitForClose = new Promise(f => server.close(f));
|
|
// First disconnect all remaining clients.
|
|
await Promise.all(Array.from(server.clients).map(async ws => {
|
|
const connection = (ws as any)[kConnectionSymbol] as WSConnection | undefined;
|
|
if (connection)
|
|
await connection.close();
|
|
try {
|
|
ws.terminate();
|
|
} catch (e) {
|
|
}
|
|
}));
|
|
await waitForClose;
|
|
debugLogger.log('server', 'closing http server');
|
|
if (this.server)
|
|
await new Promise(f => this.server!.close(f));
|
|
this._wsServer = undefined;
|
|
this.server = undefined;
|
|
debugLogger.log('server', 'closed server');
|
|
}
|
|
}
|