From 2a67e6ab3f707f691a5c52df8deb1a5a91392cb5 Mon Sep 17 00:00:00 2001 From: Alexzhu Date: Tue, 2 Jun 2026 13:15:41 +0800 Subject: [PATCH] fix(scripts): validate mock webview bridge port (#3073) Co-authored-by: Steven Enamakel --- .../mock-webview-bridge-args.test.mjs | 31 +++++++++++++++++++ scripts/mock-webview-bridge.mjs | 25 ++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 scripts/__tests__/mock-webview-bridge-args.test.mjs diff --git a/scripts/__tests__/mock-webview-bridge-args.test.mjs b/scripts/__tests__/mock-webview-bridge-args.test.mjs new file mode 100644 index 000000000..33ec006c8 --- /dev/null +++ b/scripts/__tests__/mock-webview-bridge-args.test.mjs @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { test } from 'node:test'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const SCRIPT = resolve(HERE, '..', 'mock-webview-bridge.mjs'); + +function run(args) { + return spawnSync(process.execPath, [SCRIPT, ...args], { + encoding: 'utf8', + }); +} + +test('mock-webview-bridge --help prints usage without opening a listener', () => { + const result = run(['--help']); + + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /Usage: node scripts\/mock-webview-bridge\.mjs \[port\]/); + assert.equal(result.stderr, ''); +}); + +test('mock-webview-bridge rejects invalid ports before WebSocket startup', () => { + for (const args of [['nope'], ['0'], ['65536'], ['9826', 'extra'], ['9826', '']]) { + const result = run(args); + + assert.equal(result.status, 2, result.stdout); + assert.doesNotMatch(result.stderr, /ERR_SOCKET_BAD_PORT/); + } +}); diff --git a/scripts/mock-webview-bridge.mjs b/scripts/mock-webview-bridge.mjs index 5d526d3f1..015faa8e9 100644 --- a/scripts/mock-webview-bridge.mjs +++ b/scripts/mock-webview-bridge.mjs @@ -6,7 +6,30 @@ import { WebSocketServer } from 'ws'; -const port = Number(process.argv[2] ?? 9826); +function usage() { + return 'Usage: node scripts/mock-webview-bridge.mjs [port]'; +} + +function readPortArg() { + const args = process.argv.slice(2); + const [rawPort] = args; + if (rawPort === '--help' || rawPort === '-h') { + console.log(usage()); + process.exit(0); + } + if (args.length > 1) { + console.error(usage()); + process.exit(2); + } + const port = Number(rawPort ?? 9826); + if (!Number.isInteger(port) || port <= 0 || port >= 65536) { + console.error('[mock-bridge] port must be an integer between 1 and 65535'); + process.exit(2); + } + return port; +} + +const port = readPortArg(); const wss = new WebSocketServer({ host: '127.0.0.1', port }); console.log(`[mock-bridge] listening on ws://127.0.0.1:${port}`);