@myrialabs/clopen 0.4.33 → 0.4.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/backend/auth/permissions.ts +10 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/db-client/connection-manager.ts +13 -0
  20. package/backend/files/file-watcher.test.ts +105 -0
  21. package/backend/files/file-watcher.ts +45 -1
  22. package/backend/git/git-service.test.ts +33 -0
  23. package/backend/git/git-service.ts +7 -3
  24. package/backend/git/nested-repos.test.ts +292 -1
  25. package/backend/git/nested-repos.ts +330 -17
  26. package/backend/host/runner.ts +204 -0
  27. package/backend/index.ts +20 -2
  28. package/backend/middleware/security.test.ts +95 -0
  29. package/backend/middleware/security.ts +114 -0
  30. package/backend/ports/attribute.test.ts +231 -0
  31. package/backend/ports/attribute.ts +444 -0
  32. package/backend/ports/kill.ts +203 -0
  33. package/backend/ports/monitor.ts +365 -0
  34. package/backend/ports/processes.test.ts +98 -0
  35. package/backend/ports/processes.ts +374 -0
  36. package/backend/ports/registry.ts +165 -0
  37. package/backend/ports/scan-host.ts +329 -0
  38. package/backend/ports/scan.test.ts +341 -0
  39. package/backend/ports/scan.ts +687 -0
  40. package/backend/ports/ssh-lineage.ts +318 -0
  41. package/backend/preview/browser/browser-video-capture.ts +84 -31
  42. package/backend/ssh/forwards.ts +31 -0
  43. package/backend/ws/auth/device.ts +1 -1
  44. package/backend/ws/auth/login.ts +8 -4
  45. package/backend/ws/containers/actions.ts +156 -0
  46. package/backend/ws/containers/index.ts +43 -0
  47. package/backend/ws/containers/list.ts +146 -0
  48. package/backend/ws/containers/logs.ts +43 -0
  49. package/backend/ws/containers/tunnel.ts +101 -0
  50. package/backend/ws/git/log.ts +3 -1
  51. package/backend/ws/git/status.ts +37 -27
  52. package/backend/ws/index.ts +4 -0
  53. package/backend/ws/message-rate-limiter.test.ts +45 -0
  54. package/backend/ws/message-rate-limiter.ts +34 -3
  55. package/backend/ws/ports/index.ts +19 -0
  56. package/backend/ws/ports/kill.ts +80 -0
  57. package/backend/ws/ports/list.ts +60 -0
  58. package/backend/ws/ssh/connections.ts +8 -0
  59. package/backend/ws/system/device-info.ts +99 -43
  60. package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
  61. package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
  62. package/dist/assets/main-Buko4D0t.css +1 -0
  63. package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
  64. package/dist/index.html +2 -2
  65. package/dist/manifest.json +9 -2
  66. package/package.json +1 -1
  67. package/shared/types/containers/container.ts +366 -0
  68. package/shared/types/containers/index.ts +5 -0
  69. package/shared/types/host/index.ts +18 -0
  70. package/shared/types/ports/index.ts +5 -0
  71. package/shared/types/ports/port.ts +230 -0
  72. package/shared/utils/logger.ts +3 -0
  73. package/shared/utils/ws-client.ts +67 -12
  74. package/shared/utils/ws-server.ts +64 -13
  75. package/dist/assets/main-CCvRMXlP.css +0 -1
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Port manager — recognising Clopen's own work on an SSH host.
3
+ *
4
+ * On the machine Clopen runs on, a port is traced to Clopen by walking parent
5
+ * pids up to a Clopen process. A remote host needs the same fact established
6
+ * from the other end: PtyKit addresses remote shells through an internal id,
7
+ * and ssh2 never learns what the far side numbered anything.
8
+ *
9
+ * The answer is in the environment, not the process tree. sshd sets
10
+ * `SSH_CONNECTION` for every session it opens, holding the client address and
11
+ * source port of the TCP connection behind it. Every channel Clopen opens —
12
+ * shells, SFTP, forwards, the probes in this file — rides one connection, so
13
+ * they all carry the same value, and every process started from any of them
14
+ * inherits it. Reading it back off a listening process therefore says whether
15
+ * Clopen started it, with no privileges and no guesswork.
16
+ *
17
+ * Two earlier attempts are worth not repeating:
18
+ *
19
+ * - Matching `SSH_CONNECTION` against the host's *socket table* to find the
20
+ * sshd holding the connection. That socket belongs to root's sshd, so an
21
+ * unprivileged account never sees its pid.
22
+ * - Walking up from a probe's `$PPID` to the outermost process calling itself
23
+ * `sshd:`. That depends on how a host labels its sshd processes and on where
24
+ * the daemon sits in the tree, and it found nothing on a real cPanel host.
25
+ *
26
+ * Both tried to identify a process Clopen has no right to see. Asking what
27
+ * connection a process belongs to sidesteps that entirely.
28
+ *
29
+ * macOS is the exception, and only because it cannot answer the question:
30
+ * `ps -E` returns no environment there at all under SIP, verified rather than
31
+ * assumed. A macOS host therefore falls back to the process-tree walk, which
32
+ * is sound there — its sshd labels sessions the same way. This mirrors how the
33
+ * port probes already differ per platform: one question, asked the way each
34
+ * operating system will answer it.
35
+ */
36
+
37
+ import type { PortProcess } from '$shared/types/ports';
38
+ import { posixArgv, type CommandRunner, type ProbePlatform } from '../host/runner';
39
+ import { parsePsOutput } from './processes';
40
+ import { debug } from '$shared/utils/logger';
41
+
42
+ /** `SSH_CONNECTION` is `<client ip> <client port> <server ip> <server port>`. */
43
+ export function parseSshConnection(value: string): { address: string; port: number } | null {
44
+ const parts = value.trim().split(/\s+/);
45
+ if (parts.length < 2) return null;
46
+ const port = Number.parseInt(parts[1], 10);
47
+ if (!Number.isFinite(port) || port <= 0) return null;
48
+ return { address: parts[0], port };
49
+ }
50
+
51
+ /**
52
+ * Two `SSH_CONNECTION` values describing the same connection.
53
+ *
54
+ * The source port carries the match: it is unique per connection for as long
55
+ * as that connection is open. The address is compared only as a guard against
56
+ * a port number colliding across interfaces.
57
+ */
58
+ export function sameConnection(a: string, b: string): boolean {
59
+ const left = parseSshConnection(a);
60
+ const right = parseSshConnection(b);
61
+ if (!left || !right) return false;
62
+ return left.port === right.port && left.address === right.address;
63
+ }
64
+
65
+ /** Pids are interpolated into a shell script, so they must be exactly numbers. */
66
+ function safePids(pids: number[]): number[] {
67
+ return pids.filter((pid) => Number.isInteger(pid) && pid > 0 && pid < 4_294_967_296);
68
+ }
69
+
70
+ /**
71
+ * Read `SSH_CONNECTION` out of each process's environment.
72
+ *
73
+ * On Linux that is `/proc/<pid>/environ`, a NUL-separated blob readable for
74
+ * one's own processes — which is exactly the set that could have come from
75
+ * Clopen. macOS exposes the same thing through `ps -E`. Neither needs any
76
+ * privilege beyond owning the process.
77
+ */
78
+ function environProbeArgv(pids: number[]): string[] | null {
79
+ if (pids.length === 0) return null;
80
+ const list = pids.join(' ');
81
+
82
+ // A fixed script; only vetted integers are interpolated into it.
83
+ return posixArgv([
84
+ 'sh',
85
+ '-c',
86
+ // `cat` rather than a `<` redirect: a redirect that fails is reported by
87
+ // the shell itself, before `2>/dev/null` on that command can apply.
88
+ `for p in ${list}; do printf '@%s ' "$p"; cat /proc/$p/environ 2>/dev/null | ` +
89
+ `tr '\\0' '\\n' | grep '^SSH_CONNECTION=' || printf '\\n'; done`
90
+ ]);
91
+ }
92
+
93
+ /** `@42802 SSH_CONNECTION=1.2.3.4 55 5.6.7.8 22` → pid and value. */
94
+ export function parseEnvironProbe(stdout: string): Map<number, string> {
95
+ const found = new Map<number, string>();
96
+
97
+ for (const line of stdout.split('\n')) {
98
+ const marked = line.match(/^@(\d+)\s*(.*)$/);
99
+ if (!marked) continue;
100
+ const pid = Number.parseInt(marked[1], 10);
101
+ const value = marked[2].replace(/^.*?SSH_CONNECTION=/, '');
102
+ if (Number.isFinite(pid) && value && marked[2].includes('SSH_CONNECTION=')) {
103
+ found.set(pid, value.trim());
104
+ }
105
+ }
106
+
107
+ return found;
108
+ }
109
+
110
+ /**
111
+ * A per-connection sshd, which announces itself as `sshd: user@ttys000`,
112
+ * `sshd: user@pts/0` or `sshd: user [priv]`. The listening daemon
113
+ * (`/usr/sbin/sshd -D`) deliberately does not match: it parents every session
114
+ * on the host, so treating it as the root would hand Clopen credit for every
115
+ * other user's processes.
116
+ */
117
+ function isSessionSshd(process: PortProcess | null): boolean {
118
+ return process ? /(^|\s)sshd:\s/.test(process.command) : false;
119
+ }
120
+
121
+ /**
122
+ * From the sshd serving one channel, the sshd serving the whole connection.
123
+ *
124
+ * sshd forks a child per channel, so the chain from a command runs shell →
125
+ * channel sshd → connection sshd → listening daemon. The outermost link still
126
+ * calling itself `sshd:` is the one every channel shares, which makes it the
127
+ * root of everything Clopen does on that host.
128
+ */
129
+ export function findConnectionSshd(
130
+ execParentPid: number,
131
+ processes: Map<number, PortProcess>
132
+ ): number | null {
133
+ let best: number | null = null;
134
+ let current: number | null = execParentPid;
135
+ const seen = new Set<number>();
136
+
137
+ for (let depth = 0; depth < 20 && current !== null && current > 1; depth++) {
138
+ if (seen.has(current)) break;
139
+ seen.add(current);
140
+
141
+ const process = processes.get(current);
142
+ if (!process || !isSessionSshd(process)) break;
143
+
144
+ best = current;
145
+ current = process.parentPid;
146
+ }
147
+
148
+ return best;
149
+ }
150
+
151
+ /**
152
+ * The pid and the process list must come from the *same* command: sshd reaps
153
+ * the exec channel's child the moment the command exits, so a pid read by one
154
+ * exec is already gone before a second could run `ps` against it.
155
+ */
156
+ async function probeTreeRoot(runner: CommandRunner): Promise<number | null> {
157
+ try {
158
+ const result = await runner.run(
159
+ posixArgv(['sh', '-c', 'echo "$PPID"; ps -eo pid=,ppid=,user=,lstart=,args=']),
160
+ 10_000
161
+ );
162
+
163
+ const newline = result.stdout.indexOf('\n');
164
+ if (newline === -1) return null;
165
+
166
+ const execParentPid = Number.parseInt(result.stdout.slice(0, newline).trim(), 10);
167
+ if (!Number.isFinite(execParentPid) || execParentPid <= 1) return null;
168
+
169
+ const processes = new Map<number, PortProcess>();
170
+ for (const entry of parsePsOutput(result.stdout.slice(newline + 1))) processes.set(entry.pid, entry);
171
+
172
+ return findConnectionSshd(execParentPid, processes);
173
+ } catch (error) {
174
+ debug.log('ports', `SSH tree probe failed on ${runner.label}:`, error);
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * What connection Clopen's own commands run on. Cached per host: it cannot
181
+ * change while the pooled transport lives, and re-asking would spend a round
182
+ * trip per tick on a constant.
183
+ */
184
+ const ownConnections = new Map<string, string>();
185
+
186
+ async function readOwnConnection(
187
+ hostId: string,
188
+ runner: CommandRunner,
189
+ platform: ProbePlatform
190
+ ): Promise<string | null> {
191
+ const cached = ownConnections.get(hostId);
192
+ if (cached) return cached;
193
+ if (platform === 'win32') return null;
194
+
195
+ try {
196
+ const result = await runner.run(posixArgv(['sh', '-c', 'printf %s "$SSH_CONNECTION"']), 5_000);
197
+ const value = result.stdout.trim();
198
+ // Judged on output, not exit status: a restricted shell can report a
199
+ // non-zero status and still have answered the question.
200
+ if (!parseSshConnection(value)) return null;
201
+ ownConnections.set(hostId, value);
202
+ return value;
203
+ } catch (error) {
204
+ debug.log('ports', `could not read SSH_CONNECTION on ${runner.label}:`, error);
205
+ return null;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Which of these listening processes belong to Clopen's own SSH connection.
211
+ *
212
+ * Answers per pid rather than by finding one root process, so a server that
213
+ * was disowned or reparented is still recognised — the environment survives
214
+ * what the process tree does not.
215
+ */
216
+ /**
217
+ * What has already been decided about a process, keyed by pid *and* start time
218
+ * so a recycled pid is judged afresh. A live process's environment does not
219
+ * change, so re-reading it every tick would be a round trip spent confirming a
220
+ * constant.
221
+ */
222
+ const verdicts = new Map<string, Map<string, boolean>>();
223
+
224
+ function verdictKey(pid: number, processes: Map<number, PortProcess>): string {
225
+ return `${pid}:${processes.get(pid)?.startedAt ?? ''}`;
226
+ }
227
+
228
+ export async function resolveClopenPids(
229
+ hostId: string,
230
+ runner: CommandRunner,
231
+ platform: ProbePlatform,
232
+ pids: number[],
233
+ processes: Map<number, PortProcess>
234
+ ): Promise<Set<number>> {
235
+ const ours = new Set<number>();
236
+ if (platform === 'win32') return ours;
237
+
238
+ // macOS will not report a process's environment, so its connection has to
239
+ // be identified through the process tree instead. Adding the session sshd
240
+ // is enough: the ancestry walk downstream reaches it from every descendant.
241
+ if (platform === 'darwin') {
242
+ const root = await resolveTreeRoot(hostId, runner);
243
+ if (root !== null) ours.add(root);
244
+ return ours;
245
+ }
246
+
247
+ const own = await readOwnConnection(hostId, runner, platform);
248
+ if (!own) return ours;
249
+
250
+ // Ancestors count too: a process that cleared its own environment is still
251
+ // ours if the shell that spawned it is.
252
+ const candidates = new Set<number>();
253
+ for (const pid of pids) {
254
+ let current: number | null = pid;
255
+ const seen = new Set<number>();
256
+ for (let depth = 0; depth < 20 && current !== null && current > 1; depth++) {
257
+ if (seen.has(current)) break;
258
+ seen.add(current);
259
+ candidates.add(current);
260
+ current = processes.get(current)?.parentPid ?? null;
261
+ }
262
+ }
263
+
264
+ let known = verdicts.get(hostId);
265
+ if (!known) {
266
+ known = new Map();
267
+ verdicts.set(hostId, known);
268
+ }
269
+
270
+ // Only ask about processes never judged before; the rest are already settled.
271
+ const unknown: number[] = [];
272
+ for (const pid of candidates) {
273
+ const decided = known.get(verdictKey(pid, processes));
274
+ if (decided === undefined) unknown.push(pid);
275
+ else if (decided) ours.add(pid);
276
+ }
277
+
278
+ const argv = environProbeArgv(safePids(unknown));
279
+ if (!argv) return ours;
280
+
281
+ try {
282
+ const result = await runner.run(argv, 10_000);
283
+ const values = parseEnvironProbe(result.stdout);
284
+
285
+ for (const pid of unknown) {
286
+ const value = values.get(pid);
287
+ // A process whose environment could not be read is recorded as not
288
+ // ours, so it is not asked about again — unreadable will not become
289
+ // readable while it lives.
290
+ const mine = value !== undefined && sameConnection(value, own);
291
+ known.set(verdictKey(pid, processes), mine);
292
+ if (mine) ours.add(pid);
293
+ }
294
+ } catch (error) {
295
+ debug.log('ports', `environment probe failed on ${runner.label}:`, error);
296
+ }
297
+
298
+ return ours;
299
+ }
300
+
301
+ /** Resolved once per host; a failure is not cached, so a later tick retries. */
302
+ const treeRoots = new Map<string, number>();
303
+
304
+ async function resolveTreeRoot(hostId: string, runner: CommandRunner): Promise<number | null> {
305
+ const cached = treeRoots.get(hostId);
306
+ if (cached !== undefined) return cached;
307
+
308
+ const root = await probeTreeRoot(runner);
309
+ if (root !== null) treeRoots.set(hostId, root);
310
+ return root;
311
+ }
312
+
313
+ /** Drop a host's cached connection identity when its transport goes away. */
314
+ export function forgetClopenRootPid(hostId: string): void {
315
+ ownConnections.delete(hostId);
316
+ treeRoots.delete(hostId);
317
+ verdicts.delete(hostId);
318
+ }
@@ -162,18 +162,23 @@ interface VideoStreamSession {
162
162
  scriptInjected: boolean; // Track if persistent script was injected
163
163
  scriptsPreInjected: boolean; // Track if scripts were pre-injected during tab creation
164
164
  /**
165
- * When the page last reported frames reaching its encoder. A connected
166
- * viewer while this stands still is watching a stream that has stopped
167
- * producing — which looks identical, from the client, to a slow page.
165
+ * When the page last reported ANYTHING, frames or not.
166
+ *
167
+ * This is the liveness signal, and the distinction it draws is the whole
168
+ * point: the page ticks a stats report every two seconds for as long as its
169
+ * encoder loop is alive, whether or not there was anything to encode. Reports
170
+ * arriving with zero frames mean a still picture. Reports stopping mean the
171
+ * loop itself is gone — a navigation that took the injected script with it, a
172
+ * context that was torn down — which is the only thing a repair can fix.
168
173
  */
169
- lastEncodedAt: number;
174
+ lastPageReportAt: number;
170
175
  /** Guards the watchdog against re-entering while a repair is in flight. */
171
176
  repairing: boolean;
172
177
  /**
173
- * Repairs attempted since the stream last produced anything. A repair that
174
- * did not restore frames must escalate rather than be repeated: the cheap
175
- * one asks the page what it thinks, and a page whose own answer is the
176
- * wrong one will give the same answer every time.
178
+ * Repairs attempted since the page last reported in. A repair that did not
179
+ * restore reporting must escalate rather than be repeated: the cheap one asks
180
+ * the page what it thinks, and a page whose own answer is the wrong one will
181
+ * give the same answer every time.
177
182
  */
178
183
  stallRounds: number;
179
184
  /** Codecs every viewer can decode — one encoder serves them all. */
@@ -588,11 +593,18 @@ export class BrowserVideoCapture extends EventEmitter {
588
593
  private static readonly VIEWER_HANDSHAKE_TTL_MS = 45_000;
589
594
 
590
595
  /**
591
- * Silence tolerated from a connected viewer's stream before the watchdog
592
- * repairs it. Two encoder-stat windows plus slack — long enough that a
593
- * genuinely idle page (which still tops off) never trips it.
596
+ * Silence tolerated from the PAGE before the watchdog repairs the stream,
597
+ * and the interval the watchdog itself runs on.
598
+ *
599
+ * The page reports encoder stats every two seconds for as long as its capture
600
+ * loop is alive, so this is three missed reports: late enough that a slow tick
601
+ * or a busy host is never mistaken for a dead page, early enough that a
602
+ * genuinely broken stream is repaired before anyone reaches for reload.
603
+ *
604
+ * This deliberately measures REPORTS, not frames — a still page produces no
605
+ * frames at all and is perfectly healthy. See `checkForStall`.
594
606
  */
595
- private static readonly STREAM_STALL_MS = 6_000;
607
+ private static readonly PAGE_SILENCE_MS = 6_000;
596
608
 
597
609
  /**
598
610
  * Cheap stall repairs before the watchdog stops taking the page's word for
@@ -740,7 +752,7 @@ export class BrowserVideoCapture extends EventEmitter {
740
752
  viewers: new Map(),
741
753
  scriptInjected: false,
742
754
  scriptsPreInjected: false,
743
- lastEncodedAt: 0,
755
+ lastPageReportAt: 0,
744
756
  repairing: false,
745
757
  stallRounds: 0,
746
758
  codecSupport: { ...DEFAULT_CODEC_SUPPORT },
@@ -856,7 +868,10 @@ export class BrowserVideoCapture extends EventEmitter {
856
868
  // for the first mouse move to see anything. Push one refresh
857
869
  // frame as soon as the peer is up.
858
870
  if (state === 'connected' && videoSession.tab) {
859
- videoSession.lastEncodedAt = Date.now();
871
+ // A peer that just reached `connected` is a page that was talking to
872
+ // us a moment ago — give it a fresh silence window rather than
873
+ // judging it on a clock that predates the handshake.
874
+ videoSession.lastPageReportAt = Date.now();
860
875
  void this.requestKeyframe(sessionId, videoSession.tab);
861
876
  }
862
877
 
@@ -1045,7 +1060,8 @@ export class BrowserVideoCapture extends EventEmitter {
1045
1060
  this.reconcileViewers(videoSession, health);
1046
1061
  }
1047
1062
 
1048
- videoSession.lastEncodedAt = Date.now();
1063
+ // `ensureLive` just heard from the page directly, so this IS a report.
1064
+ videoSession.lastPageReportAt = Date.now();
1049
1065
  this.ensureWatchdog();
1050
1066
  return true;
1051
1067
  }
@@ -1561,7 +1577,7 @@ export class BrowserVideoCapture extends EventEmitter {
1561
1577
  if (this.reapStaleViewers(videoSession)) continue;
1562
1578
  this.checkForStall(videoSession);
1563
1579
  }
1564
- }, BrowserVideoCapture.STREAM_STALL_MS);
1580
+ }, BrowserVideoCapture.PAGE_SILENCE_MS);
1565
1581
 
1566
1582
  // Nothing here should hold the process open on its own.
1567
1583
  this.watchdogTimer.unref?.();
@@ -1606,36 +1622,71 @@ export class BrowserVideoCapture extends EventEmitter {
1606
1622
  }
1607
1623
 
1608
1624
  /**
1609
- * Repair a stream that has stopped producing while someone is watching it.
1625
+ * Repair a stream whose PAGE has stopped reporting while someone is watching.
1610
1626
  *
1611
1627
  * Recovery used to live entirely in the viewer: it noticed no first frame,
1612
1628
  * asked for a screencast refresh, then re-handshook. That only works while
1613
1629
  * the *client's* view of the problem is right — and the failures that stuck
1614
1630
  * were the ones where the client did everything correctly and the source
1615
- * was the broken half. Repairing from here closes that gap, and costs
1616
- * nothing on a healthy stream because even an idle page still tops off.
1631
+ * was the broken half. Repairing from here closes that gap.
1632
+ *
1633
+ * WHAT COUNTS AS A STALL, AND WHY IT CHANGED
1634
+ *
1635
+ * This used to key on `lastEncodedAt` — frames reaching the encoder — on the
1636
+ * stated assumption that "even an idle page still tops off". That assumption
1637
+ * was wrong, and the bug it caused was severe.
1638
+ *
1639
+ * Capture is damage-driven: `framesAttempted` is only incremented for motion
1640
+ * frames (see `shouldSkipMotionFrame` in scripts/video-stream.ts), and the
1641
+ * still-page top-off is a one-shot that fires after motion stops, not a
1642
+ * heartbeat. So a page that is simply SITTING THERE — the normal case, a user
1643
+ * looking at their app without touching it — reports zero frames forever, and
1644
+ * every one of those reports was read as "the stream is dead".
1645
+ *
1646
+ * The result was a permanent loop on every idle preview: six seconds of
1647
+ * stillness triggered a repair, twelve seconds triggered a FORCED peer
1648
+ * rebuild, which drops every viewer into a re-handshake — the reload with a
1649
+ * progress bar that users saw arrive every few seconds and could not explain.
1650
+ * The rebuild produced a keyframe, which reset the counters, which started
1651
+ * the same clock again. It also made the failure self-sustaining across the
1652
+ * rest of the app: each rebuild is a burst of CDP work plus handshake round
1653
+ * trips on the shared socket, so the busier the instance, the more of them
1654
+ * were in flight at once.
1655
+ *
1656
+ * The honest signal is whether the PAGE is still talking to us, not whether
1657
+ * it has anything to show. Its stats timer ticks every two seconds for as
1658
+ * long as the encoder loop is alive, so silence there — and only there —
1659
+ * means the loop is genuinely gone. A still picture is not a stall.
1660
+ *
1661
+ * The other real failure, an in-page capture that ends on its own, is already
1662
+ * detected explicitly in `applyEncoderStats` rather than inferred from frame
1663
+ * absence, so nothing is lost by no longer guessing here.
1617
1664
  */
1618
1665
  private checkForStall(videoSession: VideoStreamSession): void {
1619
1666
  if (videoSession.paused || videoSession.repairing || !videoSession.tab) return;
1620
1667
  if (videoSession.viewers.size === 0) return;
1621
1668
  if (!Array.from(videoSession.viewers.values()).some((viewer) => viewer.connected)) return;
1622
1669
 
1623
- const silentFor = Date.now() - videoSession.lastEncodedAt;
1624
- if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
1670
+ // Nothing reported yet: the stream is still coming up and its own
1671
+ // handshake path owns that window.
1672
+ if (videoSession.lastPageReportAt === 0) return;
1673
+
1674
+ const silentFor = Date.now() - videoSession.lastPageReportAt;
1675
+ if (silentFor < BrowserVideoCapture.PAGE_SILENCE_MS) return;
1625
1676
 
1626
1677
  const { sessionId, tab } = videoSession;
1627
1678
  videoSession.stallRounds++;
1628
1679
 
1629
1680
  // The first round asks the page what state it is in and repairs from
1630
1681
  // that answer, which is cheap and keeps every viewer's peer intact. Once
1631
- // that has been tried and the stream is still silent, the page's own
1682
+ // that has been tried and the page is still silent, the page's own
1632
1683
  // account is the thing that cannot be trusted — so rebuild the peer
1633
1684
  // outright. Viewers lose their connection and re-handshake, which is a
1634
1685
  // visible hiccup, but they are looking at a frozen picture either way.
1635
1686
  const force = videoSession.stallRounds > BrowserVideoCapture.STALL_REPAIR_ROUNDS;
1636
1687
  debug.warn(
1637
1688
  'webcodecs',
1638
- `Stream for ${sessionId} produced nothing for ${silentFor}ms — ` +
1689
+ `Page for ${sessionId} stopped reporting for ${silentFor}ms — ` +
1639
1690
  `${force ? 'rebuilding the page peer' : 'repairing'} (round ${videoSession.stallRounds})`
1640
1691
  );
1641
1692
 
@@ -1647,7 +1698,10 @@ export class BrowserVideoCapture extends EventEmitter {
1647
1698
  .catch((error) => debug.warn('webcodecs', `Stall repair failed for ${sessionId}:`, error))
1648
1699
  .finally(() => {
1649
1700
  videoSession.repairing = false;
1650
- videoSession.lastEncodedAt = Date.now();
1701
+ // Give the repaired page a full silence window to report in before
1702
+ // it can be judged again. Without this the next tick would measure
1703
+ // against a clock that never moved and escalate immediately.
1704
+ videoSession.lastPageReportAt = Date.now();
1651
1705
  });
1652
1706
  }
1653
1707
 
@@ -1661,13 +1715,12 @@ export class BrowserVideoCapture extends EventEmitter {
1661
1715
 
1662
1716
  videoSession.captureMode = stats.captureMode || videoSession.captureMode;
1663
1717
 
1664
- // Frames reaching the encoder is the one signal that means the pipeline
1665
- // is genuinely alive end to end. The counter is per-window, so any
1666
- // non-zero report is proof of life for this window.
1667
- if (stats.framesAttempted > 0) {
1668
- videoSession.lastEncodedAt = Date.now();
1669
- videoSession.stallRounds = 0;
1670
- }
1718
+ // THE report arriving is proof the page's capture loop is alive — whether
1719
+ // or not it had anything to encode. This is what the watchdog measures.
1720
+ // Frames are a property of the CONTENT (a still page has none and is
1721
+ // perfectly healthy); reports are a property of the PIPELINE.
1722
+ videoSession.lastPageReportAt = Date.now();
1723
+ videoSession.stallRounds = 0;
1671
1724
 
1672
1725
  // In-page capture can end on its own — the captured surface goes away
1673
1726
  // on some navigations — and the page has no way to start a screencast.
@@ -74,6 +74,37 @@ class SshForwardManager {
74
74
  };
75
75
  }
76
76
 
77
+ /**
78
+ * Forwards holding a listener on the machine Clopen runs on, for the port
79
+ * manager. `server` is the local `net.Server`, so its presence is what makes
80
+ * a forward local — remote forwards bind on the far host and are reported by
81
+ * `remoteListeners` instead.
82
+ */
83
+ localListeners(): Array<{ forward: SshForward; boundPort: number }> {
84
+ const listeners: Array<{ forward: SshForward; boundPort: number }> = [];
85
+ for (const active of this.running.values()) {
86
+ if (!active.server) continue;
87
+ listeners.push({ forward: active.forward, boundPort: active.boundPort });
88
+ }
89
+ return listeners;
90
+ }
91
+
92
+ /**
93
+ * Forwards holding a listener on a given SSH host. A remote forward asks the
94
+ * host's sshd to bind a port on Clopen's behalf, so that port is every bit as
95
+ * much Clopen's doing as a local one — the port manager names it the same way
96
+ * when looking at that host.
97
+ */
98
+ remoteListeners(connectionId: string): Array<{ forward: SshForward; boundPort: number }> {
99
+ const listeners: Array<{ forward: SshForward; boundPort: number }> = [];
100
+ for (const active of this.running.values()) {
101
+ if (active.server) continue;
102
+ if (active.forward.connectionId !== connectionId) continue;
103
+ listeners.push({ forward: active.forward, boundPort: active.boundPort });
104
+ }
105
+ return listeners;
106
+ }
107
+
77
108
  statusesForConnection(connectionId: string): SshForwardStatus[] {
78
109
  return sshPortForwardQueries.listForConnection(connectionId).map((forward) => this.status(forward));
79
110
  }
@@ -89,7 +89,7 @@ export const deviceHandler = createRouter()
89
89
  ipAddress: clientIpFromConnection(conn)
90
90
  });
91
91
 
92
- authRateLimiter.recordSuccess(ip);
92
+ authRateLimiter.recordSuccess(ip, 'auth:claim-device-code');
93
93
 
94
94
  auditLogQueries.logEvent({
95
95
  userId: result.user.id,
@@ -174,7 +174,7 @@ export const loginHandler = createRouter()
174
174
 
175
175
  // Success — clear any rate limit record for this IP
176
176
  if (isRateLimited) {
177
- authRateLimiter.recordSuccess(ip);
177
+ authRateLimiter.recordSuccess(ip, 'auth:login');
178
178
  }
179
179
 
180
180
  auditLogQueries.logEvent({
@@ -226,7 +226,7 @@ export const loginHandler = createRouter()
226
226
  try {
227
227
  const result = createUserFromInvite(data.inviteToken, data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
228
228
 
229
- authRateLimiter.recordSuccess(ip);
229
+ authRateLimiter.recordSuccess(ip, 'auth:accept-invite');
230
230
 
231
231
  auditLogQueries.logEvent({
232
232
  userId: result.user.id,
@@ -272,8 +272,12 @@ export const loginHandler = createRouter()
272
272
 
273
273
  const result = validateInviteToken(data.inviteToken);
274
274
 
275
- // Record failure if invalid token (probing)
276
- if (!result.valid) {
275
+ // Record failure if invalid token (probing). On a valid token, clear this
276
+ // route's record so someone who mistyped their link a couple of times
277
+ // doesn't carry those failures into a later attempt.
278
+ if (result.valid) {
279
+ authRateLimiter.recordSuccess(ip, 'auth:validate-invite');
280
+ } else {
277
281
  authRateLimiter.recordFailure(ip, 'auth:validate-invite');
278
282
  }
279
283