@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.
- package/backend/auth/permissions.ts +10 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/db-client/connection-manager.ts +13 -0
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +45 -1
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/runner.ts +204 -0
- package/backend/index.ts +20 -2
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/scan-host.ts +329 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/ssh/forwards.ts +31 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/git/log.ts +3 -1
- package/backend/ws/git/status.ts +37 -27
- package/backend/ws/index.ts +4 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +99 -43
- package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
- package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
- package/dist/assets/main-Buko4D0t.css +1 -0
- package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +230 -0
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/ws-client.ts +67 -12
- package/shared/utils/ws-server.ts +64 -13
- package/dist/assets/main-CCvRMXlP.css +0 -1
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port manager — who the pid behind a socket actually is.
|
|
3
|
+
*
|
|
4
|
+
* A socket row carries a pid and, on some platforms, a truncated process name.
|
|
5
|
+
* Neither answers "what is this and where did it come from" — that needs the
|
|
6
|
+
* parent pid (to trace lineage back to a Clopen terminal), the full argv, and
|
|
7
|
+
* the working directory (the strongest hint at which project a dev server
|
|
8
|
+
* belongs to).
|
|
9
|
+
*
|
|
10
|
+
* The table is cached per host and refreshed incrementally: a full sweep on the
|
|
11
|
+
* first tick and every `FULL_SWEEP_MS` after, and in between only pids never
|
|
12
|
+
* seen before are looked up. That keeps a one-second poll to a single cheap
|
|
13
|
+
* probe on Unix, and makes it affordable on Windows where the only source of
|
|
14
|
+
* argv and parent pid is a PowerShell query that costs hundreds of milliseconds
|
|
15
|
+
* to start.
|
|
16
|
+
*
|
|
17
|
+
* Cache entries are keyed by pid *and* start time, so a recycled pid is treated
|
|
18
|
+
* as the new process it is rather than inheriting the dead one's identity.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { PortLimitation, PortProcess } from '$shared/types/ports';
|
|
22
|
+
import type { CommandRunner, ProbePlatform } from '../host/runner';
|
|
23
|
+
import { debug } from '$shared/utils/logger';
|
|
24
|
+
|
|
25
|
+
/** How often the whole table is re-read, so exited pids stop being reported. */
|
|
26
|
+
const FULL_SWEEP_MS = 30_000;
|
|
27
|
+
|
|
28
|
+
/** Ceiling on pids named in one targeted lookup, to stay under argv limits. */
|
|
29
|
+
const LOOKUP_BATCH = 200;
|
|
30
|
+
|
|
31
|
+
const UNIX_PS_FORMAT = 'pid=,ppid=,user=,lstart=,args=';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `ps` is run through `env LC_ALL=C` so lstart comes back in the English form
|
|
35
|
+
* the parser below expects. `env` is on every POSIX host, and going through it
|
|
36
|
+
* works identically for a local spawn and a remote exec — the alternative,
|
|
37
|
+
* setting an environment variable, has no equivalent over an SSH command.
|
|
38
|
+
*/
|
|
39
|
+
export function unixPsArgv(platform: ProbePlatform, selector: string[] = []): string[] {
|
|
40
|
+
const flag = platform === 'darwin' && selector.length === 0 ? '-axo' : '-eo';
|
|
41
|
+
return selector.length > 0
|
|
42
|
+
? ['env', 'LC_ALL=C', 'ps', '-o', UNIX_PS_FORMAT, ...selector]
|
|
43
|
+
: ['env', 'LC_ALL=C', 'ps', flag, UNIX_PS_FORMAT];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const C_LOCALE_MONTHS: Record<string, number> = {
|
|
47
|
+
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
|
|
48
|
+
Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Turn the five lstart tokens into a timestamp, strictly.
|
|
53
|
+
*
|
|
54
|
+
* `Date` must not be handed this text directly: given a French `mar. août 25`
|
|
55
|
+
* it does not fail, it reads `mar.` as March and returns a date four months
|
|
56
|
+
* off. So the shape is checked and the month looked up in a table, and
|
|
57
|
+
* anything that does not match yields null — no start time is honest, a
|
|
58
|
+
* confidently wrong one is not.
|
|
59
|
+
*/
|
|
60
|
+
export function parseCLocaleStart(tokens: string[]): string | null {
|
|
61
|
+
if (tokens.length !== 5) return null;
|
|
62
|
+
const [, month, day, time, year] = tokens;
|
|
63
|
+
|
|
64
|
+
const monthIndex = C_LOCALE_MONTHS[month];
|
|
65
|
+
if (monthIndex === undefined) return null;
|
|
66
|
+
|
|
67
|
+
const dayNumber = Number.parseInt(day, 10);
|
|
68
|
+
const yearNumber = Number.parseInt(year, 10);
|
|
69
|
+
const clock = time.match(/^(\d{2}):(\d{2}):(\d{2})$/);
|
|
70
|
+
if (!Number.isFinite(dayNumber) || !Number.isFinite(yearNumber) || !clock) return null;
|
|
71
|
+
|
|
72
|
+
const started = new Date(
|
|
73
|
+
yearNumber,
|
|
74
|
+
monthIndex,
|
|
75
|
+
dayNumber,
|
|
76
|
+
Number.parseInt(clock[1], 10),
|
|
77
|
+
Number.parseInt(clock[2], 10),
|
|
78
|
+
Number.parseInt(clock[3], 10)
|
|
79
|
+
);
|
|
80
|
+
return Number.isNaN(started.getTime()) ? null : started.toISOString();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* `ps` prints lstart as exactly five tokens ("Tue Aug 25 08:24:48 2026"), so
|
|
85
|
+
* the row is parsed positionally — that holds whatever the locale does to the
|
|
86
|
+
* words themselves.
|
|
87
|
+
*/
|
|
88
|
+
function parsePsLine(line: string): PortProcess | null {
|
|
89
|
+
const trimmed = line.trim();
|
|
90
|
+
if (!trimmed) return null;
|
|
91
|
+
|
|
92
|
+
const tokens = trimmed.split(/\s+/);
|
|
93
|
+
if (tokens.length < 9) return null;
|
|
94
|
+
|
|
95
|
+
const pid = Number.parseInt(tokens[0], 10);
|
|
96
|
+
if (!Number.isFinite(pid)) return null;
|
|
97
|
+
const parentPid = Number.parseInt(tokens[1], 10);
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
pid,
|
|
101
|
+
parentPid: Number.isFinite(parentPid) ? parentPid : null,
|
|
102
|
+
user: tokens[2] || null,
|
|
103
|
+
command: tokens.slice(8).join(' '),
|
|
104
|
+
startedAt: parseCLocaleStart(tokens.slice(3, 8)),
|
|
105
|
+
cwd: null
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function parsePsOutput(stdout: string): PortProcess[] {
|
|
110
|
+
const processes: PortProcess[] = [];
|
|
111
|
+
for (const line of stdout.split('\n')) {
|
|
112
|
+
const parsed = parsePsLine(line);
|
|
113
|
+
if (parsed) processes.push(parsed);
|
|
114
|
+
}
|
|
115
|
+
return processes;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* PowerShell CIM output, one record per blank-line-separated block of
|
|
120
|
+
* `Name: value` pairs. Windows has no `ps`, and `tasklist` reports neither the
|
|
121
|
+
* parent pid nor the command line.
|
|
122
|
+
*/
|
|
123
|
+
export function parseWindowsProcesses(stdout: string): PortProcess[] {
|
|
124
|
+
const processes: PortProcess[] = [];
|
|
125
|
+
|
|
126
|
+
for (const block of stdout.split(/\r?\n\r?\n/)) {
|
|
127
|
+
if (!block.trim()) continue;
|
|
128
|
+
const fields = new Map<string, string>();
|
|
129
|
+
for (const line of block.split(/\r?\n/)) {
|
|
130
|
+
const separator = line.indexOf(':');
|
|
131
|
+
if (separator <= 0) continue;
|
|
132
|
+
fields.set(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const pid = Number.parseInt(fields.get('ProcessId') ?? '', 10);
|
|
136
|
+
if (!Number.isFinite(pid)) continue;
|
|
137
|
+
const parentPid = Number.parseInt(fields.get('ParentProcessId') ?? '', 10);
|
|
138
|
+
const started = new Date(fields.get('CreationDate') ?? '');
|
|
139
|
+
|
|
140
|
+
processes.push({
|
|
141
|
+
pid,
|
|
142
|
+
parentPid: Number.isFinite(parentPid) ? parentPid : null,
|
|
143
|
+
user: fields.get('UserName') || null,
|
|
144
|
+
command: fields.get('CommandLine') || fields.get('Name') || '',
|
|
145
|
+
startedAt: Number.isNaN(started.getTime()) ? null : started.toISOString(),
|
|
146
|
+
cwd: null
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return processes;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** `lsof -Fn` cwd output: a `p<pid>` line followed by that process's `n<path>`. */
|
|
154
|
+
export function parseLsofCwd(stdout: string): Map<number, string> {
|
|
155
|
+
const cwds = new Map<number, string>();
|
|
156
|
+
let pid: number | null = null;
|
|
157
|
+
|
|
158
|
+
for (const line of stdout.split('\n')) {
|
|
159
|
+
if (!line) continue;
|
|
160
|
+
if (line[0] === 'p') {
|
|
161
|
+
pid = Number.parseInt(line.slice(1), 10) || null;
|
|
162
|
+
} else if (line[0] === 'n' && pid !== null) {
|
|
163
|
+
cwds.set(pid, line.slice(1));
|
|
164
|
+
pid = null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return cwds;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** `ls -l /proc/<pid>/cwd` output: `… /proc/800/cwd -> /srv/app`. */
|
|
172
|
+
export function parseProcCwd(stdout: string): Map<number, string> {
|
|
173
|
+
const cwds = new Map<number, string>();
|
|
174
|
+
|
|
175
|
+
for (const line of stdout.split('\n')) {
|
|
176
|
+
const match = line.match(/\/proc\/(\d+)\/cwd -> (.+)$/);
|
|
177
|
+
if (!match) continue;
|
|
178
|
+
const pid = Number.parseInt(match[1], 10);
|
|
179
|
+
if (Number.isFinite(pid)) cwds.set(pid, match[2].trim());
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return cwds;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const NO_CWD_ON_WINDOWS: PortLimitation = {
|
|
186
|
+
code: 'no-cwd-support',
|
|
187
|
+
message: 'Windows does not expose a process working directory, so the project a port belongs to cannot be inferred.'
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const NO_ARGS_ON_WINDOWS: PortLimitation = {
|
|
191
|
+
code: 'no-process-args',
|
|
192
|
+
message: 'PowerShell was unavailable, so only process names could be read — no command line or parent process.'
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* A host's process table. One instance per host, held for as long as that host
|
|
197
|
+
* is being watched.
|
|
198
|
+
*/
|
|
199
|
+
export class ProcessTable {
|
|
200
|
+
private readonly entries = new Map<number, PortProcess>();
|
|
201
|
+
/** Pids whose cwd has been resolved, including those that resolved to none. */
|
|
202
|
+
private readonly cwdResolved = new Set<number>();
|
|
203
|
+
private lastFullSweep = 0;
|
|
204
|
+
private readonly limitations: PortLimitation[] = [];
|
|
205
|
+
|
|
206
|
+
constructor(
|
|
207
|
+
private readonly runner: CommandRunner,
|
|
208
|
+
private readonly platform: ProbePlatform
|
|
209
|
+
) {}
|
|
210
|
+
|
|
211
|
+
/** Limitations discovered while reading this host, deduplicated by code. */
|
|
212
|
+
getLimitations(): PortLimitation[] {
|
|
213
|
+
return [...this.limitations];
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
private noteLimitation(limitation: PortLimitation): void {
|
|
217
|
+
if (this.limitations.some((existing) => existing.code === limitation.code)) return;
|
|
218
|
+
this.limitations.push(limitation);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private absorb(processes: PortProcess[]): void {
|
|
222
|
+
for (const process of processes) {
|
|
223
|
+
const existing = this.entries.get(process.pid);
|
|
224
|
+
// A pid whose start time moved is a different process wearing the same
|
|
225
|
+
// number; drop everything remembered about the old one.
|
|
226
|
+
if (existing && existing.startedAt !== process.startedAt) {
|
|
227
|
+
this.cwdResolved.delete(process.pid);
|
|
228
|
+
} else if (existing) {
|
|
229
|
+
process.cwd = existing.cwd;
|
|
230
|
+
}
|
|
231
|
+
this.entries.set(process.pid, process);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private async readAll(): Promise<PortProcess[]> {
|
|
236
|
+
if (this.platform === 'win32') return this.readWindows(null);
|
|
237
|
+
const result = await this.runner.run(unixPsArgv(this.platform));
|
|
238
|
+
return parsePsOutput(result.stdout);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private async readSome(pids: number[]): Promise<PortProcess[]> {
|
|
242
|
+
if (this.platform === 'win32') return this.readWindows(pids);
|
|
243
|
+
const result = await this.runner.run(unixPsArgv(this.platform, ['-p', pids.join(',')]));
|
|
244
|
+
return parsePsOutput(result.stdout);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Windows has no `ps`. `Get-CimInstance Win32_Process` is the one source
|
|
249
|
+
* that carries the parent pid and command line together, so it is asked for
|
|
250
|
+
* the pids in question and its cost amortised by the cache.
|
|
251
|
+
*/
|
|
252
|
+
private async readWindows(pids: number[] | null): Promise<PortProcess[]> {
|
|
253
|
+
const filter = pids && pids.length > 0 ? `-Filter "${pids.map((pid) => `ProcessId=${pid}`).join(' or ')}"` : '';
|
|
254
|
+
const script =
|
|
255
|
+
`Get-CimInstance Win32_Process ${filter} | ` +
|
|
256
|
+
'Select-Object ProcessId,ParentProcessId,Name,CommandLine,CreationDate | Format-List';
|
|
257
|
+
|
|
258
|
+
try {
|
|
259
|
+
const result = await this.runner.run(['powershell', '-NoProfile', '-NonInteractive', '-Command', script]);
|
|
260
|
+
if (result.code === 0) return parseWindowsProcesses(result.stdout);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
debug.log('ports', 'PowerShell process lookup failed:', error);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Fall back to names only, and say so — an unnamed parent means lineage
|
|
266
|
+
// attribution silently stops working, which the user should know about.
|
|
267
|
+
this.noteLimitation(NO_ARGS_ON_WINDOWS);
|
|
268
|
+
try {
|
|
269
|
+
const result = await this.runner.run(['tasklist', '/FO', 'CSV', '/NH']);
|
|
270
|
+
return result.stdout
|
|
271
|
+
.split(/\r?\n/)
|
|
272
|
+
.map((line) => line.match(/^"([^"]*)","(\d+)"/))
|
|
273
|
+
.filter((match): match is RegExpMatchArray => Boolean(match))
|
|
274
|
+
.map((match) => ({
|
|
275
|
+
pid: Number.parseInt(match[2], 10),
|
|
276
|
+
parentPid: null,
|
|
277
|
+
user: null,
|
|
278
|
+
command: match[1],
|
|
279
|
+
startedAt: null,
|
|
280
|
+
cwd: null
|
|
281
|
+
}));
|
|
282
|
+
} catch (error) {
|
|
283
|
+
debug.log('ports', 'tasklist fallback failed:', error);
|
|
284
|
+
return [];
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Resolve working directories for pids that still lack one. Best-effort by
|
|
290
|
+
* design: on Unix the kernel only reveals it for our own processes, and on
|
|
291
|
+
* Windows there is no way to ask at all.
|
|
292
|
+
*/
|
|
293
|
+
private async resolveCwds(pids: number[]): Promise<void> {
|
|
294
|
+
const pending = pids.filter((pid) => !this.cwdResolved.has(pid));
|
|
295
|
+
if (pending.length === 0) return;
|
|
296
|
+
|
|
297
|
+
if (this.platform === 'win32') {
|
|
298
|
+
this.noteLimitation(NO_CWD_ON_WINDOWS);
|
|
299
|
+
for (const pid of pending) this.cwdResolved.add(pid);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const batch = pending.slice(0, LOOKUP_BATCH);
|
|
304
|
+
try {
|
|
305
|
+
const cwds =
|
|
306
|
+
this.platform === 'darwin'
|
|
307
|
+
? parseLsofCwd((await this.runner.run(['lsof', '-a', '-d', 'cwd', '-Fn', '-p', batch.join(',')])).stdout)
|
|
308
|
+
: parseProcCwd(
|
|
309
|
+
(await this.runner.run(['ls', '-l', ...batch.map((pid) => `/proc/${pid}/cwd`)])).stdout
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
for (const pid of batch) {
|
|
313
|
+
const cwd = cwds.get(pid);
|
|
314
|
+
const entry = this.entries.get(pid);
|
|
315
|
+
if (entry) entry.cwd = cwd ?? null;
|
|
316
|
+
// Mark resolved either way: a process we may not inspect will not
|
|
317
|
+
// become inspectable on the next tick, and retrying costs a probe.
|
|
318
|
+
this.cwdResolved.add(pid);
|
|
319
|
+
}
|
|
320
|
+
} catch (error) {
|
|
321
|
+
debug.log('ports', `cwd lookup failed on ${this.runner.label}:`, error);
|
|
322
|
+
for (const pid of batch) this.cwdResolved.add(pid);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Bring the table up to date for the pids a scan just produced. Returns the
|
|
328
|
+
* table itself so callers can walk parent chains beyond the pids they asked
|
|
329
|
+
* about — lineage needs ancestors that own no socket at all.
|
|
330
|
+
*/
|
|
331
|
+
async refresh(pids: number[], now: number): Promise<Map<number, PortProcess>> {
|
|
332
|
+
const dueForSweep = now - this.lastFullSweep >= FULL_SWEEP_MS;
|
|
333
|
+
|
|
334
|
+
if (dueForSweep || this.entries.size === 0) {
|
|
335
|
+
try {
|
|
336
|
+
const all = await this.readAll();
|
|
337
|
+
this.absorb(all);
|
|
338
|
+
this.lastFullSweep = now;
|
|
339
|
+
// A full sweep is the only moment the table knows which pids are
|
|
340
|
+
// gone, so prune here rather than letting dead entries accumulate.
|
|
341
|
+
// A sweep that returned nothing failed; keep what we had.
|
|
342
|
+
if (all.length > 0) this.prune(new Set(all.map((process) => process.pid)));
|
|
343
|
+
} catch (error) {
|
|
344
|
+
debug.log('ports', `process sweep failed on ${this.runner.label}:`, error);
|
|
345
|
+
}
|
|
346
|
+
} else {
|
|
347
|
+
const unknown = pids.filter((pid) => !this.entries.has(pid)).slice(0, LOOKUP_BATCH);
|
|
348
|
+
if (unknown.length > 0) {
|
|
349
|
+
try {
|
|
350
|
+
this.absorb(await this.readSome(unknown));
|
|
351
|
+
} catch (error) {
|
|
352
|
+
debug.log('ports', `process lookup failed on ${this.runner.label}:`, error);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
await this.resolveCwds(pids.filter((pid) => this.entries.has(pid)));
|
|
358
|
+
|
|
359
|
+
return this.entries;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private prune(live: Set<number>): void {
|
|
363
|
+
for (const pid of this.entries.keys()) {
|
|
364
|
+
if (!live.has(pid)) {
|
|
365
|
+
this.entries.delete(pid);
|
|
366
|
+
this.cwdResolved.delete(pid);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
get(pid: number): PortProcess | null {
|
|
372
|
+
return this.entries.get(pid) ?? null;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port manager — the listeners Clopen itself is responsible for.
|
|
3
|
+
*
|
|
4
|
+
* This is the tier where a label is a fact rather than a guess, so it is built
|
|
5
|
+
* by asking each feature what it currently holds open instead of keeping a
|
|
6
|
+
* second list that features must remember to update. A registration that
|
|
7
|
+
* drifts is worse than none: it would confidently mislabel someone else's port.
|
|
8
|
+
*
|
|
9
|
+
* A Cloudflare tunnel is deliberately not an owner. `cloudflared` dials the
|
|
10
|
+
* local service rather than binding it, so the port still belongs to whatever
|
|
11
|
+
* is listening — the tunnel only means that port is also reachable from the
|
|
12
|
+
* public internet, which is recorded separately as an exposure.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { PortOwnerFeature, PortProtocol } from '$shared/types/ports';
|
|
16
|
+
import { LOCAL_PORT_HOST } from '$shared/types/ports';
|
|
17
|
+
import { SERVER_ENV } from '../utils/env';
|
|
18
|
+
import { sshForwardManager } from '../ssh/forwards';
|
|
19
|
+
import { connectionManager } from '../db-client/connection-manager';
|
|
20
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
21
|
+
import { tunnelKit, portFromService } from '../tunnel/tunnel-config';
|
|
22
|
+
import { debug } from '$shared/utils/logger';
|
|
23
|
+
|
|
24
|
+
export interface OwnedPort {
|
|
25
|
+
protocol: PortProtocol;
|
|
26
|
+
port: number;
|
|
27
|
+
feature: PortOwnerFeature;
|
|
28
|
+
/** The record this port belongs to, so the UI can offer the right stop path. */
|
|
29
|
+
ownerId: string | null;
|
|
30
|
+
label: string;
|
|
31
|
+
detail: string | null;
|
|
32
|
+
/** Clopen's own socket must never be offered as something to kill. */
|
|
33
|
+
isClopenItself: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A port that is reachable publicly, keyed the same way as owned ports. */
|
|
37
|
+
export interface ExposedPort {
|
|
38
|
+
port: number;
|
|
39
|
+
publicUrl: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function key(protocol: PortProtocol, port: number): string {
|
|
43
|
+
return `${protocol}:${port}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Ports Clopen opened on a given host, keyed `protocol:port`.
|
|
48
|
+
*
|
|
49
|
+
* Both kinds of host are answered here so neither is a special case: on the
|
|
50
|
+
* machine Clopen runs on that means its own socket, its local forwards and its
|
|
51
|
+
* database tunnels; on an SSH host it means the ports Clopen asked that host's
|
|
52
|
+
* sshd to bind. A remote forward is Clopen's doing just as much as a local one,
|
|
53
|
+
* and the panel says so in the same words.
|
|
54
|
+
*/
|
|
55
|
+
export function collectOwnedPorts(hostId: string): Map<string, OwnedPort> {
|
|
56
|
+
return hostId === LOCAL_PORT_HOST ? collectLocalOwnedPorts() : collectRemoteOwnedPorts(hostId);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function collectRemoteOwnedPorts(connectionId: string): Map<string, OwnedPort> {
|
|
60
|
+
const owned = new Map<string, OwnedPort>();
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
for (const { forward, boundPort } of sshForwardManager.remoteListeners(connectionId)) {
|
|
64
|
+
owned.set(key('tcp', boundPort), {
|
|
65
|
+
protocol: 'tcp',
|
|
66
|
+
port: boundPort,
|
|
67
|
+
feature: 'ssh-forward',
|
|
68
|
+
ownerId: forward.id,
|
|
69
|
+
label: `SSH forward — ${forward.name}`,
|
|
70
|
+
detail: `Clopen asked this host to listen, and forwards to ${forward.destHost}:${forward.destPort}`,
|
|
71
|
+
isClopenItself: false
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
} catch (error) {
|
|
75
|
+
debug.log('ports', 'could not read remote SSH forwards:', error);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return owned;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function collectLocalOwnedPorts(): Map<string, OwnedPort> {
|
|
82
|
+
const owned = new Map<string, OwnedPort>();
|
|
83
|
+
|
|
84
|
+
owned.set(key('tcp', SERVER_ENV.PORT), {
|
|
85
|
+
protocol: 'tcp',
|
|
86
|
+
port: SERVER_ENV.PORT,
|
|
87
|
+
feature: 'server',
|
|
88
|
+
ownerId: null,
|
|
89
|
+
label: 'Clopen server',
|
|
90
|
+
detail: 'The app you are looking at right now',
|
|
91
|
+
isClopenItself: true
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// In development the UI is served by Vite on its own port, in a process
|
|
95
|
+
// Clopen does not parent. It is still Clopen as far as anyone using it is
|
|
96
|
+
// concerned — and stopping it would take away the page they are reading.
|
|
97
|
+
if (SERVER_ENV.isDevelopment) {
|
|
98
|
+
owned.set(key('tcp', SERVER_ENV.PORT_FRONTEND), {
|
|
99
|
+
protocol: 'tcp',
|
|
100
|
+
port: SERVER_ENV.PORT_FRONTEND,
|
|
101
|
+
feature: 'server',
|
|
102
|
+
ownerId: null,
|
|
103
|
+
label: 'Clopen frontend',
|
|
104
|
+
detail: 'Vite dev server for the interface you are looking at',
|
|
105
|
+
isClopenItself: true
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
for (const { forward, boundPort } of sshForwardManager.localListeners()) {
|
|
111
|
+
const host = sshConnectionQueries.get(forward.connectionId);
|
|
112
|
+
const via = host ? ` via ${host.name}` : '';
|
|
113
|
+
owned.set(key('tcp', boundPort), {
|
|
114
|
+
protocol: 'tcp',
|
|
115
|
+
port: boundPort,
|
|
116
|
+
feature: 'ssh-forward',
|
|
117
|
+
ownerId: forward.id,
|
|
118
|
+
label: `SSH forward — ${forward.name}`,
|
|
119
|
+
detail:
|
|
120
|
+
forward.type === 'dynamic'
|
|
121
|
+
? `SOCKS5 proxy${via}`
|
|
122
|
+
: `Forwards to ${forward.destHost}:${forward.destPort}${via}`,
|
|
123
|
+
isClopenItself: false
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
} catch (error) {
|
|
127
|
+
debug.log('ports', 'could not read SSH forwards:', error);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
for (const { connectionId, localPort } of connectionManager.activeTunnelPorts()) {
|
|
132
|
+
owned.set(key('tcp', localPort), {
|
|
133
|
+
protocol: 'tcp',
|
|
134
|
+
port: localPort,
|
|
135
|
+
feature: 'db-client-tunnel',
|
|
136
|
+
ownerId: connectionId,
|
|
137
|
+
label: 'DB Client SSH tunnel',
|
|
138
|
+
detail: 'Carries one database connection over SSH',
|
|
139
|
+
isClopenItself: false
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
} catch (error) {
|
|
143
|
+
debug.log('ports', 'could not read DB Client tunnels:', error);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return owned;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Local ports currently published through a Cloudflare tunnel. */
|
|
150
|
+
export function collectExposedPorts(): Map<number, string> {
|
|
151
|
+
const exposed = new Map<number, string>();
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
for (const tunnel of tunnelKit.list()) {
|
|
155
|
+
const port = portFromService(tunnel.service);
|
|
156
|
+
if (port > 0 && tunnel.publicUrl) exposed.set(port, tunnel.publicUrl);
|
|
157
|
+
}
|
|
158
|
+
} catch (error) {
|
|
159
|
+
debug.log('ports', 'could not read tunnels:', error);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return exposed;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export const ownedPortKey = key;
|