@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Port manager — answering "where did this come from, and what is it for".
3
+ *
4
+ * Three tiers, ordered by how much Clopen actually knows, and the tier itself
5
+ * travels with the answer so the UI never dresses a guess up as a fact:
6
+ *
7
+ * 1. `clopen` Clopen opened the listener. The label comes from the feature
8
+ * that owns it, so it is exact.
9
+ * 2. `session` The process descends from a Clopen terminal session. Walking
10
+ * the parent chain proves the lineage; the purpose is still read
11
+ * off the command line, but "you started this in tab X" is fact.
12
+ * 3. `external` Everything else. Only the command line, the user and the
13
+ * working directory are known, so the label is a guess and is
14
+ * marked as one.
15
+ *
16
+ * On an SSH host tier 2 is not available. Clopen's remote shells are addressed
17
+ * through a synthetic id rather than the host's real pid (see
18
+ * `backend/ssh/pty-backend.ts`), so a lineage ending at *our* shell cannot be
19
+ * told apart from one ending at any other. The walk still reports that the
20
+ * process descends from an sshd session and for which user, which is true, and
21
+ * stops there rather than claiming a tab.
22
+ */
23
+
24
+ import type { PortOrigin, PortProcess, PortSocket } from '$shared/types/ports';
25
+ import type { ProbePlatform } from './runner';
26
+ import { ptyKitManager } from '../terminal/ptykit';
27
+ import { projectQueries } from '../database/queries';
28
+ import { collectOwnedPorts, ownedPortKey, type OwnedPort } from './registry';
29
+ import { debug } from '$shared/utils/logger';
30
+
31
+ /** A live Clopen terminal session, keyed by the pid of its shell. */
32
+ export interface SessionPid {
33
+ pid: number;
34
+ sessionId: string;
35
+ projectId: string;
36
+ projectName: string | null;
37
+ cwd: string;
38
+ }
39
+
40
+ /**
41
+ * Shell pids of every active PTY session. The manager lists per namespace and
42
+ * a namespace is a project, so every project is asked in turn.
43
+ */
44
+ export function collectSessionPids(): Map<number, SessionPid> {
45
+ const sessions = new Map<number, SessionPid>();
46
+
47
+ try {
48
+ for (const project of projectQueries.getAll()) {
49
+ for (const session of ptyKitManager.list(project.id)) {
50
+ const info = session.info();
51
+ if (info.status !== 'active' || !info.pid) continue;
52
+ sessions.set(info.pid, {
53
+ pid: info.pid,
54
+ sessionId: info.sessionId,
55
+ projectId: project.id,
56
+ projectName: project.name ?? null,
57
+ cwd: info.cwd
58
+ });
59
+ }
60
+ }
61
+ } catch (error) {
62
+ debug.log('ports', 'could not read terminal sessions:', error);
63
+ }
64
+
65
+ return sessions;
66
+ }
67
+
68
+ /** Guard against a malformed parent chain looping forever. */
69
+ const MAX_ANCESTRY_DEPTH = 40;
70
+
71
+ /**
72
+ * A Clopen server process, by the shape of its command line.
73
+ *
74
+ * Deliberately anchored on files that only exist inside a Clopen install —
75
+ * the published package path, or the repo's own entry points — rather than on
76
+ * the word "clopen" appearing anywhere. A user with a directory of that name
77
+ * should not have their processes claimed.
78
+ */
79
+ const CLOPEN_PROCESS = new RegExp(
80
+ [
81
+ '@myrialabs[/\\\\]clopen[/\\\\]',
82
+ 'clopen[/\\\\]scripts[/\\\\]start\\.ts',
83
+ 'clopen[/\\\\]backend[/\\\\]index\\.ts',
84
+ 'clopen[/\\\\]bin[/\\\\]clopen',
85
+ 'clopen[/\\\\]dist[/\\\\]'
86
+ ].join('|')
87
+ );
88
+
89
+ export function isClopenProcess(process: PortProcess | null): boolean {
90
+ return process ? CLOPEN_PROCESS.test(process.command) : false;
91
+ }
92
+
93
+ /**
94
+ * Every Clopen process on this machine, this one included.
95
+ *
96
+ * These are the roots tier-2 attribution walks up to. Anything descended from
97
+ * one was started by Clopen — a terminal shell, an engine, a command an agent
98
+ * ran, an MCP server, a dev server launched from any of them. Keying on the
99
+ * process tree rather than on terminal sessions is what makes that hold for
100
+ * all of them instead of only the shells.
101
+ *
102
+ * Other Clopen instances count too: a port opened from a second install's
103
+ * terminal is still a port Clopen opened, and the user reads it that way.
104
+ */
105
+ export function findClopenPids(
106
+ processes: Map<number, PortProcess>,
107
+ selfPid: number | null
108
+ ): Set<number> {
109
+ const pids = new Set<number>();
110
+ if (selfPid !== null) pids.add(selfPid);
111
+ for (const [pid, process] of processes) {
112
+ if (isClopenProcess(process)) pids.add(pid);
113
+ }
114
+ return pids;
115
+ }
116
+
117
+ export interface Ancestry {
118
+ /** The chain from the process itself up to init, self first. */
119
+ chain: PortProcess[];
120
+ /** The Clopen terminal session it descends from, if any. */
121
+ session: SessionPid | null;
122
+ /**
123
+ * True when the chain reaches a process Clopen is: one of its own instances
124
+ * locally, or the sshd session it is using on a remote host.
125
+ */
126
+ fromClopen: boolean;
127
+ /** The user of the sshd session it descends from, on a remote host. */
128
+ sshdUser: string | null;
129
+ }
130
+
131
+ /** `sshd: arga@pts/0` and `sshd: arga [priv]` both name the session's user. */
132
+ function sshdUserOf(command: string): string | null {
133
+ const match = command.match(/^sshd:\s+([^\s@[]+)/);
134
+ return match ? match[1] : null;
135
+ }
136
+
137
+ export function traceAncestry(
138
+ pid: number,
139
+ processes: Map<number, PortProcess>,
140
+ sessions: Map<number, SessionPid>,
141
+ clopenRootPids: ReadonlySet<number> = new Set()
142
+ ): Ancestry {
143
+ const chain: PortProcess[] = [];
144
+ const seen = new Set<number>();
145
+
146
+ let session: SessionPid | null = null;
147
+ let sshdUser: string | null = null;
148
+ let fromClopen = false;
149
+ let current: number | null = pid;
150
+
151
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH && current !== null && current > 0; depth++) {
152
+ if (seen.has(current)) break;
153
+ seen.add(current);
154
+
155
+ const found = sessions.get(current);
156
+ if (found && !session) session = found;
157
+ if (clopenRootPids.has(current)) fromClopen = true;
158
+
159
+ const process = processes.get(current);
160
+ if (!process) break;
161
+ chain.push(process);
162
+
163
+ if (!sshdUser) sshdUser = sshdUserOf(process.command);
164
+
165
+ current = process.parentPid;
166
+ }
167
+
168
+ return { chain, session, fromClopen, sshdUser };
169
+ }
170
+
171
+ /**
172
+ * What an unattributed process most likely is. Matched against the full
173
+ * command line so `node .../vite/bin/vite.js` reads as Vite rather than Node.
174
+ * Deliberately shallow: the raw command is always shown next to this, and a
175
+ * confident wrong answer is worse than "Listening process".
176
+ */
177
+ const COMMAND_HINTS: Array<{ pattern: RegExp; label: string }> = [
178
+ { pattern: /\bvite\b/, label: 'Vite dev server' },
179
+ { pattern: /\bnext(-server)?\b|\bnext\/dist\b/, label: 'Next.js' },
180
+ { pattern: /\bnuxt\b/, label: 'Nuxt' },
181
+ { pattern: /\bastro\b/, label: 'Astro' },
182
+ { pattern: /webpack-dev-server|react-scripts/, label: 'Webpack dev server' },
183
+ { pattern: /\bng\s+serve\b|@angular\/cli/, label: 'Angular dev server' },
184
+ { pattern: /\bstorybook\b/, label: 'Storybook' },
185
+ { pattern: /\bpostgres\b|\bpostmaster\b/, label: 'PostgreSQL' },
186
+ { pattern: /\bmysqld\b|\bmariadbd\b/, label: 'MySQL / MariaDB' },
187
+ { pattern: /\bredis-server\b/, label: 'Redis' },
188
+ { pattern: /\bmongod\b/, label: 'MongoDB' },
189
+ { pattern: /\bdocker-proxy\b|com\.docker/, label: 'Docker published port' },
190
+ { pattern: /\bnginx\b/, label: 'nginx' },
191
+ { pattern: /\bcaddy\b/, label: 'Caddy' },
192
+ { pattern: /\bhttpd\b|\bapache2\b/, label: 'Apache' },
193
+ { pattern: /\bsshd\b/, label: 'SSH server' },
194
+ { pattern: /\bcloudflared\b/, label: 'Cloudflare tunnel' },
195
+ { pattern: /\bollama\b/, label: 'Ollama' },
196
+ { pattern: /python[0-9.]*\s+-m\s+http\.server/, label: 'Python http.server' },
197
+ { pattern: /\bphp\b.*\s-S\s/, label: 'PHP built-in server' },
198
+ { pattern: /\brails\b|\bpuma\b/, label: 'Rails / Puma' }
199
+ ];
200
+
201
+ function guessLabel(process: PortProcess | null, fallbackName: string | null): string {
202
+ const command = process?.command ?? '';
203
+ for (const hint of COMMAND_HINTS) {
204
+ if (hint.pattern.test(command)) return hint.label;
205
+ }
206
+ if (fallbackName) return fallbackName;
207
+ if (command) return command.split(/\s+/)[0].split('/').pop() || 'Listening process';
208
+ return 'Listening process';
209
+ }
210
+
211
+ /** Trim a command line to something a table cell can hold. */
212
+ function shorten(command: string, max = 140): string {
213
+ return command.length <= max ? command : `${command.slice(0, max - 1)}…`;
214
+ }
215
+
216
+ export interface AttributionContext {
217
+ platform: ProbePlatform;
218
+ /** Ports Clopen opened on this host, whichever host it is. */
219
+ owned: Map<string, OwnedPort>;
220
+ /** Shell pids of local terminal sessions; empty on an SSH host. */
221
+ sessions: Map<number, SessionPid>;
222
+ /**
223
+ * The processes that count as "Clopen" on this host: its own instances
224
+ * locally, and remotely everything found to belong to Clopen's own SSH
225
+ * connection. One field for both, because it answers the same question
226
+ * either way — is this Clopen's doing.
227
+ */
228
+ clopenRootPids: ReadonlySet<number>;
229
+ /** Host label, so remote attributions can name where they were found. */
230
+ hostName: string;
231
+ processes: Map<number, PortProcess>;
232
+ isLocal: boolean;
233
+ }
234
+
235
+ export function buildContext(input: {
236
+ platform: ProbePlatform;
237
+ processes: Map<number, PortProcess>;
238
+ hostId: string;
239
+ hostName: string;
240
+ isLocal: boolean;
241
+ clopenPids: ReadonlySet<number>;
242
+ }): AttributionContext {
243
+ // A Clopen install is recognised the same way wherever it runs, and on a
244
+ // remote host every process on Clopen's own SSH connection counts too. One
245
+ // set, built from whichever of those apply to this host.
246
+ const clopenRootPids = findClopenPids(input.processes, input.isLocal ? process.pid : null);
247
+ for (const pid of input.clopenPids) clopenRootPids.add(pid);
248
+
249
+ return {
250
+ platform: input.platform,
251
+ owned: collectOwnedPorts(input.hostId),
252
+ sessions: input.isLocal ? collectSessionPids() : new Map(),
253
+ clopenRootPids,
254
+ hostName: input.hostName,
255
+ processes: input.processes,
256
+ isLocal: input.isLocal
257
+ };
258
+ }
259
+
260
+ /** Decide where a listening socket came from. */
261
+ export function attribute(socket: PortSocket, context: AttributionContext): PortOrigin {
262
+ const owned = context.owned.get(ownedPortKey(socket.protocol, socket.port));
263
+ if (owned) {
264
+ return {
265
+ kind: 'clopen',
266
+ confidence: 'certain',
267
+ label: owned.label,
268
+ detail: owned.detail,
269
+ ownerFeature: owned.feature,
270
+ ownerId: owned.ownerId ?? undefined
271
+ };
272
+ }
273
+
274
+ const process = socket.pid !== null ? (context.processes.get(socket.pid) ?? null) : null;
275
+
276
+ // Another Clopen install listening on its own port. The registry only knows
277
+ // the ports of *this* process, so without this the other instance would be
278
+ // filed under "outside Clopen" — which is not how anyone reads it. A Clopen
279
+ // on an SSH host is recognised by the same signature, on purpose.
280
+ if (isClopenProcess(process)) {
281
+ return {
282
+ kind: 'clopen',
283
+ confidence: 'certain',
284
+ label: 'Clopen server',
285
+ detail: context.isLocal
286
+ ? 'Another Clopen instance running on this machine'
287
+ : `A Clopen instance running on ${context.hostName}`,
288
+ ownerFeature: 'server'
289
+ };
290
+ }
291
+
292
+ const ancestry =
293
+ socket.pid !== null
294
+ ? traceAncestry(socket.pid, context.processes, context.sessions, context.clopenRootPids)
295
+ : null;
296
+
297
+ if (ancestry?.session) {
298
+ const { session } = ancestry;
299
+ const where = session.projectName ? `project ${session.projectName}` : session.cwd;
300
+ return {
301
+ kind: 'session',
302
+ confidence: 'certain',
303
+ label: guessLabel(process, socket.processName),
304
+ detail: `Started from a terminal session in ${where}`,
305
+ sessionId: session.sessionId,
306
+ projectId: session.projectId
307
+ };
308
+ }
309
+
310
+ if (ancestry?.fromClopen) {
311
+ return {
312
+ kind: 'session',
313
+ confidence: 'certain',
314
+ label: guessLabel(process, socket.processName),
315
+ // Which tab is not knowable here — every channel Clopen opens shares
316
+ // one sshd connection — but that Clopen started it is not in doubt.
317
+ detail: `Started through Clopen on ${context.hostName}`
318
+ };
319
+ }
320
+
321
+ if (ancestry?.sshdUser) {
322
+ return {
323
+ kind: 'session',
324
+ confidence: 'certain',
325
+ label: guessLabel(process, socket.processName),
326
+ // Someone else's SSH session: real lineage, but not Clopen's doing.
327
+ detail: `Started from an SSH session as ${ancestry.sshdUser}`,
328
+ remoteSessionUser: ancestry.sshdUser
329
+ };
330
+ }
331
+
332
+ const detail = process?.command ? shorten(process.command) : null;
333
+ return {
334
+ kind: 'external',
335
+ confidence: 'guess',
336
+ label: guessLabel(process, socket.processName),
337
+ detail: detail ?? (socket.pid === null ? 'Owner not visible without elevated privileges' : null)
338
+ };
339
+ }
340
+
341
+ /**
342
+ * The program a command line belongs to, used to tell a worker pool apart from
343
+ * unrelated processes that merely share a parent. `nginx: worker process` and
344
+ * `nginx: master process` both reduce to `nginx`.
345
+ */
346
+ function programKey(command: string): string {
347
+ const first = command.trim().split(/\s+/)[0] ?? '';
348
+ return (first.replace(/:$/, '').split('/').pop() ?? '').toLowerCase();
349
+ }
350
+
351
+ export interface PidGroup {
352
+ /** The process that represents the port. */
353
+ owner: number;
354
+ /** Every listening pid in the group, the owner included when it listens. */
355
+ members: number[];
356
+ }
357
+
358
+ /**
359
+ * Group the pids holding one port by the process that actually owns it.
360
+ *
361
+ * A server that pre-forks workers has every worker inherit the listening
362
+ * socket, so a plain listing shows eight identical rows for one port. Two
363
+ * shapes of that are collapsed here:
364
+ *
365
+ * 1. One candidate is an ancestor of the others — a master that also listens.
366
+ * 2. The candidates are siblings of one parent and all run the same program as
367
+ * that parent, which is what a worker pool looks like when the master holds
368
+ * no socket of its own (nginx on macOS). The parent becomes the owner even
369
+ * though it is not listening, because it is the process a user means when
370
+ * they say "nginx".
371
+ *
372
+ * Everything else stays separate. Unrelated programs can hold the same port
373
+ * number on different addresses, and merging those would invent a relationship.
374
+ */
375
+ export function groupListenerPids(pids: number[], processes: Map<number, PortProcess>): PidGroup[] {
376
+ const candidates = new Set(pids);
377
+
378
+ /** Highest ancestor that also holds this port, else the pid itself. */
379
+ const ancestorRoot = (pid: number): number => {
380
+ let root = pid;
381
+ let current: number | null = processes.get(pid)?.parentPid ?? null;
382
+ const seen = new Set<number>([pid]);
383
+
384
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH && current !== null && current > 0; depth++) {
385
+ if (seen.has(current)) break;
386
+ seen.add(current);
387
+ if (candidates.has(current)) root = current;
388
+ current = processes.get(current)?.parentPid ?? null;
389
+ }
390
+
391
+ return root;
392
+ };
393
+
394
+ const byRoot = new Map<number, number[]>();
395
+ for (const pid of pids) {
396
+ const root = ancestorRoot(pid);
397
+ const members = byRoot.get(root);
398
+ if (members) members.push(pid);
399
+ else byRoot.set(root, [pid]);
400
+ }
401
+
402
+ // Second pass: fold sibling roots onto a shared parent running the same
403
+ // program. Roots with no such parent are emitted untouched.
404
+ const bySharedParent = new Map<number, number[]>();
405
+ const groups: PidGroup[] = [];
406
+
407
+ for (const root of byRoot.keys()) {
408
+ const parentPid = processes.get(root)?.parentPid ?? null;
409
+ if (parentPid === null || parentPid <= 1) continue;
410
+ const siblings = bySharedParent.get(parentPid);
411
+ if (siblings) siblings.push(root);
412
+ else bySharedParent.set(parentPid, [root]);
413
+ }
414
+
415
+ const folded = new Set<number>();
416
+ for (const [parentPid, roots] of bySharedParent) {
417
+ if (roots.length < 2) continue;
418
+
419
+ const parent = processes.get(parentPid);
420
+ if (!parent) continue;
421
+ const parentProgram = programKey(parent.command);
422
+ if (!parentProgram) continue;
423
+
424
+ const sameProgram = roots.every((root) => {
425
+ const process = processes.get(root);
426
+ return process ? programKey(process.command) === parentProgram : false;
427
+ });
428
+ if (!sameProgram) continue;
429
+
430
+ const members: number[] = [];
431
+ for (const root of roots) {
432
+ members.push(...(byRoot.get(root) ?? [root]));
433
+ folded.add(root);
434
+ }
435
+ groups.push({ owner: parentPid, members: [...new Set(members)].sort((a, b) => a - b) });
436
+ }
437
+
438
+ for (const [root, members] of byRoot) {
439
+ if (folded.has(root)) continue;
440
+ groups.push({ owner: root, members: [...new Set(members)].sort((a, b) => a - b) });
441
+ }
442
+
443
+ return groups;
444
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Port manager — stopping what is holding a port.
3
+ *
4
+ * Three paths, because "kill it" means three different things:
5
+ *
6
+ * - A port a Clopen feature owns is released through that feature, never by
7
+ * signalling a pid. Killing the process behind an SSH forward would leave the
8
+ * forward's own record claiming it is still running.
9
+ * - Anything else is stopped by signalling the process tree, children first so
10
+ * a supervisor cannot restart them on the way down, SIGTERM before SIGKILL so
11
+ * a dev server gets its chance to shut down cleanly.
12
+ * - Clopen's own socket is never a target.
13
+ *
14
+ * A refusal by the OS is reported as what it is. Nothing here escalates to
15
+ * `sudo`: a port owned by another user is the administrator's business, and
16
+ * quietly acquiring privilege to end someone else's process is not a thing this
17
+ * panel should do behind the user's back.
18
+ */
19
+
20
+ import type { PortKillResult, PortOwnerFeature } from '$shared/types/ports';
21
+ import { parsePsOutput, unixPsArgv } from './processes';
22
+ import type { CommandRunner, ProbePlatform } from './runner';
23
+ import { sshForwardManager } from '../ssh/forwards';
24
+ import { connectionManager } from '../db-client/connection-manager';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ /** Grace between the polite signal and the final one. */
28
+ const SIGKILL_DELAY_MS = 2_000;
29
+
30
+ /** Ceiling on tree depth, so a malformed parent chain cannot loop. */
31
+ const MAX_TREE_DEPTH = 20;
32
+
33
+ export interface KillTarget {
34
+ pid: number;
35
+ /** Set when a Clopen feature owns the port. */
36
+ ownerFeature?: PortOwnerFeature;
37
+ ownerId?: string;
38
+ }
39
+
40
+ /** Release a port through the feature that opened it. */
41
+ async function stopFeature(feature: PortOwnerFeature, ownerId: string | undefined): Promise<PortKillResult> {
42
+ if (!ownerId) {
43
+ return { ok: false, killedPids: [], stoppedFeature: null, error: 'That port has no owning record to stop.' };
44
+ }
45
+
46
+ try {
47
+ switch (feature) {
48
+ case 'ssh-forward':
49
+ await sshForwardManager.stop(ownerId);
50
+ return { ok: true, killedPids: [], stoppedFeature: feature, error: null };
51
+ case 'db-client-tunnel':
52
+ await connectionManager.release(ownerId);
53
+ return { ok: true, killedPids: [], stoppedFeature: feature, error: null };
54
+ default:
55
+ return {
56
+ ok: false,
57
+ killedPids: [],
58
+ stoppedFeature: null,
59
+ error: 'That port belongs to Clopen and cannot be released from here.'
60
+ };
61
+ }
62
+ } catch (error) {
63
+ return {
64
+ ok: false,
65
+ killedPids: [],
66
+ stoppedFeature: null,
67
+ error: error instanceof Error ? error.message : String(error)
68
+ };
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Every descendant of `pid`, deepest first. Read fresh rather than from the
74
+ * scan cache: a tick-old tree could name a pid the OS has already recycled.
75
+ */
76
+ async function descendantsOf(pid: number, runner: CommandRunner, platform: ProbePlatform): Promise<number[]> {
77
+ if (platform === 'win32') return [];
78
+
79
+ const result = await runner.run(unixPsArgv(platform));
80
+
81
+ const children = new Map<number, number[]>();
82
+ for (const process of parsePsOutput(result.stdout)) {
83
+ if (process.parentPid === null) continue;
84
+ const siblings = children.get(process.parentPid);
85
+ if (siblings) siblings.push(process.pid);
86
+ else children.set(process.parentPid, [process.pid]);
87
+ }
88
+
89
+ const ordered: number[] = [];
90
+ const visit = (current: number, depth: number): void => {
91
+ if (depth >= MAX_TREE_DEPTH) return;
92
+ for (const child of children.get(current) ?? []) {
93
+ visit(child, depth + 1);
94
+ ordered.push(child);
95
+ }
96
+ };
97
+ visit(pid, 0);
98
+
99
+ return ordered;
100
+ }
101
+
102
+ /** Is the process still there? `kill -0` asks without sending anything. */
103
+ async function isAlive(pid: number, runner: CommandRunner, platform: ProbePlatform): Promise<boolean> {
104
+ try {
105
+ if (platform === 'win32') {
106
+ const result = await runner.run(['tasklist', '/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH']);
107
+ return result.stdout.includes(`"${pid}"`);
108
+ }
109
+ const result = await runner.run(['kill', '-0', String(pid)]);
110
+ return result.code === 0;
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Turn a failed signal into something worth reading. `kill` says "Operation not
118
+ * permitted" and nothing about why, which is the most common outcome here.
119
+ */
120
+ function explain(stderr: string, pid: number): string {
121
+ const text = stderr.trim();
122
+ if (/not permitted|access is denied/i.test(text)) {
123
+ return `Not allowed to stop process ${pid}. It belongs to another user — stop it from an account that owns it.`;
124
+ }
125
+ if (/no such process/i.test(text)) return `Process ${pid} had already exited.`;
126
+ return text || `Could not stop process ${pid}.`;
127
+ }
128
+
129
+ /** Signal a process tree, children first, escalating only if it survives. */
130
+ export async function killProcessTree(
131
+ pid: number,
132
+ runner: CommandRunner,
133
+ platform: ProbePlatform
134
+ ): Promise<PortKillResult> {
135
+ const killed: number[] = [];
136
+
137
+ if (platform === 'win32') {
138
+ // taskkill walks the tree itself, which is the only reliable way to do it
139
+ // on Windows — there is no signal to escalate through.
140
+ try {
141
+ const result = await runner.run(['taskkill', '/T', '/F', '/PID', String(pid)]);
142
+ if (result.code === 0) return { ok: true, killedPids: [pid], stoppedFeature: null, error: null };
143
+ return { ok: false, killedPids: [], stoppedFeature: null, error: explain(result.stderr || result.stdout, pid) };
144
+ } catch (error) {
145
+ return {
146
+ ok: false,
147
+ killedPids: [],
148
+ stoppedFeature: null,
149
+ error: error instanceof Error ? error.message : String(error)
150
+ };
151
+ }
152
+ }
153
+
154
+ const targets = [...(await descendantsOf(pid, runner, platform)), pid];
155
+ let lastError: string | null = null;
156
+
157
+ for (const target of targets) {
158
+ try {
159
+ const result = await runner.run(['kill', '-TERM', String(target)]);
160
+ if (result.code === 0) killed.push(target);
161
+ else if (target === pid) lastError = explain(result.stderr, target);
162
+ } catch (error) {
163
+ if (target === pid) lastError = error instanceof Error ? error.message : String(error);
164
+ }
165
+ }
166
+
167
+ if (killed.length === 0) {
168
+ return { ok: false, killedPids: [], stoppedFeature: null, error: lastError ?? `Could not stop process ${pid}.` };
169
+ }
170
+
171
+ await new Promise((resolve) => setTimeout(resolve, SIGKILL_DELAY_MS));
172
+
173
+ for (const target of killed) {
174
+ if (!(await isAlive(target, runner, platform))) continue;
175
+ try {
176
+ await runner.run(['kill', '-KILL', String(target)]);
177
+ } catch (error) {
178
+ debug.log('ports', `SIGKILL failed for ${target}:`, error);
179
+ }
180
+ }
181
+
182
+ // The port is only actually free if the process that held it is gone.
183
+ if (await isAlive(pid, runner, platform)) {
184
+ return {
185
+ ok: false,
186
+ killedPids: killed,
187
+ stoppedFeature: null,
188
+ error: `Process ${pid} ignored both signals and is still running.`
189
+ };
190
+ }
191
+
192
+ return { ok: true, killedPids: killed, stoppedFeature: null, error: null };
193
+ }
194
+
195
+ /** Stop whatever holds a port, by the route that suits its owner. */
196
+ export async function stopPortHolder(
197
+ target: KillTarget,
198
+ runner: CommandRunner,
199
+ platform: ProbePlatform
200
+ ): Promise<PortKillResult> {
201
+ if (target.ownerFeature) return stopFeature(target.ownerFeature, target.ownerId);
202
+ return killProcessTree(target.pid, runner, platform);
203
+ }