porthawk-core 0.1.1

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/dist/index.cjs ADDED
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ classifyOrigin: () => classifyOrigin,
34
+ getListeningPorts: () => getListeningPorts,
35
+ killProcess: () => killProcess
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/detect.ts
40
+ var import_node_child_process = require("child_process");
41
+ var import_node_util = require("util");
42
+ var si = __toESM(require("systeminformation"), 1);
43
+
44
+ // src/classify.ts
45
+ var agentHostPattern = /^(code|code-oss|cursor|windsurf)(\.exe|\s.*)?$/i;
46
+ var rules = [
47
+ { namePattern: /claude/i, origin: "agent" },
48
+ { namePattern: /^(node|python|python3|deno|bun)(\.exe)?$/i, parentPattern: agentHostPattern, origin: "agent" },
49
+ { namePattern: /^(bash|zsh|sh|fish|powershell|pwsh|cmd)(\.exe)?$/i, parentPattern: agentHostPattern, origin: "agent" }
50
+ ];
51
+ function classifyOrigin(processInfo) {
52
+ for (const rule of rules) {
53
+ if (!rule.namePattern.test(processInfo.processName)) continue;
54
+ if (rule.parentPattern && !rule.parentPattern.test(processInfo.parentName)) continue;
55
+ return rule.origin;
56
+ }
57
+ return "unknown";
58
+ }
59
+
60
+ // src/detect.ts
61
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
62
+ function isValidPid(pid) {
63
+ return typeof pid === "number" && Number.isInteger(pid) && pid > 0;
64
+ }
65
+ function normalizeProtocol(raw) {
66
+ return raw.toLowerCase().startsWith("udp") ? "udp" : "tcp";
67
+ }
68
+ async function getUnixProcessInfo(pid) {
69
+ const { stdout } = await execFileAsync("ps", ["-p", String(pid), "-o", "ppid=,comm=,args="]);
70
+ const line = stdout.trim();
71
+ const [ppidToken, commToken, ...rest] = line.split(/\s+/);
72
+ const processName = commToken ?? "";
73
+ const command = rest.length > 0 ? rest.join(" ") : processName;
74
+ const ppid = Number(ppidToken);
75
+ let parentName = "";
76
+ if (isValidPid(ppid)) {
77
+ try {
78
+ const { stdout: parentStdout } = await execFileAsync("ps", ["-p", String(ppid), "-o", "comm="]);
79
+ parentName = parentStdout.trim();
80
+ } catch {
81
+ parentName = "";
82
+ }
83
+ }
84
+ return { pid, processName, command, parentName };
85
+ }
86
+ async function queryWindowsProcess(pid) {
87
+ const script = `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object Name,CommandLine,ParentProcessId | ConvertTo-Json -Compress`;
88
+ const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
89
+ const trimmed = stdout.trim();
90
+ if (!trimmed) return void 0;
91
+ return JSON.parse(trimmed);
92
+ }
93
+ async function getWindowsProcessInfo(pid) {
94
+ const record = await queryWindowsProcess(pid);
95
+ if (!record) {
96
+ throw new Error(`No process found for pid ${pid}`);
97
+ }
98
+ let parentName = "";
99
+ if (isValidPid(record.ParentProcessId)) {
100
+ try {
101
+ const parentRecord = await queryWindowsProcess(record.ParentProcessId);
102
+ parentName = parentRecord?.Name ?? "";
103
+ } catch {
104
+ parentName = "";
105
+ }
106
+ }
107
+ return {
108
+ pid,
109
+ processName: record.Name ?? "",
110
+ command: record.CommandLine ?? record.Name ?? "",
111
+ parentName
112
+ };
113
+ }
114
+ async function getProcessInfo(pid) {
115
+ return process.platform === "win32" ? getWindowsProcessInfo(pid) : getUnixProcessInfo(pid);
116
+ }
117
+ async function getListeningPorts() {
118
+ const connections = await si.networkConnections();
119
+ const listening = connections.filter(
120
+ (conn) => conn.state?.toUpperCase() === "LISTEN" && isValidPid(conn.pid)
121
+ );
122
+ const processInfoByPid = /* @__PURE__ */ new Map();
123
+ const result = [];
124
+ for (const conn of listening) {
125
+ const pid = conn.pid;
126
+ if (!processInfoByPid.has(pid)) {
127
+ try {
128
+ processInfoByPid.set(pid, await getProcessInfo(pid));
129
+ } catch {
130
+ processInfoByPid.set(pid, null);
131
+ }
132
+ }
133
+ const processInfo = processInfoByPid.get(pid);
134
+ if (!processInfo) continue;
135
+ const port = Number(conn.localPort);
136
+ if (!Number.isInteger(port)) continue;
137
+ result.push({
138
+ port,
139
+ pid,
140
+ protocol: normalizeProtocol(conn.protocol),
141
+ processName: processInfo.processName,
142
+ command: processInfo.command,
143
+ origin: classifyOrigin(processInfo)
144
+ });
145
+ }
146
+ const seen = /* @__PURE__ */ new Set();
147
+ return result.filter((entry) => {
148
+ const key = `${entry.pid}:${entry.port}:${entry.protocol}`;
149
+ if (seen.has(key)) return false;
150
+ seen.add(key);
151
+ return true;
152
+ });
153
+ }
154
+
155
+ // src/kill.ts
156
+ var import_node_child_process2 = require("child_process");
157
+ var import_node_util2 = require("util");
158
+ var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
159
+ function assertValidPid(pid) {
160
+ if (!Number.isInteger(pid) || pid <= 0) {
161
+ throw new Error(`Invalid pid: ${pid}`);
162
+ }
163
+ }
164
+ async function killProcess(pid) {
165
+ assertValidPid(pid);
166
+ if (process.platform === "win32") {
167
+ await execFileAsync2("taskkill", ["/PID", String(pid), "/F"]);
168
+ return;
169
+ }
170
+ process.kill(pid);
171
+ }
172
+ // Annotate the CommonJS export names for ESM import in node:
173
+ 0 && (module.exports = {
174
+ classifyOrigin,
175
+ getListeningPorts,
176
+ killProcess
177
+ });
178
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/detect.ts","../src/classify.ts","../src/kill.ts"],"sourcesContent":["export { getListeningPorts } from './detect.js';\nexport { killProcess } from './kill.js';\nexport { classifyOrigin } from './classify.js';\nexport type { PortInfo, ProcessInfo, Protocol, Origin, ClassifyRule } from './types.js';\n","import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport * as si from 'systeminformation';\nimport { classifyOrigin } from './classify.js';\nimport type { PortInfo, Protocol, ProcessInfo } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nfunction isValidPid(pid: unknown): pid is number {\n return typeof pid === 'number' && Number.isInteger(pid) && pid > 0;\n}\n\nfunction normalizeProtocol(raw: string): Protocol {\n return raw.toLowerCase().startsWith('udp') ? 'udp' : 'tcp';\n}\n\nasync function getUnixProcessInfo(pid: number): Promise<ProcessInfo> {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'ppid=,comm=,args=']);\n const line = stdout.trim();\n const [ppidToken, commToken, ...rest] = line.split(/\\s+/);\n const processName = commToken ?? '';\n const command = rest.length > 0 ? rest.join(' ') : processName;\n const ppid = Number(ppidToken);\n\n let parentName = '';\n if (isValidPid(ppid)) {\n try {\n const { stdout: parentStdout } = await execFileAsync('ps', ['-p', String(ppid), '-o', 'comm=']);\n parentName = parentStdout.trim();\n } catch {\n parentName = '';\n }\n }\n\n return { pid, processName, command, parentName };\n}\n\ninterface WindowsProcessRecord {\n Name?: string;\n CommandLine?: string;\n ParentProcessId?: number;\n}\n\nasync function queryWindowsProcess(pid: number): Promise<WindowsProcessRecord | undefined> {\n const script = `Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\" | Select-Object Name,CommandLine,ParentProcessId | ConvertTo-Json -Compress`;\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);\n const trimmed = stdout.trim();\n if (!trimmed) return undefined;\n return JSON.parse(trimmed) as WindowsProcessRecord;\n}\n\nasync function getWindowsProcessInfo(pid: number): Promise<ProcessInfo> {\n const record = await queryWindowsProcess(pid);\n if (!record) {\n throw new Error(`No process found for pid ${pid}`);\n }\n\n let parentName = '';\n if (isValidPid(record.ParentProcessId)) {\n try {\n const parentRecord = await queryWindowsProcess(record.ParentProcessId);\n parentName = parentRecord?.Name ?? '';\n } catch {\n parentName = '';\n }\n }\n\n return {\n pid,\n processName: record.Name ?? '',\n command: record.CommandLine ?? record.Name ?? '',\n parentName,\n };\n}\n\nasync function getProcessInfo(pid: number): Promise<ProcessInfo> {\n return process.platform === 'win32' ? getWindowsProcessInfo(pid) : getUnixProcessInfo(pid);\n}\n\nexport async function getListeningPorts(): Promise<PortInfo[]> {\n const connections = await si.networkConnections();\n const listening = connections.filter(\n (conn) => conn.state?.toUpperCase() === 'LISTEN' && isValidPid(conn.pid),\n );\n\n const processInfoByPid = new Map<number, ProcessInfo | null>();\n\n const result: PortInfo[] = [];\n\n for (const conn of listening) {\n const pid = conn.pid;\n\n if (!processInfoByPid.has(pid)) {\n try {\n processInfoByPid.set(pid, await getProcessInfo(pid));\n } catch {\n processInfoByPid.set(pid, null);\n }\n }\n\n const processInfo = processInfoByPid.get(pid);\n if (!processInfo) continue;\n\n const port = Number(conn.localPort);\n if (!Number.isInteger(port)) continue;\n\n result.push({\n port,\n pid,\n protocol: normalizeProtocol(conn.protocol),\n processName: processInfo.processName,\n command: processInfo.command,\n origin: classifyOrigin(processInfo),\n });\n }\n\n const seen = new Set<string>();\n return result.filter((entry) => {\n const key = `${entry.pid}:${entry.port}:${entry.protocol}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n","import type { ClassifyRule, Origin, ProcessInfo } from './types.js';\n\nconst agentHostPattern = /^(code|code-oss|cursor|windsurf)(\\.exe|\\s.*)?$/i;\n\nconst rules: ClassifyRule[] = [\n { namePattern: /claude/i, origin: 'agent' },\n { namePattern: /^(node|python|python3|deno|bun)(\\.exe)?$/i, parentPattern: agentHostPattern, origin: 'agent' },\n { namePattern: /^(bash|zsh|sh|fish|powershell|pwsh|cmd)(\\.exe)?$/i, parentPattern: agentHostPattern, origin: 'agent' },\n];\n\nexport function classifyOrigin(processInfo: ProcessInfo): Origin {\n for (const rule of rules) {\n if (!rule.namePattern.test(processInfo.processName)) continue;\n if (rule.parentPattern && !rule.parentPattern.test(processInfo.parentName)) continue;\n return rule.origin;\n }\n return 'unknown';\n}\n","import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nfunction assertValidPid(pid: number): void {\n if (!Number.isInteger(pid) || pid <= 0) {\n throw new Error(`Invalid pid: ${pid}`);\n }\n}\n\nexport async function killProcess(pid: number): Promise<void> {\n assertValidPid(pid);\n\n if (process.platform === 'win32') {\n await execFileAsync('taskkill', ['/PID', String(pid), '/F']);\n return;\n }\n\n process.kill(pid);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gCAAyB;AACzB,uBAA0B;AAC1B,SAAoB;;;ACApB,IAAM,mBAAmB;AAEzB,IAAM,QAAwB;AAAA,EAC5B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B,IAAI,KAAK,IAAI;AAAA,MAChC;AAAA,IACF;AAEA,UAAM,cAAc,iBAAiB,IAAI,GAAG;AAC5C,QAAI,CAAC,YAAa;AAElB,UAAM,OAAO,OAAO,KAAK,SAAS;AAClC,QAAI,CAAC,OAAO,UAAU,IAAI,EAAG;AAE7B,WAAO,KAAK;AAAA,MACV;AAAA,MACA;AAAA,MACA,UAAU,kBAAkB,KAAK,QAAQ;AAAA,MACzC,aAAa,YAAY;AAAA,MACzB,SAAS,YAAY;AAAA,MACrB,QAAQ,eAAe,WAAW;AAAA,IACpC,CAAC;AAAA,EACH;AAEA,QAAM,OAAO,oBAAI,IAAY;AAC7B,SAAO,OAAO,OAAO,CAAC,UAAU;AAC9B,UAAM,MAAM,GAAG,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI,MAAM,QAAQ;AACxD,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AACZ,WAAO;AAAA,EACT,CAAC;AACH;;;AE3HA,IAAAA,6BAAyB;AACzB,IAAAC,oBAA0B;AAE1B,IAAMC,qBAAgB,6BAAU,mCAAQ;AAExC,SAAS,eAAe,KAAmB;AACzC,MAAI,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,GAAG;AACtC,UAAM,IAAI,MAAM,gBAAgB,GAAG,EAAE;AAAA,EACvC;AACF;AAEA,eAAsB,YAAY,KAA4B;AAC5D,iBAAe,GAAG;AAElB,MAAI,QAAQ,aAAa,SAAS;AAChC,UAAMA,eAAc,YAAY,CAAC,QAAQ,OAAO,GAAG,GAAG,IAAI,CAAC;AAC3D;AAAA,EACF;AAEA,UAAQ,KAAK,GAAG;AAClB;","names":["import_node_child_process","import_node_util","execFileAsync"]}
@@ -0,0 +1,29 @@
1
+ type Protocol = 'tcp' | 'udp';
2
+ type Origin = 'agent' | 'manual' | 'unknown';
3
+ interface ProcessInfo {
4
+ pid: number;
5
+ processName: string;
6
+ command: string;
7
+ parentName: string;
8
+ }
9
+ interface PortInfo {
10
+ port: number;
11
+ pid: number;
12
+ protocol: Protocol;
13
+ processName: string;
14
+ command: string;
15
+ origin: Origin;
16
+ }
17
+ interface ClassifyRule {
18
+ namePattern: RegExp;
19
+ parentPattern?: RegExp;
20
+ origin: Origin;
21
+ }
22
+
23
+ declare function getListeningPorts(): Promise<PortInfo[]>;
24
+
25
+ declare function killProcess(pid: number): Promise<void>;
26
+
27
+ declare function classifyOrigin(processInfo: ProcessInfo): Origin;
28
+
29
+ export { type ClassifyRule, type Origin, type PortInfo, type ProcessInfo, type Protocol, classifyOrigin, getListeningPorts, killProcess };
@@ -0,0 +1,29 @@
1
+ type Protocol = 'tcp' | 'udp';
2
+ type Origin = 'agent' | 'manual' | 'unknown';
3
+ interface ProcessInfo {
4
+ pid: number;
5
+ processName: string;
6
+ command: string;
7
+ parentName: string;
8
+ }
9
+ interface PortInfo {
10
+ port: number;
11
+ pid: number;
12
+ protocol: Protocol;
13
+ processName: string;
14
+ command: string;
15
+ origin: Origin;
16
+ }
17
+ interface ClassifyRule {
18
+ namePattern: RegExp;
19
+ parentPattern?: RegExp;
20
+ origin: Origin;
21
+ }
22
+
23
+ declare function getListeningPorts(): Promise<PortInfo[]>;
24
+
25
+ declare function killProcess(pid: number): Promise<void>;
26
+
27
+ declare function classifyOrigin(processInfo: ProcessInfo): Origin;
28
+
29
+ export { type ClassifyRule, type Origin, type PortInfo, type ProcessInfo, type Protocol, classifyOrigin, getListeningPorts, killProcess };
package/dist/index.js ADDED
@@ -0,0 +1,139 @@
1
+ // src/detect.ts
2
+ import { execFile } from "child_process";
3
+ import { promisify } from "util";
4
+ import * as si from "systeminformation";
5
+
6
+ // src/classify.ts
7
+ var agentHostPattern = /^(code|code-oss|cursor|windsurf)(\.exe|\s.*)?$/i;
8
+ var rules = [
9
+ { namePattern: /claude/i, origin: "agent" },
10
+ { namePattern: /^(node|python|python3|deno|bun)(\.exe)?$/i, parentPattern: agentHostPattern, origin: "agent" },
11
+ { namePattern: /^(bash|zsh|sh|fish|powershell|pwsh|cmd)(\.exe)?$/i, parentPattern: agentHostPattern, origin: "agent" }
12
+ ];
13
+ function classifyOrigin(processInfo) {
14
+ for (const rule of rules) {
15
+ if (!rule.namePattern.test(processInfo.processName)) continue;
16
+ if (rule.parentPattern && !rule.parentPattern.test(processInfo.parentName)) continue;
17
+ return rule.origin;
18
+ }
19
+ return "unknown";
20
+ }
21
+
22
+ // src/detect.ts
23
+ var execFileAsync = promisify(execFile);
24
+ function isValidPid(pid) {
25
+ return typeof pid === "number" && Number.isInteger(pid) && pid > 0;
26
+ }
27
+ function normalizeProtocol(raw) {
28
+ return raw.toLowerCase().startsWith("udp") ? "udp" : "tcp";
29
+ }
30
+ async function getUnixProcessInfo(pid) {
31
+ const { stdout } = await execFileAsync("ps", ["-p", String(pid), "-o", "ppid=,comm=,args="]);
32
+ const line = stdout.trim();
33
+ const [ppidToken, commToken, ...rest] = line.split(/\s+/);
34
+ const processName = commToken ?? "";
35
+ const command = rest.length > 0 ? rest.join(" ") : processName;
36
+ const ppid = Number(ppidToken);
37
+ let parentName = "";
38
+ if (isValidPid(ppid)) {
39
+ try {
40
+ const { stdout: parentStdout } = await execFileAsync("ps", ["-p", String(ppid), "-o", "comm="]);
41
+ parentName = parentStdout.trim();
42
+ } catch {
43
+ parentName = "";
44
+ }
45
+ }
46
+ return { pid, processName, command, parentName };
47
+ }
48
+ async function queryWindowsProcess(pid) {
49
+ const script = `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object Name,CommandLine,ParentProcessId | ConvertTo-Json -Compress`;
50
+ const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
51
+ const trimmed = stdout.trim();
52
+ if (!trimmed) return void 0;
53
+ return JSON.parse(trimmed);
54
+ }
55
+ async function getWindowsProcessInfo(pid) {
56
+ const record = await queryWindowsProcess(pid);
57
+ if (!record) {
58
+ throw new Error(`No process found for pid ${pid}`);
59
+ }
60
+ let parentName = "";
61
+ if (isValidPid(record.ParentProcessId)) {
62
+ try {
63
+ const parentRecord = await queryWindowsProcess(record.ParentProcessId);
64
+ parentName = parentRecord?.Name ?? "";
65
+ } catch {
66
+ parentName = "";
67
+ }
68
+ }
69
+ return {
70
+ pid,
71
+ processName: record.Name ?? "",
72
+ command: record.CommandLine ?? record.Name ?? "",
73
+ parentName
74
+ };
75
+ }
76
+ async function getProcessInfo(pid) {
77
+ return process.platform === "win32" ? getWindowsProcessInfo(pid) : getUnixProcessInfo(pid);
78
+ }
79
+ async function getListeningPorts() {
80
+ const connections = await si.networkConnections();
81
+ const listening = connections.filter(
82
+ (conn) => conn.state?.toUpperCase() === "LISTEN" && isValidPid(conn.pid)
83
+ );
84
+ const processInfoByPid = /* @__PURE__ */ new Map();
85
+ const result = [];
86
+ for (const conn of listening) {
87
+ const pid = conn.pid;
88
+ if (!processInfoByPid.has(pid)) {
89
+ try {
90
+ processInfoByPid.set(pid, await getProcessInfo(pid));
91
+ } catch {
92
+ processInfoByPid.set(pid, null);
93
+ }
94
+ }
95
+ const processInfo = processInfoByPid.get(pid);
96
+ if (!processInfo) continue;
97
+ const port = Number(conn.localPort);
98
+ if (!Number.isInteger(port)) continue;
99
+ result.push({
100
+ port,
101
+ pid,
102
+ protocol: normalizeProtocol(conn.protocol),
103
+ processName: processInfo.processName,
104
+ command: processInfo.command,
105
+ origin: classifyOrigin(processInfo)
106
+ });
107
+ }
108
+ const seen = /* @__PURE__ */ new Set();
109
+ return result.filter((entry) => {
110
+ const key = `${entry.pid}:${entry.port}:${entry.protocol}`;
111
+ if (seen.has(key)) return false;
112
+ seen.add(key);
113
+ return true;
114
+ });
115
+ }
116
+
117
+ // src/kill.ts
118
+ import { execFile as execFile2 } from "child_process";
119
+ import { promisify as promisify2 } from "util";
120
+ var execFileAsync2 = promisify2(execFile2);
121
+ function assertValidPid(pid) {
122
+ if (!Number.isInteger(pid) || pid <= 0) {
123
+ throw new Error(`Invalid pid: ${pid}`);
124
+ }
125
+ }
126
+ async function killProcess(pid) {
127
+ assertValidPid(pid);
128
+ if (process.platform === "win32") {
129
+ await execFileAsync2("taskkill", ["/PID", String(pid), "/F"]);
130
+ return;
131
+ }
132
+ process.kill(pid);
133
+ }
134
+ export {
135
+ classifyOrigin,
136
+ getListeningPorts,
137
+ killProcess
138
+ };
139
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/detect.ts","../src/classify.ts","../src/kill.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport * as si from 'systeminformation';\nimport { classifyOrigin } from './classify.js';\nimport type { PortInfo, Protocol, ProcessInfo } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nfunction isValidPid(pid: unknown): pid is number {\n return typeof pid === 'number' && Number.isInteger(pid) && pid > 0;\n}\n\nfunction normalizeProtocol(raw: string): Protocol {\n return raw.toLowerCase().startsWith('udp') ? 'udp' : 'tcp';\n}\n\nasync function getUnixProcessInfo(pid: number): Promise<ProcessInfo> {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-o', 'ppid=,comm=,args=']);\n const line = stdout.trim();\n const [ppidToken, commToken, ...rest] = line.split(/\\s+/);\n const processName = commToken ?? '';\n const command = rest.length > 0 ? rest.join(' ') : processName;\n const ppid = Number(ppidToken);\n\n let parentName = '';\n if (isValidPid(ppid)) {\n try {\n const { stdout: parentStdout } = await execFileAsync('ps', ['-p', String(ppid), '-o', 'comm=']);\n parentName = parentStdout.trim();\n } catch {\n parentName = '';\n }\n }\n\n return { pid, processName, command, parentName };\n}\n\ninterface WindowsProcessRecord {\n Name?: string;\n CommandLine?: string;\n ParentProcessId?: number;\n}\n\nasync function queryWindowsProcess(pid: number): Promise<WindowsProcessRecord | undefined> {\n const script = `Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\" | Select-Object Name,CommandLine,ParentProcessId | ConvertTo-Json -Compress`;\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);\n const trimmed = stdout.trim();\n if (!trimmed) return undefined;\n return JSON.parse(trimmed) as WindowsProcessRecord;\n}\n\nasync function getWindowsProcessInfo(pid: number): Promise<ProcessInfo> {\n const record = await queryWindowsProcess(pid);\n if (!record) {\n throw new Error(`No process found for pid ${pid}`);\n }\n\n let parentName = '';\n if (isValidPid(record.ParentProcessId)) {\n try {\n const parentRecord = await queryWindowsProcess(record.ParentProcessId);\n parentName = parentRecord?.Name ?? '';\n } catch {\n parentName = '';\n }\n }\n\n return {\n pid,\n processName: record.Name ?? '',\n command: record.CommandLine ?? record.Name ?? '',\n parentName,\n };\n}\n\nasync function getProcessInfo(pid: number): Promise<ProcessInfo> {\n return process.platform === 'win32' ? getWindowsProcessInfo(pid) : getUnixProcessInfo(pid);\n}\n\nexport async function getListeningPorts(): Promise<PortInfo[]> {\n const connections = await si.networkConnections();\n const listening = connections.filter(\n (conn) => conn.state?.toUpperCase() === 'LISTEN' && isValidPid(conn.pid),\n );\n\n const processInfoByPid = new Map<number, ProcessInfo | null>();\n\n const result: PortInfo[] = [];\n\n for (const conn of listening) {\n const pid = conn.pid;\n\n if (!processInfoByPid.has(pid)) {\n try {\n processInfoByPid.set(pid, await getProcessInfo(pid));\n } catch {\n processInfoByPid.set(pid, null);\n }\n }\n\n const processInfo = processInfoByPid.get(pid);\n if (!processInfo) continue;\n\n const port = Number(conn.localPort);\n if (!Number.isInteger(port)) continue;\n\n result.push({\n port,\n pid,\n protocol: normalizeProtocol(conn.protocol),\n processName: processInfo.processName,\n command: processInfo.command,\n origin: classifyOrigin(processInfo),\n });\n }\n\n const seen = new Set<string>();\n return result.filter((entry) => {\n const key = `${entry.pid}:${entry.port}:${entry.protocol}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n","import type { ClassifyRule, Origin, ProcessInfo } from './types.js';\n\nconst agentHostPattern = /^(code|code-oss|cursor|windsurf)(\\.exe|\\s.*)?$/i;\n\nconst rules: ClassifyRule[] = [\n { namePattern: /claude/i, origin: 'agent' },\n { namePattern: /^(node|python|python3|deno|bun)(\\.exe)?$/i, parentPattern: agentHostPattern, origin: 'agent' },\n { namePattern: /^(bash|zsh|sh|fish|powershell|pwsh|cmd)(\\.exe)?$/i, parentPattern: agentHostPattern, origin: 'agent' },\n];\n\nexport function classifyOrigin(processInfo: ProcessInfo): Origin {\n for (const rule of rules) {\n if (!rule.namePattern.test(processInfo.processName)) continue;\n if (rule.parentPattern && !rule.parentPattern.test(processInfo.parentName)) continue;\n return rule.origin;\n }\n return 'unknown';\n}\n","import { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nfunction assertValidPid(pid: number): void {\n if (!Number.isInteger(pid) || pid <= 0) {\n throw new Error(`Invalid pid: ${pid}`);\n }\n}\n\nexport async function killProcess(pid: number): Promise<void> {\n assertValidPid(pid);\n\n if (process.platform === 'win32') {\n await execFileAsync('taskkill', ['/PID', String(pid), '/F']);\n return;\n }\n\n process.kill(pid);\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,YAAY,QAAQ;;;ACApB,IAAM,mBAAmB;AAEzB,IAAM,QAAwB;AAAA,EAC5B,EAAE,aAAa,WAAW,QAAQ,QAAQ;AAAA,EAC1C,EAAE,aAAa,6CAA6C,eAAe,kBAAkB,QAAQ,QAAQ;AAAA,EAC7G,EAAE,aAAa,qDAAqD,eAAe,kBAAkB,QAAQ,QAAQ;AACvH;AAEO,SAAS,eAAe,aAAkC;AAC/D,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,KAAK,YAAY,KAAK,YAAY,WAAW,EAAG;AACrD,QAAI,KAAK,iBAAiB,CAAC,KAAK,cAAc,KAAK,YAAY,UAAU,EAAG;AAC5E,WAAO,KAAK;AAAA,EACd;AACA,SAAO;AACT;;;ADXA,IAAM,gBAAgB,UAAU,QAAQ;AAExC,SAAS,WAAW,KAA6B;AAC/C,SAAO,OAAO,QAAQ,YAAY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AAI,MAAM,IAAI,IAAI,MAAM,QAAQ;AACxD,QAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,SAAK,IAAI,GAAG;AACZ,WAAO;AAAA,EACT,CAAC;AACH;;;AE3HA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,aAAAC,kBAAiB;AAE1B,IAAMC,iBAAgBD,WAAUD,SAAQ;AAExC,SAAS,eAAe,KAAmB;AACzC,MAAI,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,GAAG;AACtC,UAAM,IAAI,MAAM,gBAAgB,GAAG,EAAE;AAAA,EACvC;AACF;AAEA,eAAsB,YAAY,KAA4B;AAC5D,iBAAe,GAAG;AAElB,MAAI,QAAQ,aAAa,SAAS;AAChC,UAAME,eAAc,YAAY,CAAC,QAAQ,OAAO,GAAG,GAAG,IAAI,CAAC;AAC3D;AAAA,EACF;AAEA,UAAQ,KAAK,GAAG;AAClB;","names":["execFile","promisify","execFileAsync"]}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "porthawk-core",
3
+ "version": "0.1.1",
4
+ "description": "Detection and process control engine for PortHawk",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "dependencies": {
20
+ "systeminformation": "^5.33.1"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.1.1",
24
+ "tsup": "^8.5.1",
25
+ "typescript": "^5.9.3",
26
+ "vitest": "^2.1.9"
27
+ },
28
+ "license": "MIT",
29
+ "scripts": {
30
+ "build": "tsup",
31
+ "test": "vitest run",
32
+ "test:integration": "vitest run --config vitest.integration.config.ts",
33
+ "typecheck": "tsc --noEmit"
34
+ }
35
+ }