fix(cli): signal only processes the OS says own the port (#3307)

* fix(cli): signal only processes the OS says own the port

`/__hyperframes_config` is unauthenticated and the PID it reports is what
`--stop` and `--kill-all` send signals to, so any local process answering on
a scanned port could name an arbitrary PID and have the CLI kill it.
Reproduced with a twenty-line HTTP server on a scanned port self-reporting an
unrelated PID: before this, `--kill-all` killed that process; after it, the
process survives and only the real listener is stopped.

The listening PID now comes from the OS — `lsof`, and `netstat` on Windows,
where the lookup was previously unavailable and the self-reported value was
taken on trust. The response's own PID is used only where the OS lookup
fails, which is also the only case where it is unfalsifiable.

Orphan cleanup moves to the last step before a launch. It reaches outside the
process and kills other people's PIDs, so it must not run for an invocation
that turns out to be a validation error and never starts anything.

* fix(cli): fail closed when the OS cannot confirm who owns a port

Review follow-up.

The two halves of this change picked opposite directions for the same
condition. `isProcessDescendant` fails closed by design; `activeServerOnPort`
fell back to the self-reported PID whenever the OS lookup came back empty —
and that is not only "unsupported platform". `lsof` may be absent (the default
on many slim images), may time out, or may not see a socket owned by another
user. On such a machine every scanned port silently reverted to pre-change
behaviour, with nothing said.

Provenance is now part of the type rather than a convention: `ActiveServer`
carries `pidSource`, so a caller cannot mistake a self-report for the kernel's
answer. `--kill-all` requires `"os"` and skips the rest, naming the ports it
left alone and why. That is the deliberate trade — a blind sweep of a port
range has no evidence beyond an unauthenticated response, so an unconfirmed
PID must not be signalled. Managed previews are unaffected: they stop through
their session record, which proves ownership by process birth identity.

The fallback branch — the one with the security consequence — now has the
coverage it lacked, via an injected lookup matching the seam `testPortOnAllHosts`
and `isProcessDescendant` already use, including a live process that survives
because nothing confirmed it owns the socket.

Also state that `killProcessTree` honours `signal` on POSIX only: Windows
always passes `/F`, deliberately, since taskkill without it posts WM_CLOSE that
a console process may ignore. The caller-side comment claiming Windows cleanup
is a no-op described the code before this change and now says the opposite.
This commit is contained in:
Miguel Ángel
2026-08-18 17:41:46 -04:00
committed by GitHub
parent 3e4b08cdc1
commit c1c70f44bd
5 changed files with 366 additions and 59 deletions
+24 -12
View File
@@ -262,8 +262,17 @@ export default defineCommand({
console.log("\n No active preview servers to kill.\n");
return;
}
const killed = await killActiveServers(startPort);
console.log(`\n Killed ${killed} preview server${killed === 1 ? "" : "s"}.\n`);
const { killed, unverified } = await killActiveServers(startPort);
console.log(`\n Killed ${killed} preview server${killed === 1 ? "" : "s"}.`);
if (unverified.length > 0) {
clack.log.warn(
`Left ${unverified.length} server${unverified.length === 1 ? "" : "s"} alone ` +
`(port${unverified.length === 1 ? "" : "s"} ${unverified.join(", ")}): the OS could ` +
`not confirm which process owns the socket, and the server's own claim is not proof. ` +
`Install lsof, or stop it with its own preview --stop.`,
);
}
console.log();
return;
}
@@ -287,14 +296,6 @@ export default defineCommand({
);
}
// Kill orphaned chrome-headless-shell processes from previous crashed sessions.
const orphansKilled = killOrphanedProcesses();
if (orphansKilled > 0) {
console.log(
` ${c.dim(`Cleaned up ${orphansKilled} orphaned process${orphansKilled === 1 ? "" : "es"} from a previous session.`)}`,
);
}
const rawArg = args.dir;
const isImplicitCwd = !rawArg || rawArg === "." || rawArg === "./";
const project = resolveProject(rawArg);
@@ -352,6 +353,17 @@ export default defineCommand({
// modes all receive identical --proxy/--no-proxy + config semantics.
const autoProxy = resolveAutoProxy(dir, args.proxy as boolean | undefined);
// Kill orphaned chrome-headless-shell processes from previous crashed
// sessions. Deliberately last: this reaches outside the process and kills
// other people's PIDs, so it must not run for an invocation that turns out
// to be a validation error and never starts anything.
const orphansKilled = killOrphanedProcesses();
if (orphansKilled > 0) {
console.log(
` ${c.dim(`Cleaned up ${orphansKilled} orphaned process${orphansKilled === 1 ? "" : "es"} from a previous session.`)}`,
);
}
if (isDevMode()) {
if (args.background) {
clack.log.error("--background currently supports the embedded preview server only");
@@ -969,8 +981,8 @@ async function runDevMode(dir: string, options?: StudioLaunchOptions): Promise<v
// SIGINT to the foreground process group (covers the common case), but
// `kill <pid>` only targets this process — the child tree (Vite + Chrome)
// would survive without explicit cleanup.
// On Windows, killProcessTree is a no-op (pgrep/ps unavailable); Ctrl+C
// propagates via the console process group instead.
// On Windows, killProcessTree delegates to taskkill's tree mode, which force
// kills the whole tree immediately — no grace period, unlike the POSIX path.
registerChildTreeShutdown(child);
return waitForChildClose(child);
}