infinity-portpilot 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +463 -2
- package/cli.js +15 -0
- package/dist/cli/app.js +83 -0
- package/dist/cli/commands.js +275 -0
- package/dist/cli/prompt.js +66 -0
- package/dist/discovery/index.js +99 -0
- package/dist/discovery/lsof.js +131 -0
- package/dist/discovery/platforms/linux.js +196 -0
- package/dist/discovery/platforms/macos.js +89 -0
- package/dist/discovery/platforms/windows.js +170 -0
- package/dist/discovery/types.js +2 -0
- package/dist/process/inspector.js +196 -0
- package/dist/process/terminator.js +275 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/exec.js +50 -0
- package/dist/utils/formatter.js +88 -0
- package/dist/utils/platform.js +15 -0
- package/dist/utils/validator.js +51 -0
- package/package.json +66 -4
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mergeProcesses = mergeProcesses;
|
|
4
|
+
exports.cmdList = cmdList;
|
|
5
|
+
exports.cmdFind = cmdFind;
|
|
6
|
+
exports.cmdInspect = cmdInspect;
|
|
7
|
+
exports.cmdFree = cmdFree;
|
|
8
|
+
exports.cmdPort = cmdPort;
|
|
9
|
+
const discovery_1 = require("../discovery");
|
|
10
|
+
const inspector_1 = require("../process/inspector");
|
|
11
|
+
const terminator_1 = require("../process/terminator");
|
|
12
|
+
const formatter_1 = require("../utils/formatter");
|
|
13
|
+
const validator_1 = require("../utils/validator");
|
|
14
|
+
const prompt_1 = require("./prompt");
|
|
15
|
+
function printErrors(errors) {
|
|
16
|
+
for (const error of errors) {
|
|
17
|
+
console.error(`${formatter_1.style.yellow(formatter_1.symbols.warn)} ${error.message}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function parsePortArgument(input, usage) {
|
|
21
|
+
if (input === undefined) {
|
|
22
|
+
console.error(`${formatter_1.style.red(formatter_1.symbols.fail)} Missing port. Usage: ${usage}`);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const result = (0, validator_1.parsePort)(input);
|
|
26
|
+
if (!result.valid || result.port === undefined) {
|
|
27
|
+
console.error(`${formatter_1.style.red(formatter_1.symbols.fail)} ${result.error}`);
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
return result.port;
|
|
31
|
+
}
|
|
32
|
+
/** Collapse multiple sockets owned by the same PID into one process entry. */
|
|
33
|
+
function mergeProcesses(processes) {
|
|
34
|
+
const byPid = new Map();
|
|
35
|
+
const unknown = [];
|
|
36
|
+
for (const process of processes) {
|
|
37
|
+
if (process.pid === null) {
|
|
38
|
+
if (!unknown.some((entry) => entry.localAddress === process.localAddress)) {
|
|
39
|
+
unknown.push(process);
|
|
40
|
+
}
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const existing = byPid.get(process.pid);
|
|
44
|
+
if (existing) {
|
|
45
|
+
existing.localAddress = `${existing.localAddress}, ${process.localAddress}`;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
byPid.set(process.pid, { ...process });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return [...byPid.values(), ...unknown];
|
|
52
|
+
}
|
|
53
|
+
function printAvailability(port, result) {
|
|
54
|
+
if (result.errors.length > 0) {
|
|
55
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} No TCP listener found on port ${port}, but discovery was incomplete.`);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
console.log(`${formatter_1.style.green(formatter_1.symbols.ok)} Port ${port} is available.`);
|
|
59
|
+
}
|
|
60
|
+
function printListenerList(processes) {
|
|
61
|
+
for (const process of processes) {
|
|
62
|
+
console.log(` ${(0, formatter_1.formatProcessSummary)(process)}`);
|
|
63
|
+
}
|
|
64
|
+
if (processes.some((process) => process.pid === null)) {
|
|
65
|
+
console.log(formatter_1.style.dim(" Some listening sockets could not be mapped to a process (permissions or missing system tooling)."));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function printOccupiedHeader(port, count) {
|
|
69
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} Port ${port} is occupied by ${count} process${count === 1 ? "" : "es"}:`);
|
|
70
|
+
}
|
|
71
|
+
async function cmdList() {
|
|
72
|
+
const result = await (0, discovery_1.listListeningPorts)();
|
|
73
|
+
printErrors(result.errors);
|
|
74
|
+
if (!result.listening) {
|
|
75
|
+
if (result.errors.length > 0) {
|
|
76
|
+
return 1;
|
|
77
|
+
}
|
|
78
|
+
console.log("No TCP listeners found.");
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
console.log(formatter_1.style.bold("\nTCP listeners\n"));
|
|
82
|
+
console.log((0, formatter_1.formatProcessTable)(result.processes));
|
|
83
|
+
console.log(formatter_1.style.dim(`\n${result.processes.length} listening endpoint${result.processes.length === 1 ? "" : "s"} found.`));
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
async function cmdFind(portArg) {
|
|
87
|
+
const port = parsePortArgument(portArg, "portpilot find <port>");
|
|
88
|
+
if (port === null) {
|
|
89
|
+
return 1;
|
|
90
|
+
}
|
|
91
|
+
const result = await (0, discovery_1.findListenersOnPort)(port);
|
|
92
|
+
printErrors(result.errors);
|
|
93
|
+
if (!result.listening) {
|
|
94
|
+
printAvailability(port, result);
|
|
95
|
+
return result.errors.length > 0 ? 1 : 0;
|
|
96
|
+
}
|
|
97
|
+
const processes = mergeProcesses(result.processes);
|
|
98
|
+
printOccupiedHeader(port, processes.length);
|
|
99
|
+
printListenerList(processes);
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
async function cmdInspect(portArg) {
|
|
103
|
+
const port = parsePortArgument(portArg, "portpilot inspect <port>");
|
|
104
|
+
if (port === null) {
|
|
105
|
+
return 1;
|
|
106
|
+
}
|
|
107
|
+
const result = await (0, discovery_1.findListenersOnPort)(port);
|
|
108
|
+
printErrors(result.errors);
|
|
109
|
+
if (!result.listening) {
|
|
110
|
+
printAvailability(port, result);
|
|
111
|
+
return result.errors.length > 0 ? 1 : 0;
|
|
112
|
+
}
|
|
113
|
+
const processes = mergeProcesses(result.processes);
|
|
114
|
+
printOccupiedHeader(port, processes.length);
|
|
115
|
+
let inspected = 0;
|
|
116
|
+
let failures = 0;
|
|
117
|
+
for (const process of processes) {
|
|
118
|
+
if (process.pid === null) {
|
|
119
|
+
console.log(`\n ${formatter_1.style.bold("Unknown process")} ${formatter_1.style.dim(`(${process.protocol} ${process.localAddress})`)}`);
|
|
120
|
+
console.log(formatter_1.style.dim(" The owning PID is not available with current permissions."));
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const details = await (0, inspector_1.inspectProcess)(process);
|
|
125
|
+
console.log(`\n ${formatter_1.style.bold(`Process ${details.pid}`)} ${formatter_1.style.dim(`(${details.protocol} ${details.localAddress})`)}`);
|
|
126
|
+
console.log((0, formatter_1.formatProcessDetails)(details));
|
|
127
|
+
inspected += 1;
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
failures += 1;
|
|
131
|
+
if (error instanceof inspector_1.ProcessNotFoundError) {
|
|
132
|
+
console.log(`\n ${formatter_1.style.yellow(formatter_1.symbols.warn)} PID ${process.pid} exited before its details could be read.`);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
console.log(`\n ${formatter_1.style.red(formatter_1.symbols.fail)} Could not inspect PID ${process.pid}: ${error.message}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
console.log("");
|
|
140
|
+
return failures > 0 && inspected === 0 ? 1 : 0;
|
|
141
|
+
}
|
|
142
|
+
function printTerminationReport(report) {
|
|
143
|
+
const label = `PID ${report.pid} (${report.name})`;
|
|
144
|
+
switch (report.status) {
|
|
145
|
+
case "terminated":
|
|
146
|
+
case "already-gone":
|
|
147
|
+
console.log(`${formatter_1.style.green(formatter_1.symbols.ok)} ${report.message}.`);
|
|
148
|
+
break;
|
|
149
|
+
case "force-terminated":
|
|
150
|
+
console.log(`${formatter_1.style.green(formatter_1.symbols.ok)} ${label}: ${report.message}.`);
|
|
151
|
+
break;
|
|
152
|
+
case "cancelled":
|
|
153
|
+
case "force-declined":
|
|
154
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} ${report.message}.`);
|
|
155
|
+
break;
|
|
156
|
+
case "permission-denied":
|
|
157
|
+
case "refused":
|
|
158
|
+
case "failed":
|
|
159
|
+
console.error(`${formatter_1.style.red(formatter_1.symbols.fail)} ${label}: ${report.message}`);
|
|
160
|
+
break;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const FAILURE_STATUSES = new Set(["permission-denied", "refused", "failed"]);
|
|
164
|
+
async function cmdFree(portArg) {
|
|
165
|
+
const port = parsePortArgument(portArg, "portpilot free <port>");
|
|
166
|
+
if (port === null) {
|
|
167
|
+
return 1;
|
|
168
|
+
}
|
|
169
|
+
const result = await (0, discovery_1.findListenersOnPort)(port);
|
|
170
|
+
printErrors(result.errors);
|
|
171
|
+
if (!result.listening) {
|
|
172
|
+
if (result.errors.length > 0) {
|
|
173
|
+
console.error(`${formatter_1.style.red(formatter_1.symbols.fail)} Could not determine what is using port ${port}. No changes were made.`);
|
|
174
|
+
return 1;
|
|
175
|
+
}
|
|
176
|
+
console.log(`${formatter_1.style.green(formatter_1.symbols.ok)} Port ${port} is already free.`);
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
const processes = mergeProcesses(result.processes);
|
|
180
|
+
printOccupiedHeader(port, processes.length);
|
|
181
|
+
printListenerList(processes);
|
|
182
|
+
const targets = processes.filter((process) => process.pid !== null);
|
|
183
|
+
if (targets.length === 0) {
|
|
184
|
+
console.error(`${formatter_1.style.red(formatter_1.symbols.fail)} Port ${port} is occupied, but PortPilot could not identify the owning process. Refusing to guess.`);
|
|
185
|
+
return 1;
|
|
186
|
+
}
|
|
187
|
+
const prompter = (0, prompt_1.createInteractivePrompter)();
|
|
188
|
+
if (!prompter) {
|
|
189
|
+
console.log(`\n${formatter_1.style.yellow(formatter_1.symbols.warn)} Termination requires an interactive terminal for confirmation. No changes were made.`);
|
|
190
|
+
return 1;
|
|
191
|
+
}
|
|
192
|
+
let exitCode = 0;
|
|
193
|
+
try {
|
|
194
|
+
for (const process of targets) {
|
|
195
|
+
let inspected;
|
|
196
|
+
try {
|
|
197
|
+
inspected = await (0, inspector_1.inspectProcess)(process);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} Could not read full details for PID ${process.pid}: ${error.message}`);
|
|
201
|
+
inspected = process;
|
|
202
|
+
}
|
|
203
|
+
console.log(`\n${formatter_1.style.bold(`Target: ${inspected.name} (PID ${inspected.pid})`)}`);
|
|
204
|
+
console.log((0, formatter_1.formatProcessDetails)(inspected));
|
|
205
|
+
console.log("");
|
|
206
|
+
const target = {
|
|
207
|
+
pid: process.pid,
|
|
208
|
+
name: inspected.name,
|
|
209
|
+
startTime: inspected.startTime,
|
|
210
|
+
};
|
|
211
|
+
const report = await (0, terminator_1.terminateProcess)(target, {
|
|
212
|
+
confirm: (question) => prompter.confirm(question),
|
|
213
|
+
forceConfirm: (question) => prompter.confirm(question),
|
|
214
|
+
});
|
|
215
|
+
printTerminationReport(report);
|
|
216
|
+
if (FAILURE_STATUSES.has(report.status)) {
|
|
217
|
+
exitCode = 1;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
prompter.close();
|
|
223
|
+
}
|
|
224
|
+
const remaining = await (0, discovery_1.findListenersOnPort)(port);
|
|
225
|
+
if (remaining.errors.length > 0) {
|
|
226
|
+
printErrors(remaining.errors);
|
|
227
|
+
}
|
|
228
|
+
if (remaining.listening) {
|
|
229
|
+
console.log(`\n${formatter_1.style.yellow(formatter_1.symbols.warn)} Port ${port} still has ${remaining.processes.length} listening endpoint${remaining.processes.length === 1 ? "" : "s"}.`);
|
|
230
|
+
exitCode = exitCode === 0 ? 1 : exitCode;
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
console.log(`\n${formatter_1.style.green(formatter_1.symbols.ok)} Port ${port} is now free.`);
|
|
234
|
+
}
|
|
235
|
+
return exitCode;
|
|
236
|
+
}
|
|
237
|
+
async function cmdPort(portArg) {
|
|
238
|
+
const port = parsePortArgument(portArg, "portpilot <port>");
|
|
239
|
+
if (port === null) {
|
|
240
|
+
return 1;
|
|
241
|
+
}
|
|
242
|
+
const result = await (0, discovery_1.findListenersOnPort)(port);
|
|
243
|
+
printErrors(result.errors);
|
|
244
|
+
if (!result.listening) {
|
|
245
|
+
printAvailability(port, result);
|
|
246
|
+
return result.errors.length > 0 ? 1 : 0;
|
|
247
|
+
}
|
|
248
|
+
const processes = mergeProcesses(result.processes);
|
|
249
|
+
printOccupiedHeader(port, processes.length);
|
|
250
|
+
printListenerList(processes);
|
|
251
|
+
const prompter = (0, prompt_1.createInteractivePrompter)();
|
|
252
|
+
if (!prompter) {
|
|
253
|
+
console.log(`\n${formatter_1.style.dim(`Non-interactive input. Run "portpilot inspect ${port}" for details or "portpilot free ${port}" to terminate a process.`)}`);
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
console.log(`\n${formatter_1.style.bold("What would you like to do?")}`);
|
|
257
|
+
console.log(" 1) Inspect process details");
|
|
258
|
+
console.log(" 2) Free the port");
|
|
259
|
+
console.log(" 3) Cancel");
|
|
260
|
+
const answer = await prompter.ask("> ");
|
|
261
|
+
prompter.close();
|
|
262
|
+
switch ((answer ?? "").trim()) {
|
|
263
|
+
case "1":
|
|
264
|
+
return cmdInspect(String(port));
|
|
265
|
+
case "2":
|
|
266
|
+
return cmdFree(String(port));
|
|
267
|
+
case "3":
|
|
268
|
+
case "":
|
|
269
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} Cancelled. Nothing was changed.`);
|
|
270
|
+
return 0;
|
|
271
|
+
default:
|
|
272
|
+
console.log(`${formatter_1.style.yellow(formatter_1.symbols.warn)} Unrecognized choice. Nothing was changed.`);
|
|
273
|
+
return 0;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createPrompter = createPrompter;
|
|
7
|
+
exports.createInteractivePrompter = createInteractivePrompter;
|
|
8
|
+
const node_readline_1 = __importDefault(require("node:readline"));
|
|
9
|
+
/**
|
|
10
|
+
* Build a prompter over explicit streams (used by tests). Returns null when
|
|
11
|
+
* input is not a terminal, which callers must treat as "cannot ask".
|
|
12
|
+
*/
|
|
13
|
+
function createPrompter(input, output) {
|
|
14
|
+
if (!input.isTTY) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
const rl = node_readline_1.default.createInterface({ input, output });
|
|
18
|
+
let closed = false;
|
|
19
|
+
rl.on("close", () => {
|
|
20
|
+
closed = true;
|
|
21
|
+
});
|
|
22
|
+
function ask(question) {
|
|
23
|
+
if (closed) {
|
|
24
|
+
return Promise.resolve(null);
|
|
25
|
+
}
|
|
26
|
+
return new Promise((resolve) => {
|
|
27
|
+
let settled = false;
|
|
28
|
+
const finish = (answer) => {
|
|
29
|
+
if (!settled) {
|
|
30
|
+
settled = true;
|
|
31
|
+
rl.removeListener("close", onClose);
|
|
32
|
+
resolve(answer);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const onClose = () => {
|
|
36
|
+
finish(null);
|
|
37
|
+
};
|
|
38
|
+
rl.once("close", onClose);
|
|
39
|
+
try {
|
|
40
|
+
rl.question(question, (answer) => finish(answer));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// stdin can close between the isTTY check and the prompt.
|
|
44
|
+
finish(null);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
ask,
|
|
50
|
+
async confirm(question) {
|
|
51
|
+
const answer = await ask(question);
|
|
52
|
+
return answer !== null && /^(y|yes)$/i.test(answer.trim());
|
|
53
|
+
},
|
|
54
|
+
close() {
|
|
55
|
+
closed = true;
|
|
56
|
+
rl.close();
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Returns null when stdin is not a terminal. Callers must treat that as
|
|
62
|
+
* "cannot ask" and never assume a confirmation.
|
|
63
|
+
*/
|
|
64
|
+
function createInteractivePrompter() {
|
|
65
|
+
return createPrompter(process.stdin, process.stdout);
|
|
66
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.selectProvider = selectProvider;
|
|
4
|
+
exports.findListenersOnPort = findListenersOnPort;
|
|
5
|
+
exports.listListeningPorts = listListeningPorts;
|
|
6
|
+
const platform_1 = require("../utils/platform");
|
|
7
|
+
const linux_1 = require("./platforms/linux");
|
|
8
|
+
const macos_1 = require("./platforms/macos");
|
|
9
|
+
const windows_1 = require("./platforms/windows");
|
|
10
|
+
function toProcessInfo(listener) {
|
|
11
|
+
return {
|
|
12
|
+
pid: listener.pid,
|
|
13
|
+
name: listener.name?.trim() || "unknown",
|
|
14
|
+
localAddress: listener.localAddress,
|
|
15
|
+
port: listener.port,
|
|
16
|
+
protocol: listener.protocol,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function sortProcesses(processes) {
|
|
20
|
+
return processes.sort((a, b) => {
|
|
21
|
+
if (a.port !== b.port) {
|
|
22
|
+
return a.port - b.port;
|
|
23
|
+
}
|
|
24
|
+
if (a.pid === b.pid) {
|
|
25
|
+
return a.localAddress.localeCompare(b.localAddress);
|
|
26
|
+
}
|
|
27
|
+
if (a.pid === null) {
|
|
28
|
+
return 1;
|
|
29
|
+
}
|
|
30
|
+
if (b.pid === null) {
|
|
31
|
+
return -1;
|
|
32
|
+
}
|
|
33
|
+
return a.pid - b.pid;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function selectProvider(platform = process.platform) {
|
|
37
|
+
switch ((0, platform_1.detectPlatform)(platform)) {
|
|
38
|
+
case "macos":
|
|
39
|
+
return macos_1.macosProvider;
|
|
40
|
+
case "linux":
|
|
41
|
+
return linux_1.linuxProvider;
|
|
42
|
+
case "windows":
|
|
43
|
+
return {
|
|
44
|
+
name: "Windows (netstat / PowerShell)",
|
|
45
|
+
findListeners: (port) => (0, windows_1.findOnWindows)(port),
|
|
46
|
+
};
|
|
47
|
+
default:
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function discover(port) {
|
|
52
|
+
const provider = selectProvider();
|
|
53
|
+
if (!provider) {
|
|
54
|
+
return {
|
|
55
|
+
port: port ?? null,
|
|
56
|
+
listening: false,
|
|
57
|
+
processes: [],
|
|
58
|
+
errors: [
|
|
59
|
+
{
|
|
60
|
+
code: "unsupported",
|
|
61
|
+
message: `Platform "${process.platform}" is not supported. PortPilot supports macOS, Linux, and Windows.`,
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
const outcome = await provider.findListeners(port);
|
|
68
|
+
const filtered = outcome.listeners
|
|
69
|
+
.filter((listener) => port === undefined || listener.port === port)
|
|
70
|
+
.map(toProcessInfo);
|
|
71
|
+
return {
|
|
72
|
+
port: port ?? null,
|
|
73
|
+
listening: filtered.length > 0,
|
|
74
|
+
processes: sortProcesses(filtered),
|
|
75
|
+
errors: outcome.errors,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
port: port ?? null,
|
|
81
|
+
listening: false,
|
|
82
|
+
processes: [],
|
|
83
|
+
errors: [
|
|
84
|
+
{
|
|
85
|
+
code: "unknown",
|
|
86
|
+
message: `Port discovery failed: ${error.message}`,
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Find TCP listeners on a specific port. */
|
|
93
|
+
function findListenersOnPort(port) {
|
|
94
|
+
return discover(port);
|
|
95
|
+
}
|
|
96
|
+
/** List every TCP listening endpoint on the machine. */
|
|
97
|
+
function listListeningPorts() {
|
|
98
|
+
return discover(undefined);
|
|
99
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseLsofOutput = parseLsofOutput;
|
|
4
|
+
exports.parseLsofAddress = parseLsofAddress;
|
|
5
|
+
exports.dedupeListeners = dedupeListeners;
|
|
6
|
+
exports.findWithLsof = findWithLsof;
|
|
7
|
+
const exec_1 = require("../utils/exec");
|
|
8
|
+
/** Parse `lsof -F pcPn` field output into listening endpoints. */
|
|
9
|
+
function parseLsofOutput(output, filterPort) {
|
|
10
|
+
const listeners = [];
|
|
11
|
+
let current = null;
|
|
12
|
+
for (const line of output.split("\n")) {
|
|
13
|
+
if (line.length < 2) {
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
const field = line[0];
|
|
17
|
+
const value = line.slice(1);
|
|
18
|
+
if (field === "p") {
|
|
19
|
+
const pid = Number.parseInt(value, 10);
|
|
20
|
+
current = Number.isInteger(pid) && pid > 0 ? { pid } : null;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (!current) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (field === "c") {
|
|
27
|
+
current.name = value.trim();
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (field !== "n" || value.includes("->")) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const endpoint = parseLsofAddress(value);
|
|
34
|
+
if (!endpoint) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (filterPort !== undefined && endpoint.port !== filterPort) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
listeners.push({
|
|
41
|
+
pid: current.pid,
|
|
42
|
+
name: current.name,
|
|
43
|
+
localAddress: `${endpoint.address}:${endpoint.port}`,
|
|
44
|
+
port: endpoint.port,
|
|
45
|
+
protocol: "TCP",
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return dedupeListeners(listeners);
|
|
49
|
+
}
|
|
50
|
+
function parseLsofAddress(value) {
|
|
51
|
+
const match = /^(.*):(\d{1,5})$/.exec(value.trim());
|
|
52
|
+
if (!match) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const address = match[1];
|
|
56
|
+
const port = Number.parseInt(match[2], 10);
|
|
57
|
+
if (!address || port < 1 || port > 65535) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return { address, port };
|
|
61
|
+
}
|
|
62
|
+
function dedupeListeners(listeners) {
|
|
63
|
+
const seen = new Set();
|
|
64
|
+
return listeners.filter((listener) => {
|
|
65
|
+
const key = `${listener.pid ?? "?"}|${listener.protocol}|${listener.localAddress}|${listener.port}`;
|
|
66
|
+
if (seen.has(key)) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
seen.add(key);
|
|
70
|
+
return true;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Query lsof for TCP listeners. Used by both macOS and Linux, with each
|
|
75
|
+
* platform deciding how to fall back when lsof is missing or restricted.
|
|
76
|
+
*/
|
|
77
|
+
async function findWithLsof(port) {
|
|
78
|
+
const args = ["-nP", port === undefined ? "-iTCP" : `-iTCP:${port}`];
|
|
79
|
+
args.push("-sTCP:LISTEN", "-F", "pcPn");
|
|
80
|
+
const result = await (0, exec_1.runCommand)("lsof", args);
|
|
81
|
+
if (!result.ok) {
|
|
82
|
+
if ((0, exec_1.isMissingCommand)(result)) {
|
|
83
|
+
return {
|
|
84
|
+
listeners: [],
|
|
85
|
+
errors: [
|
|
86
|
+
{
|
|
87
|
+
code: "unavailable",
|
|
88
|
+
message: "lsof is not installed or not on PATH",
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
if ((0, exec_1.isTimeout)(result)) {
|
|
94
|
+
return {
|
|
95
|
+
listeners: [],
|
|
96
|
+
errors: [
|
|
97
|
+
{ code: "timeout", message: "lsof timed out while scanning ports" },
|
|
98
|
+
],
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const listeners = parseLsofOutput(result.stdout, port);
|
|
102
|
+
if (listeners.length > 0) {
|
|
103
|
+
return { listeners, errors: [] };
|
|
104
|
+
}
|
|
105
|
+
if ((0, exec_1.isPermissionError)(result)) {
|
|
106
|
+
return {
|
|
107
|
+
listeners: [],
|
|
108
|
+
errors: [
|
|
109
|
+
{
|
|
110
|
+
code: "permission",
|
|
111
|
+
message: "lsof was denied access to some processes; results may be incomplete",
|
|
112
|
+
},
|
|
113
|
+
],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
// lsof exits 1 when nothing matches, which is not an error.
|
|
117
|
+
if (result.code === 1 && result.stdout.trim() === "") {
|
|
118
|
+
return { listeners: [], errors: [] };
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
listeners: [],
|
|
122
|
+
errors: [
|
|
123
|
+
{
|
|
124
|
+
code: "unknown",
|
|
125
|
+
message: `lsof failed: ${result.stderr.trim() || result.message}`,
|
|
126
|
+
},
|
|
127
|
+
],
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
return { listeners: parseLsofOutput(result.stdout, port), errors: [] };
|
|
131
|
+
}
|