port-reclaim 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  A zero-configuration, cross-platform CLI for safely reclaiming ports held by stale local development processes.
4
4
 
5
+ [![npm version](https://img.shields.io/npm/v/port-reclaim)](https://www.npmjs.com/package/port-reclaim)
6
+ [![downloads](https://img.shields.io/npm/dw/port-reclaim)](https://npmcharts.com/compare/port-reclaim?minimal=true)
7
+ [![CI](https://img.shields.io/github/actions/workflow/status/princegoel0/port-reclaim/ci.yml?label=CI)](https://github.com/princegoel0/port-reclaim/actions/workflows/ci.yml)
8
+ [![license](https://img.shields.io/npm/l/port-reclaim)](LICENSE)
9
+
5
10
  ![A recorded session: listing a busy port, releasing it, declining to kill a database and a Docker process, then reclaiming ports by process name](https://raw.githubusercontent.com/princegoel0/port-reclaim/main/assets/demo.gif)
6
11
 
7
12
  ## Why `port-reclaim`?
@@ -56,6 +61,7 @@ Both TCP and UDP listeners are discovered. Discovery costs one `netstat`/`lsof`
56
61
  | `-l`, `--list` | Report what is using each port without killing anything. |
57
62
  | `-y`, `--yes` | Terminate processes from other directories without prompting. |
58
63
  | `-m`, `--match REGEX` | Reclaim every port held by a process whose name matches REGEX, instead of naming ports. |
64
+ | `-j`, `--json` | Print a machine-readable report. Never terminates anything. |
59
65
  | `--no-color` | Disable coloured output. |
60
66
  | `-h`, `--help` | Show the help message. |
61
67
  | `-v`, `--version` | Show the installed version. |
@@ -71,6 +77,31 @@ port-reclaim --match '^node$' --yes
71
77
 
72
78
  The same safety rules apply: refusals still block Docker and operating-system PIDs, data services still prompt, and a process holding any protected port is skipped entirely. `--match` cannot be combined with port arguments, and an invalid expression exits with status `2`.
73
79
 
80
+ ### WSL2
81
+
82
+ Under WSL2's default **NAT** networking, Linux and Windows keep separate port spaces: a port held by a Windows process is invisible to `lsof` and `ss`, and binding it inside WSL succeeds. The tool detects that case through WSL's Windows interop and names the process instead of staying silent:
83
+
84
+ ```
85
+ Port 4951 is free inside WSL, but a Windows tcp listener 'node.exe' (PID 19220) already holds it.
86
+ ```
87
+
88
+ It still exits `0`, because the port genuinely is free in your WSL namespace and your server will start — only `localhost` from Windows keeps reaching the other process. Reclaim it from Windows, or set `networkingMode=mirrored` in `.wslconfig` to share one space. WSL's own forwarding helper (`wslrelay`) is ignored deliberately: it mirrors ports your WSL processes already serve, so reporting it would be a false alarm. Windows processes are never killed from WSL.
89
+
90
+ ### Machine-readable output
91
+
92
+ `--json` reports and never terminates, which makes it safe to drop into CI:
93
+
94
+ ```sh
95
+ port-reclaim 3000 5173 --json
96
+ ```
97
+
98
+ ```json
99
+ {"ports":[{"port":3000,"state":"occupied","processes":[{"pid":28468,"name":"node","protocol":"tcp","ageMs":4341.3,"ports":[3000],"cwd":"C:\\repo","alwaysConfirm":false}],"host":null},
100
+ {"port":5173,"state":"free","processes":[],"host":null}]}
101
+ ```
102
+
103
+ Each port carries a `state`: `free`, `occupied`, `invisible` (something holds it but the owner is not visible to this user), `host-occupied` (a Windows process holds it while you are in WSL2 NAT), `unverifiable`, or `protected`. `--match` works too and echoes the pattern. `--json` cannot be combined with `--yes`, since that would ask for a report and an action at the same time.
104
+
74
105
  ### Colour
75
106
 
76
107
  Successes are green, refusals and errors red, prompts yellow, and process details dim. Colour switches itself off when output is redirected, can be forced off with `--no-color` or the `NO_COLOR` environment variable, and forced on with `FORCE_COLOR=1` for CI logs and recorded demos.
@@ -163,7 +194,7 @@ npm test
163
194
  npm run build
164
195
  ```
165
196
 
166
- Pull requests are tested on Ubuntu, macOS, and Windows with Node.js 18, 20, and 22.
197
+ Pull requests are tested on Ubuntu, macOS, and Windows with Node.js 18, 20, 22, and 24.
167
198
 
168
199
  ## License
169
200
 
@@ -5,6 +5,7 @@ export interface CliOptions {
5
5
  yes: boolean;
6
6
  list: boolean;
7
7
  noColor: boolean;
8
+ json: boolean;
8
9
  match?: string;
9
10
  }
10
11
  export declare function parseArgs(argv: string[]): CliOptions | undefined;
package/dist/src/args.js CHANGED
@@ -3,6 +3,7 @@ const VERSION_FLAGS = new Set(["--version", "-v"]);
3
3
  const YES_FLAGS = new Set(["--yes", "-y", "--force", "-f"]);
4
4
  const LIST_FLAGS = new Set(["--list", "-l"]);
5
5
  const NO_COLOR_FLAGS = new Set(["--no-color"]);
6
+ const JSON_FLAGS = new Set(["--json", "-j"]);
6
7
  const MATCH_FLAGS = new Set(["--match", "-m"]);
7
8
  function parsePort(value) {
8
9
  if (!/^\d+$/.test(value))
@@ -11,7 +12,7 @@ function parsePort(value) {
11
12
  return port >= 1 && port <= 65535 ? port : undefined;
12
13
  }
13
14
  export function parseArgs(argv) {
14
- const options = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
15
+ const options = { ports: [], help: false, version: false, yes: false, list: false, noColor: false, json: false };
15
16
  for (let index = 0; index < argv.length; index += 1) {
16
17
  const arg = argv[index];
17
18
  if (MATCH_FLAGS.has(arg)) {
@@ -42,6 +43,9 @@ export function parseArgs(argv) {
42
43
  else if (NO_COLOR_FLAGS.has(arg)) {
43
44
  options.noColor = true;
44
45
  }
46
+ else if (JSON_FLAGS.has(arg)) {
47
+ options.json = true;
48
+ }
45
49
  else {
46
50
  const port = parsePort(arg);
47
51
  if (port === undefined)
package/dist/src/cli.js CHANGED
@@ -16,6 +16,7 @@ Options:
16
16
  -l, --list Report what is using each port without killing anything.
17
17
  -y, --yes Terminate processes without prompting (never overrides a refusal).
18
18
  -m, --match REGEX Reclaim every port held by a process whose name matches REGEX.
19
+ -j, --json Print a machine-readable report; never terminates anything.
19
20
  --no-color Disable coloured output.
20
21
  -h, --help Show this help message.
21
22
  -v, --version Show the installed version.
@@ -110,6 +111,15 @@ async function reclaimPort(port, runner, options, known) {
110
111
  console.error(`Rerun with sudo or from an elevated PowerShell session, or inspect it with 'netstat -ano | findstr :${port}'.`);
111
112
  return false;
112
113
  }
114
+ const host = await runner.hostListener(port);
115
+ if (host) {
116
+ // Success is correct here: the port really is bindable in this namespace. The tool can
117
+ // report the host-side owner but cannot signal across the boundary, so it must not fail
118
+ // a chained dev script that will start fine.
119
+ console.error(paint("yellow", `Port ${port} is free inside WSL, but a Windows ${host.protocol} listener${host.name ? ` '${host.name}'` : ""} (PID ${host.pid}) already holds it.`));
120
+ console.error(`WSL2's default NAT networking keeps the two apart: a server started here binds fine, yet localhost:${port} from Windows still reaches the Windows process. Reclaim it from Windows, or set networkingMode=mirrored in .wslconfig.`);
121
+ return true;
122
+ }
113
123
  if (options.list) {
114
124
  console.log(state === "free" ? paint("green", `Port ${port} is free.`) : paint("yellow", `Port ${port} appears free but could not be verified.`));
115
125
  }
@@ -161,6 +171,48 @@ async function reclaimMatching(runner, options, pattern, ignored) {
161
171
  }
162
172
  return exitCode;
163
173
  }
174
+ async function describePort(port, runner, ignored) {
175
+ if (ignored.has(port))
176
+ return { port, state: "protected", processes: [], host: null };
177
+ const processes = await runner.discover(port);
178
+ if (processes.length > 0)
179
+ return { port, state: "occupied", processes, host: null };
180
+ const state = await runner.probe(port);
181
+ if (state === "occupied")
182
+ return { port, state: "invisible", processes, host: null };
183
+ const host = await runner.hostListener(port);
184
+ if (host)
185
+ return { port, state: "host-occupied", processes, host };
186
+ return { port, state: state === "free" ? "free" : "unverifiable", processes, host: null };
187
+ }
188
+ async function reportJson(ports, runner, ignored) {
189
+ const results = [];
190
+ for (const port of ports)
191
+ results.push(await describePort(port, runner, ignored));
192
+ console.log(JSON.stringify({ ports: results }));
193
+ return 0;
194
+ }
195
+ async function reportMatchJson(runner, pattern, ignored) {
196
+ const found = await runner.discoverListening(new RegExp(pattern, "i"));
197
+ const byPort = new Map();
198
+ for (const portProcess of found) {
199
+ for (const port of portProcess.ports ?? []) {
200
+ const listed = byPort.get(port);
201
+ if (listed)
202
+ listed.push(portProcess);
203
+ else
204
+ byPort.set(port, [portProcess]);
205
+ }
206
+ }
207
+ const results = [];
208
+ for (const port of [...byPort.keys()].sort((left, right) => left - right)) {
209
+ results.push(ignored.has(port)
210
+ ? { port, state: "protected", processes: [], host: null }
211
+ : { port, state: "occupied", processes: byPort.get(port) ?? [], host: null });
212
+ }
213
+ console.log(JSON.stringify({ match: pattern, ports: results }));
214
+ return 0;
215
+ }
164
216
  export async function main(argv = process.argv.slice(2), runner = createProcessRunner()) {
165
217
  const options = parseArgs(argv);
166
218
  if (!options) {
@@ -176,6 +228,10 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
176
228
  console.log(await version());
177
229
  return 0;
178
230
  }
231
+ if (options.json && options.yes) {
232
+ console.error(paint("red", "port-reclaim: --json only reports and never terminates, so it cannot be combined with --yes."));
233
+ return 2;
234
+ }
179
235
  const config = await loadConfig(process.cwd());
180
236
  const ignored = new Set(config.ignore);
181
237
  if (options.match !== undefined) {
@@ -188,6 +244,8 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
188
244
  printUsage();
189
245
  return 2;
190
246
  }
247
+ if (options.json)
248
+ return reportMatchJson(runner, options.match, ignored);
191
249
  return reclaimMatching(runner, options, options.match, ignored);
192
250
  }
193
251
  const ports = options.ports.length > 0 ? options.ports : config.ports;
@@ -195,6 +253,8 @@ export async function main(argv = process.argv.slice(2), runner = createProcessR
195
253
  printUsage();
196
254
  return 2;
197
255
  }
256
+ if (options.json)
257
+ return reportJson(ports, runner, ignored);
198
258
  let exitCode = 0;
199
259
  for (const port of ports) {
200
260
  if (ignored.has(port)) {
@@ -1,5 +1,5 @@
1
- export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
2
- export type { ListenerRow, NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, commandName, isProtectedService, isWslInfrastructure, refusalReason, usesNatNetworking, } from "./process.js";
2
+ export type { HostListener, ListenerRow, NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
3
3
  export { colourEnabled, paint, setColourMode } from "./style.js";
4
4
  export type { Colour, ColourMode } from "./style.js";
5
5
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
package/dist/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, commandName, isProtectedService, isWslInfrastructure, refusalReason, usesNatNetworking, } from "./process.js";
2
2
  export { colourEnabled, paint, setColourMode } from "./style.js";
3
3
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
4
4
  export { parseArgs } from "./args.js";
@@ -10,11 +10,18 @@ export interface PortProcess {
10
10
  refusal?: string;
11
11
  alwaysConfirm?: boolean;
12
12
  }
13
+ export interface HostListener {
14
+ pid: number;
15
+ protocol: Protocol;
16
+ name: string;
17
+ kind: "windows";
18
+ }
13
19
  export interface ProcessRunner {
14
20
  discover(port: number): Promise<PortProcess[]>;
15
21
  discoverListening(match: RegExp): Promise<PortProcess[]>;
16
22
  terminate(pid: number): Promise<void>;
17
23
  probe(port: number): Promise<PortState>;
24
+ hostListener(port: number): Promise<HostListener | null>;
18
25
  }
19
26
  export interface ListenerRow {
20
27
  pid: number;
@@ -40,4 +47,7 @@ export interface ProcessRow {
40
47
  }
41
48
  export declare function parsePipeTable(output: string): ProcessRow[];
42
49
  export declare function parsePsTable(output: string): ProcessRow[];
50
+ export declare function commandName(args: string): string;
51
+ export declare function usesNatNetworking(networkingMode: string, distroName: string | undefined, procVersion: string): boolean;
52
+ export declare function isWslInfrastructure(name: string): boolean;
43
53
  export declare function createProcessRunner(): ProcessRunner;
@@ -1,6 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import process from "node:process";
4
+ import { readFile } from "node:fs/promises";
4
5
  import net from "node:net";
5
6
  import dgram from "node:dgram";
6
7
  import pidCwd from "pid-cwd";
@@ -140,17 +141,31 @@ export function parsePsTable(output) {
140
141
  const rows = [];
141
142
  const seen = new Set();
142
143
  for (const line of output.split(/\r?\n/)) {
143
- const match = /^\s*(\d+)\s+(.+?)\s+(\S+)\s*$/.exec(line);
144
+ // pid and etime are single tokens, so everything after them is args - which procps only
145
+ // leaves untruncated when it is the final column.
146
+ const match = /^\s*(\d+)\s+(\S+)\s+(.+)$/.exec(line);
144
147
  if (!match)
145
148
  continue;
146
149
  const pid = Number(match[1]);
147
150
  if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid))
148
151
  continue;
149
152
  seen.add(pid);
150
- rows.push({ pid, name: match[2].trim(), ageMs: parseEtime(match[3]) });
153
+ rows.push({ pid, name: commandName(match[3]), ageMs: parseEtime(match[2]) });
151
154
  }
152
155
  return rows;
153
156
  }
157
+ // The command name comes from argv[0], not from ps's comm/ucomm columns: macOS truncates the
158
+ // path in comm to 16 characters, and Node 24 renames its main thread so comm reports
159
+ // "MainThread" on Linux. Neither would match the name-based protection rules.
160
+ export function commandName(args) {
161
+ const trimmed = args.trim();
162
+ if (!trimmed)
163
+ return "unknown";
164
+ const quoted = trimmed.startsWith('"');
165
+ const first = quoted ? (/"([^"]*)"/.exec(trimmed)?.[1] ?? "") : (trimmed.split(/\s+/)[0] ?? "");
166
+ const segments = first.split("/").filter(Boolean);
167
+ return segments[segments.length - 1] ?? "unknown";
168
+ }
154
169
  async function run(command, args, checked = false) {
155
170
  try {
156
171
  const result = await execFileAsync(command, args, { windowsHide: true, maxBuffer: 1024 * 1024 });
@@ -185,7 +200,10 @@ async function processNames(pids) {
185
200
  if (process.platform === "win32") {
186
201
  return byPid(parsePipeTable(await powershell(windowsNamesScript(pids))));
187
202
  }
188
- return byPid(parsePsTable(await run("ps", ["-p", pids.join(","), "-o", "pid=,comm=,etime="])));
203
+ // args last: procps truncates any earlier args column to a fixed width. comm/ucomm are not
204
+ // usable as names - macOS cuts the path at 16 characters and Node 24 renames its main thread,
205
+ // which would silently defeat every name-based protection rule.
206
+ return byPid(parsePsTable(await run("ps", ["-ww", "-p", pids.join(","), "-o", "pid=,etime=,args="])));
189
207
  }
190
208
  async function discoverUnix(port) {
191
209
  const protocols = new Map();
@@ -273,6 +291,69 @@ async function probePortState(port) {
273
291
  return "occupied";
274
292
  return tcp === "free" && udp === "free" ? "free" : "unknown";
275
293
  }
294
+ export function usesNatNetworking(networkingMode, distroName, procVersion) {
295
+ if (!distroName && !/microsoft/i.test(procVersion))
296
+ return false;
297
+ const mode = networkingMode.trim().toLowerCase();
298
+ // WSL builds without the flag only ever offered NAT, so an unknown mode is treated as NAT.
299
+ return mode === "" || mode === "nat";
300
+ }
301
+ let wslNat;
302
+ async function wslinfoMode() {
303
+ try {
304
+ return (await run("wslinfo", ["--networking-mode"])).trim();
305
+ }
306
+ catch {
307
+ return "";
308
+ }
309
+ }
310
+ async function detectWslNat() {
311
+ if (wslNat !== undefined)
312
+ return wslNat;
313
+ wslNat = false;
314
+ if (process.platform === "linux") {
315
+ const version = await readFile("/proc/version", "utf8").catch(() => "");
316
+ if (version || process.env.WSL_DISTRO_NAME) {
317
+ wslNat = usesNatNetworking(await wslinfoMode(), process.env.WSL_DISTRO_NAME, version);
318
+ }
319
+ }
320
+ return wslNat;
321
+ }
322
+ // wslrelay is WSL's own localhost-forwarding helper: it appears on the Windows side as a
323
+ // listener for a port a WSL process is serving, so treating it as a foreign holder is wrong.
324
+ export function isWslInfrastructure(name) {
325
+ return /^wsl/i.test(name.trim());
326
+ }
327
+ async function windowsProcessName(pid) {
328
+ try {
329
+ const output = await run("tasklist.exe", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"]);
330
+ return /^"([^"]+)"/.exec(output.trim())?.[1] ?? "";
331
+ }
332
+ catch {
333
+ return "";
334
+ }
335
+ }
336
+ // Under NAT, a Windows listener is invisible to lsof/ss and does not block binding, so the
337
+ // port reads as free while Windows still answers localhost. These PIDs belong to a different
338
+ // namespace and are reported only — they must never reach terminate().
339
+ async function hostListener(port) {
340
+ if (!(await detectWslNat()))
341
+ return null;
342
+ let output;
343
+ try {
344
+ output = await run("netstat.exe", ["-ano"]);
345
+ }
346
+ catch {
347
+ return null;
348
+ }
349
+ const [entry] = parseNetstatPids(output, port);
350
+ if (!entry)
351
+ return null;
352
+ const name = await windowsProcessName(entry.pid);
353
+ if (isWslInfrastructure(name))
354
+ return null;
355
+ return { pid: entry.pid, protocol: entry.protocol, name, kind: "windows" };
356
+ }
276
357
  export function createProcessRunner() {
277
358
  return {
278
359
  async discover(port) {
@@ -302,5 +383,6 @@ export function createProcessRunner() {
302
383
  }
303
384
  },
304
385
  probe: probePortState,
386
+ hostListener,
305
387
  };
306
388
  }
@@ -1,7 +1,7 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { parseArgs } from "../src/args.js";
4
- const EMPTY = { ports: [], help: false, version: false, yes: false, list: false, noColor: false };
4
+ const EMPTY = { ports: [], help: false, version: false, yes: false, list: false, noColor: false, json: false };
5
5
  test("parses multiple ports and deduplicates", () => {
6
6
  assert.deepEqual(parseArgs(["3000", "5173", "3000"]), { ...EMPTY, ports: [3000, 5173] });
7
7
  });
@@ -12,6 +12,10 @@ test("parses flags", () => {
12
12
  assert.deepEqual(parseArgs(["-v"]), { ...EMPTY, version: true });
13
13
  assert.deepEqual(parseArgs(["--no-color", "3000"]), { ...EMPTY, noColor: true, ports: [3000] });
14
14
  });
15
+ test("parses --json", () => {
16
+ assert.deepEqual(parseArgs(["--json", "3000"]), { ...EMPTY, json: true, ports: [3000] });
17
+ assert.deepEqual(parseArgs(["-j", "3000"]), { ...EMPTY, json: true, ports: [3000] });
18
+ });
15
19
  test("parses --match with a pattern", () => {
16
20
  assert.deepEqual(parseArgs(["--match", "next-server"]), { ...EMPTY, match: "next-server" });
17
21
  assert.deepEqual(parseArgs(["-m", "^node$"]), { ...EMPTY, match: "^node$" });
@@ -6,7 +6,7 @@ import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { main } from "../src/cli.js";
8
8
  import { refusalReason, isProtectedService } from "../src/process.js";
9
- function fakeRunner(byPort, probeState = "free", listening = []) {
9
+ function fakeRunner(byPort, probeState = "free", listening = [], host = null) {
10
10
  const calls = { discovered: [], terminated: [], probed: [], patterns: [] };
11
11
  return {
12
12
  calls,
@@ -26,6 +26,9 @@ function fakeRunner(byPort, probeState = "free", listening = []) {
26
26
  calls.probed.push(port);
27
27
  return probeState;
28
28
  },
29
+ async hostListener() {
30
+ return host;
31
+ },
29
32
  },
30
33
  };
31
34
  }
@@ -69,6 +72,20 @@ test("reports a port held by a process it cannot see and exits 1", async () => {
69
72
  output.restore();
70
73
  }
71
74
  });
75
+ test("reports a Windows-side listener under WSL2 NAT and still succeeds", async () => {
76
+ const { runner, calls } = fakeRunner({}, "free", [], { pid: 18804, protocol: "tcp", name: "node", kind: "windows" });
77
+ const output = capture();
78
+ try {
79
+ assert.equal(await main(["4920"], runner), 0);
80
+ assert.deepEqual(calls.terminated, []);
81
+ assert.match(output.error.join("\n"), /free inside WSL/);
82
+ assert.match(output.error.join("\n"), /'node'/);
83
+ assert.match(output.error.join("\n"), /PID 18804/);
84
+ }
85
+ finally {
86
+ output.restore();
87
+ }
88
+ });
72
89
  test("does not probe ports that already have visible processes", async () => {
73
90
  const { runner, calls } = fakeRunner({ 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] });
74
91
  const output = capture();
@@ -215,6 +232,64 @@ test("invalid input exits 2", async () => {
215
232
  function staleServer() {
216
233
  return [{ pid: 77, name: "next-server", cwd: "/elsewhere", ports: [3000, 5173] }];
217
234
  }
235
+ test("--json reports a busy port without terminating anything", async () => {
236
+ const { runner, calls } = fakeRunner({ 3000: [{ pid: 7, name: "node", cwd: "/elsewhere", protocol: "tcp", ageMs: 5000 }] });
237
+ const output = capture();
238
+ try {
239
+ assert.equal(await main(["3000", "--json"], runner), 0);
240
+ assert.deepEqual(calls.terminated, []);
241
+ const report = JSON.parse(output.log.join(""));
242
+ assert.equal(report.ports[0].port, 3000);
243
+ assert.equal(report.ports[0].state, "occupied");
244
+ assert.equal(report.ports[0].processes[0].pid, 7);
245
+ assert.equal(report.ports[0].processes[0].name, "node");
246
+ }
247
+ finally {
248
+ output.restore();
249
+ }
250
+ });
251
+ test("--json distinguishes free, invisible, and Windows-side ports", async () => {
252
+ const cases = [
253
+ ["free", fakeRunner({}), "free"],
254
+ ["invisible", fakeRunner({}, "occupied"), "invisible"],
255
+ ["host", fakeRunner({}, "free", [], { pid: 18804, protocol: "tcp", name: "node.exe", kind: "windows" }), "host-occupied"],
256
+ ];
257
+ for (const [label, { runner }, expected] of cases) {
258
+ const output = capture();
259
+ try {
260
+ assert.equal(await main(["4700", "--json"], runner), 0, label);
261
+ assert.equal(JSON.parse(output.log.join("")).ports[0].state, expected, label);
262
+ }
263
+ finally {
264
+ output.restore();
265
+ }
266
+ }
267
+ });
268
+ test("--json with --match groups the matched processes by port", async () => {
269
+ const { runner, calls } = fakeRunner({}, "free", staleServer());
270
+ const output = capture();
271
+ try {
272
+ assert.equal(await main(["--match", "next-server", "--json"], runner), 0);
273
+ assert.deepEqual(calls.terminated, []);
274
+ const report = JSON.parse(output.log.join(""));
275
+ assert.equal(report.match, "next-server");
276
+ assert.deepEqual(report.ports.map((entry) => entry.port), [3000, 5173]);
277
+ }
278
+ finally {
279
+ output.restore();
280
+ }
281
+ });
282
+ test("--json cannot be combined with --yes", async () => {
283
+ const { runner } = fakeRunner({});
284
+ const output = capture();
285
+ try {
286
+ assert.equal(await main(["3000", "--json", "--yes"], runner), 2);
287
+ assert.match(output.error.join("\n"), /only reports and never terminates/);
288
+ }
289
+ finally {
290
+ output.restore();
291
+ }
292
+ });
218
293
  test("--match reclaims every port a matching process holds and kills it once", async () => {
219
294
  const { runner, calls } = fakeRunner({}, "free", staleServer());
220
295
  const output = capture();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,101 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import process from "node:process";
4
+ import { spawn } from "node:child_process";
5
+ import { createProcessRunner } from "../src/process.js";
6
+ // The listener runs in its own process on purpose: the runner then has to find it the way it
7
+ // finds a real stale dev server, through netstat/lsof and the platform name lookup, rather than
8
+ // through anything this test already knows. Unit tests with a fake runner cannot catch a wrong
9
+ // cmdlet name or a missing taskkill flag; these two can.
10
+ const LISTENER = [
11
+ "const net = require('net'), dgram = require('dgram');",
12
+ "if (process.argv[1] === 'udp') {",
13
+ " const s = dgram.createSocket('udp4');",
14
+ " s.bind(0, '127.0.0.1', () => console.log(JSON.stringify({ port: s.address().port })));",
15
+ "} else {",
16
+ " const srv = net.createServer();",
17
+ " srv.listen(0, '127.0.0.1', () => console.log(JSON.stringify({ port: srv.address().port })));",
18
+ "}",
19
+ ].join(" ");
20
+ function start(kind) {
21
+ const child = spawn(process.execPath, ["-e", LISTENER, kind], { stdio: ["ignore", "pipe", "pipe"] });
22
+ // Settled at spawn time, not after terminate(): the child dies from a signal, so exitCode
23
+ // stays null, and a listener registered once terminate() has returned never fires because the
24
+ // event was already delivered.
25
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
26
+ return new Promise((resolve, reject) => {
27
+ let stdout = "";
28
+ let stderr = "";
29
+ child.stdout?.on("data", (chunk) => {
30
+ stdout += chunk.toString();
31
+ const end = stdout.indexOf("\n");
32
+ if (end < 0 || child.pid === undefined)
33
+ return;
34
+ const { port } = JSON.parse(stdout.slice(0, end));
35
+ resolve({ child, pid: child.pid, port, exited });
36
+ });
37
+ child.stderr?.on("data", (chunk) => {
38
+ stderr += chunk.toString();
39
+ });
40
+ child.on("exit", (code) => reject(new Error(`listener exited early (code ${code}) ${stderr.trim()}`)));
41
+ });
42
+ }
43
+ // Releasing a bound port is not instantaneous across platforms, so poll rather than assume.
44
+ async function waitUntilFree(runner, port) {
45
+ const deadline = Date.now() + 5000;
46
+ while (Date.now() < deadline) {
47
+ if (await runner.probe(port) === "free")
48
+ return true;
49
+ await new Promise((resolve) => setTimeout(resolve, 150));
50
+ }
51
+ return false;
52
+ }
53
+ test("finds and releases a real TCP listener using the platform path", async (context) => {
54
+ let running;
55
+ try {
56
+ running = await start("tcp");
57
+ }
58
+ catch (error) {
59
+ context.skip(`cannot bind a local socket in this environment: ${error.message}`);
60
+ return;
61
+ }
62
+ const { child, pid, port, exited } = running;
63
+ const runner = createProcessRunner();
64
+ try {
65
+ const found = await runner.discover(port);
66
+ const match = found.find((entry) => entry.pid === pid);
67
+ assert.ok(match, `expected to find PID ${pid} on port ${port}, saw ${JSON.stringify(found)}`);
68
+ assert.match(match.name, /node/i);
69
+ assert.equal(match.protocol, "tcp");
70
+ assert.equal(match.refusal, undefined, "a plain node server must not be protected");
71
+ await runner.terminate(pid);
72
+ await exited;
73
+ assert.ok(await waitUntilFree(runner, port), `port ${port} should be bindable again after the listener was released`);
74
+ }
75
+ finally {
76
+ child.kill();
77
+ }
78
+ });
79
+ test("finds a real UDP socket, which Windows discovery silently missed", async (context) => {
80
+ let running;
81
+ try {
82
+ running = await start("udp");
83
+ }
84
+ catch (error) {
85
+ context.skip(`cannot bind a local socket in this environment: ${error.message}`);
86
+ return;
87
+ }
88
+ const { child, pid, port, exited } = running;
89
+ const runner = createProcessRunner();
90
+ try {
91
+ const found = await runner.discover(port);
92
+ const match = found.find((entry) => entry.pid === pid);
93
+ assert.ok(match, `expected to find UDP PID ${pid} on port ${port}, saw ${JSON.stringify(found)}`);
94
+ assert.equal(match.protocol, "udp");
95
+ await runner.terminate(pid);
96
+ await exited;
97
+ }
98
+ finally {
99
+ child.kill();
100
+ }
101
+ });
@@ -1,6 +1,6 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, isProtectedService, refusalReason, } from "../src/process.js";
3
+ import { parseEtime, parseNetstatListeners, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, parseUnixLsofListeners, commandName, isProtectedService, isWslInfrastructure, refusalReason, usesNatNetworking, } from "../src/process.js";
4
4
  test("parses lsof PID records", () => {
5
5
  assert.deepEqual(parseUnixLsof("p1234\ncnode\np5678\np1234\n"), [1234, 5678]);
6
6
  });
@@ -13,15 +13,24 @@ test("parses ps etime durations", () => {
13
13
  assert.equal(parseEtime("abc"), undefined);
14
14
  assert.equal(parseEtime("1:2:3:4"), undefined);
15
15
  });
16
- test("parses one batched ps table, keeping spaces in command names", () => {
16
+ test("derives the command name from argv[0], not from the thread name", () => {
17
+ assert.equal(commandName("/usr/bin/node -e require('net')"), "node");
18
+ assert.equal(commandName("node server.js"), "node");
19
+ assert.equal(commandName('"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --flag'), "Google Chrome");
20
+ assert.equal(commandName("/usr/bin/docker-proxy"), "docker-proxy");
21
+ assert.equal(commandName(""), "unknown");
22
+ });
23
+ test("parses one batched ps table and names processes from args", () => {
17
24
  const output = [
18
- " 1234 node 01:02:03",
19
- " 5678 Google Chrome 45:00",
25
+ " 1234 01:02:03 /usr/bin/node -e require('net')",
26
+ ' 5678 45:00 "/opt/app/Google Chrome.app/Contents/MacOS/Google Chrome" --flag',
27
+ " 99 00:05 MainThread",
20
28
  "ps: unknown process 9999",
21
29
  ].join("\n");
22
30
  assert.deepEqual(parsePsTable(output), [
23
31
  { pid: 1234, name: "node", ageMs: 3723000 },
24
32
  { pid: 5678, name: "Google Chrome", ageMs: 2700000 },
33
+ { pid: 99, name: "MainThread", ageMs: 5000 },
25
34
  ]);
26
35
  });
27
36
  test("parses pipe-delimited process rows", () => {
@@ -67,6 +76,20 @@ test("parses grouped lsof field output into listeners", () => {
67
76
  { pid: 77, port: 3000, protocol: "tcp" },
68
77
  ]);
69
78
  });
79
+ test("treats only mirrored networking as safe to trust the Linux view", () => {
80
+ assert.equal(usesNatNetworking("nat", "Ubuntu", "Linux version 6.6"), true);
81
+ assert.equal(usesNatNetworking("mirrored", "Ubuntu", "Linux version 6.6"), false);
82
+ assert.equal(usesNatNetworking("", "Ubuntu", "Linux version 6.6"), true, "older WSL builds report no mode and only ever had NAT");
83
+ assert.equal(usesNatNetworking("", undefined, "Linux version 6.6 (normal kernel)"), false, "not WSL at all");
84
+ assert.equal(usesNatNetworking("nat", undefined, "6.6.0-microsoft-standard-WSL2"), true, "detected via /proc/version");
85
+ });
86
+ test("does not mistake WSL's own relay for a foreign Windows holder", () => {
87
+ assert.equal(isWslInfrastructure("wslrelay"), true);
88
+ assert.equal(isWslInfrastructure("WSLService"), true);
89
+ assert.equal(isWslInfrastructure("node"), false);
90
+ assert.equal(isWslInfrastructure("System"), false);
91
+ assert.equal(isWslInfrastructure(""), false);
92
+ });
70
93
  test("recognises data services that must never auto-kill", () => {
71
94
  assert.equal(isProtectedService("postgres"), true);
72
95
  assert.equal(isProtectedService("Redis-Server"), true);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "port-reclaim",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Free up a port already in use: find and kill the process holding it (EADDRINUSE). Cross-platform, zero-config, Docker-safe.",
5
5
  "author": "princegoel0",
6
6
  "license": "MIT",
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "scripts": {
33
33
  "build": "tsc",
34
- "test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/style.test.js dist/tests/cli.test.js",
34
+ "test": "npm run build && node --test dist/tests/process.test.js dist/tests/args.test.js dist/tests/config.test.js dist/tests/style.test.js dist/tests/cli.test.js dist/tests/integration.test.js",
35
35
  "prepublishOnly": "npm test"
36
36
  },
37
37
  "keywords": [