@myrialabs/clopen 0.4.32 → 0.4.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +3 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/chat/stream-manager.ts +4 -1
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +21 -1
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +33 -4
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/stream.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +7 -0
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/nested-repos.test.ts +108 -5
- package/backend/git/nested-repos.ts +103 -18
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +25 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- 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/runner.ts +195 -0
- package/backend/ports/scan-host.ts +260 -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 +51 -4
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +340 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/index.ts +6 -0
- 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/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
- package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
- package/dist/assets/main-CYCMEbXB.css +1 -0
- package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +192 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +2 -0
- package/dist/assets/main-Ciuw0wF0.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 './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
|
+
}
|
|
@@ -169,6 +169,13 @@ interface VideoStreamSession {
|
|
|
169
169
|
lastEncodedAt: number;
|
|
170
170
|
/** Guards the watchdog against re-entering while a repair is in flight. */
|
|
171
171
|
repairing: boolean;
|
|
172
|
+
/**
|
|
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.
|
|
177
|
+
*/
|
|
178
|
+
stallRounds: number;
|
|
172
179
|
/** Codecs every viewer can decode — one encoder serves them all. */
|
|
173
180
|
codecSupport: ClientCodecSupport;
|
|
174
181
|
/** Display metrics of the most demanding viewer. */
|
|
@@ -587,6 +594,12 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
587
594
|
*/
|
|
588
595
|
private static readonly STREAM_STALL_MS = 6_000;
|
|
589
596
|
|
|
597
|
+
/**
|
|
598
|
+
* Cheap stall repairs before the watchdog stops taking the page's word for
|
|
599
|
+
* its own health and rebuilds the peer from scratch.
|
|
600
|
+
*/
|
|
601
|
+
private static readonly STALL_REPAIR_ROUNDS = 1;
|
|
602
|
+
|
|
590
603
|
private sessions = new Map<string, VideoStreamSession>();
|
|
591
604
|
private feeders = new Map<string, ScreencastFeeder>();
|
|
592
605
|
private preInjectPromises = new Map<string, Promise<boolean>>();
|
|
@@ -729,6 +742,7 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
729
742
|
scriptsPreInjected: false,
|
|
730
743
|
lastEncodedAt: 0,
|
|
731
744
|
repairing: false,
|
|
745
|
+
stallRounds: 0,
|
|
732
746
|
codecSupport: { ...DEFAULT_CODEC_SUPPORT },
|
|
733
747
|
display: {},
|
|
734
748
|
profile,
|
|
@@ -978,6 +992,20 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
978
992
|
const codecChanged = injection.codecSignature !== this.codecSignature(videoSession);
|
|
979
993
|
const needsInjection = epochMismatch || codecChanged;
|
|
980
994
|
|
|
995
|
+
// In push mode the page is only the encoder — the frames come from a CDP
|
|
996
|
+
// screencast this process owns. `capturing: true` then means "willing",
|
|
997
|
+
// not "being fed", so a feeder that has gone away leaves a session both
|
|
998
|
+
// halves call healthy and which produces nothing at all. That state is
|
|
999
|
+
// self-sustaining: the page keeps answering, so this check keeps taking
|
|
1000
|
+
// the cheap branch, and the viewer keeps waiting for a first frame that
|
|
1001
|
+
// no longer has a source.
|
|
1002
|
+
const sourceMissing =
|
|
1003
|
+
!needsInjection &&
|
|
1004
|
+
!!health?.capturing &&
|
|
1005
|
+
health.captureMode === 'push' &&
|
|
1006
|
+
!videoSession.paused &&
|
|
1007
|
+
!this.feeders.has(sessionId);
|
|
1008
|
+
|
|
981
1009
|
if (needsInjection) {
|
|
982
1010
|
const reason = options.force
|
|
983
1011
|
? 'forced'
|
|
@@ -993,7 +1021,10 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
993
1021
|
this.feeders.get(sessionId)?.invalidatePeerHandle();
|
|
994
1022
|
}
|
|
995
1023
|
|
|
996
|
-
if (needsInjection || !health?.capturing) {
|
|
1024
|
+
if (needsInjection || !health?.capturing || sourceMissing) {
|
|
1025
|
+
if (sourceMissing) {
|
|
1026
|
+
debug.warn('webcodecs', `Page for ${sessionId} reports capturing with no frame source — rebuilding it`);
|
|
1027
|
+
}
|
|
997
1028
|
const started = await this.startPageCapture(page);
|
|
998
1029
|
if (!started) {
|
|
999
1030
|
debug.error('webcodecs', `Page refused to start capturing for ${sessionId}`);
|
|
@@ -1593,10 +1624,23 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
1593
1624
|
if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
|
|
1594
1625
|
|
|
1595
1626
|
const { sessionId, tab } = videoSession;
|
|
1596
|
-
|
|
1627
|
+
videoSession.stallRounds++;
|
|
1628
|
+
|
|
1629
|
+
// The first round asks the page what state it is in and repairs from
|
|
1630
|
+
// 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
|
|
1632
|
+
// account is the thing that cannot be trusted — so rebuild the peer
|
|
1633
|
+
// outright. Viewers lose their connection and re-handshake, which is a
|
|
1634
|
+
// visible hiccup, but they are looking at a frozen picture either way.
|
|
1635
|
+
const force = videoSession.stallRounds > BrowserVideoCapture.STALL_REPAIR_ROUNDS;
|
|
1636
|
+
debug.warn(
|
|
1637
|
+
'webcodecs',
|
|
1638
|
+
`Stream for ${sessionId} produced nothing for ${silentFor}ms — ` +
|
|
1639
|
+
`${force ? 'rebuilding the page peer' : 'repairing'} (round ${videoSession.stallRounds})`
|
|
1640
|
+
);
|
|
1597
1641
|
|
|
1598
1642
|
videoSession.repairing = true;
|
|
1599
|
-
void this.ensureLive(sessionId, tab, () => !tab.isDestroyed)
|
|
1643
|
+
void this.ensureLive(sessionId, tab, () => !tab.isDestroyed, { force })
|
|
1600
1644
|
.then((live) => {
|
|
1601
1645
|
if (live) return this.requestKeyframe(sessionId, tab);
|
|
1602
1646
|
})
|
|
@@ -1620,7 +1664,10 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
1620
1664
|
// Frames reaching the encoder is the one signal that means the pipeline
|
|
1621
1665
|
// is genuinely alive end to end. The counter is per-window, so any
|
|
1622
1666
|
// non-zero report is proof of life for this window.
|
|
1623
|
-
if (stats.framesAttempted > 0)
|
|
1667
|
+
if (stats.framesAttempted > 0) {
|
|
1668
|
+
videoSession.lastEncodedAt = Date.now();
|
|
1669
|
+
videoSession.stallRounds = 0;
|
|
1670
|
+
}
|
|
1624
1671
|
|
|
1625
1672
|
// In-page capture can end on its own — the captured surface goes away
|
|
1626
1673
|
// on some navigations — and the page has no way to start a screencast.
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — one live ssh2 client per saved connection, shared by everything.
|
|
3
|
+
*
|
|
4
|
+
* SSH multiplexes channels over a single transport, so a host's terminal tabs,
|
|
5
|
+
* its file browser and its port forwards all ride one authenticated connection
|
|
6
|
+
* — the user authenticates once, not once per feature.
|
|
7
|
+
*
|
|
8
|
+
* Leases decide when that connection may close. A terminal tab or a running
|
|
9
|
+
* forward holds a lease for as long as it lives; a one-shot SFTP call holds one
|
|
10
|
+
* for the length of the call. An entry with no leases is swept after IDLE_MS.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Client as SshClient } from 'ssh2';
|
|
14
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
15
|
+
import { closeChain, dial, type DialResult } from './connect';
|
|
16
|
+
import { debug } from '$shared/utils/logger';
|
|
17
|
+
|
|
18
|
+
/** How long a lease-free connection stays warm before being dropped. */
|
|
19
|
+
const IDLE_MS = 60 * 1000;
|
|
20
|
+
const SWEEP_INTERVAL_MS = 30 * 1000;
|
|
21
|
+
|
|
22
|
+
interface PoolEntry {
|
|
23
|
+
dialed: DialResult;
|
|
24
|
+
leases: number;
|
|
25
|
+
lastUsedAt: number;
|
|
26
|
+
alive: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SshLease {
|
|
30
|
+
client: SshClient;
|
|
31
|
+
/** Release this lease. Idempotent — calling it twice does not double-count. */
|
|
32
|
+
release(): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class SshClientPool {
|
|
36
|
+
private entries = new Map<string, PoolEntry>();
|
|
37
|
+
private pending = new Map<string, Promise<PoolEntry>>();
|
|
38
|
+
/**
|
|
39
|
+
* Hosts the user explicitly disconnected. The pool dials on demand, so
|
|
40
|
+
* without this a "Disconnect" would be undone by the next keystroke in a
|
|
41
|
+
* terminal or click in the file browser — the button has to actually mean
|
|
42
|
+
* something. Runtime-only: a restart starts every host reconnectable.
|
|
43
|
+
*/
|
|
44
|
+
private suspended = new Set<string>();
|
|
45
|
+
private sweeperHandle: ReturnType<typeof setInterval> | null = null;
|
|
46
|
+
|
|
47
|
+
private startSweeper(): void {
|
|
48
|
+
if (this.sweeperHandle) return;
|
|
49
|
+
this.sweeperHandle = setInterval(() => this.sweepIdle(), SWEEP_INTERVAL_MS);
|
|
50
|
+
// Don't keep the process alive just for this timer.
|
|
51
|
+
(this.sweeperHandle as unknown as { unref?: () => void }).unref?.();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private async openEntry(connectionId: string): Promise<PoolEntry> {
|
|
55
|
+
const connection = sshConnectionQueries.get(connectionId);
|
|
56
|
+
if (!connection) throw new Error('ssh connection not found');
|
|
57
|
+
|
|
58
|
+
const dialed = await dial(connection);
|
|
59
|
+
const entry: PoolEntry = { dialed, leases: 0, lastUsedAt: Date.now(), alive: true };
|
|
60
|
+
|
|
61
|
+
// A dropped transport must not be handed to the next caller. Mark the
|
|
62
|
+
// entry dead and drop it so the following acquire dials fresh.
|
|
63
|
+
const invalidate = (): void => {
|
|
64
|
+
if (!entry.alive) return;
|
|
65
|
+
entry.alive = false;
|
|
66
|
+
if (this.entries.get(connectionId) === entry) {
|
|
67
|
+
this.entries.delete(connectionId);
|
|
68
|
+
}
|
|
69
|
+
debug.log('ssh', `connection ${connectionId} closed`);
|
|
70
|
+
};
|
|
71
|
+
dialed.client.on('close', invalidate);
|
|
72
|
+
dialed.client.on('end', invalidate);
|
|
73
|
+
dialed.client.on('error', (error: Error) => {
|
|
74
|
+
debug.warn('ssh', `connection ${connectionId} error: ${error.message}`);
|
|
75
|
+
invalidate();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
sshConnectionQueries.markUsed(connectionId);
|
|
79
|
+
return entry;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Take a lease on the connection, dialing it if needed. Concurrent callers
|
|
84
|
+
* for the same host share one dial rather than racing two handshakes.
|
|
85
|
+
*/
|
|
86
|
+
async acquire(connectionId: string): Promise<SshLease> {
|
|
87
|
+
if (this.suspended.has(connectionId)) {
|
|
88
|
+
throw new Error('This host is disconnected — use Connect to open it again');
|
|
89
|
+
}
|
|
90
|
+
this.startSweeper();
|
|
91
|
+
|
|
92
|
+
const existing = this.entries.get(connectionId);
|
|
93
|
+
if (existing?.alive) {
|
|
94
|
+
return this.leaseOf(connectionId, existing);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let inFlight = this.pending.get(connectionId);
|
|
98
|
+
if (!inFlight) {
|
|
99
|
+
inFlight = this.openEntry(connectionId).finally(() => this.pending.delete(connectionId));
|
|
100
|
+
this.pending.set(connectionId, inFlight);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const entry = await inFlight;
|
|
104
|
+
// Another caller's dial may already be registered; prefer whichever entry
|
|
105
|
+
// is live so both callers end up on the same transport.
|
|
106
|
+
const current = this.entries.get(connectionId);
|
|
107
|
+
if (current?.alive && current !== entry) {
|
|
108
|
+
closeChain(entry.dialed.chain);
|
|
109
|
+
return this.leaseOf(connectionId, current);
|
|
110
|
+
}
|
|
111
|
+
this.entries.set(connectionId, entry);
|
|
112
|
+
return this.leaseOf(connectionId, entry);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private leaseOf(connectionId: string, entry: PoolEntry): SshLease {
|
|
116
|
+
entry.leases++;
|
|
117
|
+
entry.lastUsedAt = Date.now();
|
|
118
|
+
let released = false;
|
|
119
|
+
return {
|
|
120
|
+
client: entry.dialed.client,
|
|
121
|
+
release: () => {
|
|
122
|
+
if (released) return;
|
|
123
|
+
released = true;
|
|
124
|
+
entry.leases = Math.max(0, entry.leases - 1);
|
|
125
|
+
entry.lastUsedAt = Date.now();
|
|
126
|
+
debug.log('ssh', `lease released for ${connectionId} (${entry.leases} remaining)`);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Run one operation under a lease, releasing it even if the operation throws. */
|
|
132
|
+
async use<T>(connectionId: string, operation: (client: SshClient) => Promise<T>): Promise<T> {
|
|
133
|
+
const lease = await this.acquire(connectionId);
|
|
134
|
+
try {
|
|
135
|
+
return await operation(lease.client);
|
|
136
|
+
} finally {
|
|
137
|
+
lease.release();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** True when the host currently has a live, authenticated transport. */
|
|
142
|
+
isLive(connectionId: string): boolean {
|
|
143
|
+
return this.entries.get(connectionId)?.alive === true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** True when the user disconnected this host and has not reconnected it. */
|
|
147
|
+
isSuspended(connectionId: string): boolean {
|
|
148
|
+
return this.suspended.has(connectionId);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Close the host and refuse to redial it until `resume` is called. */
|
|
152
|
+
suspend(connectionId: string): void {
|
|
153
|
+
this.suspended.add(connectionId);
|
|
154
|
+
this.release(connectionId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Allow the host to be dialed again. */
|
|
158
|
+
resume(connectionId: string): void {
|
|
159
|
+
this.suspended.delete(connectionId);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Close a host's transport now, whatever its leases. Used on edit and delete. */
|
|
163
|
+
release(connectionId: string): void {
|
|
164
|
+
const entry = this.entries.get(connectionId);
|
|
165
|
+
if (!entry) return;
|
|
166
|
+
this.entries.delete(connectionId);
|
|
167
|
+
entry.alive = false;
|
|
168
|
+
closeChain(entry.dialed.chain);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private sweepIdle(): void {
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
for (const [connectionId, entry] of this.entries) {
|
|
174
|
+
if (entry.leases > 0) continue;
|
|
175
|
+
if (!entry.alive || now - entry.lastUsedAt > IDLE_MS) {
|
|
176
|
+
debug.log('ssh', `idle sweep: closing ${connectionId}`);
|
|
177
|
+
this.entries.delete(connectionId);
|
|
178
|
+
entry.alive = false;
|
|
179
|
+
closeChain(entry.dialed.chain);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
closeAll(): void {
|
|
185
|
+
this.suspended.clear();
|
|
186
|
+
for (const connectionId of [...this.entries.keys()]) {
|
|
187
|
+
this.release(connectionId);
|
|
188
|
+
}
|
|
189
|
+
if (this.sweeperHandle) {
|
|
190
|
+
clearInterval(this.sweeperHandle);
|
|
191
|
+
this.sweeperHandle = null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export const sshClientPool = new SshClientPool();
|