@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
@@ -76,6 +76,221 @@ const IGNORED_DESCENT_LEVELS = 1;
76
76
  /** Depth limit below the project root — a runaway walk helps nobody. */
77
77
  const MAX_DEPTH = 12;
78
78
 
79
+ /**
80
+ * Discovery caching, and who is allowed to decide it is stale.
81
+ *
82
+ * Every `git:status` / `git:branches` used to re-answer "which directories
83
+ * under this root are repos" from scratch: an `fs.readdir` over the whole tree
84
+ * plus a `git check-ignore` spawn per repo per depth level, then one
85
+ * `git status` per repo sitting inside an ignored tree. Measured on a real
86
+ * project that is 132ms and 7 spawns for the walk alone, and the panel fires it
87
+ * three or four times a second while staging. On Windows every spawn and every
88
+ * readdir also pays for Defender, which is what made Stage All look frozen.
89
+ *
90
+ * The answer barely ever changes, and the file watcher already knows exactly
91
+ * when it does. So the watcher, not a clock, is the invalidation authority:
92
+ *
93
+ * - `beginWatchedDiscovery` / `endWatchedDiscovery` — a root is "watched"
94
+ * while a live watcher is feeding it signals.
95
+ * - `invalidateRepoSet` — a `.git` appeared or vanished, or `.gitignore` /
96
+ * `.gitmodules` changed. The set of repos may be different.
97
+ * - `invalidateLocalWork` — something was written inside one repo, so only
98
+ * that repo's "does it have work to show" verdict is suspect.
99
+ *
100
+ * THE SAFETY RULE, which every change here must preserve: **the watcher only
101
+ * ever makes an answer fresher, never staler.** A TTL is always the floor, so
102
+ * losing every signal degrades to re-walking on a timer — never to an answer
103
+ * that is wrong forever. That failure mode is not hypothetical: `resolveGitDirs`
104
+ * decides which git dirs get watched at all and rejects unaccounted-for ones
105
+ * permanently, so one stale walk there took a sub-repo out of the panel for the
106
+ * whole session.
107
+ *
108
+ * The two halves have different exposure, so they are cached separately:
109
+ *
110
+ * - The WALK (which dirs hold a `.git`) is stable, and the signal for it —
111
+ * a `.git` entry appearing — is one the watcher sees reliably on every
112
+ * platform, because the repo's parent directory is watched. Long floor.
113
+ * - LOCAL WORK (whether a repo inside an ignored tree has anything to show)
114
+ * changes with ordinary file writes, and the watcher is blind inside the
115
+ * directories it prunes by name. Cached ONLY for watched roots, where a
116
+ * write lands as an invalidation; an unwatched caller (the snapshot
117
+ * scanner, a CLI path) still probes live, exactly as before. Hiding a
118
+ * sub-repo the user edits is the worst failure this module can produce, so
119
+ * it does not get cached on a guess.
120
+ *
121
+ * What is never cached, at any point: file status. Staged, unstaged, untracked
122
+ * and conflicted entries come from a live `git status` per repo on every call.
123
+ * The Changes tab cannot go stale through this module.
124
+ */
125
+
126
+ /** Floor for a root nobody is invalidating — the clock is the only signal. */
127
+ const UNWATCHED_TTL_MS = process.platform === 'win32' ? 5000 : 3000;
128
+
129
+ /**
130
+ * Floor for a watched root. Long, because the watcher normally invalidates
131
+ * within milliseconds; this only bounds the damage if a signal is ever missed
132
+ * (a platform that drops an event, a watcher that faulted and is restarting).
133
+ */
134
+ const WATCHED_TTL_MS = 60_000;
135
+
136
+ interface WalkEntryCache {
137
+ found: string[];
138
+ provisional: string[];
139
+ expiresAt: number;
140
+ }
141
+
142
+ /** Whether a sub-repo has anything the panel could show. Watched roots only. */
143
+ interface LocalWorkCache {
144
+ hasWork: boolean;
145
+ expiresAt: number;
146
+ }
147
+
148
+ const nestedRepoWalkCache = new Map<string, WalkEntryCache>();
149
+ const nestedRepoInflight = new Map<string, Promise<string[]>>();
150
+ const localWorkCache = new Map<string, LocalWorkCache>();
151
+
152
+ /**
153
+ * Project roots a live file watcher is feeding signals for, and how many
154
+ * watchers are doing so. Refcounted because two projects can be opened at the
155
+ * same directory: without it the first one to close would revoke the claim
156
+ * while the second is still reporting, and discovery would quietly go back to
157
+ * the clock while a perfectly good signal source was still running.
158
+ */
159
+ const watchedRoots = new Map<string, number>();
160
+
161
+ /**
162
+ * The key every cache and the watched-root set is stored under. Callers reach
163
+ * this module from both sides of a `path.normalize()` — the watcher normalises
164
+ * the project path before registering, `git:status` passes `project.path`
165
+ * straight through — and on Windows those differ by separator alone. Keying on
166
+ * the raw string would put them in two entries: the watcher would invalidate
167
+ * one while the panel read the other, silently turning the signal off.
168
+ * Values keep their native separators; only keys are folded.
169
+ */
170
+ function cacheKey(inputPath: string): string {
171
+ return inputPath.replace(/\\/g, '/').replace(/\/+$/, '');
172
+ }
173
+
174
+ /** Whether `candidate` is `base` or sits underneath it. */
175
+ function isUnder(base: string, candidate: string): boolean {
176
+ const baseKey = cacheKey(base);
177
+ const candidateKey = cacheKey(candidate);
178
+ return candidateKey === baseKey || candidateKey.startsWith(baseKey + '/');
179
+ }
180
+
181
+ function isWatched(rootPath: string): boolean {
182
+ return (watchedRoots.get(cacheKey(rootPath)) ?? 0) > 0;
183
+ }
184
+
185
+ function ttlFor(rootPath: string): number {
186
+ return isWatched(rootPath) ? WATCHED_TTL_MS : UNWATCHED_TTL_MS;
187
+ }
188
+
189
+ /**
190
+ * Declare that a live file watcher will report changes for `rootPath`. Until
191
+ * `endWatchedDiscovery`, discovery may lean on those signals instead of the
192
+ * short clock — and `hasLocalWork` verdicts become cacheable at all.
193
+ */
194
+ export function beginWatchedDiscovery(rootPath: string): void {
195
+ const key = cacheKey(rootPath);
196
+ watchedRoots.set(key, (watchedRoots.get(key) ?? 0) + 1);
197
+ }
198
+
199
+ /**
200
+ * The watcher for `rootPath` is gone. Drop everything that was only safe
201
+ * because it was being invalidated, so the next call re-probes live.
202
+ */
203
+ export function endWatchedDiscovery(rootPath: string): void {
204
+ const key = cacheKey(rootPath);
205
+ const remaining = (watchedRoots.get(key) ?? 0) - 1;
206
+ if (remaining > 0) {
207
+ watchedRoots.set(key, remaining);
208
+ return;
209
+ }
210
+ watchedRoots.delete(key);
211
+ nestedRepoWalkCache.delete(key);
212
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
213
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * The set of repos under `rootPath` may have changed — a `.git` appeared or
219
+ * vanished, or the rules that decide what counts (`.gitignore`, `.gitmodules`)
220
+ * were edited. Forces a fresh walk on the next call.
221
+ */
222
+ export function invalidateRepoSet(rootPath: string): void {
223
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
224
+ }
225
+
226
+ /**
227
+ * Whether a changed path is one that can change WHICH repos are reported, as
228
+ * opposed to what is inside one.
229
+ *
230
+ * These live here rather than in the watcher on purpose. They are facts about
231
+ * the sub-repo policy at the top of this file, not about filesystem events, so
232
+ * extending that policy has to mean editing one place. Splitting them across
233
+ * the two files is what let discovery and its invalidation drift apart in the
234
+ * first place.
235
+ */
236
+ function isRepoSetRule(changedPath: string): boolean {
237
+ const segments = cacheKey(changedPath).split('/');
238
+ const basename = segments[segments.length - 1];
239
+
240
+ // The repository itself appearing or vanishing.
241
+ if (basename === '.git') return true;
242
+
243
+ // Rule (2) and rule (3): what the project ignores, and what it declares.
244
+ if (basename === '.gitignore' || basename === '.gitmodules') return true;
245
+
246
+ // `.git/info/exclude` is a per-repo ignore file `git check-ignore` obeys
247
+ // exactly like `.gitignore`, so it moves the same boundary. The watcher
248
+ // filters it out of the panel's git-state events — correctly, the panel has
249
+ // nothing to show for it — which is precisely why discovery has to ask for
250
+ // it by name instead of riding along with those.
251
+ return (
252
+ basename === 'exclude' &&
253
+ segments[segments.length - 2] === 'info' &&
254
+ segments[segments.length - 3] === '.git'
255
+ );
256
+ }
257
+
258
+ /**
259
+ * A path under `rootPath` changed. The single entry point the file watcher
260
+ * uses: it forwards raw paths and this module decides what each one means, so
261
+ * no caller has to carry a copy of the sub-repo policy.
262
+ *
263
+ * Ignored entirely for a root nobody claimed — an unwatched root caches
264
+ * nothing that a signal could correct, and answering it here would only hide
265
+ * that fact.
266
+ */
267
+ export function notifyPathChanged(rootPath: string, changedPath: string): void {
268
+ if (!isWatched(rootPath)) return;
269
+ if (isRepoSetRule(changedPath)) invalidateRepoSet(rootPath);
270
+ dropLocalWorkUnder(changedPath);
271
+ }
272
+
273
+ /**
274
+ * Something at or under `changedPath` moved, so the "has work to show" verdict
275
+ * of every cached repo containing it is suspect.
276
+ *
277
+ * Matching by containment rather than taking a repo path directly is what makes
278
+ * the important case work. A pristine sub-repo inside an ignored tree is NOT in
279
+ * the watcher's repo list — it is deliberately unreported until it has
280
+ * something to show, so the watcher has never resolved a git dir for it. The
281
+ * transition that must be caught is exactly the first write into it, and at
282
+ * that moment the only place it is known by name is this cache, holding the
283
+ * `false` verdict that is about to become wrong.
284
+ *
285
+ * Still scoped: a write in one sub-repo says nothing about its siblings, and
286
+ * re-probing all of them is the cost this cache exists to avoid.
287
+ */
288
+ function dropLocalWorkUnder(changedPath: string): void {
289
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
290
+ if (isUnder(cachedRepoKey, changedPath)) localWorkCache.delete(cachedRepoKey);
291
+ }
292
+ }
293
+
79
294
  /**
80
295
  * Upper bound on reported sub-repos. A project with more than this is either
81
296
  * pathological or hit a detection hole; either way the UI cannot usefully show
@@ -141,7 +356,7 @@ async function filterIgnored(repoRoot: string, relPaths: string[]): Promise<Set<
141
356
  * A repo we cannot read is reported as having work: hiding a sub-repo the user
142
357
  * edits is a far worse failure than showing one they do not care about.
143
358
  */
144
- async function hasLocalWork(repoPath: string): Promise<boolean> {
359
+ async function probeLocalWork(repoPath: string): Promise<boolean> {
145
360
  try {
146
361
  const result = await execGit(['status', '--porcelain', '-z'], repoPath, { timeout: 15000 });
147
362
  if (result.exitCode !== 0) return true;
@@ -151,6 +366,29 @@ async function hasLocalWork(repoPath: string): Promise<boolean> {
151
366
  }
152
367
  }
153
368
 
369
+ /**
370
+ * `probeLocalWork` with the verdict remembered — but only under a root the
371
+ * watcher is invalidating, where a write inside the repo lands as an
372
+ * `invalidateLocalWork` before anyone can read a stale answer. Unwatched roots
373
+ * probe live every time: this is the verdict that decides whether a sub-repo is
374
+ * shown at all, and a cached "nothing to show" with no signal behind it would
375
+ * hide a repo the user is working in.
376
+ */
377
+ async function hasLocalWork(rootPath: string, repoPath: string): Promise<boolean> {
378
+ if (!isWatched(rootPath)) return probeLocalWork(repoPath);
379
+
380
+ const cached = localWorkCache.get(cacheKey(repoPath));
381
+ if (cached && Date.now() < cached.expiresAt) return cached.hasWork;
382
+
383
+ const hasWork = await probeLocalWork(repoPath);
384
+ // Re-read the flag: the watcher may have stopped while the probe ran, and a
385
+ // verdict nobody will invalidate must not be left behind.
386
+ if (isWatched(rootPath)) {
387
+ localWorkCache.set(cacheKey(repoPath), { hasWork, expiresAt: Date.now() + WATCHED_TTL_MS });
388
+ }
389
+ return hasWork;
390
+ }
391
+
154
392
  /** Whether `dirPath` is a git repo (`.git` is a dir for clones, a file for worktrees/submodules). */
155
393
  async function isRepoDir(dirPath: string): Promise<boolean> {
156
394
  try {
@@ -165,8 +403,76 @@ async function isRepoDir(dirPath: string): Promise<boolean> {
165
403
  * Find every nested git repo under `rootPath`, skipping dependency caches and
166
404
  * ignored trees (see the module comment for the exact policy). Does NOT scan
167
405
  * the repos — just returns their absolute paths, sorted for stable UI order.
406
+ *
407
+ * The filesystem walk is cached for a few seconds (longer on Windows) and
408
+ * concurrent callers for the same root share a single walk via inflight
409
+ * deduplication. The provisional → found filtering is re-run on every call
410
+ * so a newly-dirtied repo appears immediately.
168
411
  */
169
412
  export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
413
+ const cachedWalk = nestedRepoWalkCache.get(cacheKey(rootPath));
414
+ if (cachedWalk && Date.now() < cachedWalk.expiresAt) {
415
+ return resolveProvisional(rootPath, cachedWalk.found, cachedWalk.provisional);
416
+ }
417
+
418
+ // A caller that arrives while a walk is running shares it instead of
419
+ // starting a second one, but gets its own copy of the result: the array
420
+ // goes out to unrelated call sites, and one of them mutating it in place
421
+ // would corrupt the others.
422
+ const inflight = nestedRepoInflight.get(cacheKey(rootPath));
423
+ if (inflight) return [...(await inflight)];
424
+
425
+ const promise = (async (): Promise<string[]> => {
426
+ const walk = await walkNestedRepos(rootPath);
427
+ nestedRepoWalkCache.set(cacheKey(rootPath), {
428
+ found: walk.found,
429
+ provisional: walk.provisional,
430
+ expiresAt: Date.now() + ttlFor(rootPath)
431
+ });
432
+ return resolveProvisional(rootPath, walk.found, walk.provisional);
433
+ })();
434
+
435
+ nestedRepoInflight.set(cacheKey(rootPath), promise);
436
+ try {
437
+ return await promise;
438
+ } finally {
439
+ nestedRepoInflight.delete(cacheKey(rootPath));
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Decide which provisional repos (those found inside an ignored tree) earn a
445
+ * place in the result, and return the sorted list. Deliberately outside the
446
+ * WALK cache: a repo qualifies the moment it gains local work, so a cached walk
447
+ * must never carry a cached verdict with it. The verdicts have their own,
448
+ * signal-backed cache — see `hasLocalWork`.
449
+ */
450
+ async function resolveProvisional(rootPath: string, found: string[], provisional: string[]): Promise<string[]> {
451
+ if (provisional.length === 0) {
452
+ const out = [...found];
453
+ out.sort();
454
+ return out;
455
+ }
456
+ const submodulePaths = await findSubmodulePaths(rootPath);
457
+ const isDeclared = (repoPath: string) =>
458
+ submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
459
+ const verdicts = await Promise.all(
460
+ provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(rootPath, repoPath)))
461
+ );
462
+ const out = [...found];
463
+ provisional.forEach((repoPath, i) => {
464
+ if (verdicts[i]) out.push(repoPath);
465
+ });
466
+ out.sort();
467
+ return out;
468
+ }
469
+
470
+ /**
471
+ * The raw, uncached filesystem walk. Returns repos split into those reportable
472
+ * on structure alone and those still needing to prove local work — the split
473
+ * `findNestedRepoPaths` caches, because only the first half is stable.
474
+ */
475
+ async function walkNestedRepos(rootPath: string): Promise<{ found: string[]; provisional: string[] }> {
170
476
  const found: string[] = [];
171
477
  /** Repos found inside an ignored tree — reported only if they prove local work. */
172
478
  const provisional: string[] = [];
@@ -278,22 +584,7 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
278
584
  debug.warn('git', `Nested repo scan of ${rootPath} stopped at ${MAX_REPOS} repos`);
279
585
  }
280
586
 
281
- if (provisional.length > 0) {
282
- // A submodule is the user declaring the sub-repo themselves, which
283
- // outranks anything we could infer from its working tree.
284
- const submodulePaths = await findSubmodulePaths(rootPath);
285
- const isDeclared = (repoPath: string) =>
286
- submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
287
- const verdicts = await Promise.all(
288
- provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(repoPath)))
289
- );
290
- provisional.forEach((repoPath, i) => {
291
- if (verdicts[i]) found.push(repoPath);
292
- });
293
- }
294
-
295
- found.sort();
296
- return found;
587
+ return { found, provisional };
297
588
  }
298
589
 
299
590
  /**
@@ -347,6 +638,28 @@ export async function findSubmodulePaths(rootPath: string): Promise<Set<string>>
347
638
  return out;
348
639
  }
349
640
 
641
+ /**
642
+ * Drop every cached answer so the next call re-scans and re-probes. Exists for
643
+ * tests, which mutate a project's layout far faster than any TTL and would
644
+ * otherwise assert against the previous fixture. Production code should reach
645
+ * for the targeted `invalidateRepoSet` / `invalidateLocalWork` instead, so one
646
+ * repo's churn does not throw away every other repo's answer.
647
+ */
648
+ export function clearNestedRepoCache(rootPath?: string): void {
649
+ if (rootPath) {
650
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
651
+ nestedRepoInflight.delete(cacheKey(rootPath));
652
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
653
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
654
+ }
655
+ } else {
656
+ nestedRepoWalkCache.clear();
657
+ nestedRepoInflight.clear();
658
+ localWorkCache.clear();
659
+ watchedRoots.clear();
660
+ }
661
+ }
662
+
350
663
  /**
351
664
  * Given a file path relative to the project root, find the deepest nested
352
665
  * git repo that contains it. Returns the repo's absolute path and the file
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Host commands — one command interface, two transports.
3
+ *
4
+ * Every host-scoped feature in Clopen — the port table, and the container list
5
+ * that followed it — is built out of small POSIX/Windows commands, and the same
6
+ * command has to run on the machine hosting Clopen and on a saved SSH host. So
7
+ * they are written once against `CommandRunner` and the transport is swapped
8
+ * underneath: `Bun.spawn` locally, an exec channel remotely.
9
+ *
10
+ * Commands are argv arrays rather than shell strings. Locally that removes
11
+ * quoting from the picture entirely; remotely each argument is quoted by
12
+ * `shellQuote` on the way out, so a hostile process or container name in an
13
+ * argument can never turn into a second command.
14
+ *
15
+ * This lives outside `ports/` because `local` is not a special case and neither
16
+ * is any one feature: whatever asks a host a question asks it through here.
17
+ */
18
+
19
+ import type { Client as SshClient } from 'ssh2';
20
+ import { runCommandDetailed, shellQuote } from '../ssh/connect';
21
+ import { sshClientPool } from '../ssh/client-pool';
22
+ import { debug } from '$shared/utils/logger';
23
+
24
+ /**
25
+ * The directories a probe might live in, prepended for every POSIX command.
26
+ *
27
+ * A non-interactive SSH exec channel gets whatever PATH the account's shell
28
+ * sets up, and on shared hosting that routinely omits `/usr/sbin` and `/sbin`
29
+ * — which is exactly where `ss`, `netstat` and `lsof` are installed. Without
30
+ * this, a host with every tool present still reports having none.
31
+ */
32
+ const PROBE_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/homebrew/bin';
33
+
34
+ /**
35
+ * Wrap a POSIX command so it runs with a predictable PATH and locale.
36
+ *
37
+ * Going through `env` rather than a shell keeps the no-shell rule intact —
38
+ * arguments stay arguments — while fixing both problems a bare command has on
39
+ * a remote host: a PATH too narrow to find the tool, and a locale that renders
40
+ * dates in words nothing can parse.
41
+ *
42
+ * `locale: null` drops the `LC_ALL=C` half. A probe wants a machine-readable
43
+ * locale; an interactive shell opened through the same PATH fix does not —
44
+ * forcing C on one would leave the user unable to type a non-ASCII character.
45
+ */
46
+ export function posixArgv(argv: string[], options: { locale?: string | null } = {}): string[] {
47
+ const locale = options.locale === undefined ? 'C' : options.locale;
48
+ return ['env', ...(locale === null ? [] : [`LC_ALL=${locale}`]), `PATH=${PROBE_PATH}`, ...argv];
49
+ }
50
+
51
+ export interface RunResult {
52
+ stdout: string;
53
+ stderr: string;
54
+ code: number;
55
+ }
56
+
57
+ /** Platforms the probes know how to interrogate. */
58
+ export type ProbePlatform = 'darwin' | 'linux' | 'win32' | 'unknown';
59
+
60
+ export interface CommandRunner {
61
+ /** Human label for logs and errors ("this machine", the host name). */
62
+ readonly label: string;
63
+ run(argv: string[], timeoutMs?: number): Promise<RunResult>;
64
+ }
65
+
66
+ const DEFAULT_TIMEOUT_MS = 15_000;
67
+
68
+ /** Runs probes on the machine Clopen itself is running on. */
69
+ export class LocalCommandRunner implements CommandRunner {
70
+ readonly label = 'this machine';
71
+
72
+ async run(argv: string[], timeoutMs = DEFAULT_TIMEOUT_MS): Promise<RunResult> {
73
+ const child = Bun.spawn(argv, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
74
+ // A probe that hangs must not wedge the poll loop; kill it and report
75
+ // the timeout as a failed command so the caller can fall back.
76
+ const timer = setTimeout(() => {
77
+ try {
78
+ child.kill();
79
+ } catch {
80
+ // Already gone — nothing to do.
81
+ }
82
+ }, timeoutMs);
83
+ try {
84
+ const [stdout, stderr, code] = await Promise.all([
85
+ new Response(child.stdout).text(),
86
+ new Response(child.stderr).text(),
87
+ child.exited
88
+ ]);
89
+ return { stdout, stderr, code };
90
+ } finally {
91
+ clearTimeout(timer);
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Runs probes on a saved SSH host over the shared pooled transport, so the
98
+ * scan reuses whatever connection the terminal and file browser already hold
99
+ * open instead of dialing its own.
100
+ */
101
+ export class SshCommandRunner implements CommandRunner {
102
+ /**
103
+ * Commands run one at a time on a connection.
104
+ *
105
+ * Every `exec` opens an SSH channel, and sshd caps how many a connection may
106
+ * hold at once — `MaxSessions`, ten by default. A scan issues several
107
+ * commands, and the terminal, SFTP browser and forwards share the same
108
+ * transport, so letting them overlap exhausts that budget and the server
109
+ * answers `Unable to exec` before dropping the connection outright. Queueing
110
+ * costs a little latency and removes the ceiling entirely.
111
+ */
112
+ private queue: Promise<unknown> = Promise.resolve();
113
+
114
+ constructor(
115
+ readonly label: string,
116
+ private readonly client: SshClient
117
+ ) {}
118
+
119
+ async run(argv: string[], timeoutMs = DEFAULT_TIMEOUT_MS): Promise<RunResult> {
120
+ const command = argv.map(shellQuote).join(' ');
121
+ // Chained on the tail whether or not the previous command succeeded, so
122
+ // one failure cannot wedge every command behind it.
123
+ const result = this.queue.then(
124
+ () => runCommandDetailed(this.client, command, timeoutMs),
125
+ () => runCommandDetailed(this.client, command, timeoutMs)
126
+ );
127
+ this.queue = result.catch(() => undefined);
128
+
129
+ const { stdout, stderr, code } = await result;
130
+ return { stdout, stderr, code };
131
+ }
132
+ }
133
+
134
+ /** Borrow a pooled SSH transport for the duration of `fn`. */
135
+ export async function withSshRunner<T>(
136
+ connectionId: string,
137
+ label: string,
138
+ fn: (runner: CommandRunner) => Promise<T>
139
+ ): Promise<T> {
140
+ const lease = await sshClientPool.acquire(connectionId);
141
+ try {
142
+ return await fn(new SshCommandRunner(label, lease.client));
143
+ } finally {
144
+ lease.release();
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Which OS a runner is talking to. Local is known outright; a remote host is
150
+ * asked once and remembered, because `uname` per scan tick is a round-trip
151
+ * spent on an answer that cannot change while the connection lives.
152
+ */
153
+ const remotePlatforms = new Map<string, ProbePlatform>();
154
+
155
+ export function localPlatform(): ProbePlatform {
156
+ switch (process.platform) {
157
+ case 'darwin':
158
+ return 'darwin';
159
+ case 'linux':
160
+ return 'linux';
161
+ case 'win32':
162
+ return 'win32';
163
+ default:
164
+ // The BSDs answer the Linux probes closely enough to be worth trying.
165
+ return process.platform === 'freebsd' || process.platform === 'openbsd' ? 'linux' : 'unknown';
166
+ }
167
+ }
168
+
169
+ export async function detectRemotePlatform(cacheKey: string, runner: CommandRunner): Promise<ProbePlatform> {
170
+ const cached = remotePlatforms.get(cacheKey);
171
+ if (cached) return cached;
172
+
173
+ let platform: ProbePlatform = 'unknown';
174
+ try {
175
+ const result = await runner.run(['uname', '-s'], 5_000);
176
+ const name = result.stdout.trim().toLowerCase();
177
+ if (result.code === 0 && name) {
178
+ if (name.includes('darwin')) platform = 'darwin';
179
+ else if (name.includes('linux')) platform = 'linux';
180
+ else if (name.includes('bsd')) platform = 'linux';
181
+ }
182
+ } catch (error) {
183
+ debug.log('host', `uname failed on ${runner.label}:`, error);
184
+ }
185
+
186
+ // No `uname` usually means a Windows host answering over OpenSSH, where the
187
+ // shell is cmd and `ver` is the equivalent question.
188
+ if (platform === 'unknown') {
189
+ try {
190
+ const result = await runner.run(['cmd', '/c', 'ver'], 5_000);
191
+ if (result.code === 0 && /windows/i.test(result.stdout)) platform = 'win32';
192
+ } catch {
193
+ // Leave it unknown — the caller reports that honestly.
194
+ }
195
+ }
196
+
197
+ remotePlatforms.set(cacheKey, platform);
198
+ return platform;
199
+ }
200
+
201
+ /** Drop a host's cached platform when its connection goes away. */
202
+ export function forgetRemotePlatform(cacheKey: string): void {
203
+ remotePlatforms.delete(cacheKey);
204
+ }
package/backend/index.ts CHANGED
@@ -20,6 +20,7 @@ import { Elysia } from 'elysia';
20
20
  import { corsMiddleware } from './middleware/cors';
21
21
  import { errorHandlerMiddleware } from './middleware/error-handler';
22
22
  import { loggerMiddleware } from './middleware/logger';
23
+ import { securityMiddleware } from './middleware/security';
23
24
 
24
25
  // Database initialization
25
26
  import { initializeDatabase, closeDatabase } from './database';
@@ -63,6 +64,9 @@ import { getAuthMode } from './settings/system-settings';
63
64
  import { authQueries } from './database/queries';
64
65
  import { authRateLimiter } from './auth';
65
66
  import { sessionCleanupScheduler } from './auth/session-cleanup';
67
+ import { portMonitor } from './ports/monitor';
68
+ import { containerMonitor } from './containers/monitor';
69
+ import { stopAllLogStreams as stopAllContainerLogStreams } from './containers/logs';
66
70
  import { uploadTempCleanup } from './http/upload-temp-cleanup';
67
71
  import { ws as wsServer } from './utils/ws';
68
72
  import { messageRateLimiter } from './ws/message-rate-limiter';
@@ -100,8 +104,8 @@ wsRouter.setAuthMiddleware(async (conn, action) => {
100
104
  });
101
105
 
102
106
  // Register message rate limiter on WebSocket router — prevents DoS via message spam
103
- wsRouter.setRateLimiter((conn, action) => {
104
- return messageRateLimiter.checkRateLimit(conn, action);
107
+ wsRouter.setRateLimiter((conn, action, isRequest) => {
108
+ return messageRateLimiter.checkRateLimit(conn, action, isRequest);
105
109
  });
106
110
 
107
111
  /**
@@ -129,6 +133,7 @@ const HOST = SERVER_ENV.HOST;
129
133
  const app = new Elysia()
130
134
  // Apply middleware
131
135
  .use(corsMiddleware)
136
+ .use(securityMiddleware)
132
137
  .use(errorHandlerMiddleware)
133
138
  .use(loggerMiddleware)
134
139
 
@@ -267,6 +272,14 @@ async function startServer() {
267
272
  // which also runs on the live process during "Clear All Data".
268
273
  startEngineHotReload();
269
274
  startEngineConfigWatcher();
275
+ // Sidebar count for the port manager. Idle-cheap by construction: with no
276
+ // terminal sessions running there are no session-born ports to count, so
277
+ // the tick skips the scan entirely.
278
+ portMonitor.start();
279
+ // Sidebar count for the container manager: containers running on this
280
+ // machine. Idle-cheap too — a machine with no runtime is remembered as
281
+ // having none, so the tick costs a cached lookup and no command at all.
282
+ containerMonitor.start();
270
283
  } catch (error) {
271
284
  console.error('❌ Database initialization failed — refusing to start:', error);
272
285
  console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
@@ -330,6 +343,11 @@ async function gracefulShutdown() {
330
343
  sessionCleanupScheduler.dispose();
331
344
  // Dispose upload temp cleanup timer
332
345
  uploadTempCleanup.dispose();
346
+ // Stop port polling and release any SSH leases it holds
347
+ portMonitor.stop();
348
+ // Same for the container list, and the log streams it may still be pumping
349
+ stopAllContainerLogStreams();
350
+ containerMonitor.stop();
333
351
  // Close MCP remote server (before engines, as they may still reference it)
334
352
  await closeMcpServer();
335
353
  // Cleanup browser preview sessions