@myrialabs/clopen 0.4.33 → 0.4.35

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.
Files changed (75) hide show
  1. package/backend/auth/permissions.ts +10 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/db-client/connection-manager.ts +13 -0
  20. package/backend/files/file-watcher.test.ts +105 -0
  21. package/backend/files/file-watcher.ts +45 -1
  22. package/backend/git/git-service.test.ts +33 -0
  23. package/backend/git/git-service.ts +7 -3
  24. package/backend/git/nested-repos.test.ts +292 -1
  25. package/backend/git/nested-repos.ts +330 -17
  26. package/backend/host/runner.ts +204 -0
  27. package/backend/index.ts +20 -2
  28. package/backend/middleware/security.test.ts +95 -0
  29. package/backend/middleware/security.ts +114 -0
  30. package/backend/ports/attribute.test.ts +231 -0
  31. package/backend/ports/attribute.ts +444 -0
  32. package/backend/ports/kill.ts +203 -0
  33. package/backend/ports/monitor.ts +365 -0
  34. package/backend/ports/processes.test.ts +98 -0
  35. package/backend/ports/processes.ts +374 -0
  36. package/backend/ports/registry.ts +165 -0
  37. package/backend/ports/scan-host.ts +329 -0
  38. package/backend/ports/scan.test.ts +341 -0
  39. package/backend/ports/scan.ts +687 -0
  40. package/backend/ports/ssh-lineage.ts +318 -0
  41. package/backend/preview/browser/browser-video-capture.ts +84 -31
  42. package/backend/ssh/forwards.ts +31 -0
  43. package/backend/ws/auth/device.ts +1 -1
  44. package/backend/ws/auth/login.ts +8 -4
  45. package/backend/ws/containers/actions.ts +156 -0
  46. package/backend/ws/containers/index.ts +43 -0
  47. package/backend/ws/containers/list.ts +146 -0
  48. package/backend/ws/containers/logs.ts +43 -0
  49. package/backend/ws/containers/tunnel.ts +101 -0
  50. package/backend/ws/git/log.ts +3 -1
  51. package/backend/ws/git/status.ts +37 -27
  52. package/backend/ws/index.ts +4 -0
  53. package/backend/ws/message-rate-limiter.test.ts +45 -0
  54. package/backend/ws/message-rate-limiter.ts +34 -3
  55. package/backend/ws/ports/index.ts +19 -0
  56. package/backend/ws/ports/kill.ts +80 -0
  57. package/backend/ws/ports/list.ts +60 -0
  58. package/backend/ws/ssh/connections.ts +8 -0
  59. package/backend/ws/system/device-info.ts +99 -43
  60. package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
  61. package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
  62. package/dist/assets/main-Buko4D0t.css +1 -0
  63. package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
  64. package/dist/index.html +2 -2
  65. package/dist/manifest.json +9 -2
  66. package/package.json +1 -1
  67. package/shared/types/containers/container.ts +366 -0
  68. package/shared/types/containers/index.ts +5 -0
  69. package/shared/types/host/index.ts +18 -0
  70. package/shared/types/ports/index.ts +5 -0
  71. package/shared/types/ports/port.ts +230 -0
  72. package/shared/utils/logger.ts +3 -0
  73. package/shared/utils/ws-client.ts +67 -12
  74. package/shared/utils/ws-server.ts +64 -13
  75. package/dist/assets/main-CCvRMXlP.css +0 -1
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Port manager — one host, one scan, one table.
3
+ *
4
+ * Ties the probe, the process table and the attribution together into the rows
5
+ * the panel renders. Held per host so the process cache survives between ticks,
6
+ * which is what makes a one-second poll cost a single cheap probe.
7
+ */
8
+
9
+ import os from 'node:os';
10
+ import type {
11
+ PortContainerRef,
12
+ PortEntry,
13
+ PortIpVersion,
14
+ PortKillBlockedReason,
15
+ PortLimitation,
16
+ PortOrigin,
17
+ PortPeer,
18
+ PortProtocol,
19
+ PortScanResult,
20
+ PortSocket
21
+ } from '$shared/types/ports';
22
+ import { LOCAL_PORT_HOST } from '$shared/types/ports';
23
+ import { scanSockets, type ProbeMemo } from './scan';
24
+ import { ProcessTable } from './processes';
25
+ import { attribute, buildContext, groupListenerPids } from './attribute';
26
+ import { collectExposedPorts } from './registry';
27
+ import { resolveClopenPids } from './ssh-lineage';
28
+ import {
29
+ addressesOverlap,
30
+ containerPortIndex,
31
+ refreshContainerPortIndex
32
+ } from '../containers/port-index';
33
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
34
+
35
+ /** Who the scan is running as, which decides what it may signal. */
36
+ export interface ScanPrincipal {
37
+ user: string | null;
38
+ isRoot: boolean;
39
+ }
40
+
41
+ export function localPrincipal(): ScanPrincipal {
42
+ let user: string | null = null;
43
+ try {
44
+ user = os.userInfo().username;
45
+ } catch {
46
+ // Some container images have no passwd entry for the running uid.
47
+ user = null;
48
+ }
49
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null;
50
+ // Windows has no uid; an Administrator there still fails to signal some
51
+ // processes, so the kill attempt reports the truth rather than predicting it.
52
+ return { user, isRoot: uid === 0 };
53
+ }
54
+
55
+ const NO_CLOPEN_LINEAGE: PortLimitation = {
56
+ code: 'no-session-attribution',
57
+ message:
58
+ 'Nothing listening here belongs to Clopen’s own SSH connection. If you started a server from a Clopen terminal on this host and it is not listed under “Started from Clopen”, this host does not let Clopen read a process’s environment.'
59
+ };
60
+
61
+ /** How a published port describes itself: by the container, not the proxy. */
62
+ function containerOrigin(ref: PortContainerRef): PortOrigin {
63
+ return {
64
+ kind: 'container',
65
+ // The runtime states this outright — there is nothing to infer.
66
+ confidence: 'certain',
67
+ label: ref.name,
68
+ detail: `${ref.image} · container port ${ref.containerPort}`,
69
+ containerId: ref.id
70
+ };
71
+ }
72
+
73
+ function protocolPortKey(protocol: PortProtocol, port: number): string {
74
+ return `${protocol}:${port}`;
75
+ }
76
+
77
+ /** Peers connected to each listening port, keyed `protocol:port`. */
78
+ function collectPeers(sockets: PortSocket[]): Map<string, PortPeer[]> {
79
+ const peers = new Map<string, PortPeer[]>();
80
+
81
+ for (const socket of sockets) {
82
+ if (socket.state !== 'established' || socket.peerAddress === null || socket.peerPort === null) continue;
83
+ const key = protocolPortKey(socket.protocol, socket.port);
84
+ const list = peers.get(key);
85
+ const peer: PortPeer = {
86
+ address: socket.peerAddress,
87
+ port: socket.peerPort,
88
+ processName: socket.processName
89
+ };
90
+ if (list) list.push(peer);
91
+ else peers.set(key, [peer]);
92
+ }
93
+
94
+ return peers;
95
+ }
96
+
97
+ function unique<T>(values: T[]): T[] {
98
+ return [...new Set(values)];
99
+ }
100
+
101
+ /**
102
+ * One host's scanner. Construct once per watched host so the process table and
103
+ * its cwd cache persist; drop it when the host stops being watched.
104
+ */
105
+ export class HostPortScanner {
106
+ private readonly processes: ProcessTable;
107
+ /** Which probe answered for this host; the chain is walked once. */
108
+ private readonly probeMemo: ProbeMemo = {};
109
+ /**
110
+ * A scan already running. Callers join it instead of starting a second one:
111
+ * a remote scan can outlast the poll interval, and two in flight would double
112
+ * the SSH channels while writing to the same process cache.
113
+ */
114
+ private inFlight: Promise<PortScanResult> | null = null;
115
+
116
+ constructor(
117
+ private readonly hostId: string,
118
+ private readonly hostName: string,
119
+ private readonly runner: CommandRunner,
120
+ private readonly platform: ProbePlatform,
121
+ private readonly principal: ScanPrincipal
122
+ ) {
123
+ this.processes = new ProcessTable(runner, platform);
124
+ }
125
+
126
+ private get isLocal(): boolean {
127
+ return this.hostId === LOCAL_PORT_HOST;
128
+ }
129
+
130
+ /**
131
+ * Whether this scan could plausibly signal a process. Ownership is the only
132
+ * thing knowable in advance; anything subtler is left to the kill attempt,
133
+ * which reports what the OS actually said.
134
+ */
135
+ private killability(
136
+ pid: number | null,
137
+ ownerUser: string | null,
138
+ isClopenItself: boolean
139
+ ): { canKill: boolean; reason: PortKillBlockedReason | null } {
140
+ if (isClopenItself) return { canKill: false, reason: 'is-clopen-itself' };
141
+ if (pid === null) return { canKill: false, reason: 'unknown-pid' };
142
+ if (pid <= 1) return { canKill: false, reason: 'system-process' };
143
+ if (this.principal.isRoot) return { canKill: true, reason: null };
144
+ if (ownerUser && this.principal.user && ownerUser !== this.principal.user) {
145
+ return { canKill: false, reason: 'not-permitted' };
146
+ }
147
+ return { canKill: true, reason: null };
148
+ }
149
+
150
+ /** Read this host, joining a scan already in progress rather than racing it. */
151
+ async scan(now = Date.now()): Promise<PortScanResult> {
152
+ if (this.inFlight) return this.inFlight;
153
+ this.inFlight = this.runScan(now).finally(() => {
154
+ this.inFlight = null;
155
+ });
156
+ return this.inFlight;
157
+ }
158
+
159
+ private async runScan(now: number): Promise<PortScanResult> {
160
+ const scannedAt = new Date(now).toISOString();
161
+
162
+ let sockets: PortSocket[];
163
+ let limitations: PortLimitation[];
164
+ let probe: string;
165
+ try {
166
+ const result = await scanSockets(this.runner, this.platform, this.probeMemo);
167
+ sockets = result.sockets;
168
+ limitations = result.limitations;
169
+ probe = result.probe;
170
+ } catch (error) {
171
+ return {
172
+ hostId: this.hostId,
173
+ scannedAt,
174
+ platform: this.platform,
175
+ probe: 'none',
176
+ entries: [],
177
+ limitations: [],
178
+ error: error instanceof Error ? error.message : String(error)
179
+ };
180
+ }
181
+
182
+ const listening = sockets.filter((socket) => socket.state === 'listen');
183
+ const pids = unique(listening.map((socket) => socket.pid).filter((pid): pid is number => pid !== null));
184
+
185
+ const processes = await this.processes.refresh(pids, now);
186
+ limitations = [...limitations, ...this.processes.getLimitations()];
187
+
188
+ // On an SSH host, a process is Clopen's if it belongs to Clopen's own SSH
189
+ // connection — the same tier as locally, established from the far end.
190
+ const clopenPids = this.isLocal
191
+ ? new Set<number>()
192
+ : await resolveClopenPids(this.hostId, this.runner, this.platform, pids, processes);
193
+ if (!this.isLocal && clopenPids.size === 0 && pids.length > 0) {
194
+ limitations.push(NO_CLOPEN_LINEAGE);
195
+ }
196
+
197
+ const context = buildContext({
198
+ platform: this.platform,
199
+ processes,
200
+ hostId: this.hostId,
201
+ hostName: this.hostName,
202
+ isLocal: this.isLocal,
203
+ clopenPids
204
+ });
205
+ const peers = collectPeers(sockets);
206
+ const exposed = this.isLocal ? collectExposedPorts() : new Map<number, string>();
207
+ // Read now, refresh behind us: a table that ticks every second must never
208
+ // wait on a `docker ps`, and a mapping that lands one tick late is
209
+ // invisible next to one that made the whole table stutter.
210
+ const containers = containerPortIndex(this.hostId);
211
+ refreshContainerPortIndex(this.hostId, this.runner, this.platform, now);
212
+
213
+ // Bucket the listening sockets per protocol+port first; a port is the
214
+ // unit the user thinks in, and the addresses under it are detail.
215
+ const buckets = new Map<string, PortSocket[]>();
216
+ for (const socket of listening) {
217
+ const key = protocolPortKey(socket.protocol, socket.port);
218
+ const bucket = buckets.get(key);
219
+ if (bucket) bucket.push(socket);
220
+ else buckets.set(key, [socket]);
221
+ }
222
+
223
+ const entries: PortEntry[] = [];
224
+ /** Mappings that found a socket to sit on; the rest get their own row. */
225
+ const annotated = new Set<string>();
226
+
227
+ for (const [key, bucket] of buckets) {
228
+ const { protocol, port } = bucket[0];
229
+ const bucketPids = unique(bucket.map((socket) => socket.pid).filter((pid): pid is number => pid !== null));
230
+ const groups = groupListenerPids(bucketPids, processes);
231
+
232
+ // Sockets whose owner the probe could not name still deserve a row —
233
+ // an unexplained open port is exactly what someone opens this for.
234
+ const orphans = bucket.filter((socket) => socket.pid === null);
235
+ if (orphans.length > 0) groups.push({ owner: -1, members: [] });
236
+
237
+ for (const { owner, members } of groups) {
238
+ const memberPids = new Set(members);
239
+ const groupSockets =
240
+ owner === -1
241
+ ? orphans
242
+ : bucket.filter((socket) => socket.pid !== null && memberPids.has(socket.pid));
243
+ if (groupSockets.length === 0) continue;
244
+
245
+ const representative = groupSockets[0];
246
+ const pid = owner === -1 ? null : owner;
247
+ const process = pid !== null ? (processes.get(pid) ?? null) : null;
248
+ const attributed = attribute({ ...representative, pid }, context);
249
+ // A published container port outranks whatever holds the socket: the
250
+ // listener is the runtime's own proxy, and signalling it would either
251
+ // fail or be undone by the daemon a moment later. Clopen's own
252
+ // listeners are the exception — those it does know better.
253
+ const candidate = attributed.kind === 'clopen' ? undefined : containers.get(key);
254
+ const groupAddresses = unique(groupSockets.map((socket) => socket.address));
255
+ const mapping =
256
+ candidate && addressesOverlap(groupAddresses, candidate.addresses) ? candidate : undefined;
257
+ if (mapping) annotated.add(key);
258
+ const origin = mapping ? containerOrigin(mapping.ref) : attributed;
259
+ const ownerUser = process?.user ?? representative.user;
260
+ const { canKill, reason } = mapping
261
+ ? { canKill: false, reason: 'managed-by-container' as PortKillBlockedReason }
262
+ : this.killability(pid, ownerUser, origin.ownerFeature === 'server');
263
+
264
+ entries.push({
265
+ key: `${this.hostId}:${key}:${pid ?? 'unknown'}`,
266
+ protocol,
267
+ port,
268
+ addresses: [...groupAddresses].sort(),
269
+ ipVersions: unique(groupSockets.map((socket) => socket.ipVersion)).sort(),
270
+ pid,
271
+ process,
272
+ workerPids: members,
273
+ origin,
274
+ peers: peers.get(key) ?? [],
275
+ peerCount: (peers.get(key) ?? []).length,
276
+ publicUrl: exposed.get(port) ?? null,
277
+ container: mapping?.ref ?? null,
278
+ canKill,
279
+ killBlockedReason: reason
280
+ });
281
+ }
282
+ }
283
+
284
+ // Mappings with no socket behind them still get a row. Docker publishes
285
+ // through a firewall rule when its userland proxy is off, and Podman's
286
+ // rootless networking often leaves nothing for the probe to find either —
287
+ // so without this the port a user can actually reach would be missing from
288
+ // the one table that claims to list what is reachable.
289
+ for (const [mappingKey, mapping] of containers) {
290
+ if (annotated.has(mappingKey)) continue;
291
+ const [protocolText, portText] = mappingKey.split(':');
292
+ const port = Number(portText);
293
+ if (!Number.isFinite(port)) continue;
294
+ const protocol = protocolText === 'udp' ? 'udp' : 'tcp';
295
+
296
+ entries.push({
297
+ key: `${this.hostId}:${mappingKey}:container`,
298
+ protocol,
299
+ port,
300
+ addresses: [...mapping.addresses].sort(),
301
+ ipVersions: unique(
302
+ mapping.addresses.map((address): PortIpVersion => (address.includes(':') ? 'v6' : 'v4'))
303
+ ).sort(),
304
+ pid: null,
305
+ process: null,
306
+ workerPids: [],
307
+ origin: containerOrigin(mapping.ref),
308
+ peers: peers.get(mappingKey) ?? [],
309
+ peerCount: (peers.get(mappingKey) ?? []).length,
310
+ publicUrl: exposed.get(port) ?? null,
311
+ container: mapping.ref,
312
+ canKill: false,
313
+ killBlockedReason: 'managed-by-container'
314
+ });
315
+ }
316
+
317
+ entries.sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol));
318
+
319
+ return {
320
+ hostId: this.hostId,
321
+ scannedAt,
322
+ platform: this.platform,
323
+ probe,
324
+ entries,
325
+ limitations,
326
+ error: null
327
+ };
328
+ }
329
+ }
@@ -0,0 +1,341 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { CommandRunner } from '../host/runner';
3
+ import {
4
+ parseLsof,
5
+ parseNetstatUnix,
6
+ parseNetstatWindows,
7
+ parseProcFdInodes,
8
+ parseProcNet,
9
+ parseSs,
10
+ scanSockets
11
+ } from './scan';
12
+
13
+ /**
14
+ * Fixtures are shaped like real probe output but describe an invented machine,
15
+ * so nothing about a contributor's own box ends up in the repository.
16
+ */
17
+
18
+ describe('parseLsof', () => {
19
+ // Field blocks as `lsof -FpcLfPntT` emits them: a process block, then one
20
+ // block per socket, with process fields carrying forward.
21
+ const output = [
22
+ 'p1200',
23
+ 'cnginx',
24
+ 'Lwww',
25
+ 'f6',
26
+ 'tIPv4',
27
+ 'PTCP',
28
+ 'n*:8080',
29
+ 'TST=LISTEN',
30
+ 'TQR=0',
31
+ 'f7',
32
+ 'tIPv6',
33
+ 'PTCP',
34
+ 'n[::1]:8080',
35
+ 'TST=LISTEN',
36
+ 'p1310',
37
+ 'cnode',
38
+ 'Ldeploy',
39
+ 'f22',
40
+ 'tIPv4',
41
+ 'PTCP',
42
+ 'n127.0.0.1:5173',
43
+ 'TST=LISTEN',
44
+ 'f23',
45
+ 'tIPv4',
46
+ 'PTCP',
47
+ 'n127.0.0.1:5173->127.0.0.1:54120',
48
+ 'TST=ESTABLISHED',
49
+ 'f24',
50
+ 'tIPv4',
51
+ 'PUDP',
52
+ 'n*:5353',
53
+ ''
54
+ ].join('\n');
55
+
56
+ const sockets = parseLsof(output);
57
+
58
+ test('reads every socket across process blocks', () => {
59
+ expect(sockets).toHaveLength(5);
60
+ });
61
+
62
+ test('carries process identity forward across a process’s sockets', () => {
63
+ expect(sockets[0]).toMatchObject({ pid: 1200, processName: 'nginx', user: 'www' });
64
+ expect(sockets[1]).toMatchObject({ pid: 1200, port: 8080, ipVersion: 'v6', address: '::1' });
65
+ expect(sockets[2]).toMatchObject({ pid: 1310, processName: 'node', user: 'deploy' });
66
+ });
67
+
68
+ test('splits an established socket into local and peer', () => {
69
+ expect(sockets[3]).toMatchObject({
70
+ state: 'established',
71
+ port: 5173,
72
+ peerAddress: '127.0.0.1',
73
+ peerPort: 54120
74
+ });
75
+ });
76
+
77
+ test('treats a bound UDP socket with no peer as listening', () => {
78
+ expect(sockets[4]).toMatchObject({ protocol: 'udp', port: 5353, state: 'listen', address: '*' });
79
+ });
80
+ });
81
+
82
+ describe('parseSs', () => {
83
+ const output = [
84
+ 'Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process',
85
+ 'tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=800,fd=3))',
86
+ 'tcp LISTEN 0 511 [::]:443 [::]:* users:(("caddy",pid=910,fd=8),("caddy",pid=911,fd=8))',
87
+ 'tcp ESTAB 0 0 10.0.0.5:22 10.0.0.9:51234 users:(("sshd",pid=1422,fd=4))',
88
+ 'udp UNCONN 0 0 0.0.0.0:68 0.0.0.0:*',
89
+ ''
90
+ ].join('\n');
91
+
92
+ const sockets = parseSs(output);
93
+
94
+ test('skips the header and keeps every socket row', () => {
95
+ expect(sockets).toHaveLength(4);
96
+ });
97
+
98
+ test('pulls the owning pid out of the users:(…) field', () => {
99
+ expect(sockets[0]).toMatchObject({ port: 22, state: 'listen', pid: 800, processName: 'sshd' });
100
+ expect(sockets[1]).toMatchObject({ port: 443, pid: 910, processName: 'caddy' });
101
+ });
102
+
103
+ test('normalises a wildcard bind and reads the IP family from the address', () => {
104
+ expect(sockets[0].address).toBe('*');
105
+ expect(sockets[1]).toMatchObject({ address: '*', ipVersion: 'v4' });
106
+ });
107
+
108
+ test('records the peer of an established socket', () => {
109
+ expect(sockets[2]).toMatchObject({ state: 'established', peerAddress: '10.0.0.9', peerPort: 51234 });
110
+ });
111
+
112
+ test('leaves the owner null when the kernel withheld it', () => {
113
+ expect(sockets[3]).toMatchObject({ protocol: 'udp', port: 68, pid: null, state: 'listen' });
114
+ });
115
+ });
116
+
117
+ describe('parseNetstatUnix', () => {
118
+ const output = [
119
+ 'Active Internet connections (servers and established)',
120
+ 'Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name',
121
+ 'tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 800/sshd',
122
+ 'tcp6 0 0 :::443 :::* LISTEN -',
123
+ 'tcp 0 0 10.0.0.5:22 10.0.0.9:5123 ESTABLISHED 1422/sshd: deploy',
124
+ 'udp 0 0 0.0.0.0:68 0.0.0.0:* 640/dhclient',
125
+ ''
126
+ ].join('\n');
127
+
128
+ const sockets = parseNetstatUnix(output);
129
+
130
+ test('keeps only socket rows', () => {
131
+ expect(sockets).toHaveLength(4);
132
+ });
133
+
134
+ test('reads the family from the proto column rather than guessing', () => {
135
+ // A wildcard IPv6 bind prints as `:::443`, which looks like no address at
136
+ // all once normalised — only `tcp6` says which family it is.
137
+ expect(sockets[1]).toMatchObject({ port: 443, ipVersion: 'v6', address: '*' });
138
+ });
139
+
140
+ test('treats a withheld owner as unknown rather than pid 0', () => {
141
+ expect(sockets[1].pid).toBeNull();
142
+ });
143
+
144
+ test('takes the owner from the right column for UDP, which has no state', () => {
145
+ expect(sockets[3]).toMatchObject({ protocol: 'udp', port: 68, pid: 640, processName: 'dhclient' });
146
+ });
147
+
148
+ test('splits pid from program name', () => {
149
+ expect(sockets[0]).toMatchObject({ pid: 800, processName: 'sshd' });
150
+ });
151
+ });
152
+
153
+ describe('parseNetstatWindows', () => {
154
+ const output = [
155
+ 'Active Connections',
156
+ '',
157
+ ' Proto Local Address Foreign Address State PID',
158
+ ' TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1044',
159
+ ' TCP [::]:445 [::]:0 LISTENING 4',
160
+ ' TCP 10.0.0.5:52200 93.184.216.34:443 ESTABLISHED 7320',
161
+ ' UDP 0.0.0.0:5353 *:* 3180',
162
+ ''
163
+ ].join('\n');
164
+
165
+ const sockets = parseNetstatWindows(output);
166
+
167
+ test('keeps only socket rows', () => {
168
+ expect(sockets).toHaveLength(4);
169
+ });
170
+
171
+ test('reads the pid from the state-shifted column per protocol', () => {
172
+ expect(sockets[0]).toMatchObject({ port: 135, state: 'listen', pid: 1044 });
173
+ // UDP rows have no state column, so the pid sits one place to the left.
174
+ expect(sockets[3]).toMatchObject({ protocol: 'udp', port: 5353, pid: 3180, state: 'listen' });
175
+ });
176
+
177
+ test('unwraps a bracketed IPv6 address', () => {
178
+ expect(sockets[1]).toMatchObject({ address: '*', port: 445, ipVersion: 'v4' });
179
+ });
180
+
181
+ test('records the peer of an established socket', () => {
182
+ expect(sockets[2]).toMatchObject({
183
+ state: 'established',
184
+ peerAddress: '93.184.216.34',
185
+ peerPort: 443
186
+ });
187
+ });
188
+
189
+ test('never names a process, leaving that to the process table', () => {
190
+ expect(sockets.every((socket) => socket.processName === null)).toBe(true);
191
+ });
192
+ });
193
+
194
+ describe('parseProcNet', () => {
195
+ // What `grep '' /proc/net/tcp /proc/net/tcp6 …` prints: each line prefixed
196
+ // with the file it came from, which is what names the protocol and family.
197
+ const output = [
198
+ '/proc/net/tcp: sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode',
199
+ '/proc/net/tcp: 0: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 14200 1 0000 100 0 0 10 0',
200
+ '/proc/net/tcp: 1: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 25100 1 0000 100 0 0 10 0',
201
+ '/proc/net/tcp: 2: 0500000A:0016 0900000A:C822 01 00000000:00000000 00:00000000 00000000 0 0 25999 1 0000 20 0 0 10 -1',
202
+ '/proc/net/tcp6: 0: 00000000000000000000000000000000:01BB 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 14555 1 0000 100 0 0 10 0',
203
+ '/proc/net/tcp6: 1: 0000000000000000FFFF00000100007F:2383 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 30100 1 0000 100 0 0 10 0',
204
+ '/proc/net/udp: 2680: 00000000:0044 00000000:0000 07 00000000:00000000 00:00000000 00000000 0 0 15001 2 0000 0',
205
+ ''
206
+ ].join('\n');
207
+
208
+ const rows = parseProcNet(output);
209
+
210
+ test('skips the header and reads every socket', () => {
211
+ expect(rows).toHaveLength(6);
212
+ });
213
+
214
+ test('decodes little-endian hex addresses and ports', () => {
215
+ expect(rows[1].socket).toMatchObject({ address: '127.0.0.1', port: 8080, state: 'listen' });
216
+ });
217
+
218
+ test('renders an all-zero IPv6 bind as a wildcard, not a stray colon', () => {
219
+ expect(rows[3].socket).toMatchObject({ address: '*', port: 443, ipVersion: 'v6' });
220
+ });
221
+
222
+ test('renders a v4-mapped IPv6 address as the address people recognise', () => {
223
+ expect(rows[4].socket).toMatchObject({ address: '127.0.0.1', port: 9091, ipVersion: 'v6' });
224
+ });
225
+
226
+ test('reads the peer of an established socket', () => {
227
+ expect(rows[2].socket).toMatchObject({
228
+ state: 'established',
229
+ address: '10.0.0.5',
230
+ peerAddress: '10.0.0.9',
231
+ peerPort: 51234
232
+ });
233
+ });
234
+
235
+ test('treats a bound UDP socket as listening whatever its state column says', () => {
236
+ expect(rows[5].socket).toMatchObject({ protocol: 'udp', port: 68, state: 'listen' });
237
+ });
238
+
239
+ test('carries the inode, which is the only link back to a process', () => {
240
+ expect(rows.map((row) => row.inode)).toEqual([14200, 25100, 25999, 14555, 30100, 15001]);
241
+ });
242
+ });
243
+
244
+ describe('parseProcFdInodes', () => {
245
+ const output = [
246
+ '/proc/1234/fd/:',
247
+ 'lrwx------ 1 deploy deploy 64 Aug 25 09:00 3 -> socket:[25100]',
248
+ 'lrwx------ 1 deploy deploy 64 Aug 25 09:00 4 -> /dev/null',
249
+ '',
250
+ '/proc/1300/fd/:',
251
+ 'lrwx------ 1 deploy deploy 64 Aug 25 09:00 7 -> socket:[30100]',
252
+ 'lrwx------ 1 deploy deploy 64 Aug 25 09:00 8 -> socket:[25100]',
253
+ ''
254
+ ].join('\n');
255
+
256
+ const owners = parseProcFdInodes(output);
257
+
258
+ test('maps each socket inode to the process holding it', () => {
259
+ expect(owners.get(25100)).toBe(1234);
260
+ expect(owners.get(30100)).toBe(1300);
261
+ });
262
+
263
+ test('credits an inherited socket to the parent, not the forked child', () => {
264
+ // 1300 also holds inode 25100, but 1234 saw it first and is the ancestor.
265
+ expect(owners.get(25100)).toBe(1234);
266
+ });
267
+
268
+ test('ignores descriptors that are not sockets', () => {
269
+ expect(owners.size).toBe(2);
270
+ });
271
+ });
272
+
273
+ describe('probe selection on a host with no port tools', () => {
274
+ /** A host where `ss`, `netstat` and `lsof` are all absent. */
275
+ function bareHost(): { runner: CommandRunner; calls: string[] } {
276
+ const calls: string[] = [];
277
+ const runner: CommandRunner = {
278
+ label: 'bare host',
279
+ async run(argv: string[]) {
280
+ const name = argv.find((part) => !part.includes('=') && part !== 'env') ?? argv[0];
281
+ calls.push(name);
282
+ if (name === 'grep') {
283
+ return {
284
+ stdout:
285
+ '/proc/net/tcp: 0: 0100007F:1F90 00000000:0000 0A 0:0 00:0 0 1000 0 25100 1\n',
286
+ stderr: '',
287
+ code: 0
288
+ };
289
+ }
290
+ if (name === 'sh') return { stdout: '', stderr: '', code: 0 };
291
+ return { stdout: '', stderr: 'command not found', code: 127 };
292
+ }
293
+ };
294
+ return { runner, calls };
295
+ }
296
+
297
+ test('falls through to the kernel’s own tables and still reports the port', async () => {
298
+ const { runner } = bareHost();
299
+ const scan = await scanSockets(runner, 'linux');
300
+
301
+ expect(scan.probe).toBe('/proc/net');
302
+ expect(scan.sockets).toHaveLength(1);
303
+ expect(scan.sockets[0]).toMatchObject({ port: 8080, state: 'listen' });
304
+ });
305
+
306
+ test('remembers what worked instead of re-walking the chain every scan', async () => {
307
+ // This is what exhausted an SSH connection: four failing commands per
308
+ // tick, each one a channel, on a host that will never have those tools.
309
+ const { runner, calls } = bareHost();
310
+ const memo = {};
311
+
312
+ await scanSockets(runner, 'linux', memo);
313
+ const firstPass = calls.length;
314
+ calls.length = 0;
315
+
316
+ await scanSockets(runner, 'linux', memo);
317
+
318
+ expect(firstPass).toBeGreaterThan(3);
319
+ expect(calls).not.toContain('ss');
320
+ expect(calls).not.toContain('netstat');
321
+ expect(calls).not.toContain('lsof');
322
+ });
323
+
324
+ test('re-derives the probe if the remembered one stops answering', async () => {
325
+ const { runner } = bareHost();
326
+ const memo = {};
327
+ await scanSockets(runner, 'linux', memo);
328
+
329
+ // The host changes under us — every probe now fails.
330
+ const dead: CommandRunner = {
331
+ label: 'bare host',
332
+ async run() {
333
+ return { stdout: '', stderr: 'command not found', code: 127 };
334
+ }
335
+ };
336
+
337
+ // Re-derivation finds nothing either, and says so rather than reporting
338
+ // an empty table as though the host had no open ports.
339
+ await expect(scanSockets(dead, 'linux', memo)).rejects.toThrow(/Could not read the port table/);
340
+ });
341
+ });