dsh-remote-vs 0.13.0 → 0.15.1
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/README.en.md +455 -443
- package/README.md +408 -396
- package/lib/client.js +8062 -2651
- package/lib/index.js +1058 -288
- package/lib/p2-router-fs.js +1 -1
- package/lib/p2-router-refs.js +89 -10
- package/lib/p2-router-spill.js +73 -1
- package/lib/p2-router-subprocess.js +18 -6
- package/lib/spill-retention-BwKEWrl5.js +115 -0
- package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
- package/lib/types/archive.d.ts +1 -1
- package/lib/types/changes/recorder.d.ts +34 -2
- package/lib/types/client/CodeEditor.d.ts +12 -0
- package/lib/types/client/ConnectionStatus.d.ts +17 -0
- package/lib/types/client/DirectoryFlow.d.ts +2 -0
- package/lib/types/client/DoctorPanel.d.ts +25 -0
- package/lib/types/client/QuickOpen.d.ts +17 -0
- package/lib/types/client/RemoteExplorer.d.ts +192 -1
- package/lib/types/client/RemoteRoot.d.ts +17 -0
- package/lib/types/client/SearchView.d.ts +55 -0
- package/lib/types/client/TerminalView.d.ts +38 -0
- package/lib/types/client/WorkspaceWizard.d.ts +17 -0
- package/lib/types/client/api.d.ts +54 -4
- package/lib/types/client/changes/undo-affordance.d.ts +16 -0
- package/lib/types/client/changes/undo-context.d.ts +14 -18
- package/lib/types/client/changes/undo-target.d.ts +78 -0
- package/lib/types/client/connection.d.ts +111 -0
- package/lib/types/client/doctor.d.ts +122 -0
- package/lib/types/client/download.d.ts +35 -5
- package/lib/types/client/downloads.d.ts +18 -1
- package/lib/types/client/file-open-probe.d.ts +64 -0
- package/lib/types/client/i18n.d.ts +1 -1
- package/lib/types/client/quickopen-model.d.ts +332 -0
- package/lib/types/client/scm/DiffView.d.ts +34 -0
- package/lib/types/client/scm/actions.d.ts +18 -0
- package/lib/types/client/scm/diff-model.d.ts +17 -1
- package/lib/types/client/scm/git-cache.d.ts +10 -2
- package/lib/types/client/scm/read-queue.d.ts +2 -1
- package/lib/types/client/scm/stage-queue.d.ts +13 -0
- package/lib/types/client/scm/status-map.d.ts +3 -1
- package/lib/types/client/store.d.ts +114 -5
- package/lib/types/client/vsc/FindWidget.d.ts +7 -0
- package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
- package/lib/types/deploy.d.ts +44 -2
- package/lib/types/git-format.d.ts +15 -0
- package/lib/types/http.d.ts +44 -0
- package/lib/types/p2/file-refs.d.ts +39 -2
- package/lib/types/p2/helper-rpc.d.ts +26 -0
- package/lib/types/p2/router-spill.d.ts +19 -0
- package/lib/types/p2/router-subprocess.d.ts +2 -0
- package/lib/types/p2/spill-retention.d.ts +74 -0
- package/lib/types/p2/worlds.d.ts +11 -0
- package/lib/types/pool.d.ts +73 -11
- package/lib/types/protocol.d.ts +63 -0
- package/lib/types/routes.d.ts +18 -0
- package/lib/types/sftp.d.ts +114 -8
- package/lib/types/store.d.ts +34 -0
- package/lib/types/timeouts.d.ts +14 -0
- package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
- package/package.json +1 -1
- package/src/archive.ts +41 -9
- package/src/changes/recorder.ts +227 -31
- package/src/changes/status.ts +37 -1
- package/src/client/CodeEditor.tsx +84 -2
- package/src/client/ConnectionStatus.tsx +130 -0
- package/src/client/DirectoryFlow.tsx +40 -5
- package/src/client/DoctorPanel.tsx +202 -0
- package/src/client/DownloadDock.tsx +13 -25
- package/src/client/EditorPane.tsx +291 -7
- package/src/client/HostsView.tsx +17 -8
- package/src/client/QuickOpen.tsx +371 -0
- package/src/client/RemoteDirectoryPicker.tsx +54 -3
- package/src/client/RemoteExplorer.tsx +879 -160
- package/src/client/RemoteRoot.tsx +178 -1
- package/src/client/SearchView.tsx +180 -6
- package/src/client/SettingsHosts.tsx +1 -1
- package/src/client/TerminalView.tsx +174 -9
- package/src/client/WorkspaceWizard.tsx +110 -16
- package/src/client/WorkspacesView.tsx +22 -6
- package/src/client/api.ts +197 -11
- package/src/client/changes/ChangesDock.tsx +35 -8
- package/src/client/changes/undo-affordance.ts +33 -0
- package/src/client/changes/undo-context.ts +14 -18
- package/src/client/changes/undo-target.ts +139 -0
- package/src/client/connection.ts +264 -0
- package/src/client/doctor.ts +441 -0
- package/src/client/download.ts +148 -12
- package/src/client/downloads.ts +43 -2
- package/src/client/file-open-probe.ts +83 -0
- package/src/client/i18n.ts +244 -0
- package/src/client/index.tsx +5 -2
- package/src/client/quickopen-model.ts +778 -0
- package/src/client/remote-file-open.ts +21 -33
- package/src/client/scm/DiffView.tsx +116 -6
- package/src/client/scm/ScmPanel.tsx +19 -0
- package/src/client/scm/actions.ts +34 -2
- package/src/client/scm/diff-model.ts +33 -37
- package/src/client/scm/git-cache.ts +61 -4
- package/src/client/scm/read-queue.ts +33 -2
- package/src/client/scm/stage-queue.ts +72 -1
- package/src/client/scm/status-map.ts +22 -1
- package/src/client/store.tsx +704 -21
- package/src/client/vsc/FindWidget.tsx +20 -0
- package/src/client/vsc/kit.tsx +115 -6
- package/src/client/vsc/reveal-line.ts +33 -14
- package/src/client/vsc/save-shortcut.ts +131 -0
- package/src/client/vsc/vsc.css +419 -0
- package/src/deploy.ts +185 -33
- package/src/git-format.ts +136 -22
- package/src/git-ops.ts +14 -6
- package/src/http.ts +80 -12
- package/src/importers.ts +80 -21
- package/src/index.ts +21 -1
- package/src/p2/file-refs.ts +112 -10
- package/src/p2/helper-rpc.ts +73 -36
- package/src/p2/router-spill.ts +96 -1
- package/src/p2/router-subprocess.ts +18 -5
- package/src/p2/spill-retention.ts +134 -0
- package/src/p2/ssh-proc.ts +22 -0
- package/src/p2/worlds.ts +24 -0
- package/src/pool.ts +329 -47
- package/src/protocol.ts +66 -0
- package/src/routes.ts +251 -43
- package/src/sftp.ts +486 -26
- package/src/store.ts +207 -85
- package/src/terminal.ts +38 -2
- package/src/timeouts.ts +14 -0
- package/src/tools.ts +14 -5
package/lib/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as pushPipeline, c as
|
|
1
|
+
import { C as storePath, S as keysDir, _ as resolveTimeouts, a as pushPipeline, b as dshHome, c as WriteConflictError, d as DEFAULT_READ_TIMEOUT_MS, f as DEFAULT_TIMEOUTS, g as clampExecTimeout, h as MIN_TIMEOUT_MS, i as probe, l as attachmentHeader, m as MAX_TIMEOUT_MS, o as seedHelperCache, p as DeadlineError, r as helperAvailability, s as RemoteFiles, t as RemoteWorlds, u as DEFAULT_GIT_TIMEOUT_MS, v as require_lib, x as ensurePrivateDir, y as aliasRoot } from "./worlds-Be1YE2Ot.js";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
|
-
import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
|
|
3
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
5
|
import { dirname, join, posix } from "node:path";
|
|
6
6
|
import { homedir } from "node:os";
|
|
@@ -34,6 +34,26 @@ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
|
34
34
|
function assertAlias(alias) {
|
|
35
35
|
if (typeof alias !== "string" || !ALIAS_RE.test(alias)) throw new Error("alias must match [A-Za-z0-9._-]{1,64} and start with an alphanumeric");
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Replays one read-modify-write before giving up. Two processes sharing
|
|
39
|
+
* `$DSH_HOME` (desktop + `dsh web`) can each land an edit between the other's
|
|
40
|
+
* read and write; a single retry almost always settles it, and the third attempt
|
|
41
|
+
* fails loud instead of silently dropping someone's change.
|
|
42
|
+
*/
|
|
43
|
+
const MUTATION_ATTEMPTS = 3;
|
|
44
|
+
/**
|
|
45
|
+
* Validate the SHAPE of an `auth` patch before it is merged.
|
|
46
|
+
*
|
|
47
|
+
* `update()` used to treat anything whose `kind` was not `'key'` as a password
|
|
48
|
+
* patch: `{kind:'garbage'}` silently kept the stored password (HTTP 200), and
|
|
49
|
+
* `auth: null` threw an engine TypeError. The merge below (and `normalize()`)
|
|
50
|
+
* must only ever see the two declared kinds, with a real object to read from.
|
|
51
|
+
*/
|
|
52
|
+
function assertAuthPatch(auth) {
|
|
53
|
+
if (typeof auth !== "object" || auth === null) throw new Error("auth must be an object");
|
|
54
|
+
const kind = auth.kind;
|
|
55
|
+
if (kind !== "key" && kind !== "password") throw new Error("auth.kind must be key or password");
|
|
56
|
+
}
|
|
37
57
|
var RemoteStore = class {
|
|
38
58
|
file;
|
|
39
59
|
doc;
|
|
@@ -101,14 +121,57 @@ var RemoteStore = class {
|
|
|
101
121
|
save() {
|
|
102
122
|
this.stamp = void 0;
|
|
103
123
|
const payload = JSON.stringify(this.doc, null, 2);
|
|
124
|
+
const dir = dirname(this.file);
|
|
125
|
+
mkdirSync(dir, { recursive: true });
|
|
104
126
|
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
105
127
|
const fd = openSync(tmp, "w", 384);
|
|
106
128
|
try {
|
|
107
129
|
writeSync(fd, payload);
|
|
130
|
+
try {
|
|
131
|
+
fsyncSync(fd);
|
|
132
|
+
} catch {}
|
|
108
133
|
} finally {
|
|
109
134
|
closeSync(fd);
|
|
110
135
|
}
|
|
111
136
|
renameSync(tmp, this.file);
|
|
137
|
+
if (process.platform !== "win32") {
|
|
138
|
+
let dirFd;
|
|
139
|
+
try {
|
|
140
|
+
dirFd = openSync(dir, "r");
|
|
141
|
+
fsyncSync(dirFd);
|
|
142
|
+
} catch {} finally {
|
|
143
|
+
if (dirFd !== void 0) try {
|
|
144
|
+
closeSync(dirFd);
|
|
145
|
+
} catch {}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Re-read, mutate, then write only while the file has not changed underneath.
|
|
151
|
+
*
|
|
152
|
+
* Every mutation here rewrites the WHOLE document, so a plain
|
|
153
|
+
* read-modify-write let the last writer win: desktop and `dsh web` share
|
|
154
|
+
* `$DSH_HOME/dsh-remote.json` by design, and one side's host edit could
|
|
155
|
+
* disappear without any error. Re-reading at the start plus a stamp re-check
|
|
156
|
+
* right before the write turns that into a replay on fresh content.
|
|
157
|
+
*
|
|
158
|
+
* `apply` must only touch `this.doc` and return a value (no I/O, no logging):
|
|
159
|
+
* a conflicting attempt is executed again against the reloaded document.
|
|
160
|
+
* The final rename window is still unguarded (a real lock needs blocking I/O);
|
|
161
|
+
* this narrows the lost-update window from a whole user edit to microseconds.
|
|
162
|
+
*/
|
|
163
|
+
mutate(apply) {
|
|
164
|
+
for (let attempt = 0; attempt < MUTATION_ATTEMPTS; attempt += 1) {
|
|
165
|
+
this.reload();
|
|
166
|
+
const base = this.stamp ?? null;
|
|
167
|
+
const before = JSON.stringify(this.doc);
|
|
168
|
+
const result = apply(this.doc);
|
|
169
|
+
if (JSON.stringify(this.doc) === before) return result;
|
|
170
|
+
if (!sameStamp(base, this.stampOf() ?? null)) continue;
|
|
171
|
+
this.save();
|
|
172
|
+
return result;
|
|
173
|
+
}
|
|
174
|
+
throw new Error(`${this.file}: another process keeps editing the store; retry the operation`);
|
|
112
175
|
}
|
|
113
176
|
list() {
|
|
114
177
|
this.reload();
|
|
@@ -125,51 +188,68 @@ var RemoteStore = class {
|
|
|
125
188
|
}
|
|
126
189
|
create(payload) {
|
|
127
190
|
assertAlias(payload.alias);
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
191
|
+
return this.mutate(() => {
|
|
192
|
+
if (this.doc.hosts.some((host) => host.alias === payload.alias)) throw new Error(`alias already exists: ${payload.alias}`);
|
|
193
|
+
const entry = this.normalize(payload, void 0);
|
|
194
|
+
this.doc.hosts.push(entry);
|
|
195
|
+
return entry;
|
|
196
|
+
});
|
|
133
197
|
}
|
|
134
198
|
update(alias, patch) {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
199
|
+
if (patch.auth !== void 0) assertAuthPatch(patch.auth);
|
|
200
|
+
return this.mutate(() => {
|
|
201
|
+
const index = this.doc.hosts.findIndex((h) => h.alias === alias);
|
|
202
|
+
if (index < 0) throw new Error(`unknown host alias: ${alias}`);
|
|
203
|
+
const current = this.doc.hosts[index];
|
|
204
|
+
let auth = patch.auth ?? current.auth;
|
|
205
|
+
if (patch.auth !== void 0) if (patch.auth.kind === "key") {
|
|
206
|
+
const keyPath = (patch.auth.keyPath ?? "").trim();
|
|
207
|
+
auth = {
|
|
208
|
+
kind: "key",
|
|
209
|
+
keyPath: keyPath !== "" ? keyPath : current.auth.kind === "key" ? current.auth.keyPath : "",
|
|
210
|
+
...patch.auth.passphrase !== void 0 ? { passphrase: patch.auth.passphrase } : current.auth.kind === "key" && current.auth.passphrase !== void 0 ? { passphrase: current.auth.passphrase } : {}
|
|
211
|
+
};
|
|
212
|
+
} else {
|
|
213
|
+
const password = patch.auth.password ?? "";
|
|
214
|
+
auth = {
|
|
215
|
+
kind: "password",
|
|
216
|
+
password: password !== "" ? password : current.auth.kind === "password" ? current.auth.password : ""
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
const merged = {
|
|
220
|
+
alias,
|
|
221
|
+
host: patch.host ?? current.host,
|
|
222
|
+
port: patch.port ?? current.port,
|
|
223
|
+
user: patch.user ?? current.user,
|
|
224
|
+
auth,
|
|
225
|
+
description: patch.description ?? current.description,
|
|
226
|
+
tags: patch.tags ?? current.tags
|
|
149
227
|
};
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
port: patch.port ?? current.port,
|
|
155
|
-
user: patch.user ?? current.user,
|
|
156
|
-
auth,
|
|
157
|
-
description: patch.description ?? current.description,
|
|
158
|
-
tags: patch.tags ?? current.tags
|
|
159
|
-
};
|
|
160
|
-
const next = this.normalize(merged, current);
|
|
161
|
-
const index = this.doc.hosts.findIndex((h) => h.alias === alias);
|
|
162
|
-
this.doc.hosts[index] = next;
|
|
163
|
-
this.save();
|
|
164
|
-
return next;
|
|
228
|
+
const next = this.normalize(merged, current);
|
|
229
|
+
this.doc.hosts[index] = next;
|
|
230
|
+
return next;
|
|
231
|
+
});
|
|
165
232
|
}
|
|
233
|
+
/**
|
|
234
|
+
* Delete one host AND its workspace bindings.
|
|
235
|
+
*
|
|
236
|
+
* The cascade has to keep the tombstone contract (see `removeWorkspace`): a
|
|
237
|
+
* binding that disappears while its alias dir stays on disk is no longer
|
|
238
|
+
* routed, but DSH's workspace registry still lists that dir, so a session
|
|
239
|
+
* rooted there would quietly execute LOCALLY against an empty folder instead
|
|
240
|
+
* of failing closed. Every cascaded binding is therefore tombstoned in the
|
|
241
|
+
* SAME atomic write as the removal — there is no on-disk state where the
|
|
242
|
+
* binding is gone but its tombstone is missing.
|
|
243
|
+
*/
|
|
166
244
|
remove(alias) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
245
|
+
return this.mutate(() => {
|
|
246
|
+
const hosts = this.doc.hosts.filter((h) => h.alias !== alias);
|
|
247
|
+
if (hosts.length === this.doc.hosts.length) return false;
|
|
248
|
+
this.doc.hosts = hosts;
|
|
249
|
+
for (const binding of this.doc.workspaces) if (binding.alias === alias) this.recordTombstone(join(aliasRoot(), binding.id));
|
|
250
|
+
this.doc.workspaces = this.doc.workspaces.filter((w) => w.alias !== alias);
|
|
251
|
+
return true;
|
|
252
|
+
});
|
|
173
253
|
}
|
|
174
254
|
normalize(payload, current) {
|
|
175
255
|
if (typeof payload.host !== "string" || payload.host.trim() === "") throw new Error("host must be a non-empty string");
|
|
@@ -227,10 +307,12 @@ var RemoteStore = class {
|
|
|
227
307
|
};
|
|
228
308
|
}
|
|
229
309
|
setDeploy(alias, state) {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
310
|
+
this.mutate(() => {
|
|
311
|
+
const entry = this.doc.hosts.find((h) => h.alias === alias);
|
|
312
|
+
if (entry === void 0) throw new Error(`unknown host alias: ${alias}`);
|
|
313
|
+
entry.deploy = state;
|
|
314
|
+
entry.updatedAt = Date.now();
|
|
315
|
+
});
|
|
234
316
|
}
|
|
235
317
|
listWorkspaces() {
|
|
236
318
|
this.reload();
|
|
@@ -238,33 +320,43 @@ var RemoteStore = class {
|
|
|
238
320
|
}
|
|
239
321
|
createWorkspace(payload) {
|
|
240
322
|
if (typeof payload.name !== "string" || payload.name.trim() === "") throw new Error("name must be a non-empty string");
|
|
241
|
-
this.require(payload.alias);
|
|
242
323
|
if (typeof payload.remotePath !== "string" || !payload.remotePath.startsWith("/")) throw new Error("remotePath must be an absolute POSIX path");
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
324
|
+
return this.mutate(() => {
|
|
325
|
+
if (!this.doc.hosts.some((host) => host.alias === payload.alias)) throw new Error(`unknown host alias: ${payload.alias}`);
|
|
326
|
+
const binding = {
|
|
327
|
+
id: randomUUID().slice(0, 8),
|
|
328
|
+
name: payload.name.trim(),
|
|
329
|
+
alias: payload.alias,
|
|
330
|
+
remotePath: payload.remotePath,
|
|
331
|
+
createdAt: Date.now()
|
|
332
|
+
};
|
|
333
|
+
this.doc.workspaces.push(binding);
|
|
334
|
+
return binding;
|
|
335
|
+
});
|
|
253
336
|
}
|
|
254
337
|
removeWorkspace(id) {
|
|
255
|
-
this.
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
338
|
+
return this.mutate(() => {
|
|
339
|
+
if (this.doc.workspaces.find((w) => w.id === id) === void 0) return false;
|
|
340
|
+
this.recordTombstone(join(aliasRoot(), id));
|
|
341
|
+
this.doc.workspaces = this.doc.workspaces.filter((w) => w.id !== id);
|
|
342
|
+
return true;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Record one tombstone without writing (idempotent).
|
|
347
|
+
*
|
|
348
|
+
* The caller owns `save()` so a change covering several bindings lands in ONE
|
|
349
|
+
* atomic write: a crash between two writes must never leave a binding removed
|
|
350
|
+
* while its tombstone is still missing.
|
|
351
|
+
*/
|
|
352
|
+
recordTombstone(aliasPath) {
|
|
353
|
+
if (!this.doc.tombstones.includes(aliasPath)) this.doc.tombstones.push(aliasPath);
|
|
261
354
|
}
|
|
262
355
|
/** Record a removed alias path (idempotent). */
|
|
263
356
|
addTombstone(aliasPath) {
|
|
264
|
-
|
|
265
|
-
this.
|
|
266
|
-
|
|
267
|
-
}
|
|
357
|
+
this.mutate(() => {
|
|
358
|
+
this.recordTombstone(aliasPath);
|
|
359
|
+
});
|
|
268
360
|
}
|
|
269
361
|
listTombstones() {
|
|
270
362
|
this.reload();
|
|
@@ -299,16 +391,37 @@ const READY_TIMEOUT_MS = (() => {
|
|
|
299
391
|
const raw = Number(process.env.DSH_REMOTE_VS_CONNECT_TIMEOUT_MS);
|
|
300
392
|
return Number.isFinite(raw) && raw >= 1e3 ? raw : 45e3;
|
|
301
393
|
})();
|
|
394
|
+
/**
|
|
395
|
+
* Extra wall clock on top of `READY_TIMEOUT_MS` for the dial's own watchdog.
|
|
396
|
+
*
|
|
397
|
+
* `readyTimeout` only covers "the socket stays open and the handshake stalls":
|
|
398
|
+
* ssh2 clears it as soon as the socket closes, and it only re-reports a close as
|
|
399
|
+
* an `error` when the SSH banner never arrived (client.js `onDone`). The shape
|
|
400
|
+
* left over is "no event at all", which used to leave the dial promise pending
|
|
401
|
+
* forever and the caller holding a channel slot. Override with
|
|
402
|
+
* DSH_REMOTE_VS_DIAL_GUARD_MS (milliseconds, >= 0); the dial gate keeps its case
|
|
403
|
+
* fast that way.
|
|
404
|
+
*/
|
|
405
|
+
const DIAL_GUARD_MARGIN_MS = (() => {
|
|
406
|
+
const raw = Number(process.env.DSH_REMOTE_VS_DIAL_GUARD_MS);
|
|
407
|
+
return Number.isFinite(raw) && raw >= 0 ? raw : 5e3;
|
|
408
|
+
})();
|
|
302
409
|
/** Per-stream output cap (stdout/stderr each); overflow truncates with a marker. */
|
|
303
410
|
const OUTPUT_CAP = 2 * 1024 * 1024;
|
|
304
411
|
/**
|
|
305
|
-
* Wall-clock cap for one SFTP callback body
|
|
306
|
-
* its own, so a server that never answers would hold
|
|
307
|
-
* pooled connection's hold count) open forever — the leak
|
|
308
|
-
* exhausts the server's channel budget. The timeout rejects so
|
|
309
|
-
* `finally` still ends the session and releases the connection.
|
|
412
|
+
* Wall-clock cap for one SFTP callback body (and for opening the session). SSH
|
|
413
|
+
* gives no request timeout of its own, so a server that never answers would hold
|
|
414
|
+
* the session (and the pooled connection's hold count) open forever — the leak
|
|
415
|
+
* that eventually exhausts the server's channel budget. The timeout rejects so
|
|
416
|
+
* the caller's `finally` still ends the session and releases the connection.
|
|
417
|
+
*
|
|
418
|
+
* Override with DSH_REMOTE_VS_SFTP_TIMEOUT_MS (milliseconds, >= 100) so the
|
|
419
|
+
* session-lifecycle gate can exercise the deadline without waiting a minute.
|
|
310
420
|
*/
|
|
311
|
-
const SFTP_OP_TIMEOUT_MS =
|
|
421
|
+
const SFTP_OP_TIMEOUT_MS = (() => {
|
|
422
|
+
const raw = Number(process.env.DSH_REMOTE_VS_SFTP_TIMEOUT_MS);
|
|
423
|
+
return Number.isFinite(raw) && raw >= 100 ? raw : 6e4;
|
|
424
|
+
})();
|
|
312
425
|
/**
|
|
313
426
|
* No-progress budget for a bulk upload. Deliberately an *idle* timeout rather
|
|
314
427
|
* than a wall clock: the point is to catch a stream that stopped moving, not
|
|
@@ -358,6 +471,21 @@ const CHANNEL_WAIT_MS = 3e4;
|
|
|
358
471
|
* is spelled out in withBrowseSftp's docstring.
|
|
359
472
|
*/
|
|
360
473
|
const BROWSE_IDLE_MS = 120 * 1e3;
|
|
474
|
+
/**
|
|
475
|
+
* Connection-level failures the status indicator must show.
|
|
476
|
+
*
|
|
477
|
+
* Deliberately about the TRANSPORT, not about the remote's answer: a missing
|
|
478
|
+
* file, a rejected password prompt or a non-zero git exit are all business
|
|
479
|
+
* outcomes and must not paint the host as disconnected. `timed out` is in here
|
|
480
|
+
* because a handshake/channel deadline means the link (or the server behind it)
|
|
481
|
+
* is not answering, which is exactly what the indicator is for.
|
|
482
|
+
*/
|
|
483
|
+
const CONNECTION_ERROR_RE = /not connected|no response from server|connection lost|connection closed|connection refused|socket hang up|channel open fail(?:ed|ure)|stalled|host .* was disconnected|timed out|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EHOSTDOWN|EPIPE/i;
|
|
484
|
+
/** Whether `error` is a transport-level failure worth showing as a link problem. */
|
|
485
|
+
function isConnectionFailure(error) {
|
|
486
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
487
|
+
return message !== "" && CONNECTION_ERROR_RE.test(message);
|
|
488
|
+
}
|
|
361
489
|
var RemotePool = class {
|
|
362
490
|
store;
|
|
363
491
|
conns = /* @__PURE__ */ new Map();
|
|
@@ -369,6 +497,8 @@ var RemotePool = class {
|
|
|
369
497
|
slots = /* @__PURE__ */ new Map();
|
|
370
498
|
/** Per-alias BROWSE SFTP session (see withBrowseSftp). */
|
|
371
499
|
browsed = /* @__PURE__ */ new Map();
|
|
500
|
+
/** Per-alias connection health for the browser's status chip (see status). */
|
|
501
|
+
health = /* @__PURE__ */ new Map();
|
|
372
502
|
constructor(store) {
|
|
373
503
|
this.store = store;
|
|
374
504
|
}
|
|
@@ -388,23 +518,118 @@ var RemotePool = class {
|
|
|
388
518
|
dispose() {
|
|
389
519
|
for (const alias of [...this.conns.keys()]) this.drop(alias);
|
|
390
520
|
}
|
|
391
|
-
/**
|
|
521
|
+
/**
|
|
522
|
+
* Forget one alias's connection HEALTH (host edited/removed), not just its
|
|
523
|
+
* connection.
|
|
524
|
+
*
|
|
525
|
+
* `drop` is also the idle eviction path, so it must keep the health record
|
|
526
|
+
* (idle-closed is not an error). Only a host mutation discards what the pool
|
|
527
|
+
* learned about that alias.
|
|
528
|
+
*/
|
|
529
|
+
forget(alias) {
|
|
530
|
+
this.drop(alias);
|
|
531
|
+
this.health.delete(alias);
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Per-alias connection health for the browser's status indicator.
|
|
535
|
+
*
|
|
536
|
+
* Read-only and dial-free: it reports what the pool already knows, so the
|
|
537
|
+
* indicator's poll never creates a connection as a side effect.
|
|
538
|
+
*/
|
|
539
|
+
status() {
|
|
540
|
+
const aliases = /* @__PURE__ */ new Set([...this.conns.keys(), ...this.health.keys()]);
|
|
541
|
+
try {
|
|
542
|
+
for (const host of this.store.list()) aliases.add(host.alias);
|
|
543
|
+
} catch {}
|
|
544
|
+
return [...aliases].sort().map((alias) => {
|
|
545
|
+
const entry = this.health.get(alias);
|
|
546
|
+
const pooled = this.conns.get(alias);
|
|
547
|
+
return {
|
|
548
|
+
alias,
|
|
549
|
+
state: entry?.state ?? "idle",
|
|
550
|
+
open: pooled !== void 0 && pooled.connecting === void 0,
|
|
551
|
+
...entry?.okAt === void 0 ? {} : { okAt: entry.okAt },
|
|
552
|
+
...entry?.errorAt === void 0 ? {} : { errorAt: entry.errorAt },
|
|
553
|
+
...entry?.error === void 0 ? {} : { error: entry.error }
|
|
554
|
+
};
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
/** Record a successful dial or transport-level operation. */
|
|
558
|
+
markOk(alias) {
|
|
559
|
+
this.health.set(alias, {
|
|
560
|
+
state: "ok",
|
|
561
|
+
okAt: Date.now()
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
/** Record a connection-level failure the status chip should show. */
|
|
565
|
+
markError(alias, error) {
|
|
566
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
567
|
+
this.health.set(alias, {
|
|
568
|
+
state: "error",
|
|
569
|
+
errorAt: Date.now(),
|
|
570
|
+
error: message
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Record one operation's failure, EXCEPT when the budget simply ran out.
|
|
575
|
+
*
|
|
576
|
+
* A deadline means "this request did not answer in time", not "the link is
|
|
577
|
+
* down": the connection can be perfectly healthy and merely slow (a huge
|
|
578
|
+
* directory, an 8 MiB read on a thin link, a cold filesystem). Painting the
|
|
579
|
+
* chip red used to flip the editor to read-only and block saving — a false
|
|
580
|
+
* alarm with a real cost. Real transport failures still arrive as transport
|
|
581
|
+
* errors (`close`, `No response from server`, a channel open failure), and
|
|
582
|
+
* those keep marking; the operation itself still fails either way.
|
|
583
|
+
*/
|
|
584
|
+
noteOpFailure(alias, error) {
|
|
585
|
+
if (error instanceof DeadlineError) return;
|
|
586
|
+
if (isConnectionFailure(error)) this.markError(alias, error);
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Probe one connection and record the outcome for the status indicator.
|
|
590
|
+
*
|
|
591
|
+
* "Test" must PROVE the link, not report that a pooled Client object exists:
|
|
592
|
+
* the old version answered ok without any traffic, so a retry against a
|
|
593
|
+
* half-open link painted the host green until the next real request failed.
|
|
594
|
+
*
|
|
595
|
+
* It must also NOT disturb the pool: this is what host settings' "test" and
|
|
596
|
+
* the chip's retry run, and the host being tested is often the one the user is
|
|
597
|
+
* working on (a terminal open, a transfer running). So a live connection gets
|
|
598
|
+
* a real round trip on itself (a trivial bare command under the control
|
|
599
|
+
* deadline), and only a COLD alias dials. Tearing the connection down instead
|
|
600
|
+
* would end every channel on it, including the terminal that the user opened
|
|
601
|
+
* to debug the flaky host.
|
|
602
|
+
*/
|
|
392
603
|
async test(alias) {
|
|
393
604
|
const started = Date.now();
|
|
605
|
+
const finish = (ok, error) => ({
|
|
606
|
+
ok,
|
|
607
|
+
...error === void 0 ? {} : { error },
|
|
608
|
+
durationMs: Date.now() - started
|
|
609
|
+
});
|
|
610
|
+
if (this.conns.has(alias)) try {
|
|
611
|
+
const probe = await this.exec(alias, "true", {
|
|
612
|
+
timeoutMs: CONTROL_TIMEOUT_MS,
|
|
613
|
+
bare: true
|
|
614
|
+
});
|
|
615
|
+
if (probe.success || probe.exitCode !== null) {
|
|
616
|
+
this.markOk(alias);
|
|
617
|
+
return finish(true);
|
|
618
|
+
}
|
|
619
|
+
if (probe.error !== void 0 && isConnectionFailure(probe.error)) this.markError(alias, probe.error);
|
|
620
|
+
return finish(false, probe.error ?? "the probe command did not complete");
|
|
621
|
+
} catch (error) {
|
|
622
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
623
|
+
if (isConnectionFailure(error)) this.markError(alias, error);
|
|
624
|
+
return finish(false, message);
|
|
625
|
+
}
|
|
394
626
|
try {
|
|
395
627
|
await this.acquire(alias);
|
|
396
|
-
this.
|
|
397
|
-
|
|
398
|
-
return {
|
|
399
|
-
ok: true,
|
|
400
|
-
durationMs: Date.now() - started
|
|
401
|
-
};
|
|
628
|
+
this.markOk(alias);
|
|
629
|
+
return finish(true);
|
|
402
630
|
} catch (error) {
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
error: error instanceof Error ? error.message : String(error),
|
|
406
|
-
durationMs: Date.now() - started
|
|
407
|
-
};
|
|
631
|
+
if (isConnectionFailure(error)) this.markError(alias, error);
|
|
632
|
+
return finish(false, error instanceof Error ? error.message : String(error));
|
|
408
633
|
}
|
|
409
634
|
}
|
|
410
635
|
/**
|
|
@@ -433,7 +658,10 @@ var RemotePool = class {
|
|
|
433
658
|
};
|
|
434
659
|
}
|
|
435
660
|
try {
|
|
436
|
-
|
|
661
|
+
const result = await this.runExec(alias, command, opts);
|
|
662
|
+
if (result.error !== void 0 && isConnectionFailure(result.error)) this.markError(alias, result.error);
|
|
663
|
+
else if (result.success || result.exitCode !== null) this.markOk(alias);
|
|
664
|
+
return result;
|
|
437
665
|
} finally {
|
|
438
666
|
this.releaseSlot(alias);
|
|
439
667
|
}
|
|
@@ -665,9 +893,11 @@ var RemotePool = class {
|
|
|
665
893
|
});
|
|
666
894
|
});
|
|
667
895
|
channel.once("close", () => this.release(alias));
|
|
896
|
+
this.markOk(alias);
|
|
668
897
|
return channel;
|
|
669
898
|
} catch (error) {
|
|
670
899
|
this.release(alias);
|
|
900
|
+
if (isConnectionFailure(error)) this.markError(alias, error);
|
|
671
901
|
throw error;
|
|
672
902
|
}
|
|
673
903
|
}
|
|
@@ -683,9 +913,11 @@ var RemotePool = class {
|
|
|
683
913
|
});
|
|
684
914
|
});
|
|
685
915
|
channel.once("close", () => this.release(alias));
|
|
916
|
+
this.markOk(alias);
|
|
686
917
|
return channel;
|
|
687
918
|
} catch (error) {
|
|
688
919
|
this.release(alias);
|
|
920
|
+
if (isConnectionFailure(error)) this.markError(alias, error);
|
|
689
921
|
throw error;
|
|
690
922
|
}
|
|
691
923
|
}
|
|
@@ -704,13 +936,17 @@ var RemotePool = class {
|
|
|
704
936
|
const sftp = await this.openSession(conn);
|
|
705
937
|
try {
|
|
706
938
|
const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
|
|
707
|
-
|
|
708
|
-
|
|
939
|
+
const result = limit <= 0 ? await fn(sftp) : await withDeadline(fn(sftp), limit, `SFTP operation timed out after ${limit / 1e3}s`);
|
|
940
|
+
this.markOk(alias);
|
|
941
|
+
return result;
|
|
709
942
|
} finally {
|
|
710
943
|
try {
|
|
711
944
|
sftp.end();
|
|
712
945
|
} catch {}
|
|
713
946
|
}
|
|
947
|
+
} catch (error) {
|
|
948
|
+
this.noteOpFailure(alias, error);
|
|
949
|
+
throw error;
|
|
714
950
|
} finally {
|
|
715
951
|
this.release(alias);
|
|
716
952
|
this.releaseSlot(alias);
|
|
@@ -776,7 +1012,12 @@ var RemotePool = class {
|
|
|
776
1012
|
return;
|
|
777
1013
|
}
|
|
778
1014
|
};
|
|
779
|
-
|
|
1015
|
+
const result = await fn(sessions[0], addChannel);
|
|
1016
|
+
this.markOk(alias);
|
|
1017
|
+
return result;
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
this.noteOpFailure(alias, error);
|
|
1020
|
+
throw error;
|
|
780
1021
|
} finally {
|
|
781
1022
|
closed = true;
|
|
782
1023
|
for (const session of sessions) try {
|
|
@@ -809,13 +1050,21 @@ var RemotePool = class {
|
|
|
809
1050
|
* bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
|
|
810
1051
|
*/
|
|
811
1052
|
async withBrowseSftp(alias, fn, opts = {}) {
|
|
812
|
-
|
|
1053
|
+
let lease;
|
|
1054
|
+
try {
|
|
1055
|
+
lease = await this.leaseBrowse(alias);
|
|
1056
|
+
} catch (error) {
|
|
1057
|
+
this.noteOpFailure(alias, error);
|
|
1058
|
+
throw error;
|
|
1059
|
+
}
|
|
813
1060
|
const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
|
|
814
1061
|
try {
|
|
815
|
-
|
|
816
|
-
|
|
1062
|
+
const result = limit <= 0 ? await fn(lease.sftp) : await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1e3}s`);
|
|
1063
|
+
this.markOk(alias);
|
|
1064
|
+
return result;
|
|
817
1065
|
} catch (error) {
|
|
818
1066
|
if (error instanceof DeadlineError) lease.state.stale = true;
|
|
1067
|
+
else this.noteOpFailure(alias, error);
|
|
819
1068
|
throw error;
|
|
820
1069
|
} finally {
|
|
821
1070
|
this.touchBrowse(alias, lease.state);
|
|
@@ -863,14 +1112,40 @@ var RemotePool = class {
|
|
|
863
1112
|
* ssh2 has no channel-open timeout: a server that never answers leaves this
|
|
864
1113
|
* promise pending forever, which pins the connection's hold count and blocks
|
|
865
1114
|
* idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
|
|
1115
|
+
*
|
|
1116
|
+
* The deadline is spelled out here instead of wrapped around the promise
|
|
1117
|
+
* because the ANSWER can arrive after it: `conn.sftp`'s callback is the only
|
|
1118
|
+
* place that can still see the session, and a late one would otherwise leak a
|
|
1119
|
+
* server-side channel that no slot or hold accounts for (the caller has long
|
|
1120
|
+
* returned its own and moved on).
|
|
866
1121
|
*/
|
|
867
1122
|
openSession(conn) {
|
|
868
|
-
return
|
|
869
|
-
|
|
1123
|
+
return new Promise((resolve, reject) => {
|
|
1124
|
+
let settled = false;
|
|
1125
|
+
const timer = setTimeout(() => {
|
|
1126
|
+
if (settled) return;
|
|
1127
|
+
settled = true;
|
|
1128
|
+
reject(new DeadlineError(`SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1e3}s`));
|
|
1129
|
+
}, SFTP_OP_TIMEOUT_MS);
|
|
1130
|
+
timer.unref?.();
|
|
1131
|
+
const finish = (error, session) => {
|
|
1132
|
+
if (settled) {
|
|
1133
|
+
try {
|
|
1134
|
+
session?.end();
|
|
1135
|
+
} catch {}
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
settled = true;
|
|
1139
|
+
clearTimeout(timer);
|
|
870
1140
|
if (error !== void 0 && error !== null) reject(error);
|
|
871
1141
|
else resolve(session);
|
|
872
|
-
}
|
|
873
|
-
|
|
1142
|
+
};
|
|
1143
|
+
try {
|
|
1144
|
+
conn.sftp((error, session) => finish(error, session));
|
|
1145
|
+
} catch (error) {
|
|
1146
|
+
finish(error);
|
|
1147
|
+
}
|
|
1148
|
+
});
|
|
874
1149
|
}
|
|
875
1150
|
/**
|
|
876
1151
|
* Take the browse channel for one operation (open it on first use).
|
|
@@ -1141,31 +1416,67 @@ var RemotePool = class {
|
|
|
1141
1416
|
held: 0
|
|
1142
1417
|
};
|
|
1143
1418
|
this.conns.set(alias, entry);
|
|
1419
|
+
/**
|
|
1420
|
+
* The entry object IS the ownership token: `drop()` deletes it and a later
|
|
1421
|
+
* `acquire()` creates a NEW one, so comparing identity answers "does this
|
|
1422
|
+
* dial still own the alias?" without any extra field.
|
|
1423
|
+
*
|
|
1424
|
+
* Both halves matter. Without the success check, a dial that finishes after
|
|
1425
|
+
* `drop()` (host edited/deleted while connecting) leaves a live connection
|
|
1426
|
+
* nobody can ever close: the entry is out of the map, `release()` is a no-op
|
|
1427
|
+
* so no idle timer arms, and `dispose()` only walks the map. Without the
|
|
1428
|
+
* failure check, a failed OLD dial deletes the NEW entry by alias.
|
|
1429
|
+
*/
|
|
1144
1430
|
entry.connecting = this.dial(alias).then((conn) => {
|
|
1431
|
+
if (this.conns.get(alias) !== entry) {
|
|
1432
|
+
try {
|
|
1433
|
+
conn.end();
|
|
1434
|
+
} catch {}
|
|
1435
|
+
throw new Error(`host ${alias} was disconnected while connecting`);
|
|
1436
|
+
}
|
|
1145
1437
|
entry.conn = conn;
|
|
1146
1438
|
entry.connecting = void 0;
|
|
1439
|
+
this.markOk(alias);
|
|
1147
1440
|
conn.on("close", () => {
|
|
1148
|
-
if (this.conns.get(alias)
|
|
1441
|
+
if (this.conns.get(alias) !== entry) return;
|
|
1442
|
+
this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
|
|
1443
|
+
this.drop(alias);
|
|
1149
1444
|
});
|
|
1150
|
-
conn.on("error", () => {
|
|
1151
|
-
if (this.conns.get(alias)
|
|
1445
|
+
conn.on("error", (error) => {
|
|
1446
|
+
if (this.conns.get(alias) !== entry) return;
|
|
1447
|
+
this.markError(alias, error);
|
|
1448
|
+
this.drop(alias);
|
|
1152
1449
|
});
|
|
1153
1450
|
this.release(alias);
|
|
1154
1451
|
return conn;
|
|
1155
1452
|
}, (error) => {
|
|
1156
|
-
this.conns.delete(alias);
|
|
1453
|
+
if (this.conns.get(alias) === entry) this.conns.delete(alias);
|
|
1454
|
+
this.markError(alias, error);
|
|
1157
1455
|
throw error;
|
|
1158
1456
|
});
|
|
1159
1457
|
return entry.connecting;
|
|
1160
1458
|
}
|
|
1459
|
+
/**
|
|
1460
|
+
* The ssh2 client factory.
|
|
1461
|
+
*
|
|
1462
|
+
* A seam, not a preference: `dial` is the only place that has to react to
|
|
1463
|
+
* "connect emitted close but never error", and a fake client is the only way a
|
|
1464
|
+
* self-check can produce that shape without a real server. Production never
|
|
1465
|
+
* overrides it.
|
|
1466
|
+
*/
|
|
1467
|
+
makeClient() {
|
|
1468
|
+
return new import_lib.Client();
|
|
1469
|
+
}
|
|
1161
1470
|
dial(alias) {
|
|
1162
1471
|
const host = this.store.require(alias);
|
|
1163
1472
|
return new Promise((resolve, reject) => {
|
|
1164
|
-
const conn =
|
|
1473
|
+
const conn = this.makeClient();
|
|
1165
1474
|
let settled = false;
|
|
1475
|
+
let guard;
|
|
1166
1476
|
const fail = (error) => {
|
|
1167
1477
|
if (settled) return;
|
|
1168
1478
|
settled = true;
|
|
1479
|
+
if (guard !== void 0) clearTimeout(guard);
|
|
1169
1480
|
try {
|
|
1170
1481
|
conn.end();
|
|
1171
1482
|
} catch {}
|
|
@@ -1174,9 +1485,22 @@ var RemotePool = class {
|
|
|
1174
1485
|
conn.on("ready", () => {
|
|
1175
1486
|
if (settled) return;
|
|
1176
1487
|
settled = true;
|
|
1488
|
+
if (guard !== void 0) clearTimeout(guard);
|
|
1177
1489
|
resolve(conn);
|
|
1178
1490
|
});
|
|
1179
1491
|
conn.on("error", (error) => fail(error));
|
|
1492
|
+
/**
|
|
1493
|
+
* ssh2 turns a socket close into an `error` only when the SSH banner never
|
|
1494
|
+
* arrived (client.js `onDone`: `wasConnected && !sawHeader`). A clean FIN
|
|
1495
|
+
* after the banner — a server restart or a middlebox dropping the flow
|
|
1496
|
+
* during KEX/auth — emits `end`/`close` and nothing else, which used to
|
|
1497
|
+
* leave this promise pending forever while the caller held a channel slot.
|
|
1498
|
+
*/
|
|
1499
|
+
conn.on("close", () => fail(/* @__PURE__ */ new Error("connection closed during SSH handshake")));
|
|
1500
|
+
guard = setTimeout(() => {
|
|
1501
|
+
fail(/* @__PURE__ */ new Error(`SSH handshake did not settle within ${(READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS) / 1e3}s`));
|
|
1502
|
+
}, READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS);
|
|
1503
|
+
guard.unref?.();
|
|
1180
1504
|
conn.on("keyboard-interactive", (_name, _instructions, _lang, prompts, finish) => {
|
|
1181
1505
|
const password = host.auth.kind === "password" ? host.auth.password : void 0;
|
|
1182
1506
|
if (password !== void 0 && prompts.length === 1 && prompts[0]?.echo === false) {
|
|
@@ -1302,14 +1626,6 @@ function warnDetached(alias) {
|
|
|
1302
1626
|
console.warn(`[dsh-remote-vs] exec timed out on ${alias}: the channel is closed but the remote command may still be running (no killable process group)`);
|
|
1303
1627
|
}
|
|
1304
1628
|
/**
|
|
1305
|
-
* An operation that ran out of its wall-clock budget.
|
|
1306
|
-
*
|
|
1307
|
-
* Tagged on purpose: callers have to tell "the remote never answered" from a real
|
|
1308
|
-
* remote failure (a missing path must not cost the session), and matching on the
|
|
1309
|
-
* message text would silently stop working the moment the template changed.
|
|
1310
|
-
*/
|
|
1311
|
-
var DeadlineError = class extends Error {};
|
|
1312
|
-
/**
|
|
1313
1629
|
* Reject when `promise` has not settled within `ms`, so a stalled remote
|
|
1314
1630
|
* callback cannot keep a session (and its pooled connection) alive forever.
|
|
1315
1631
|
*/
|
|
@@ -1333,31 +1649,61 @@ const JSON_HEADERS = {
|
|
|
1333
1649
|
"referrer-policy": "no-referrer"
|
|
1334
1650
|
};
|
|
1335
1651
|
/**
|
|
1336
|
-
*
|
|
1337
|
-
*
|
|
1652
|
+
* Extra bytes a too-large body may stream past its cap before the socket is
|
|
1653
|
+
* dropped. Draining the rest keeps the caller's error response readable; the
|
|
1654
|
+
* hard stop below refuses to read an unbounded body from a stuck/hostile client.
|
|
1655
|
+
*/
|
|
1656
|
+
const DRAIN_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
1657
|
+
/**
|
|
1658
|
+
* Bounded body reader with a truthful outcome.
|
|
1659
|
+
*
|
|
1660
|
+
* Oversize no longer destroys the request immediately: returning early from the
|
|
1661
|
+
* `for await` loop would tear the socket down, and the caller's 400/413 then
|
|
1662
|
+
* reaches the client as a connection reset (the reported A11 symptom). The body
|
|
1663
|
+
* is drained instead, up to `DRAIN_LIMIT_BYTES`, so the route can answer with a
|
|
1664
|
+
* readable JSON error; an absurd stream is still cut off with `destroy()`.
|
|
1338
1665
|
*/
|
|
1339
|
-
async function
|
|
1666
|
+
async function readJsonBodyResult(req, opts = {}) {
|
|
1340
1667
|
const maxBytes = opts.maxBytes ?? 64 * 1024;
|
|
1341
1668
|
const chunks = [];
|
|
1342
1669
|
let size = 0;
|
|
1670
|
+
let tooLarge = false;
|
|
1343
1671
|
for await (const chunk of req) {
|
|
1344
1672
|
const buffer = chunk;
|
|
1345
1673
|
size += buffer.length;
|
|
1346
|
-
if (size > maxBytes) {
|
|
1347
|
-
|
|
1348
|
-
|
|
1674
|
+
if (!tooLarge && size > maxBytes) {
|
|
1675
|
+
tooLarge = true;
|
|
1676
|
+
chunks.length = 0;
|
|
1677
|
+
}
|
|
1678
|
+
if (tooLarge) {
|
|
1679
|
+
if (size > maxBytes + DRAIN_LIMIT_BYTES) {
|
|
1680
|
+
req.destroy();
|
|
1681
|
+
return {
|
|
1682
|
+
kind: "too-large",
|
|
1683
|
+
maxBytes
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
continue;
|
|
1349
1687
|
}
|
|
1350
1688
|
chunks.push(buffer);
|
|
1351
1689
|
}
|
|
1690
|
+
if (tooLarge) return {
|
|
1691
|
+
kind: "too-large",
|
|
1692
|
+
maxBytes
|
|
1693
|
+
};
|
|
1352
1694
|
const text = Buffer.concat(chunks).toString("utf8");
|
|
1353
|
-
if (text === "") return
|
|
1695
|
+
if (text === "") return { kind: "empty" };
|
|
1696
|
+
let parsed;
|
|
1354
1697
|
try {
|
|
1355
|
-
|
|
1356
|
-
if (opts.objectOnly && !isJsonObject(parsed)) return null;
|
|
1357
|
-
return parsed;
|
|
1698
|
+
parsed = JSON.parse(text);
|
|
1358
1699
|
} catch {
|
|
1359
|
-
return
|
|
1700
|
+
return { kind: "invalid" };
|
|
1360
1701
|
}
|
|
1702
|
+
if (opts.objectOnly === true && !isJsonObject(parsed)) return { kind: "invalid" };
|
|
1703
|
+
return {
|
|
1704
|
+
kind: "ok",
|
|
1705
|
+
value: parsed
|
|
1706
|
+
};
|
|
1361
1707
|
}
|
|
1362
1708
|
function isJsonObject(value) {
|
|
1363
1709
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1370,6 +1716,21 @@ function writeJson(res, status, body, headers = {}) {
|
|
|
1370
1716
|
});
|
|
1371
1717
|
res.end(JSON.stringify(body));
|
|
1372
1718
|
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Write one failed-operation response, tagging a budget that merely ran out.
|
|
1721
|
+
*
|
|
1722
|
+
* `code: 'deadline'` is what lets the browser tell "this one request was too
|
|
1723
|
+
* slow" from "the link is down": the client keeps the status chip green and the
|
|
1724
|
+
* editor editable, while the operation still fails with a readable reason. Only
|
|
1725
|
+
* the error object carries that distinction — the message is prose, and matching
|
|
1726
|
+
* on prose stops working the moment the sentence changes.
|
|
1727
|
+
*/
|
|
1728
|
+
function writeRouteError(res, error) {
|
|
1729
|
+
writeJson(res, 502, {
|
|
1730
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1731
|
+
...error instanceof DeadlineError ? { code: "deadline" } : {}
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1373
1734
|
//#endregion
|
|
1374
1735
|
//#region src/loopback.ts
|
|
1375
1736
|
function isIPv4Loopback(v4) {
|
|
@@ -1418,6 +1779,8 @@ function isLoopbackRequest(request) {
|
|
|
1418
1779
|
const REMOTE_API = {
|
|
1419
1780
|
hosts: "/api/dsh-remote/hosts",
|
|
1420
1781
|
test: "/api/dsh-remote/test",
|
|
1782
|
+
/** Per-alias SSH connection health for the client's status indicator. */
|
|
1783
|
+
status: "/api/dsh-remote/status",
|
|
1421
1784
|
keygen: "/api/dsh-remote/keygen",
|
|
1422
1785
|
exec: "/api/dsh-remote/exec",
|
|
1423
1786
|
/** Streaming exec (server-sent events) for the long network verbs. */
|
|
@@ -1463,14 +1826,46 @@ function shQuote(value) {
|
|
|
1463
1826
|
* writes it to its own disk. Pure string builders (no fs, no exec) so the
|
|
1464
1827
|
* download gate can pin the exact command shape.
|
|
1465
1828
|
*/
|
|
1466
|
-
/**
|
|
1829
|
+
/**
|
|
1830
|
+
* Best-effort normal form of one remote path, shared by the guard, the command
|
|
1831
|
+
* and the download NAME.
|
|
1832
|
+
*
|
|
1833
|
+
* The name used to take its basename from the RAW string while the command
|
|
1834
|
+
* normalized: `/a/b/..` archived `/a` but was saved as `...tar.gz`. One
|
|
1835
|
+
* normalization for both is the only way the file name can be trusted to name
|
|
1836
|
+
* what is inside.
|
|
1837
|
+
*/
|
|
1838
|
+
function normalizeArchivePath(raw) {
|
|
1839
|
+
return posix.normalize(String(raw).replace(/\\/g, "/")).replace(/\/+$/, "");
|
|
1840
|
+
}
|
|
1841
|
+
/** Download file name for one archived directory (normalized like the command). */
|
|
1467
1842
|
function directoryArchiveName(dir) {
|
|
1468
|
-
const trimmed =
|
|
1469
|
-
const at =
|
|
1843
|
+
const trimmed = normalizeArchivePath(dir);
|
|
1844
|
+
const at = trimmed.lastIndexOf("/");
|
|
1470
1845
|
const base = at < 0 ? trimmed : trimmed.slice(at + 1);
|
|
1471
1846
|
return `${base === "" ? "root" : base}.tar.gz`;
|
|
1472
1847
|
}
|
|
1473
1848
|
/**
|
|
1849
|
+
* Normalize one remote path into the exact string the tar command will use.
|
|
1850
|
+
*
|
|
1851
|
+
* The normalization has to live HERE, not only in the caller: `files.stat()`
|
|
1852
|
+
* normalizes internally (`remotePath()`), so a raw `/..` passed the "is it a
|
|
1853
|
+
* directory" check and still reached the builder un-normalized — `-C '/' './..'`
|
|
1854
|
+
* then archived the whole remote root, which is exactly what the guard is
|
|
1855
|
+
* supposed to refuse. Guard and command therefore have to be derived from the
|
|
1856
|
+
* SAME value; a character-class check on the raw string cannot do it.
|
|
1857
|
+
*
|
|
1858
|
+
* `/a/b/..` → `/a`: climbing down to a real directory is a legitimate target,
|
|
1859
|
+
* only the root itself (and anything relative) is refused.
|
|
1860
|
+
*/
|
|
1861
|
+
function archivePath(raw) {
|
|
1862
|
+
const path = normalizeArchivePath(raw);
|
|
1863
|
+
if (path === "" || path === "/") throw new Error("refusing to archive the remote root");
|
|
1864
|
+
if (!path.startsWith("/")) throw new Error("remote path must be absolute");
|
|
1865
|
+
if (path.split("/").includes("..")) throw new Error("path must not contain ..");
|
|
1866
|
+
return path;
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1474
1869
|
* One POSIX shell command that writes the directory's gzip tar to stdout.
|
|
1475
1870
|
*
|
|
1476
1871
|
* The member name is prefixed with `./` so a directory whose name starts with
|
|
@@ -1479,9 +1874,7 @@ function directoryArchiveName(dir) {
|
|
|
1479
1874
|
* quotes and `$()` in a real path cannot escape into the command.
|
|
1480
1875
|
*/
|
|
1481
1876
|
function directoryArchiveCommand(dir) {
|
|
1482
|
-
const path =
|
|
1483
|
-
if (path === "" || path === "/") throw new Error("refusing to archive the remote root");
|
|
1484
|
-
if (!path.startsWith("/")) throw new Error("remote path must be absolute");
|
|
1877
|
+
const path = archivePath(dir);
|
|
1485
1878
|
const parent = posix.dirname(path);
|
|
1486
1879
|
const name = posix.basename(path);
|
|
1487
1880
|
return `tar -czf - -C ${shQuote(parent)} ${shQuote(`./${name}`)}`;
|
|
@@ -1501,9 +1894,7 @@ function selectionArchiveCommand(paths) {
|
|
|
1501
1894
|
if (paths.length > 100) throw new Error(`too many entries: ${paths.length} (max 100)`);
|
|
1502
1895
|
let command = "tar -czf -";
|
|
1503
1896
|
for (const raw of paths) {
|
|
1504
|
-
const path =
|
|
1505
|
-
if (path === "" || path === "/") throw new Error("refusing to archive the remote root");
|
|
1506
|
-
if (!path.startsWith("/")) throw new Error("remote path must be absolute");
|
|
1897
|
+
const path = archivePath(raw);
|
|
1507
1898
|
command += ` -C ${shQuote(posix.dirname(path))} ${shQuote(`./${posix.basename(path)}`)}`;
|
|
1508
1899
|
}
|
|
1509
1900
|
return command;
|
|
@@ -1596,6 +1987,18 @@ function expandHome(path) {
|
|
|
1596
1987
|
if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2));
|
|
1597
1988
|
return path;
|
|
1598
1989
|
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Parse one configured port (number, or a decimal string from older stores).
|
|
1992
|
+
*
|
|
1993
|
+
* `undefined` means absent (caller defaults to 22); `NaN`/out-of-range returns
|
|
1994
|
+
* `undefined` too, and callers turn that into an explicit skip — silently
|
|
1995
|
+
* importing an invalid port as 22 would connect to the wrong sshd (or none).
|
|
1996
|
+
*/
|
|
1997
|
+
function validPort(value) {
|
|
1998
|
+
const port = typeof value === "number" ? value : /^\d+$/.test(value) ? Number(value) : NaN;
|
|
1999
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
|
|
2000
|
+
return port;
|
|
2001
|
+
}
|
|
1599
2002
|
/** Parse OpenSSH client config text into host payloads. */
|
|
1600
2003
|
function parseSshConfig(text) {
|
|
1601
2004
|
const payloads = [];
|
|
@@ -1623,39 +2026,71 @@ function parseSshConfig(text) {
|
|
|
1623
2026
|
alias: "(match)",
|
|
1624
2027
|
reason: "Match conditional blocks are not imported"
|
|
1625
2028
|
});
|
|
1626
|
-
} else if (
|
|
2029
|
+
} else if (key === "include") skipped.push({
|
|
2030
|
+
alias: "(include)",
|
|
2031
|
+
reason: `Include ${value} is not expanded — import that file separately`
|
|
2032
|
+
});
|
|
2033
|
+
else if (current !== void 0 && !current.fields.has(key)) current.fields.set(key, value);
|
|
1627
2034
|
}
|
|
1628
2035
|
for (const block of blocks) {
|
|
1629
|
-
const
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
2036
|
+
const concrete = block.patterns.filter((pattern) => pattern !== "" && !/[*?!]/.test(pattern));
|
|
2037
|
+
const special = block.patterns.filter((pattern) => pattern !== "" && /[*?!]/.test(pattern));
|
|
2038
|
+
if (special.length > 0) skipped.push({
|
|
2039
|
+
alias: special.join(" "),
|
|
2040
|
+
reason: "wildcard/negation patterns are not imported"
|
|
2041
|
+
});
|
|
2042
|
+
if (concrete.length === 0) {
|
|
2043
|
+
if (special.length === 0) skipped.push({
|
|
2044
|
+
alias: "(empty)",
|
|
2045
|
+
reason: "Host line has no pattern"
|
|
1634
2046
|
});
|
|
1635
2047
|
continue;
|
|
1636
2048
|
}
|
|
1637
2049
|
if (block.fields.has("proxyjump") || block.fields.has("proxycommand")) {
|
|
1638
|
-
skipped.push({
|
|
2050
|
+
for (const alias of concrete) skipped.push({
|
|
1639
2051
|
alias,
|
|
1640
2052
|
reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
|
|
1641
2053
|
});
|
|
1642
2054
|
continue;
|
|
1643
2055
|
}
|
|
2056
|
+
const rawPort = block.fields.get("port");
|
|
2057
|
+
const port = rawPort === void 0 ? 22 : validPort(rawPort);
|
|
1644
2058
|
const identityFile = block.fields.get("identityfile")?.split(/\s+/)[0];
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
}
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
2059
|
+
const user = block.fields.get("user") ?? "";
|
|
2060
|
+
for (const alias of concrete) {
|
|
2061
|
+
if (port === void 0) {
|
|
2062
|
+
skipped.push({
|
|
2063
|
+
alias,
|
|
2064
|
+
reason: `invalid Port '${rawPort ?? ""}' (expected 1-65535)`
|
|
2065
|
+
});
|
|
2066
|
+
continue;
|
|
2067
|
+
}
|
|
2068
|
+
if (user === "") {
|
|
2069
|
+
skipped.push({
|
|
2070
|
+
alias,
|
|
2071
|
+
reason: "no User in ssh_config — set the login user after import"
|
|
2072
|
+
});
|
|
2073
|
+
continue;
|
|
2074
|
+
}
|
|
2075
|
+
if (identityFile === void 0) {
|
|
2076
|
+
skipped.push({
|
|
2077
|
+
alias,
|
|
2078
|
+
reason: "no IdentityFile in ssh_config — add the key or password after import"
|
|
2079
|
+
});
|
|
2080
|
+
continue;
|
|
2081
|
+
}
|
|
2082
|
+
payloads.push({
|
|
2083
|
+
alias,
|
|
2084
|
+
host: block.fields.get("hostname") ?? alias,
|
|
2085
|
+
port,
|
|
2086
|
+
user,
|
|
2087
|
+
auth: {
|
|
2088
|
+
kind: "key",
|
|
2089
|
+
keyPath: expandHome(identityFile)
|
|
2090
|
+
},
|
|
2091
|
+
tags: ["imported:ssh-config"]
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
1659
2094
|
}
|
|
1660
2095
|
return {
|
|
1661
2096
|
payloads,
|
|
@@ -1680,8 +2115,9 @@ function migrateDshSsh(home = dshHome()) {
|
|
|
1680
2115
|
const alias = typeof raw.alias === "string" ? raw.alias : "(unknown)";
|
|
1681
2116
|
const auth = raw.auth ?? {};
|
|
1682
2117
|
const kind = auth.kind;
|
|
1683
|
-
const proxyJump = raw.proxyJump
|
|
2118
|
+
const proxyJump = raw.proxyJump;
|
|
1684
2119
|
const proxyCommand = raw.proxyCommand;
|
|
2120
|
+
const hasProxy = Array.isArray(proxyJump) && proxyJump.length > 0 || typeof proxyJump === "string" && proxyJump !== "" || typeof proxyCommand === "string" && proxyCommand !== "";
|
|
1685
2121
|
if (kind !== "key" && kind !== "password") {
|
|
1686
2122
|
skipped.push({
|
|
1687
2123
|
alias,
|
|
@@ -1689,32 +2125,57 @@ function migrateDshSsh(home = dshHome()) {
|
|
|
1689
2125
|
});
|
|
1690
2126
|
continue;
|
|
1691
2127
|
}
|
|
1692
|
-
if (
|
|
2128
|
+
if (hasProxy) {
|
|
1693
2129
|
skipped.push({
|
|
1694
2130
|
alias,
|
|
1695
2131
|
reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
|
|
1696
2132
|
});
|
|
1697
2133
|
continue;
|
|
1698
2134
|
}
|
|
1699
|
-
if (kind === "key" && typeof auth.keyPath !== "string") {
|
|
2135
|
+
if (kind === "key" && (typeof auth.keyPath !== "string" || auth.keyPath.trim() === "")) {
|
|
1700
2136
|
skipped.push({
|
|
1701
2137
|
alias,
|
|
1702
2138
|
reason: "key auth without keyPath"
|
|
1703
2139
|
});
|
|
1704
2140
|
continue;
|
|
1705
2141
|
}
|
|
1706
|
-
if (kind === "password" && typeof auth.password !== "string") {
|
|
2142
|
+
if (kind === "password" && (typeof auth.password !== "string" || auth.password === "")) {
|
|
1707
2143
|
skipped.push({
|
|
1708
2144
|
alias,
|
|
1709
2145
|
reason: "password auth without stored password (enter it manually)"
|
|
1710
2146
|
});
|
|
1711
2147
|
continue;
|
|
1712
2148
|
}
|
|
2149
|
+
const host = typeof raw.host === "string" ? raw.host : "";
|
|
2150
|
+
const user = typeof raw.user === "string" ? raw.user : "";
|
|
2151
|
+
const rawPort = raw.port;
|
|
2152
|
+
const port = rawPort === void 0 ? 22 : validPort(rawPort);
|
|
2153
|
+
if (host === "") {
|
|
2154
|
+
skipped.push({
|
|
2155
|
+
alias,
|
|
2156
|
+
reason: "no host address — enter it manually after import"
|
|
2157
|
+
});
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
if (user === "") {
|
|
2161
|
+
skipped.push({
|
|
2162
|
+
alias,
|
|
2163
|
+
reason: "no login user — enter it manually after import"
|
|
2164
|
+
});
|
|
2165
|
+
continue;
|
|
2166
|
+
}
|
|
2167
|
+
if (port === void 0) {
|
|
2168
|
+
skipped.push({
|
|
2169
|
+
alias,
|
|
2170
|
+
reason: `invalid port '${String(rawPort)}' (expected 1-65535)`
|
|
2171
|
+
});
|
|
2172
|
+
continue;
|
|
2173
|
+
}
|
|
1713
2174
|
payloads.push({
|
|
1714
2175
|
alias,
|
|
1715
|
-
host
|
|
1716
|
-
port
|
|
1717
|
-
user
|
|
2176
|
+
host,
|
|
2177
|
+
port,
|
|
2178
|
+
user,
|
|
1718
2179
|
auth: kind === "key" ? {
|
|
1719
2180
|
kind: "key",
|
|
1720
2181
|
keyPath: auth.keyPath,
|
|
@@ -1777,6 +2238,13 @@ const OUT_LOW_WATER = 1 * 1024 * 1024;
|
|
|
1777
2238
|
* process that also runs the agent.
|
|
1778
2239
|
*/
|
|
1779
2240
|
const TERMINAL_MAX_FRAME_BYTES = 1024 * 1024;
|
|
2241
|
+
/**
|
|
2242
|
+
* `WebSocket.OPEN` (RFC 6455 readyState 1).
|
|
2243
|
+
*
|
|
2244
|
+
* Used to detect a socket that closed while a shell was still being opened: the
|
|
2245
|
+
* library never replays a `close` event to a listener attached afterwards.
|
|
2246
|
+
*/
|
|
2247
|
+
const WS_OPEN = 1;
|
|
1780
2248
|
var TerminalSessionRegistry = class {
|
|
1781
2249
|
pool;
|
|
1782
2250
|
sessions = /* @__PURE__ */ new Map();
|
|
@@ -1811,24 +2279,32 @@ var TerminalSessionRegistry = class {
|
|
|
1811
2279
|
sockets: /* @__PURE__ */ new Set(),
|
|
1812
2280
|
pending: 0,
|
|
1813
2281
|
paused: false,
|
|
1814
|
-
reap: void 0
|
|
2282
|
+
reap: void 0,
|
|
2283
|
+
outDecoder: new StringDecoder("utf8"),
|
|
2284
|
+
errDecoder: new StringDecoder("utf8")
|
|
1815
2285
|
};
|
|
1816
2286
|
this.sessions.set(id, session);
|
|
1817
2287
|
channel.on("data", (chunk) => {
|
|
1818
|
-
|
|
2288
|
+
const text = session.outDecoder.write(chunk);
|
|
2289
|
+
if (text !== "") this.broadcast(session, {
|
|
1819
2290
|
t: "out",
|
|
1820
|
-
d:
|
|
2291
|
+
d: text
|
|
1821
2292
|
});
|
|
1822
2293
|
});
|
|
1823
2294
|
channel.stderr.on("data", (chunk) => {
|
|
1824
|
-
|
|
2295
|
+
const text = session.errDecoder.write(chunk);
|
|
2296
|
+
if (text !== "") this.broadcast(session, {
|
|
1825
2297
|
t: "out",
|
|
1826
|
-
d:
|
|
2298
|
+
d: text
|
|
1827
2299
|
});
|
|
1828
2300
|
});
|
|
1829
2301
|
channel.on("close", (code) => {
|
|
1830
2302
|
session.alive = false;
|
|
1831
2303
|
session.exitCode = code;
|
|
2304
|
+
for (const tail of [session.outDecoder.end(), session.errDecoder.end()]) if (tail !== "") this.broadcast(session, {
|
|
2305
|
+
t: "out",
|
|
2306
|
+
d: tail
|
|
2307
|
+
});
|
|
1832
2308
|
this.broadcast(session, {
|
|
1833
2309
|
t: "exit",
|
|
1834
2310
|
code
|
|
@@ -1927,6 +2403,16 @@ var TerminalSessionRegistry = class {
|
|
|
1927
2403
|
};
|
|
1928
2404
|
ws.on("close", detach);
|
|
1929
2405
|
ws.on("error", detach);
|
|
2406
|
+
/**
|
|
2407
|
+
* The socket may have closed while `pool.shell()` was still dialing: a cold
|
|
2408
|
+
* connection takes seconds, and a page reload (or a closed tab) during it
|
|
2409
|
+
* happens well before those listeners exist. EventEmitter does not replay
|
|
2410
|
+
* events, so without this the socket would sit in `sockets` forever, no
|
|
2411
|
+
* detach would ever run, no reap would ever arm — and the session, its PTY
|
|
2412
|
+
* and the pooled connection's hold would leak for the life of the process.
|
|
2413
|
+
* `readyState` is the only way to observe "already gone" from here.
|
|
2414
|
+
*/
|
|
2415
|
+
if (ws.readyState !== WS_OPEN) detach();
|
|
1930
2416
|
}
|
|
1931
2417
|
/** Keep the shell for a while (reload can reattach), then close it for good. */
|
|
1932
2418
|
armReap(session) {
|
|
@@ -1979,75 +2465,107 @@ var TerminalSessionRegistry = class {
|
|
|
1979
2465
|
}
|
|
1980
2466
|
};
|
|
1981
2467
|
//#endregion
|
|
1982
|
-
//#region src/
|
|
1983
|
-
/**
|
|
1984
|
-
const
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
const MAX_TIMEOUT_MS = 18e5;
|
|
2468
|
+
//#region src/routes.ts
|
|
2469
|
+
/** One noServer WebSocket server for terminal upgrades (RFC 6455). */
|
|
2470
|
+
const terminalWss = new WebSocketServer({
|
|
2471
|
+
noServer: true,
|
|
2472
|
+
maxPayload: TERMINAL_MAX_FRAME_BYTES
|
|
2473
|
+
});
|
|
2474
|
+
function queryParam(url, name) {
|
|
2475
|
+
const value = url.searchParams.get(name);
|
|
2476
|
+
return value === null ? void 0 : value;
|
|
2477
|
+
}
|
|
1993
2478
|
/**
|
|
1994
|
-
*
|
|
2479
|
+
* A caller mistake the route can name: well-formed HTTP, unusable payload.
|
|
1995
2480
|
*
|
|
1996
|
-
*
|
|
1997
|
-
*
|
|
1998
|
-
*
|
|
1999
|
-
* plausible cold index walk.
|
|
2481
|
+
* `/files` used to throw plain Errors for missing fields and map EVERY failure
|
|
2482
|
+
* to 502, so "your request had no path" was reported as "the remote host
|
|
2483
|
+
* failed". The class keeps that distinction at the HTTP status.
|
|
2000
2484
|
*/
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
gitMs: DEFAULT_GIT_TIMEOUT_MS,
|
|
2007
|
-
readMs: DEFAULT_READ_TIMEOUT_MS
|
|
2485
|
+
var BadRequestError = class extends Error {
|
|
2486
|
+
constructor(message) {
|
|
2487
|
+
super(message);
|
|
2488
|
+
this.name = "BadRequestError";
|
|
2489
|
+
}
|
|
2008
2490
|
};
|
|
2009
2491
|
/**
|
|
2010
|
-
*
|
|
2492
|
+
* Reject an oversized JSON body BEFORE reading it.
|
|
2011
2493
|
*
|
|
2012
|
-
*
|
|
2013
|
-
*
|
|
2014
|
-
*
|
|
2494
|
+
* A known Content-Length lets the route answer 413 without draining the body at
|
|
2495
|
+
* all (the GUI always sends one). A chunked body without the header is caught by
|
|
2496
|
+
* `readJsonBodyResult` after the read and answered with the same 413, so this
|
|
2497
|
+
* preflight is only the cheap path — not the only one.
|
|
2015
2498
|
*/
|
|
2016
|
-
function
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2499
|
+
function bodyTooLarge(req, maxBytes) {
|
|
2500
|
+
const raw = req.headers["content-length"];
|
|
2501
|
+
if (typeof raw !== "string") return false;
|
|
2502
|
+
const length = Number(raw);
|
|
2503
|
+
return Number.isFinite(length) && length > maxBytes;
|
|
2504
|
+
}
|
|
2505
|
+
/** Answer 413 and drain the rest of the body so the socket is not reset mid-response. */
|
|
2506
|
+
function writePayloadTooLarge(req, res, maxBytes) {
|
|
2507
|
+
writeJson(res, 413, { error: `request body exceeds ${maxBytes} bytes` }, { connection: "close" });
|
|
2508
|
+
req.resume();
|
|
2022
2509
|
}
|
|
2023
2510
|
/**
|
|
2024
|
-
*
|
|
2025
|
-
*
|
|
2511
|
+
* Read one JSON request body, answering the outcomes every route shares the same
|
|
2512
|
+
* way: an oversized body is a 413 (the connection closes), malformed JSON is a
|
|
2513
|
+
* 400. `{ ok: false }` means a response was already written — the handler returns.
|
|
2026
2514
|
*
|
|
2027
|
-
*
|
|
2028
|
-
*
|
|
2515
|
+
* An EMPTY body still arrives as `null`, so each route keeps its own "missing
|
|
2516
|
+
* object" answer, and `objectOnly` is passed through unchanged.
|
|
2029
2517
|
*/
|
|
2030
|
-
function
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
}
|
|
2034
|
-
|
|
2035
|
-
|
|
2518
|
+
async function readBodyOrError(req, res, opts = {}) {
|
|
2519
|
+
const result = await readJsonBodyResult(req, opts);
|
|
2520
|
+
if (result.kind === "too-large") {
|
|
2521
|
+
writeJson(res, 413, { error: `request body exceeds ${result.maxBytes} bytes` }, { connection: "close" });
|
|
2522
|
+
return { ok: false };
|
|
2523
|
+
}
|
|
2524
|
+
if (result.kind === "invalid") {
|
|
2525
|
+
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2526
|
+
return { ok: false };
|
|
2527
|
+
}
|
|
2036
2528
|
return {
|
|
2037
|
-
|
|
2038
|
-
|
|
2529
|
+
ok: true,
|
|
2530
|
+
body: result.kind === "ok" ? result.value : null
|
|
2039
2531
|
};
|
|
2040
2532
|
}
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
/**
|
|
2044
|
-
const
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2533
|
+
/** Body cap of the /files route (base64/UTF-8 file content). */
|
|
2534
|
+
const FILES_BODY_LIMIT = 10 * 1024 * 1024;
|
|
2535
|
+
/** Body cap of the ssh_config import route (pasted config text). */
|
|
2536
|
+
const SSH_CONFIG_BODY_LIMIT = 1024 * 1024;
|
|
2537
|
+
/**
|
|
2538
|
+
* Total budget for one archive stream (directory or multi-selection download).
|
|
2539
|
+
*
|
|
2540
|
+
* A hung remote `tar` (a stalled mount, a failing disk, a huge tree) otherwise
|
|
2541
|
+
* pins the Host channel until the CLIENT disconnects, and `channel.close()`
|
|
2542
|
+
* alone cannot stop a tar that is blocked on a read. Enforced on the remote side
|
|
2543
|
+
* so it survives a dead HTTP socket too.
|
|
2544
|
+
*/
|
|
2545
|
+
const ARCHIVE_TIMEOUT_SECONDS = 600;
|
|
2546
|
+
/**
|
|
2547
|
+
* Wrap one archive command in a remote-side deadline.
|
|
2548
|
+
*
|
|
2549
|
+
* The command is a single `tar` invocation with already-quoted operands
|
|
2550
|
+
* (`archive.ts` builders), so prefixing is syntactically safe and makes tar the
|
|
2551
|
+
* direct child of `timeout` — TERM (then KILL after 3 s) reaches tar itself, no
|
|
2552
|
+
* process-group id is needed (2026-10 audit, A16-1). Hosts without GNU `timeout`
|
|
2553
|
+
* (BSD/macOS) fall back to today's behaviour instead of failing the download.
|
|
2554
|
+
*/
|
|
2555
|
+
function archiveCommandWithDeadline(command) {
|
|
2556
|
+
return `if command -v timeout >/dev/null 2>&1; then timeout -k 3 ${ARCHIVE_TIMEOUT_SECONDS} ${command}; else ${command}; fi`;
|
|
2557
|
+
}
|
|
2558
|
+
/**
|
|
2559
|
+
* Error for a failed archive stream.
|
|
2560
|
+
*
|
|
2561
|
+
* GNU `timeout` reports 124 when TERM sufficed and 137 when KILL was needed;
|
|
2562
|
+
* both mean "the remote budget ran out", which is more actionable than
|
|
2563
|
+
* `tar failed (124): no stderr`.
|
|
2564
|
+
*/
|
|
2565
|
+
function archiveFailureMessage(exitCode, stderr) {
|
|
2566
|
+
if (exitCode === 124 || exitCode === 137) return /* @__PURE__ */ new Error(`archive timed out after ${ARCHIVE_TIMEOUT_SECONDS}s`);
|
|
2567
|
+
const detail = stderr.trim() === "" ? "no stderr" : stderr.trim().slice(0, 400);
|
|
2568
|
+
return /* @__PURE__ */ new Error(`tar failed (${exitCode === null || exitCode === void 0 ? "signal" : exitCode}): ${detail}`);
|
|
2051
2569
|
}
|
|
2052
2570
|
/** This plugin's version from the shipped package.json (Settings display). */
|
|
2053
2571
|
let cachedVersion;
|
|
@@ -2134,9 +2652,9 @@ function makeRoutes(deps) {
|
|
|
2134
2652
|
const streamArchive = async (alias, command, res, downloadName) => {
|
|
2135
2653
|
let channel;
|
|
2136
2654
|
try {
|
|
2137
|
-
channel = await pool.execChannel(alias, command);
|
|
2655
|
+
channel = await pool.execChannel(alias, archiveCommandWithDeadline(command));
|
|
2138
2656
|
} catch (error) {
|
|
2139
|
-
|
|
2657
|
+
writeRouteError(res, error);
|
|
2140
2658
|
return;
|
|
2141
2659
|
}
|
|
2142
2660
|
res.writeHead(200, {
|
|
@@ -2145,6 +2663,7 @@ function makeRoutes(deps) {
|
|
|
2145
2663
|
"cache-control": "no-store",
|
|
2146
2664
|
"x-content-type-options": "nosniff"
|
|
2147
2665
|
});
|
|
2666
|
+
res.flushHeaders();
|
|
2148
2667
|
let closed = false;
|
|
2149
2668
|
/** `undefined` until the remote process reports one. */
|
|
2150
2669
|
let exitCode;
|
|
@@ -2187,8 +2706,7 @@ function makeRoutes(deps) {
|
|
|
2187
2706
|
channel.on("close", () => {
|
|
2188
2707
|
if (closed) return;
|
|
2189
2708
|
if (exitCode !== 0) {
|
|
2190
|
-
|
|
2191
|
-
stop(/* @__PURE__ */ new Error(`tar failed (${exitCode === null ? "signal" : exitCode}): ${detail}`));
|
|
2709
|
+
stop(archiveFailureMessage(exitCode, stderr));
|
|
2192
2710
|
return;
|
|
2193
2711
|
}
|
|
2194
2712
|
stop();
|
|
@@ -2239,7 +2757,9 @@ function makeRoutes(deps) {
|
|
|
2239
2757
|
return;
|
|
2240
2758
|
}
|
|
2241
2759
|
if (method === "POST") {
|
|
2242
|
-
const
|
|
2760
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2761
|
+
if (!read.ok) return;
|
|
2762
|
+
const body = read.body;
|
|
2243
2763
|
if (body === null) {
|
|
2244
2764
|
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2245
2765
|
return;
|
|
@@ -2262,7 +2782,7 @@ function makeRoutes(deps) {
|
|
|
2262
2782
|
return;
|
|
2263
2783
|
}
|
|
2264
2784
|
if (method === "DELETE") {
|
|
2265
|
-
pool.
|
|
2785
|
+
pool.forget(alias);
|
|
2266
2786
|
worlds.dropHost(alias).catch(() => void 0);
|
|
2267
2787
|
if (!store.remove(alias)) {
|
|
2268
2788
|
writeJson(res, 404, { error: `unknown host alias: ${alias}` });
|
|
@@ -2272,13 +2792,15 @@ function makeRoutes(deps) {
|
|
|
2272
2792
|
writeJson(res, 200, { ok: true });
|
|
2273
2793
|
return;
|
|
2274
2794
|
}
|
|
2275
|
-
const
|
|
2795
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2796
|
+
if (!read.ok) return;
|
|
2797
|
+
const body = read.body;
|
|
2276
2798
|
if (body === null) {
|
|
2277
2799
|
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2278
2800
|
return;
|
|
2279
2801
|
}
|
|
2280
2802
|
try {
|
|
2281
|
-
pool.
|
|
2803
|
+
pool.forget(alias);
|
|
2282
2804
|
worlds.dropHost(alias).catch(() => void 0);
|
|
2283
2805
|
const entry = store.update(alias, body);
|
|
2284
2806
|
writeJson(res, 200, { host: store.summarize(entry) });
|
|
@@ -2287,6 +2809,21 @@ function makeRoutes(deps) {
|
|
|
2287
2809
|
}
|
|
2288
2810
|
}
|
|
2289
2811
|
},
|
|
2812
|
+
{
|
|
2813
|
+
kind: "exact",
|
|
2814
|
+
path: REMOTE_API.status,
|
|
2815
|
+
handler: (req, res) => {
|
|
2816
|
+
if (!isLoopbackRequest(req)) {
|
|
2817
|
+
writeJson(res, 403, { error: "forbidden: loopback-only" });
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
if (req.method !== "GET") {
|
|
2821
|
+
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2822
|
+
return;
|
|
2823
|
+
}
|
|
2824
|
+
writeJson(res, 200, { connections: pool.status() });
|
|
2825
|
+
}
|
|
2826
|
+
},
|
|
2290
2827
|
{
|
|
2291
2828
|
kind: "exact",
|
|
2292
2829
|
path: REMOTE_API.test,
|
|
@@ -2299,7 +2836,9 @@ function makeRoutes(deps) {
|
|
|
2299
2836
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2300
2837
|
return;
|
|
2301
2838
|
}
|
|
2302
|
-
const
|
|
2839
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2840
|
+
if (!read.ok) return;
|
|
2841
|
+
const body = read.body;
|
|
2303
2842
|
if (body === null || typeof body.alias !== "string") {
|
|
2304
2843
|
writeJson(res, 400, { error: "alias is required" });
|
|
2305
2844
|
return;
|
|
@@ -2319,7 +2858,9 @@ function makeRoutes(deps) {
|
|
|
2319
2858
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2320
2859
|
return;
|
|
2321
2860
|
}
|
|
2322
|
-
const
|
|
2861
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2862
|
+
if (!read.ok) return;
|
|
2863
|
+
const body = read.body;
|
|
2323
2864
|
if (body === null || typeof body.alias !== "string") {
|
|
2324
2865
|
writeJson(res, 400, { error: "alias is required" });
|
|
2325
2866
|
return;
|
|
@@ -2327,7 +2868,8 @@ function makeRoutes(deps) {
|
|
|
2327
2868
|
try {
|
|
2328
2869
|
writeJson(res, 200, await bootstrap(pool, store, body.alias));
|
|
2329
2870
|
} catch (error) {
|
|
2330
|
-
|
|
2871
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2872
|
+
writeJson(res, message.startsWith("unknown host alias") ? 404 : 502, { error: message });
|
|
2331
2873
|
}
|
|
2332
2874
|
}
|
|
2333
2875
|
},
|
|
@@ -2343,7 +2885,9 @@ function makeRoutes(deps) {
|
|
|
2343
2885
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2344
2886
|
return;
|
|
2345
2887
|
}
|
|
2346
|
-
const
|
|
2888
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2889
|
+
if (!read.ok) return;
|
|
2890
|
+
const body = read.body;
|
|
2347
2891
|
if (body === null || typeof body.alias !== "string" || typeof body.command !== "string" || body.command === "") {
|
|
2348
2892
|
writeJson(res, 400, { error: "alias and a non-empty command are required" });
|
|
2349
2893
|
return;
|
|
@@ -2364,7 +2908,9 @@ function makeRoutes(deps) {
|
|
|
2364
2908
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2365
2909
|
return;
|
|
2366
2910
|
}
|
|
2367
|
-
const
|
|
2911
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
2912
|
+
if (!read.ok) return;
|
|
2913
|
+
const body = read.body;
|
|
2368
2914
|
if (body === null || typeof body.alias !== "string" || typeof body.command !== "string" || body.command === "") {
|
|
2369
2915
|
writeJson(res, 400, { error: "alias and a non-empty command are required" });
|
|
2370
2916
|
return;
|
|
@@ -2376,6 +2922,7 @@ function makeRoutes(deps) {
|
|
|
2376
2922
|
Connection: "keep-alive",
|
|
2377
2923
|
"X-Accel-Buffering": "no"
|
|
2378
2924
|
});
|
|
2925
|
+
res.flushHeaders();
|
|
2379
2926
|
/** No more events to the client (finished, or the socket broke). */
|
|
2380
2927
|
let outputClosed = false;
|
|
2381
2928
|
/** `res.end` already called. */
|
|
@@ -2488,10 +3035,16 @@ function makeRoutes(deps) {
|
|
|
2488
3035
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2489
3036
|
return;
|
|
2490
3037
|
}
|
|
2491
|
-
|
|
3038
|
+
if (bodyTooLarge(req, FILES_BODY_LIMIT)) {
|
|
3039
|
+
writePayloadTooLarge(req, res, FILES_BODY_LIMIT);
|
|
3040
|
+
return;
|
|
3041
|
+
}
|
|
3042
|
+
const read = await readBodyOrError(req, res, {
|
|
2492
3043
|
objectOnly: true,
|
|
2493
|
-
maxBytes:
|
|
3044
|
+
maxBytes: FILES_BODY_LIMIT
|
|
2494
3045
|
});
|
|
3046
|
+
if (!read.ok) return;
|
|
3047
|
+
const body = read.body;
|
|
2495
3048
|
if (body === null || typeof body.op !== "string" || typeof body.alias !== "string") {
|
|
2496
3049
|
writeJson(res, 400, { error: "op and alias are required" });
|
|
2497
3050
|
return;
|
|
@@ -2500,42 +3053,81 @@ function makeRoutes(deps) {
|
|
|
2500
3053
|
try {
|
|
2501
3054
|
switch (body.op) {
|
|
2502
3055
|
case "list":
|
|
2503
|
-
if (typeof body.path !== "string") throw new
|
|
3056
|
+
if (typeof body.path !== "string") throw new BadRequestError("path is required");
|
|
2504
3057
|
writeJson(res, 200, { entries: await files.list(alias, body.path) });
|
|
2505
3058
|
return;
|
|
2506
3059
|
case "stat":
|
|
2507
|
-
if (typeof body.path !== "string") throw new
|
|
3060
|
+
if (typeof body.path !== "string") throw new BadRequestError("path is required");
|
|
2508
3061
|
writeJson(res, 200, { entry: await files.stat(alias, body.path) });
|
|
2509
3062
|
return;
|
|
2510
3063
|
case "read":
|
|
2511
|
-
if (typeof body.path !== "string") throw new
|
|
3064
|
+
if (typeof body.path !== "string") throw new BadRequestError("path is required");
|
|
2512
3065
|
writeJson(res, 200, await files.read(alias, body.path));
|
|
2513
3066
|
return;
|
|
2514
3067
|
case "write": {
|
|
2515
|
-
if (typeof body.path !== "string" || typeof body.content !== "string") throw new
|
|
3068
|
+
if (typeof body.path !== "string" || typeof body.content !== "string") throw new BadRequestError("path and content are required");
|
|
2516
3069
|
const encoding = body.encoding === "base64" ? "base64" : "utf8";
|
|
2517
|
-
|
|
3070
|
+
/**
|
|
3071
|
+
* Optional optimistic lock. `expectMtime` is the version the client
|
|
3072
|
+
* loaded; when present the Host refuses a file that changed since.
|
|
3073
|
+
* Requests without it (helpers, deploy, the agent's write tool)
|
|
3074
|
+
* keep the old unconditional semantics — the guard protects a
|
|
3075
|
+
* human's buffer, it must not make programmatic writes fail.
|
|
3076
|
+
*/
|
|
3077
|
+
const expectMtime = body.expectMtime;
|
|
3078
|
+
const expectSize = body.expectSize;
|
|
3079
|
+
/**
|
|
3080
|
+
* A malformed baseline is a CALLER mistake, not "no baseline".
|
|
3081
|
+
*
|
|
3082
|
+
* Silently dropping it would turn `{expectMtime: "123"}` (a client
|
|
3083
|
+
* bug, a serializer change) into an UNGUARDED write — the exact
|
|
3084
|
+
* overwrite the caller was asking to be protected from, reported as
|
|
3085
|
+
* a success.
|
|
3086
|
+
*/
|
|
3087
|
+
if (expectMtime !== void 0 && (typeof expectMtime !== "number" || !Number.isFinite(expectMtime))) throw new BadRequestError("expectMtime must be a finite number");
|
|
3088
|
+
if (expectSize !== void 0 && (typeof expectSize !== "number" || !Number.isFinite(expectSize))) throw new BadRequestError("expectSize must be a finite number");
|
|
3089
|
+
const guard = typeof expectMtime === "number" ? {
|
|
3090
|
+
expectMtime,
|
|
3091
|
+
...typeof expectSize === "number" ? { expectSize } : {}
|
|
3092
|
+
} : void 0;
|
|
3093
|
+
writeJson(res, 200, await files.write(alias, body.path, body.content, encoding, guard));
|
|
2518
3094
|
return;
|
|
2519
3095
|
}
|
|
2520
3096
|
case "mkdir":
|
|
2521
|
-
if (typeof body.path !== "string") throw new
|
|
3097
|
+
if (typeof body.path !== "string") throw new BadRequestError("path is required");
|
|
2522
3098
|
await files.mkdir(alias, body.path);
|
|
2523
3099
|
writeJson(res, 200, { ok: true });
|
|
2524
3100
|
return;
|
|
2525
3101
|
case "rm":
|
|
2526
|
-
if (typeof body.path !== "string") throw new
|
|
3102
|
+
if (typeof body.path !== "string") throw new BadRequestError("path is required");
|
|
2527
3103
|
await files.remove(alias, body.path, body.recursive === true);
|
|
2528
3104
|
writeJson(res, 200, { ok: true });
|
|
2529
3105
|
return;
|
|
2530
3106
|
case "rename":
|
|
2531
|
-
if (typeof body.from !== "string" || typeof body.to !== "string") throw new
|
|
3107
|
+
if (typeof body.from !== "string" || typeof body.to !== "string") throw new BadRequestError("from and to are required");
|
|
2532
3108
|
await files.rename(alias, body.from, body.to);
|
|
2533
3109
|
writeJson(res, 200, { ok: true });
|
|
2534
3110
|
return;
|
|
2535
3111
|
default: writeJson(res, 400, { error: `unknown op: ${body.op}` });
|
|
2536
3112
|
}
|
|
2537
3113
|
} catch (error) {
|
|
2538
|
-
|
|
3114
|
+
/**
|
|
3115
|
+
* A save the remote side refused because the file moved on.
|
|
3116
|
+
*
|
|
3117
|
+
* 409, not 502: the operation did not fail, it was DECLINED — and the
|
|
3118
|
+
* client needs the current version to offer overwrite / reload / see
|
|
3119
|
+
* the difference. Collapsing this into the generic remote-error path
|
|
3120
|
+
* is how a silent overwrite becomes a red toast nobody can act on.
|
|
3121
|
+
*/
|
|
3122
|
+
if (error instanceof WriteConflictError) {
|
|
3123
|
+
writeJson(res, 409, {
|
|
3124
|
+
error: error.message,
|
|
3125
|
+
code: "conflict",
|
|
3126
|
+
conflict: error.conflict
|
|
3127
|
+
});
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
3130
|
+
writeJson(res, error instanceof BadRequestError ? 400 : 502, { error: error instanceof Error ? error.message : String(error) });
|
|
2539
3131
|
}
|
|
2540
3132
|
}
|
|
2541
3133
|
},
|
|
@@ -2578,7 +3170,7 @@ function makeRoutes(deps) {
|
|
|
2578
3170
|
size: (await files.upload(alias, path, req, void 0, overwrite)).size
|
|
2579
3171
|
});
|
|
2580
3172
|
} catch (error) {
|
|
2581
|
-
|
|
3173
|
+
writeRouteError(res, error);
|
|
2582
3174
|
}
|
|
2583
3175
|
}
|
|
2584
3176
|
},
|
|
@@ -2608,8 +3200,7 @@ function makeRoutes(deps) {
|
|
|
2608
3200
|
try {
|
|
2609
3201
|
await files.download(alias, path, res);
|
|
2610
3202
|
} catch (error) {
|
|
2611
|
-
|
|
2612
|
-
if (!res.headersSent && !res.destroyed) writeJson(res, 502, { error: message });
|
|
3203
|
+
if (!res.headersSent && !res.destroyed) writeRouteError(res, error);
|
|
2613
3204
|
else res.destroy(error instanceof Error ? error : void 0);
|
|
2614
3205
|
}
|
|
2615
3206
|
}
|
|
@@ -2645,7 +3236,7 @@ function makeRoutes(deps) {
|
|
|
2645
3236
|
}
|
|
2646
3237
|
command = directoryArchiveCommand(path);
|
|
2647
3238
|
} catch (error) {
|
|
2648
|
-
|
|
3239
|
+
writeRouteError(res, error);
|
|
2649
3240
|
return;
|
|
2650
3241
|
}
|
|
2651
3242
|
await streamArchive(alias, command, res, directoryArchiveName(path));
|
|
@@ -2683,7 +3274,7 @@ function makeRoutes(deps) {
|
|
|
2683
3274
|
for (const path of paths) await files.stat(alias, path);
|
|
2684
3275
|
command = selectionArchiveCommand(paths);
|
|
2685
3276
|
} catch (error) {
|
|
2686
|
-
|
|
3277
|
+
writeRouteError(res, error);
|
|
2687
3278
|
return;
|
|
2688
3279
|
}
|
|
2689
3280
|
await streamArchive(alias, command, res, selectionDownloadName(paths.length));
|
|
@@ -2715,7 +3306,9 @@ function makeRoutes(deps) {
|
|
|
2715
3306
|
return;
|
|
2716
3307
|
}
|
|
2717
3308
|
if (method === "POST") {
|
|
2718
|
-
const
|
|
3309
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3310
|
+
if (!read.ok) return;
|
|
3311
|
+
const body = read.body;
|
|
2719
3312
|
if (body === null) {
|
|
2720
3313
|
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2721
3314
|
return;
|
|
@@ -2767,7 +3360,9 @@ function makeRoutes(deps) {
|
|
|
2767
3360
|
writeJson(res, 405, { error: `method not allowed: ${req.method ?? "GET"}` });
|
|
2768
3361
|
return;
|
|
2769
3362
|
}
|
|
2770
|
-
const
|
|
3363
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3364
|
+
if (!read.ok) return;
|
|
3365
|
+
const body = read.body;
|
|
2771
3366
|
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
2772
3367
|
if (sessionId === "") {
|
|
2773
3368
|
writeJson(res, 400, { error: "sessionId must be a non-empty string" });
|
|
@@ -2788,7 +3383,9 @@ function makeRoutes(deps) {
|
|
|
2788
3383
|
writeJson(res, 405, { error: `method not allowed: ${req.method ?? "GET"}` });
|
|
2789
3384
|
return;
|
|
2790
3385
|
}
|
|
2791
|
-
const
|
|
3386
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3387
|
+
if (!read.ok) return;
|
|
3388
|
+
const body = read.body;
|
|
2792
3389
|
const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
2793
3390
|
const op = typeof body?.op === "string" ? body.op : "";
|
|
2794
3391
|
if (sessionId === "" || op !== "list" && op !== "diff") {
|
|
@@ -2825,7 +3422,7 @@ function makeRoutes(deps) {
|
|
|
2825
3422
|
try {
|
|
2826
3423
|
writeJson(res, 200, { diff: await ledger.diff(sessionId, path) });
|
|
2827
3424
|
} catch (error) {
|
|
2828
|
-
|
|
3425
|
+
writeRouteError(res, error);
|
|
2829
3426
|
}
|
|
2830
3427
|
}
|
|
2831
3428
|
},
|
|
@@ -2841,7 +3438,9 @@ function makeRoutes(deps) {
|
|
|
2841
3438
|
writeJson(res, 405, { error: `method not allowed: ${req.method ?? "GET"}` });
|
|
2842
3439
|
return;
|
|
2843
3440
|
}
|
|
2844
|
-
const
|
|
3441
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3442
|
+
if (!read.ok) return;
|
|
3443
|
+
const mode = read.body?.mode;
|
|
2845
3444
|
if (mode !== "off" && mode !== "shadow" && mode !== "enforce") {
|
|
2846
3445
|
writeJson(res, 400, { error: `mode must be one of off/shadow/enforce (got ${JSON.stringify(mode) ?? "missing"})` });
|
|
2847
3446
|
return;
|
|
@@ -2856,7 +3455,7 @@ function makeRoutes(deps) {
|
|
|
2856
3455
|
await settings.update(ns, { routingMode: mode });
|
|
2857
3456
|
writeJson(res, 200, { mode: worlds.mode });
|
|
2858
3457
|
} catch (error) {
|
|
2859
|
-
|
|
3458
|
+
writeRouteError(res, error);
|
|
2860
3459
|
}
|
|
2861
3460
|
}
|
|
2862
3461
|
},
|
|
@@ -2881,7 +3480,7 @@ function makeRoutes(deps) {
|
|
|
2881
3480
|
try {
|
|
2882
3481
|
writeJson(res, 200, await probe(pool, alias));
|
|
2883
3482
|
} catch (error) {
|
|
2884
|
-
|
|
3483
|
+
writeRouteError(res, error);
|
|
2885
3484
|
}
|
|
2886
3485
|
return;
|
|
2887
3486
|
}
|
|
@@ -2903,7 +3502,9 @@ function makeRoutes(deps) {
|
|
|
2903
3502
|
writeJson(res, 405, { error: `method not allowed: ${method}` });
|
|
2904
3503
|
return;
|
|
2905
3504
|
}
|
|
2906
|
-
const
|
|
3505
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3506
|
+
if (!read.ok) return;
|
|
3507
|
+
const body = read.body;
|
|
2907
3508
|
if (body === null || typeof body.alias !== "string") {
|
|
2908
3509
|
writeJson(res, 400, { error: "alias is required" });
|
|
2909
3510
|
return;
|
|
@@ -2911,7 +3512,7 @@ function makeRoutes(deps) {
|
|
|
2911
3512
|
try {
|
|
2912
3513
|
writeJson(res, 200, await pushPipeline(pool, store, body.alias, typeof body.version === "string" ? { version: body.version } : {}));
|
|
2913
3514
|
} catch (error) {
|
|
2914
|
-
|
|
3515
|
+
writeRouteError(res, error);
|
|
2915
3516
|
}
|
|
2916
3517
|
}
|
|
2917
3518
|
},
|
|
@@ -2927,7 +3528,13 @@ function makeRoutes(deps) {
|
|
|
2927
3528
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2928
3529
|
return;
|
|
2929
3530
|
}
|
|
2930
|
-
|
|
3531
|
+
if (bodyTooLarge(req, SSH_CONFIG_BODY_LIMIT)) {
|
|
3532
|
+
writePayloadTooLarge(req, res, SSH_CONFIG_BODY_LIMIT);
|
|
3533
|
+
return;
|
|
3534
|
+
}
|
|
3535
|
+
const read = await readBodyOrError(req, res, { maxBytes: SSH_CONFIG_BODY_LIMIT });
|
|
3536
|
+
if (!read.ok) return;
|
|
3537
|
+
const body = read.body;
|
|
2931
3538
|
try {
|
|
2932
3539
|
const text = body !== null && typeof body.text === "string" ? body.text : readDefaultSshConfig();
|
|
2933
3540
|
writeJson(res, 200, applyImport(parseSshConfig(text)));
|
|
@@ -2967,7 +3574,9 @@ function makeRoutes(deps) {
|
|
|
2967
3574
|
writeJson(res, 405, { error: `method not allowed: ${req.method}` });
|
|
2968
3575
|
return;
|
|
2969
3576
|
}
|
|
2970
|
-
const
|
|
3577
|
+
const read = await readBodyOrError(req, res, { objectOnly: true });
|
|
3578
|
+
if (!read.ok) return;
|
|
3579
|
+
const body = read.body;
|
|
2971
3580
|
if (body === null || typeof body.id !== "string" || body.id === "") {
|
|
2972
3581
|
writeJson(res, 400, { error: "id is required" });
|
|
2973
3582
|
return;
|
|
@@ -3034,6 +3643,35 @@ const READ_EXIT = {
|
|
|
3034
3643
|
};
|
|
3035
3644
|
/** Marker that starts one file block in a read reply. */
|
|
3036
3645
|
const FILE_MARKER = "@@RVS-FILE ";
|
|
3646
|
+
/**
|
|
3647
|
+
* Strict UTF-8 decoder — one instance, reused.
|
|
3648
|
+
*
|
|
3649
|
+
* A file's bytes are only "text" if they decode as UTF-8; anything else used to be
|
|
3650
|
+
* decoded lossily into U+FFFD, which made the panel show mojibake with counts that
|
|
3651
|
+
* were pure fiction AND made every revert fail (the patch's context lines could
|
|
3652
|
+
* never match the real bytes). "Not decodable" is reported as binary instead — the
|
|
3653
|
+
* one honest answer, and the one the undo path already refuses to touch.
|
|
3654
|
+
*
|
|
3655
|
+
* `ignoreBOM: true` is required, despite the confusing name: with the default
|
|
3656
|
+
* (false) the decoder CONSUMES a leading UTF-8 BOM, while the editor's read path
|
|
3657
|
+
* (`sftp.ts` → `Buffer.toString('utf8')`) keeps it. Stripping it here would make
|
|
3658
|
+
* the ledger's text one code point shorter than the file on disk; the patch the
|
|
3659
|
+
* undo path builds from that text then lacks the BOM on the first line and
|
|
3660
|
+
* `git apply -R` rejects it (fail-closed, but the revert is unusable), and the
|
|
3661
|
+
* first-line inline marks shift by one column.
|
|
3662
|
+
*/
|
|
3663
|
+
const strictUtf8 = new TextDecoder("utf-8", {
|
|
3664
|
+
fatal: true,
|
|
3665
|
+
ignoreBOM: true
|
|
3666
|
+
});
|
|
3667
|
+
/** Decode strict UTF-8, or undefined when the bytes are not valid UTF-8. */
|
|
3668
|
+
function decodeUtf8Strict(bytes) {
|
|
3669
|
+
try {
|
|
3670
|
+
return strictUtf8.decode(bytes);
|
|
3671
|
+
} catch {
|
|
3672
|
+
return;
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3037
3675
|
/** POSIX single-quote one shell word. Throws on NUL, which no shell can carry. */
|
|
3038
3676
|
function shq(word) {
|
|
3039
3677
|
if (word.includes("\0")) throw new Error("NUL byte in shell word");
|
|
@@ -3360,8 +3998,19 @@ function parseReads(stdout) {
|
|
|
3360
3998
|
});
|
|
3361
3999
|
continue;
|
|
3362
4000
|
}
|
|
4001
|
+
const text = decodeUtf8Strict(bytes);
|
|
4002
|
+
if (text === void 0) {
|
|
4003
|
+
results.set(path, {
|
|
4004
|
+
text: null,
|
|
4005
|
+
truncated: false,
|
|
4006
|
+
binary: true,
|
|
4007
|
+
absent: false,
|
|
4008
|
+
...stats
|
|
4009
|
+
});
|
|
4010
|
+
continue;
|
|
4011
|
+
}
|
|
3363
4012
|
results.set(path, {
|
|
3364
|
-
text
|
|
4013
|
+
text,
|
|
3365
4014
|
truncated: false,
|
|
3366
4015
|
binary: false,
|
|
3367
4016
|
absent: false,
|
|
@@ -3776,6 +4425,7 @@ var SessionChanges = class {
|
|
|
3776
4425
|
summary(sessionId) {
|
|
3777
4426
|
const ledger = this.ledgers.get(sessionId);
|
|
3778
4427
|
if (ledger === void 0) return null;
|
|
4428
|
+
const unavailable = ledger.unavailable ?? (ledger.untrackedFailure === void 0 ? void 0 : `new-file scan unavailable: ${ledger.untrackedFailure} (use the refresh button to retry)`);
|
|
3779
4429
|
return {
|
|
3780
4430
|
alias: ledger.alias,
|
|
3781
4431
|
root: ledger.root,
|
|
@@ -3786,7 +4436,7 @@ var SessionChanges = class {
|
|
|
3786
4436
|
at: ledger.at,
|
|
3787
4437
|
pending: ledger.untrackedJob !== void 0 || ledger.pending && ledger.files.length > 0,
|
|
3788
4438
|
...ledger.truncated === true ? { truncated: true } : {},
|
|
3789
|
-
...
|
|
4439
|
+
...unavailable === void 0 ? {} : { unavailable }
|
|
3790
4440
|
};
|
|
3791
4441
|
}
|
|
3792
4442
|
/**
|
|
@@ -3834,7 +4484,7 @@ var SessionChanges = class {
|
|
|
3834
4484
|
newCount: hunk.newLines,
|
|
3835
4485
|
heading: "",
|
|
3836
4486
|
lines: hunk.lines,
|
|
3837
|
-
patch: hunkPatch(record.display, hunk)
|
|
4487
|
+
patch: record.undoable ? hunkPatch(record.display, hunk) : ""
|
|
3838
4488
|
}));
|
|
3839
4489
|
if (hunks.length === 0) return {
|
|
3840
4490
|
kind: "missing",
|
|
@@ -3883,7 +4533,12 @@ var SessionChanges = class {
|
|
|
3883
4533
|
rescan(sessionId) {
|
|
3884
4534
|
const ledger = this.ledgers.get(sessionId);
|
|
3885
4535
|
if (ledger === void 0 || ledger.disposed) return;
|
|
4536
|
+
if (ledger.untrackedGivenUp) {
|
|
4537
|
+
ledger.untrackedGivenUp = false;
|
|
4538
|
+
this.warn("manual refresh re-arms the untracked scan for this session");
|
|
4539
|
+
}
|
|
3886
4540
|
ledger.untrackedAt = 0;
|
|
4541
|
+
ledger.untrackedMs = void 0;
|
|
3887
4542
|
this.schedule(ledger);
|
|
3888
4543
|
}
|
|
3889
4544
|
/**
|
|
@@ -3922,39 +4577,98 @@ var SessionChanges = class {
|
|
|
3922
4577
|
if (clean === ledger.subdir) return;
|
|
3923
4578
|
ledger.subdir = clean;
|
|
3924
4579
|
ledger.root = clean === "" ? ledger.baseRoot : `${ledger.baseRoot}/${clean}`;
|
|
4580
|
+
this.resetObservation(ledger);
|
|
4581
|
+
this.schedule(ledger);
|
|
4582
|
+
}
|
|
4583
|
+
/**
|
|
4584
|
+
* Forget everything observed against the ledger's previous root.
|
|
4585
|
+
*
|
|
4586
|
+
* The root is the subject of every fact this ledger holds: the baseline
|
|
4587
|
+
* describes that tree, both scans name paths relative to it, and the flags
|
|
4588
|
+
* that gate them (`absorbed`, `untrackedGivenUp`) are verdicts about that
|
|
4589
|
+
* repository. Moving the root therefore makes the whole observation set
|
|
4590
|
+
* meaningless at once — resetting only the ones a caller happened to remember
|
|
4591
|
+
* is how the first cut of `useRepoSubdir` forgot `untracked` and `absorbed`,
|
|
4592
|
+
* which announced the newly selected repository's PRE-EXISTING untracked
|
|
4593
|
+
* files as this session's work (full-file additions, revertible — and a
|
|
4594
|
+
* revert of an untracked file destroys a copy git never had).
|
|
4595
|
+
*
|
|
4596
|
+
* One entry point on purpose: a field added later belongs here by default,
|
|
4597
|
+
* instead of needing every root-move path to be found again.
|
|
4598
|
+
*/
|
|
4599
|
+
resetObservation(ledger) {
|
|
3925
4600
|
ledger.baseline = void 0;
|
|
3926
4601
|
ledger.baselineTaken = false;
|
|
4602
|
+
ledger.absorbed = false;
|
|
3927
4603
|
ledger.adoptedSubdir = false;
|
|
4604
|
+
ledger.tracked = [];
|
|
4605
|
+
ledger.untracked = void 0;
|
|
4606
|
+
ledger.untrackedAt = 0;
|
|
4607
|
+
ledger.untrackedMs = void 0;
|
|
4608
|
+
ledger.untrackedGivenUp = false;
|
|
4609
|
+
ledger.untrackedFailure = void 0;
|
|
3928
4610
|
ledger.files = [];
|
|
3929
4611
|
ledger.records = /* @__PURE__ */ new Map();
|
|
3930
4612
|
ledger.added = 0;
|
|
3931
4613
|
ledger.deleted = 0;
|
|
4614
|
+
ledger.truncated = void 0;
|
|
3932
4615
|
ledger.at = 0;
|
|
3933
|
-
|
|
4616
|
+
ledger.unavailable = void 0;
|
|
4617
|
+
ledger.startedAt = Date.now();
|
|
3934
4618
|
}
|
|
3935
|
-
/**
|
|
4619
|
+
/**
|
|
4620
|
+
* Resolve (or rebind) the ledger for one session from its CURRENT cwd.
|
|
4621
|
+
*
|
|
4622
|
+
* The cwd is re-resolved on every turn boundary instead of once per session: a
|
|
4623
|
+
* session can change its working directory mid-conversation (a workspace
|
|
4624
|
+
* switch, `working-directory.set`), and a ledger pinned to the first binding
|
|
4625
|
+
* then keeps answering "what did this session change" about a tree the session
|
|
4626
|
+
* is no longer working in — and points file-open and undo at it.
|
|
4627
|
+
*
|
|
4628
|
+
* Rebinding happens IN PLACE rather than forget+create: the panel keeps its
|
|
4629
|
+
* identity and `turn` counter (no null-summary flicker) and one
|
|
4630
|
+
* `resetObservation()` drops every fact that belonged to the previous root, so
|
|
4631
|
+
* the field list stays in that one method. C1's root-snapshot guards in
|
|
4632
|
+
* `refresh`/`publish`/`kickUntracked`/`absorbPreExisting` are exactly what makes
|
|
4633
|
+
* this safe while a scan of the old root is still in flight.
|
|
4634
|
+
*/
|
|
3936
4635
|
ensure(target) {
|
|
3937
4636
|
if (target.cwd.trim() === "") return void 0;
|
|
3938
|
-
const existing = this.ledgers.get(target.sessionId);
|
|
3939
|
-
if (existing !== void 0 && !existing.disposed && existing.root !== "") return existing;
|
|
3940
4637
|
let route;
|
|
3941
4638
|
try {
|
|
3942
4639
|
route = this.deps.worlds.routeDir(target.cwd);
|
|
3943
4640
|
} catch {
|
|
4641
|
+
this.forget(target.sessionId);
|
|
3944
4642
|
return;
|
|
3945
4643
|
}
|
|
3946
4644
|
if (route.kind !== "remote") {
|
|
3947
|
-
this.
|
|
4645
|
+
this.forget(target.sessionId);
|
|
3948
4646
|
return;
|
|
3949
4647
|
}
|
|
3950
4648
|
const root = route.remotePath.length > 1 && route.remotePath.endsWith("/") ? route.remotePath.replace(/\/+$/, "") : route.remotePath;
|
|
4649
|
+
const existing = this.ledgers.get(target.sessionId);
|
|
4650
|
+
if (existing !== void 0 && !existing.disposed && existing.root !== "") {
|
|
4651
|
+
existing.cwd = target.cwd;
|
|
4652
|
+
if (existing.routeId === route.id) return existing;
|
|
4653
|
+
this.warn(`session working directory moved to ${route.alias}:${root}; re-observing the new binding`);
|
|
4654
|
+
existing.routeId = route.id;
|
|
4655
|
+
existing.alias = route.alias;
|
|
4656
|
+
existing.baseRoot = root;
|
|
4657
|
+
existing.subdir = "";
|
|
4658
|
+
existing.root = root;
|
|
4659
|
+
this.resetObservation(existing);
|
|
4660
|
+
return existing;
|
|
4661
|
+
}
|
|
3951
4662
|
const ledger = {
|
|
3952
4663
|
sessionId: target.sessionId,
|
|
4664
|
+
cwd: target.cwd,
|
|
4665
|
+
routeId: route.id,
|
|
3953
4666
|
alias: route.alias,
|
|
3954
4667
|
root,
|
|
3955
4668
|
baseline: void 0,
|
|
3956
4669
|
baselineTaken: false,
|
|
3957
4670
|
untrackedGivenUp: false,
|
|
4671
|
+
untrackedFailure: void 0,
|
|
3958
4672
|
startedAt: Date.now(),
|
|
3959
4673
|
absorbed: false,
|
|
3960
4674
|
adoptedSubdir: false,
|
|
@@ -3976,6 +4690,7 @@ var SessionChanges = class {
|
|
|
3976
4690
|
pending: false,
|
|
3977
4691
|
queue: Promise.resolve(),
|
|
3978
4692
|
dirty: false,
|
|
4693
|
+
publishSeq: 0,
|
|
3979
4694
|
disposed: false
|
|
3980
4695
|
};
|
|
3981
4696
|
this.ledgers.set(target.sessionId, ledger);
|
|
@@ -4008,15 +4723,18 @@ var SessionChanges = class {
|
|
|
4008
4723
|
*/
|
|
4009
4724
|
async refresh(ledger) {
|
|
4010
4725
|
if (ledger.disposed || ledger.root === "") return;
|
|
4011
|
-
const
|
|
4012
|
-
if (ledger.disposed ||
|
|
4013
|
-
ledger.
|
|
4726
|
+
const scanned = await this.scanTracked(ledger);
|
|
4727
|
+
if (ledger.disposed || scanned === void 0) return;
|
|
4728
|
+
if (ledger.root !== scanned.root) return;
|
|
4729
|
+
ledger.tracked = scanned.entries;
|
|
4014
4730
|
await this.publish(ledger);
|
|
4015
4731
|
this.kickUntracked(ledger);
|
|
4016
4732
|
}
|
|
4017
4733
|
/** Recompute the panel's list from the scans currently known. */
|
|
4018
4734
|
async publish(ledger) {
|
|
4019
4735
|
if (ledger.disposed) return;
|
|
4736
|
+
const seq = ++ledger.publishSeq;
|
|
4737
|
+
const root = ledger.root;
|
|
4020
4738
|
const merged = /* @__PURE__ */ new Map();
|
|
4021
4739
|
for (const entry of ledger.tracked) merged.set(entry.path, entry);
|
|
4022
4740
|
for (const entry of ledger.untracked ?? []) if (!merged.has(entry.path)) merged.set(entry.path, entry);
|
|
@@ -4025,8 +4743,10 @@ var SessionChanges = class {
|
|
|
4025
4743
|
const listed = entries.slice(0, cap);
|
|
4026
4744
|
const truncated = entries.length > cap;
|
|
4027
4745
|
if (!ledger.baselineTaken) {
|
|
4028
|
-
|
|
4029
|
-
if (ledger.disposed) return;
|
|
4746
|
+
const first = await this.readPaths(ledger, listed.map((entry) => entry.path), "worktree");
|
|
4747
|
+
if (ledger.disposed || ledger.root !== root) return;
|
|
4748
|
+
if (ledger.publishSeq !== seq) return;
|
|
4749
|
+
ledger.baseline = first;
|
|
4030
4750
|
ledger.baselineTaken = true;
|
|
4031
4751
|
ledger.files = [];
|
|
4032
4752
|
ledger.records = /* @__PURE__ */ new Map();
|
|
@@ -4040,7 +4760,7 @@ var SessionChanges = class {
|
|
|
4040
4760
|
const fromHead = listed.filter((entry) => !baseline.has(entry.path)).map((entry) => entry.path);
|
|
4041
4761
|
const head = fromHead.length === 0 ? /* @__PURE__ */ new Map() : await this.readPaths(ledger, fromHead, "head");
|
|
4042
4762
|
const after = await this.readPaths(ledger, listed.map((entry) => entry.path), "worktree");
|
|
4043
|
-
if (ledger.disposed) return;
|
|
4763
|
+
if (ledger.disposed || ledger.root !== root) return;
|
|
4044
4764
|
const records = /* @__PURE__ */ new Map();
|
|
4045
4765
|
const files = [];
|
|
4046
4766
|
let added = 0;
|
|
@@ -4056,6 +4776,7 @@ var SessionChanges = class {
|
|
|
4056
4776
|
if (!binary && !fileTruncated && before === afterText) continue;
|
|
4057
4777
|
if ((binary || fileTruncated) && sameStat(beforeSide, afterSide)) continue;
|
|
4058
4778
|
const oversized = fileTruncated && !binary;
|
|
4779
|
+
const undoable = !binary && !oversized && beforeSide !== void 0 && !(before === null);
|
|
4059
4780
|
const diff = binary || oversized ? {
|
|
4060
4781
|
added: 0,
|
|
4061
4782
|
deleted: 0
|
|
@@ -4069,7 +4790,8 @@ var SessionChanges = class {
|
|
|
4069
4790
|
before,
|
|
4070
4791
|
after: afterText,
|
|
4071
4792
|
binary,
|
|
4072
|
-
truncated: fileTruncated
|
|
4793
|
+
truncated: fileTruncated,
|
|
4794
|
+
undoable
|
|
4073
4795
|
});
|
|
4074
4796
|
added += diff.added;
|
|
4075
4797
|
deleted += diff.deleted;
|
|
@@ -4084,6 +4806,8 @@ var SessionChanges = class {
|
|
|
4084
4806
|
});
|
|
4085
4807
|
}
|
|
4086
4808
|
files.sort((left, right) => left.display.localeCompare(right.display));
|
|
4809
|
+
if (ledger.root !== root) return;
|
|
4810
|
+
if (ledger.publishSeq !== seq) return;
|
|
4087
4811
|
ledger.records = records;
|
|
4088
4812
|
ledger.files = files;
|
|
4089
4813
|
ledger.added = added;
|
|
@@ -4103,35 +4827,47 @@ var SessionChanges = class {
|
|
|
4103
4827
|
* ledger looks one level down once and adopts the repository it finds, which
|
|
4104
4828
|
* is the same idea the SCM panel's `repoSubdir` expresses by hand.
|
|
4105
4829
|
*
|
|
4106
|
-
* @returns entries
|
|
4830
|
+
* @returns the entries and the root they are relative to, or undefined when no
|
|
4107
4831
|
* repository could be found (the ledger then reports why).
|
|
4108
4832
|
*/
|
|
4109
4833
|
async scanTracked(ledger) {
|
|
4110
|
-
|
|
4834
|
+
let root = ledger.root;
|
|
4835
|
+
const tracked = await this.run(ledger.alias, trackedStatusCommand(root));
|
|
4836
|
+
if (ledger.root !== root) return void 0;
|
|
4111
4837
|
if (tracked.ok) {
|
|
4112
4838
|
ledger.unavailable = void 0;
|
|
4113
|
-
return
|
|
4839
|
+
return {
|
|
4840
|
+
root,
|
|
4841
|
+
entries: parseStatusZ(tracked.stdout)
|
|
4842
|
+
};
|
|
4114
4843
|
}
|
|
4115
4844
|
if (tracked.code === 90 && ledger.subdir !== "") {
|
|
4116
4845
|
this.warn(`repository directory "${ledger.subdir}" is missing on the host; falling back to the session root`);
|
|
4117
4846
|
ledger.subdir = "";
|
|
4118
4847
|
ledger.root = ledger.baseRoot;
|
|
4119
|
-
ledger
|
|
4120
|
-
|
|
4121
|
-
const retry = await this.run(ledger.alias, trackedStatusCommand(
|
|
4848
|
+
this.resetObservation(ledger);
|
|
4849
|
+
root = ledger.root;
|
|
4850
|
+
const retry = await this.run(ledger.alias, trackedStatusCommand(root));
|
|
4122
4851
|
if (retry.ok) {
|
|
4123
4852
|
ledger.unavailable = void 0;
|
|
4124
|
-
return
|
|
4853
|
+
return {
|
|
4854
|
+
root,
|
|
4855
|
+
entries: parseStatusZ(retry.stdout)
|
|
4856
|
+
};
|
|
4125
4857
|
}
|
|
4126
4858
|
ledger.unavailable = retry.reason;
|
|
4127
4859
|
return;
|
|
4128
4860
|
}
|
|
4129
4861
|
if (!ledger.adoptedSubdir) {
|
|
4130
4862
|
if (await this.adoptRepositoryBelow(ledger) !== void 0) {
|
|
4131
|
-
|
|
4863
|
+
root = ledger.root;
|
|
4864
|
+
const retry = await this.run(ledger.alias, trackedStatusCommand(root));
|
|
4132
4865
|
if (retry.ok) {
|
|
4133
4866
|
ledger.unavailable = void 0;
|
|
4134
|
-
return
|
|
4867
|
+
return {
|
|
4868
|
+
root,
|
|
4869
|
+
entries: parseStatusZ(retry.stdout)
|
|
4870
|
+
};
|
|
4135
4871
|
}
|
|
4136
4872
|
ledger.unavailable = retry.reason;
|
|
4137
4873
|
return;
|
|
@@ -4161,7 +4897,10 @@ var SessionChanges = class {
|
|
|
4161
4897
|
ledger.unavailable = `no git repository at the workspace root, and ${found.length} candidates below it — set the repository directory in Source Control`;
|
|
4162
4898
|
return;
|
|
4163
4899
|
}
|
|
4164
|
-
|
|
4900
|
+
const adopted = `${ledger.root}/${found[0]}`;
|
|
4901
|
+
this.resetObservation(ledger);
|
|
4902
|
+
ledger.root = adopted;
|
|
4903
|
+
ledger.adoptedSubdir = true;
|
|
4165
4904
|
this.warn(`no repository at the session root; using ${ledger.root}`);
|
|
4166
4905
|
return ledger.root;
|
|
4167
4906
|
}
|
|
@@ -4178,17 +4917,21 @@ var SessionChanges = class {
|
|
|
4178
4917
|
async kickUntracked(ledger) {
|
|
4179
4918
|
if (ledger.disposed || ledger.untrackedGivenUp || ledger.untrackedJob !== void 0) return;
|
|
4180
4919
|
if (ledger.untracked !== void 0 && Date.now() - ledger.untrackedAt < this.untrackedCadence(ledger)) return;
|
|
4920
|
+
const root = ledger.root;
|
|
4181
4921
|
ledger.untrackedAt = Date.now();
|
|
4182
4922
|
ledger.untrackedJob = (async () => {
|
|
4183
4923
|
const started = Date.now();
|
|
4184
|
-
const scan = await this.run(ledger.alias, untrackedCommand(
|
|
4924
|
+
const scan = await this.run(ledger.alias, untrackedCommand(root), this.untrackedBudget());
|
|
4185
4925
|
ledger.untrackedMs = Date.now() - started;
|
|
4186
4926
|
if (ledger.disposed) return;
|
|
4927
|
+
if (ledger.root !== root) return;
|
|
4187
4928
|
if (!scan.ok) {
|
|
4188
4929
|
ledger.untrackedGivenUp = true;
|
|
4930
|
+
ledger.untrackedFailure = scan.reason;
|
|
4189
4931
|
this.warn(`untracked scan unusable (${scan.reason}); new files will not be listed`);
|
|
4190
4932
|
return;
|
|
4191
4933
|
}
|
|
4934
|
+
ledger.untrackedFailure = void 0;
|
|
4192
4935
|
ledger.untracked = parseUntrackedZ(scan.stdout);
|
|
4193
4936
|
await this.absorbPreExisting(ledger);
|
|
4194
4937
|
await this.publish(ledger);
|
|
@@ -4227,12 +4970,13 @@ var SessionChanges = class {
|
|
|
4227
4970
|
async absorbPreExisting(ledger) {
|
|
4228
4971
|
if (ledger.untracked === void 0 || ledger.absorbed) return;
|
|
4229
4972
|
ledger.absorbed = true;
|
|
4973
|
+
const root = ledger.root;
|
|
4230
4974
|
const baseline = ledger.baseline ?? /* @__PURE__ */ new Map();
|
|
4231
4975
|
ledger.baseline = baseline;
|
|
4232
4976
|
const unknown = ledger.untracked.map((entry) => entry.path).filter((path) => !baseline.has(path));
|
|
4233
4977
|
if (unknown.length === 0) return;
|
|
4234
4978
|
const reads = await this.readPaths(ledger, unknown, "worktree");
|
|
4235
|
-
if (ledger.disposed) return;
|
|
4979
|
+
if (ledger.disposed || ledger.root !== root) return;
|
|
4236
4980
|
for (const [path, read] of reads) {
|
|
4237
4981
|
if (read.mtime === void 0) continue;
|
|
4238
4982
|
if (read.mtime * 1e3 < ledger.startedAt) baseline.set(path, read);
|
|
@@ -4514,7 +5258,7 @@ function remoteExecTool(deps) {
|
|
|
4514
5258
|
},
|
|
4515
5259
|
timeoutMs: {
|
|
4516
5260
|
type: "number",
|
|
4517
|
-
description:
|
|
5261
|
+
description: `Timeout in ms (default 60000, max ${MAX_TIMEOUT_MS}).`
|
|
4518
5262
|
}
|
|
4519
5263
|
},
|
|
4520
5264
|
output: {
|
|
@@ -4552,7 +5296,7 @@ function remoteExecTool(deps) {
|
|
|
4552
5296
|
}))
|
|
4553
5297
|
},
|
|
4554
5298
|
async execute(args) {
|
|
4555
|
-
const timeoutMs =
|
|
5299
|
+
const timeoutMs = clampExecTimeout(args.timeoutMs);
|
|
4556
5300
|
const result = await deps.pool.exec(args.alias, args.command, timeoutMs === void 0 ? {} : { timeoutMs });
|
|
4557
5301
|
return {
|
|
4558
5302
|
success: result.success,
|
|
@@ -4706,7 +5450,14 @@ function remoteWriteTool(deps) {
|
|
|
4706
5450
|
render: (_args, value) => text(`wrote ${value.size ?? 0} bytes`)
|
|
4707
5451
|
},
|
|
4708
5452
|
async execute(args) {
|
|
4709
|
-
|
|
5453
|
+
/**
|
|
5454
|
+
* Exactly the declared shape. `write` also reports the version it left
|
|
5455
|
+
* behind (the editor's save guard reads it), but the model has no use for
|
|
5456
|
+
* a timestamp and this schema refuses undeclared keys — DSH rejects such a
|
|
5457
|
+
* result BEFORE the model ever sees it, which would make this tool
|
|
5458
|
+
* uncallable rather than merely verbose.
|
|
5459
|
+
*/
|
|
5460
|
+
return { size: (await new RemoteFiles(deps.pool).write(args.alias, args.path, args.content, "utf8")).size };
|
|
4710
5461
|
}
|
|
4711
5462
|
});
|
|
4712
5463
|
}
|
|
@@ -4916,6 +5667,26 @@ function apply(ctx, config) {
|
|
|
4916
5667
|
timeouts: resolveTimeoutsNow,
|
|
4917
5668
|
changes
|
|
4918
5669
|
});
|
|
5670
|
+
/**
|
|
5671
|
+
* PTY sessions own their own lifetime, separate from route registration.
|
|
5672
|
+
*
|
|
5673
|
+
* `sync()` rebuilds the route/tool registrations whenever a volatile config
|
|
5674
|
+
* value changes (`loader/volatile-update` fires for every settings edit), and a
|
|
5675
|
+
* cleanup that also closed terminals made "change one setting" kill every live
|
|
5676
|
+
* remote shell. So the registry gets a fiber-scoped effect of its own: it is
|
|
5677
|
+
* disposed exactly once — when the plugin is actually unloaded — and never by
|
|
5678
|
+
* the route re-registration in `sync()`.
|
|
5679
|
+
*
|
|
5680
|
+
* Cleanup order is load-bearing: this effect is registered AFTER the pool
|
|
5681
|
+
* effect but BEFORE the routes effect created in `sync()`, and cordis starts a
|
|
5682
|
+
* fiber's effect cleanups in reverse registration order (these cleanups are
|
|
5683
|
+
* synchronous) — so on unload the routes are unregistered first (no new shell
|
|
5684
|
+
* can be opened), then the terminals close (a channel close still has a live
|
|
5685
|
+
* pool), and the pool is disposed last.
|
|
5686
|
+
*/
|
|
5687
|
+
ctx.effect(() => () => {
|
|
5688
|
+
terminalSessions.dispose();
|
|
5689
|
+
}, "dsh-remote-vs: terminal sessions");
|
|
4919
5690
|
let disposeRoutes;
|
|
4920
5691
|
const tools = [
|
|
4921
5692
|
remoteHostsTool({
|
|
@@ -4970,7 +5741,6 @@ function apply(ctx, config) {
|
|
|
4970
5741
|
return () => {
|
|
4971
5742
|
for (const dispose of disposers) dispose();
|
|
4972
5743
|
upgradeDisposer();
|
|
4973
|
-
terminalSessions.dispose();
|
|
4974
5744
|
};
|
|
4975
5745
|
}, "dsh-remote-vs: routes");
|
|
4976
5746
|
disposeTools = ctx.effect(() => {
|