Detect root-process ports and harden web port probing
- Include terminal root PID in port scans so listener-only sessions are marked active - Improve web port detection for slow/large HTML responses and redirects - Add integration-style tests for terminal subprocess and web port inspectors
This commit is contained in:
1 parent
c11027be4d
commit
38644b0d81
4 files changed
+254
-16
No files matched your search
@@ -0,0 +1,130 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { defaultSubprocessInspector } from "./index";
|
||||
|
||||
interface StartedProcess {
|
||||
process: ChildProcessWithoutNullStreams;
|
||||
port: number;
|
||||
}
|
||||
|
||||
async function waitForPort(child: ChildProcessWithoutNullStreams): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("Timed out waiting for listener port"));
|
||||
}, 3_000);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("exit", onExit);
|
||||
};
|
||||
|
||||
const onStdout = (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
const match = stdout.match(/PORT:(\d+)/);
|
||||
if (!match?.[1]) return;
|
||||
const port = Number(match[1]);
|
||||
if (!Number.isInteger(port) || port <= 0) return;
|
||||
cleanup();
|
||||
resolve(port);
|
||||
};
|
||||
|
||||
const onStderr = (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
};
|
||||
|
||||
const onExit = (code: number | null) => {
|
||||
cleanup();
|
||||
reject(
|
||||
new Error(
|
||||
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.on("exit", onExit);
|
||||
});
|
||||
}
|
||||
|
||||
async function startListenerProcess(): Promise<StartedProcess> {
|
||||
const script = [
|
||||
"const { createServer } = require('node:http');",
|
||||
"const server = createServer((_req, res) => {",
|
||||
" res.statusCode = 200;",
|
||||
" res.end('ok');",
|
||||
"});",
|
||||
"server.listen(0, '127.0.0.1', () => {",
|
||||
" const address = server.address();",
|
||||
" if (typeof address !== 'object' || !address) process.exit(1);",
|
||||
" console.log(`PORT:${address.port}`);",
|
||||
"});",
|
||||
"const shutdown = () => server.close(() => process.exit(0));",
|
||||
"process.on('SIGTERM', shutdown);",
|
||||
"process.on('SIGINT', shutdown);",
|
||||
"setInterval(() => {}, 10_000);",
|
||||
].join("");
|
||||
|
||||
const process = spawn("node", ["-e", script], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const port = await waitForPort(process);
|
||||
return { process, port };
|
||||
}
|
||||
|
||||
async function stopProcess(child: ChildProcessWithoutNullStreams): Promise<void> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
child.kill("SIGTERM");
|
||||
await new Promise<void>((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000);
|
||||
child.once("exit", () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("defaultSubprocessInspector", () => {
|
||||
const spawned: ChildProcessWithoutNullStreams[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(spawned.splice(0, spawned.length).map((child) => stopProcess(child)));
|
||||
});
|
||||
|
||||
it("detects listening ports when the terminal root PID is the listener", async () => {
|
||||
const listener = await startListenerProcess();
|
||||
spawned.push(listener.process);
|
||||
|
||||
const activity = await defaultSubprocessInspector(listener.process.pid);
|
||||
|
||||
expect(activity.hasRunningSubprocess).toBe(true);
|
||||
expect(activity.runningPorts).toContain(listener.port);
|
||||
});
|
||||
|
||||
it("returns idle activity when root process has no children and no listening ports", async () => {
|
||||
const idle = spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
});
|
||||
spawned.push(idle);
|
||||
|
||||
const activity = await defaultSubprocessInspector(idle.pid);
|
||||
|
||||
expect(activity.hasRunningSubprocess).toBe(false);
|
||||
expect(activity.runningPorts).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -28,21 +28,25 @@ export async function defaultSubprocessInspector(
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const childPids = await collectWindowsChildPids(terminalPid);
|
||||
if (childPids.length === 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
const runningPorts = await checkWindowsListeningPorts(childPids);
|
||||
return { hasRunningSubprocess: true, runningPorts };
|
||||
const processPidsForPortScan = [terminalPid, ...childPids];
|
||||
const runningPorts = await checkWindowsListeningPorts(processPidsForPortScan);
|
||||
return {
|
||||
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
};
|
||||
}
|
||||
|
||||
const processFamilyPids = await collectPosixProcessFamilyPids(terminalPid);
|
||||
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
|
||||
if (subprocessPids.length === 0) {
|
||||
if (processFamilyPids.length === 0) {
|
||||
return { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}
|
||||
|
||||
const runningPorts = await checkPosixListeningPorts(subprocessPids);
|
||||
return { hasRunningSubprocess: true, runningPorts };
|
||||
const subprocessPids = processFamilyPids.filter((pid) => pid !== terminalPid);
|
||||
const runningPorts = await checkPosixListeningPorts(processFamilyPids);
|
||||
return {
|
||||
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
};
|
||||
}
|
||||
|
||||
export function subprocessCheckerToInspector(
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { defaultWebPortInspector } from "./webPortInspector";
|
||||
|
||||
async function listenServer(server: Server): Promise<number> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", (error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
throw new Error("Server did not provide a valid listening address.");
|
||||
}
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function closeServer(server: Server): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error?: Error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("defaultWebPortInspector", () => {
|
||||
const servers: Server[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(servers.splice(0, servers.length).map((server) => closeServer(server)));
|
||||
});
|
||||
|
||||
it("treats slow HTML responses as web ports", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
setTimeout(() => {
|
||||
res.statusCode = 200;
|
||||
res.setHeader("content-type", "text/html; charset=utf-8");
|
||||
res.end("<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>");
|
||||
}, 800);
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("treats HTML responses with large bodies as web ports", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
res.statusCode = 200;
|
||||
res.setHeader("content-type", "text/html; charset=utf-8");
|
||||
res.end(`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`);
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("ignores HTTP 404 responses", async () => {
|
||||
const server = createServer((_req, res) => {
|
||||
res.statusCode = 404;
|
||||
res.end();
|
||||
});
|
||||
servers.push(server);
|
||||
const port = await listenServer(server);
|
||||
|
||||
await expect(defaultWebPortInspector(port)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { request as httpRequest } from "node:http";
|
||||
|
||||
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
|
||||
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 500;
|
||||
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
|
||||
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
|
||||
|
||||
interface WebProbeResult {
|
||||
@@ -60,6 +60,35 @@ async function probeWebPortOnHost(
|
||||
timeout: DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
const status = res.statusCode ?? 0;
|
||||
const contentType = normalizeHeaderValue(res.headers["content-type"]);
|
||||
const location = normalizeHeaderValue(res.headers.location);
|
||||
|
||||
const settleFromChunks = (chunks: string[]) => {
|
||||
settle({
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: chunks.join(""),
|
||||
});
|
||||
};
|
||||
|
||||
// Resolve immediately for clear web responses based on status/headers.
|
||||
if (
|
||||
(status >= 300 && status < 400 && location.length > 0) ||
|
||||
contentType.toLowerCase().includes("text/html") ||
|
||||
contentType.toLowerCase().includes("application/xhtml+xml")
|
||||
) {
|
||||
settle({
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: "",
|
||||
});
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: string[] = [];
|
||||
let received = 0;
|
||||
res.setEncoding("utf8");
|
||||
@@ -70,16 +99,12 @@ async function probeWebPortOnHost(
|
||||
received += fragment.length;
|
||||
chunks.push(fragment);
|
||||
if (received >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
|
||||
settleFromChunks(chunks);
|
||||
res.destroy();
|
||||
}
|
||||
});
|
||||
res.on("end", () => {
|
||||
settle({
|
||||
status: res.statusCode ?? 0,
|
||||
contentType: normalizeHeaderValue(res.headers["content-type"]),
|
||||
location: normalizeHeaderValue(res.headers.location),
|
||||
body: chunks.join(""),
|
||||
});
|
||||
settleFromChunks(chunks);
|
||||
});
|
||||
res.on("error", () => {
|
||||
settle(null);
|
||||
|
||||
Reference in new issue
Block a user