diff --git a/src/infra/ports-inspect.ts b/src/infra/ports-inspect.ts index cd896c376c9..500c0f00bd7 100644 --- a/src/infra/ports-inspect.ts +++ b/src/infra/ports-inspect.ts @@ -76,19 +76,27 @@ function normalizeTcpHost(host: string): string { return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized; } +function parseTcpPort(raw: string | undefined): number | null { + if (!raw || !/^\d+$/.test(raw)) { + return null; + } + const port = Number(raw); + return Number.isSafeInteger(port) && port >= 0 && port <= 65_535 ? port : null; +} + function parseTcpEndpoint(raw: string): { host: string; port: number } | null { const endpoint = raw.trim(); const bracketMatch = endpoint.match(/^\[([^\]]+)\]:(\d+)$/); if (bracketMatch) { - const port = Number.parseInt(bracketMatch[2], 10); - return Number.isFinite(port) ? { host: normalizeTcpHost(bracketMatch[1]), port } : null; + const port = parseTcpPort(bracketMatch[2]); + return port === null ? null : { host: normalizeTcpHost(bracketMatch[1]), port }; } const lastColon = endpoint.lastIndexOf(":"); if (lastColon <= 0 || lastColon >= endpoint.length - 1) { return null; } - const port = Number.parseInt(endpoint.slice(lastColon + 1), 10); - if (!Number.isFinite(port)) { + const port = parseTcpPort(endpoint.slice(lastColon + 1)); + if (port === null) { return null; } return { host: normalizeTcpHost(endpoint.slice(0, lastColon)), port }; diff --git a/src/infra/ports.test.ts b/src/infra/ports.test.ts index a823df52d28..dcba528866a 100644 --- a/src/infra/ports.test.ts +++ b/src/infra/ports.test.ts @@ -206,6 +206,8 @@ describeUnix("inspectPortUsage", () => { "p111\ncnode\nnTCP 127.0.0.1:50123->127.0.0.1:18789 (ESTABLISHED)\n" + "p222\ncnode\nnTCP 127.0.0.1:18789->127.0.0.1:50123 (ESTABLISHED)\n" + "p444\ncnode\nnTCP 127.0.0.1:50125->[::ffff:127.0.0.1]:18789 (ESTABLISHED)\n" + + "p555\ncnode\nnTCP 127.0.0.1:50126->127.0.0.1:18789abc (ESTABLISHED)\n" + + "p666\ncnode\nnTCP 127.0.0.1:50127->127.0.0.1:99999 (ESTABLISHED)\n" + "p333\ncBrowser\nnTCP 127.0.0.1:50124->198.51.100.7:18789 (ESTABLISHED)\n", stderr: "", code: 0,