// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import http from 'node:http'; import type { AddressInfo } from 'node:net'; import { URL } from 'node:url'; import { WebSocketServer, type WebSocket } from 'ws'; import type { ITerminal } from '@rushstack/terminal'; const LOCALHOST: string = 'localhost'; /** * Formats an address info object into a WebSocket-compatible address string. * IPv6 addresses are formatted with brackets: [address]:port * IPv4 addresses are formatted as: address:port */ function formatAddress(addressInfo: AddressInfo): string { return addressInfo.family === 'IPv6' ? `[${addressInfo.address}]:${addressInfo.port}` : `${addressInfo.address}:${addressInfo.port}`; } /** * This HttpServer is used for the localProxyWs WebSocketServer. * The purpose is to parse the query params and path for the websocket url to get the * browserName and launchOptions. */ export class HttpServer { readonly #server: http.Server; readonly #wsServer: WebSocketServer; // local proxy websocket server accepting browser clients #listeningAddress: string | undefined; #logger: ITerminal; public constructor(logger: ITerminal) { this.#logger = logger; // We'll create an HTTP server and attach a WebSocketServer in noServer mode so we can // manually parse the URL and extract query parameters before upgrading. this.#server = http.createServer(); this.#wsServer = new WebSocketServer({ noServer: true }); this.#server.on('upgrade', (request, socket, head) => { // Accept all upgrades on the root path. We parse query string for browserName + launchOptions. this.#wsServer.handleUpgrade(request, socket, head, (ws: WebSocket) => { this.#wsServer.emit('connection', ws, request); }); }); } public async listenAsync(): Promise { return await new Promise((resolve) => { // Bind to 'localhost' which resolves to IPv4 (127.0.0.1) or IPv6 (::1) // depending on system configuration and DNS resolution this.#server.listen(0, LOCALHOST, () => { const addressInfo: AddressInfo | string | null = this.#server.address(); if (!addressInfo) { throw new Error('Server address is null - server may not be bound properly'); } if (typeof addressInfo === 'string') { throw new Error(`Server address is a pipe/socket path (${addressInfo}), expected an IP address`); } const formattedAddress: string = formatAddress(addressInfo); this.#listeningAddress = formattedAddress; // This MUST be printed to terminal so VS Code can auto-port forward this.#logger.writeLine(`Local proxy HttpServer listening at ws://${formattedAddress}`); resolve(new URL(`ws://${formattedAddress}`)); }); }); } public get endpoint(): string { if (this.#listeningAddress === undefined) { throw new Error('HttpServer not listening yet'); } return `ws://${this.#listeningAddress}`; } public get wsServer(): WebSocketServer { return this.#wsServer; } public [Symbol.dispose](): void { this.#wsServer.close(); this.#server.close(); } }