dsh-remote 1.4.1 → 1.6.0
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 +1 -1
- package/README.md +1 -1
- package/lib/binding.js +100 -84
- package/lib/boot.js +1 -0
- package/lib/client.js +252 -46
- package/lib/connect-summary.js +28 -0
- package/lib/file-reference.js +63 -7
- package/lib/forwards.js +72 -23
- package/lib/host-api.js +26 -37
- package/lib/hostkey.js +128 -10
- package/lib/http-transport.js +72 -5
- package/lib/ignore.js +64 -21
- package/lib/index.js +1 -0
- package/lib/main.js +221 -231
- package/lib/mirror-paths.js +107 -2
- package/lib/openssh.js +55 -2
- package/lib/pool.js +23 -1
- package/lib/registry.js +50 -6
- package/lib/remote-fs.js +43 -19
- package/lib/remote-git.js +53 -5
- package/lib/remote-shell-child.cjs +9 -1
- package/lib/routes-fs.js +159 -7
- package/lib/routes-machines.js +16 -8
- package/lib/routes-web-attach.js +115 -43
- package/lib/routes-workspace.js +15 -9
- package/lib/search.js +96 -16
- package/lib/sftp-surface.js +5 -1
- package/lib/sshconfig.js +62 -7
- package/lib/sync-status.js +3 -2
- package/lib/sync.js +109 -48
- package/lib/terminal.js +7 -3
- package/lib/update.js +65 -10
- package/lib/web-attach.js +184 -22
- package/lib/workspace-cleanup.js +85 -60
- package/lib/workspace-files-remote.js +154 -3
- package/package.json +2 -2
package/lib/routes-fs.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// same mirror binding as rw_* tools and never fall back to the active machine.
|
|
7
7
|
// URLSearchParams already decodes query paths. Another decoding pass corrupts
|
|
8
8
|
// literal percent characters and names containing sequences such as `%2F`.
|
|
9
|
-
import { mkdirSync } from 'node:fs'
|
|
9
|
+
import { mkdirSync, existsSync } from 'node:fs'
|
|
10
10
|
import path from 'node:path'
|
|
11
11
|
import { mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
|
|
12
12
|
export { mirrorDownloadTarget } from './mirror-paths.js'
|
|
@@ -18,6 +18,67 @@ import { requestSessionHint } from './binding.js'
|
|
|
18
18
|
import { captureRemoteFile, atomicRemoteWrite, remoteRevision, missingRemoteFile } from './remote-write.js'
|
|
19
19
|
import { listDirStructured, listRemoteDrives, removeRemoteTree, previewRemoteFile } from './remote-fs.js'
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* RFC 6266/5987 attachment header: an ASCII fallback plus the UTF-8 name, so a
|
|
23
|
+
* file called `报告 2026.pdf` keeps its name in every browser while a quote or a
|
|
24
|
+
* CR/LF inside the path can never break out of the header.
|
|
25
|
+
*/
|
|
26
|
+
function contentDisposition(name) {
|
|
27
|
+
const raw = String(name || 'download')
|
|
28
|
+
const ascii = raw.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_')
|
|
29
|
+
const encoded = encodeURIComponent(raw).replace(/['()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
|
|
30
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Resolve once the response can take more bytes, or reject when the client left. */
|
|
34
|
+
function responseDrained(res) {
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const done = (err) => {
|
|
37
|
+
res.removeListener('drain', ok)
|
|
38
|
+
res.removeListener('close', closed)
|
|
39
|
+
res.removeListener('error', fail)
|
|
40
|
+
if (err) reject(err)
|
|
41
|
+
else resolve()
|
|
42
|
+
}
|
|
43
|
+
const ok = () => done()
|
|
44
|
+
const closed = () => done(Object.assign(new Error('download aborted by the client'), { code: 'CLIENT_GONE' }))
|
|
45
|
+
const fail = (err) => done(err)
|
|
46
|
+
res.once('drain', ok)
|
|
47
|
+
res.once('close', closed)
|
|
48
|
+
res.once('error', fail)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The SFTP surface exposes no read stream. Read one 1 MiB range at a time
|
|
53
|
+
// so both response transports can drive reads with their own backpressure.
|
|
54
|
+
async function* downloadChunks(sftp, remotePath, size, verifySize) {
|
|
55
|
+
const CHUNK = 1024 * 1024
|
|
56
|
+
if (typeof sftp.readPartial !== 'function') {
|
|
57
|
+
// Surface without bounded reads (tests, older adapters): one full read is
|
|
58
|
+
// still better than fastGet, which would park the bytes on the host's disk.
|
|
59
|
+
const buf = await sftp.readFile(remotePath)
|
|
60
|
+
if (verifySize && (buf?.length || 0) !== size) throw new Error('file size changed during download')
|
|
61
|
+
if (buf && buf.length) yield buf
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
let offset = 0
|
|
65
|
+
while (offset < size) {
|
|
66
|
+
const buf = await sftp.readPartial(remotePath, offset, Math.min(CHUNK, size - offset))
|
|
67
|
+
if (!buf || !buf.length) break
|
|
68
|
+
offset += buf.length
|
|
69
|
+
yield buf
|
|
70
|
+
}
|
|
71
|
+
if (verifySize && offset !== size) throw new Error('file size changed during download')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function streamFileToResponse(sftp, remotePath, size, res) {
|
|
75
|
+
const waitForDrain = typeof sftp.readPartial === 'function'
|
|
76
|
+
for await (const buf of downloadChunks(sftp, remotePath, size, false)) {
|
|
77
|
+
if (!res.write(buf) && waitForDrain) await responseDrained(res)
|
|
78
|
+
}
|
|
79
|
+
res.end()
|
|
80
|
+
}
|
|
81
|
+
|
|
21
82
|
export function createFsRoutes({
|
|
22
83
|
sendJson,
|
|
23
84
|
readBody,
|
|
@@ -27,7 +88,10 @@ export function createFsRoutes({
|
|
|
27
88
|
audit,
|
|
28
89
|
config,
|
|
29
90
|
mirrorDirFor,
|
|
91
|
+
ensureBoundMirror,
|
|
30
92
|
onRemoteMutation = () => {},
|
|
93
|
+
openLocalPath,
|
|
94
|
+
mirrorRoot,
|
|
31
95
|
}) {
|
|
32
96
|
const bindOrReply = async (req, res, body = {}) => {
|
|
33
97
|
try {
|
|
@@ -119,6 +183,65 @@ export function createFsRoutes({
|
|
|
119
183
|
}
|
|
120
184
|
},
|
|
121
185
|
},
|
|
186
|
+
{
|
|
187
|
+
// Bytes for the machine running the BROWSER, not for the harness host.
|
|
188
|
+
//
|
|
189
|
+
// `fs op=download` writes the file into the DSH host's local mirror, which
|
|
190
|
+
// is the wrong machine as soon as the page is opened from another desktop:
|
|
191
|
+
// the file lands next to the harness and the browser is handed a path. This
|
|
192
|
+
// route answers the bytes themselves — GET, so the browser's own download
|
|
193
|
+
// manager owns progress, resume and cancel.
|
|
194
|
+
//
|
|
195
|
+
// The binding is the usual session one (query `sessionId`, plus
|
|
196
|
+
// `workspace=local` for a local workspace) and resolveWorkbenchBinding
|
|
197
|
+
// fences this route like /read, so a click in one session's explorer can
|
|
198
|
+
// never pull a file from another session's host, nor read outside a local
|
|
199
|
+
// workspace's root.
|
|
200
|
+
kind: 'exact',
|
|
201
|
+
path: '/dsh-remote/download',
|
|
202
|
+
handler: async (req, res) => {
|
|
203
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
204
|
+
let streaming = false
|
|
205
|
+
try {
|
|
206
|
+
const q = new URL(req.url, 'http://localhost').searchParams
|
|
207
|
+
const requested = q.get('path') || ''
|
|
208
|
+
if (!requested) return sendJson(res, 400, { ok: false, error: 'path is required' })
|
|
209
|
+
const b = await bindOrReply(req, res, {})
|
|
210
|
+
if (!b) return
|
|
211
|
+
const p = normalizeRemotePath(requested)
|
|
212
|
+
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path is required' })
|
|
213
|
+
const sftp = await b.pool.sftp()
|
|
214
|
+
const st = await sftp.stat(p).catch((error) => {
|
|
215
|
+
if (missingRemoteFile(error)) return null
|
|
216
|
+
throw error
|
|
217
|
+
})
|
|
218
|
+
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
219
|
+
if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
|
|
220
|
+
const size = Number(st.size) || 0
|
|
221
|
+
if (config.maxFileBytes > 0 && size > config.maxFileBytes) {
|
|
222
|
+
return sendJson(res, 400, { ok: false, error: `file is ${size} bytes (over ${config.maxFileBytes} cap)` })
|
|
223
|
+
}
|
|
224
|
+
const name = String(p).split(/[\\/]/).filter(Boolean).pop() || 'download'
|
|
225
|
+
res.statusCode = 200
|
|
226
|
+
res.setHeader('Content-Type', 'application/octet-stream')
|
|
227
|
+
res.setHeader('Content-Disposition', contentDisposition(name))
|
|
228
|
+
res.setHeader('Content-Length', String(size))
|
|
229
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
230
|
+
// Read by the UI to name the saved file: Content-Disposition parsing
|
|
231
|
+
// differs per browser, a plain field does not.
|
|
232
|
+
res.setHeader('X-Dsh-Download-Name', encodeURIComponent(name))
|
|
233
|
+
if (!b.local) audit('download', `download ${p} (to browser)`, 0, b)
|
|
234
|
+
// Fetch consumers can receive a body without Content-Length after
|
|
235
|
+
// carrier forwarding. Explicitly fail if the file ends early.
|
|
236
|
+
if (typeof res.stream === 'function') return res.stream(downloadChunks(sftp, p, size, true))
|
|
237
|
+
streaming = true
|
|
238
|
+
await streamFileToResponse(sftp, p, size, res)
|
|
239
|
+
} catch (err) {
|
|
240
|
+
if (streaming) { try { res.destroy(err) } catch { /* already gone */ } return }
|
|
241
|
+
return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err) })
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
},
|
|
122
245
|
{
|
|
123
246
|
kind: 'exact',
|
|
124
247
|
path: '/dsh-remote/read',
|
|
@@ -208,6 +331,26 @@ export function createFsRoutes({
|
|
|
208
331
|
const b = await bindOrReply(req, res, body)
|
|
209
332
|
if (!b) return
|
|
210
333
|
if (b.local && op === 'download') return sendJson(res, 400, { ok: false, error: 'Local files are already on this host; no mirror download is needed' })
|
|
334
|
+
if (op === 'revealLocal') {
|
|
335
|
+
// Issue #207: "download to local mirror" used to end in a file the
|
|
336
|
+
// user could not find — no path picker is involved by design, and
|
|
337
|
+
// the explorer discarded the response entirely. The UI now offers
|
|
338
|
+
// "show in folder", backed by this op. The target is ALWAYS fenced
|
|
339
|
+
// to the plugin's own mirror tree; arbitrary local paths are
|
|
340
|
+
// refused (this is not a file launcher).
|
|
341
|
+
if (typeof openLocalPath !== 'function' || typeof mirrorRoot !== 'function') {
|
|
342
|
+
return sendJson(res, 501, { ok: false, error: 'reveal is not available on this host' })
|
|
343
|
+
}
|
|
344
|
+
const resolved = path.resolve(String(body.path || ''))
|
|
345
|
+
const rootDir = path.resolve(mirrorRoot())
|
|
346
|
+
if (!resolved.startsWith(rootDir + path.sep)) {
|
|
347
|
+
return sendJson(res, 400, { ok: false, error: 'revealLocal only accepts paths inside the local mirror tree' })
|
|
348
|
+
}
|
|
349
|
+
if (!existsSync(resolved)) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
350
|
+
const r = await openLocalPath(resolved, 'reveal')
|
|
351
|
+
if (!r.ok) return sendJson(res, r.httpStatus || 500, { ok: false, error: r.error, path: resolved })
|
|
352
|
+
return sendJson(res, 200, { ok: true, path: resolved, how: r.how })
|
|
353
|
+
}
|
|
211
354
|
const sftp = await b.pool.sftp()
|
|
212
355
|
if (op === 'mkdir') {
|
|
213
356
|
const p = normalizeRemotePath(String(body.path || ''))
|
|
@@ -230,11 +373,18 @@ export function createFsRoutes({
|
|
|
230
373
|
if (op === 'remove') {
|
|
231
374
|
const p = normalizeRemotePath(String(body.path || ''))
|
|
232
375
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
233
|
-
const st = await sftp.
|
|
376
|
+
const st = await sftp.lstat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
|
|
234
377
|
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
235
|
-
if (st.isDirectory
|
|
378
|
+
if (st.isDirectory?.()) {
|
|
236
379
|
if (b.local) await b.pool.removeTree(p)
|
|
237
|
-
else
|
|
380
|
+
else {
|
|
381
|
+
const result = await removeRemoteTree(sftp, p)
|
|
382
|
+
if (result.error) {
|
|
383
|
+
audit('remove', result.error, 1, b)
|
|
384
|
+
if (result.removed) onRemoteMutation()
|
|
385
|
+
return sendJson(res, result.failed ? 500 : 409, { ok: false, code: 'REMOTE_REMOVE_INCOMPLETE', ...result })
|
|
386
|
+
}
|
|
387
|
+
}
|
|
238
388
|
} else {
|
|
239
389
|
await sftp.unlink(p)
|
|
240
390
|
}
|
|
@@ -263,15 +413,17 @@ export function createFsRoutes({
|
|
|
263
413
|
const ws = b.ws
|
|
264
414
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
265
415
|
if (!ws) return sendJson(res, 400, { ok: false, error: 'no remote workspace set' })
|
|
266
|
-
const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port)
|
|
267
|
-
const
|
|
416
|
+
const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port, b.alias)
|
|
417
|
+
const target = mirrorDownloadTarget(base, ws, p)
|
|
268
418
|
const st = await sftp.stat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
|
|
269
419
|
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
270
420
|
if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
|
|
271
421
|
if (config.maxFileBytes > 0 && st.size > config.maxFileBytes) {
|
|
272
422
|
return sendJson(res, 400, { ok: false, error: `file is ${st.size} bytes (over ${config.maxFileBytes} cap)` })
|
|
273
423
|
}
|
|
274
|
-
|
|
424
|
+
const mirror = b.bound ? base : ensureBoundMirror(ws, b)
|
|
425
|
+
const local = mirror === base ? target : mirrorDownloadTarget(mirror, ws, p)
|
|
426
|
+
assertDownloadHasNoSymlinks(mirror, local)
|
|
275
427
|
mkdirSync(path.dirname(local), { recursive: true })
|
|
276
428
|
await sftp.fastGet(p, local)
|
|
277
429
|
if (!b.local) audit('download', `download ${p}`, 0, b)
|
package/lib/routes-machines.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { existsSync, mkdirSync, writeFileSync, readFileSync, renameSync, rmSync, statSync, chmodSync, realpathSync, lstatSync } from 'node:fs'
|
|
9
9
|
import { createHash, randomUUID } from 'node:crypto'
|
|
10
10
|
import path from 'node:path'
|
|
11
|
-
import { listAliases, sshConfigPath, readSshConfigText } from './sshconfig.js'
|
|
11
|
+
import { listAliases, sshConfigPath, readSshConfigText, sshAliasTarget } from './sshconfig.js'
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* @param {object} deps
|
|
@@ -67,6 +67,16 @@ export function createMachineRoutes({ sendJson, readBody, parseJsonObject, store
|
|
|
67
67
|
})
|
|
68
68
|
}
|
|
69
69
|
const existing = machines.find((m) => m.useSshConfig && String(m.host) === alias)
|
|
70
|
+
// Issue #211: an alias whose Host block carries an IdentityFile
|
|
71
|
+
// (and nothing native cannot honor, like a jump host) can go on
|
|
72
|
+
// the native backend — one persistent connection instead of a
|
|
73
|
+
// `ssh` spawn per command, which costs a full TCP+SSH handshake
|
|
74
|
+
// every time (6x per-command latency on a 72ms link). Only a Host
|
|
75
|
+
// block with no key for ssh2 (agent/keychain/GSSAPI territory)
|
|
76
|
+
// still needs the system `ssh`.
|
|
77
|
+
const aliasTarget = sshAliasTarget(alias, { text: sshConfigText() })
|
|
78
|
+
const aliasKeyPath = (aliasTarget && aliasTarget.privateKeyPath) || ''
|
|
79
|
+
const aliasNeedsSsh = !aliasKeyPath || !!(aliasTarget && aliasTarget.proxy)
|
|
70
80
|
let rec = existing
|
|
71
81
|
if (!rec) {
|
|
72
82
|
rec = {
|
|
@@ -77,18 +87,16 @@ export function createMachineRoutes({ sendJson, readBody, parseJsonObject, store
|
|
|
77
87
|
port: Number(known.port) || 22,
|
|
78
88
|
username: String(known.user || ''),
|
|
79
89
|
password: '',
|
|
80
|
-
|
|
90
|
+
// A snapshot of the file's IdentityFile for the backend
|
|
91
|
+
// decision; the file itself stays the source of truth at dial
|
|
92
|
+
// time (withSshConfig re-resolves on every connect).
|
|
93
|
+
privateKeyPath: aliasKeyPath,
|
|
81
94
|
passphrase: '',
|
|
82
95
|
workspace: '',
|
|
83
96
|
hostKeyMode: '',
|
|
84
97
|
useAgent: false,
|
|
85
98
|
keyboardInteractive: false,
|
|
86
|
-
|
|
87
|
-
// is what interprets that file (default identity discovery,
|
|
88
|
-
// agent/keychain, ProxyJump, GSSAPI). Native cannot see any of
|
|
89
|
-
// it, so a Host block with no IdentityFile would be reported as
|
|
90
|
-
// "no credentials".
|
|
91
|
-
backend: 'openssh',
|
|
99
|
+
backend: aliasNeedsSsh ? 'openssh' : 'native',
|
|
92
100
|
sshBinary: '',
|
|
93
101
|
credentialBackend: 'plain',
|
|
94
102
|
recentWorkspaces: [],
|
package/lib/routes-web-attach.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// file only adapts the HTTP surface to it. The state it drives belongs to the
|
|
6
6
|
// plugin entry and arrives as `deps`: the live-attach map, the machine
|
|
7
7
|
// registry array, the per-identity pool resolver, and the audit sink.
|
|
8
|
-
import { WebAttach } from './web-attach.js'
|
|
8
|
+
import { WebAttach, stopRemoteReport } from './web-attach.js'
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* @param {object} deps
|
|
@@ -25,6 +25,21 @@ import { WebAttach } from './web-attach.js'
|
|
|
25
25
|
* @returns {Array<object>} route descriptors for registerHttpTransports.
|
|
26
26
|
*/
|
|
27
27
|
export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, config, webAttaches, store, machines, poolForMachine, identityOf, webAttachCommandFor, webAttachDiscoverCommandFor, audit }) {
|
|
28
|
+
// Concurrent-open gate for the `open` action: machineId → the promise of
|
|
29
|
+
// the open currently holding the slot. The factory is mounted exactly once
|
|
30
|
+
// per boot (main.js route table), so closure scope is all the state this
|
|
31
|
+
// serialization needs. Continues the web-attach lifecycle line — #54
|
|
32
|
+
// (stale client), #125 (discovery), #204 (self-reconnect): those fixes
|
|
33
|
+
// made one SESSION survive its connection; this one makes one MACHINE
|
|
34
|
+
// hold one session even when two opens are fired at it at once. Without
|
|
35
|
+
// the gate, the live-check ran before the multi-second `await
|
|
36
|
+
// attach.open()`, so both requests saw "no live tunnel" and both
|
|
37
|
+
// proceeded; the second `webAttaches.set` overwrote the first session,
|
|
38
|
+
// stranding a local listener that stayed bound but invisible (status
|
|
39
|
+
// lists map values, close touches the map entry, the unload sweeper in
|
|
40
|
+
// main.js iterates map values) — and on the launch path an extra remote
|
|
41
|
+
// `dsh web` kept running that nothing could stop.
|
|
42
|
+
const opening = new Map()
|
|
28
43
|
return [
|
|
29
44
|
{
|
|
30
45
|
kind: 'exact',
|
|
@@ -56,46 +71,85 @@ export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
56
71
|
// second remote DSH and leak the first one's process.
|
|
57
72
|
const live = webAttaches.get(machineId)
|
|
58
73
|
if (live && live.active) return sendJson(res, 200, { ok: true, attach: live.describe(), reused: true })
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
74
|
+
for (;;) {
|
|
75
|
+
const pending = opening.get(machineId)
|
|
76
|
+
if (!pending) {
|
|
77
|
+
// This request holds the slot: the WHOLE open sequence —
|
|
78
|
+
// stale teardown included — runs as one task, so a concurrent
|
|
79
|
+
// request can neither double-close a stale entry nor land its
|
|
80
|
+
// own `webAttaches.set` between the live-check above and the
|
|
81
|
+
// first one's.
|
|
82
|
+
const task = (async () => {
|
|
83
|
+
// A tunnel that is no longer listening still owns sockets and
|
|
84
|
+
// a log path; release it before this machine gets a fresh
|
|
85
|
+
// session. Its remote process is left alone — stopping it
|
|
86
|
+
// stays an explicit act. Re-read the registry: this request
|
|
87
|
+
// may have waited behind an earlier open (or its failure)
|
|
88
|
+
// that changed it in the meantime.
|
|
89
|
+
const stale = webAttaches.get(machineId)
|
|
90
|
+
if (stale) { try { await stale.close() } catch { /* already torn down */ } }
|
|
91
|
+
const machine = machines.find((m) => m.id === machineId)
|
|
92
|
+
if (!machine) return sendJson(res, 404, { ok: false, error: `机器不存在:${machineId}` })
|
|
93
|
+
const attachPool = poolForMachine(identityOf(machine))
|
|
94
|
+
const attach = new WebAttach({
|
|
95
|
+
localPortStart: config.webAttachPortStart,
|
|
96
|
+
// Issue #54: follow the chosen pool's lifecycle so a dropped
|
|
97
|
+
// SSH connection degrades to "disconnected" and then
|
|
98
|
+
// self-heals, instead of leaving a dead client that crashes
|
|
99
|
+
// the host process.
|
|
100
|
+
trackPool: true,
|
|
101
|
+
})
|
|
102
|
+
try {
|
|
103
|
+
await attach.open({
|
|
104
|
+
pool: attachPool,
|
|
105
|
+
machineId,
|
|
106
|
+
command: String(body.command || '').trim() || webAttachCommandFor(machine),
|
|
107
|
+
profile: 'web',
|
|
108
|
+
existingUrl: String(body.existingUrl || ''),
|
|
109
|
+
// Issue #125: a per-call override wins, then the machine's
|
|
110
|
+
// own setting; '' disables discovery entirely (previous
|
|
111
|
+
// behaviour).
|
|
112
|
+
discoverCommand: String(body.discoverCommand || '').trim()
|
|
113
|
+
|| (typeof webAttachDiscoverCommandFor === 'function' ? webAttachDiscoverCommandFor(machine) : ''),
|
|
114
|
+
dshHome: config.webAttachDshHome || '',
|
|
115
|
+
waitSeconds: config.webAttachWaitSeconds,
|
|
116
|
+
})
|
|
117
|
+
} catch (err) {
|
|
118
|
+
try { await attach.close() } catch { /* nothing was listening */ }
|
|
119
|
+
const msg = String((err && err.message) || err)
|
|
120
|
+
audit('web-attach', `open ${machine.host} failed: ${msg}`, 1, machine)
|
|
121
|
+
return sendJson(res, 500, { ok: false, error: msg })
|
|
122
|
+
}
|
|
123
|
+
webAttaches.set(machineId, attach)
|
|
124
|
+
// The audit line records WHICH path opened the tunnel, but
|
|
125
|
+
// never the discovered URL itself — it carries a live login
|
|
126
|
+
// token.
|
|
127
|
+
audit('web-attach', `open ${machine.host} → 127.0.0.1:${attach.localPort}`
|
|
128
|
+
+ (attach.discovery ? ` (discover: ${attach.discovery})` : ''), 0, machine)
|
|
129
|
+
return sendJson(res, 200, { ok: true, attach: attach.describe() })
|
|
130
|
+
})()
|
|
131
|
+
opening.set(machineId, task)
|
|
132
|
+
try {
|
|
133
|
+
await task
|
|
134
|
+
} finally {
|
|
135
|
+
// Hand the slot back only when it still holds THIS task: a
|
|
136
|
+
// joiner that fell through after a failure installs its own.
|
|
137
|
+
if (opening.get(machineId) === task) opening.delete(machineId)
|
|
138
|
+
}
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
// Another request is already opening this machine. Its own
|
|
142
|
+
// outcome (200 or 500) was answered on ITS response, so only
|
|
143
|
+
// "did it leave a live tunnel" matters here.
|
|
144
|
+
try { await pending } catch { /* already answered as a 500 */ }
|
|
145
|
+
const winner = webAttaches.get(machineId)
|
|
146
|
+
if (winner && winner.active) {
|
|
147
|
+
return sendJson(res, 200, { ok: true, attach: winner.describe(), reused: true })
|
|
148
|
+
}
|
|
149
|
+
// No live tunnel (the in-flight open failed, or its session was
|
|
150
|
+
// closed again): loop — join the next in-flight open if one
|
|
151
|
+
// started, or claim the slot and run it ourselves.
|
|
92
152
|
}
|
|
93
|
-
webAttaches.set(machineId, attach)
|
|
94
|
-
// The audit line records WHICH path opened the tunnel, but never
|
|
95
|
-
// the discovered URL itself — it carries a live login token.
|
|
96
|
-
audit('web-attach', `open ${machine.host} → 127.0.0.1:${attach.localPort}`
|
|
97
|
-
+ (attach.discovery ? ` (discover: ${attach.discovery})` : ''), 0, machine)
|
|
98
|
-
return sendJson(res, 200, { ok: true, attach: attach.describe() })
|
|
99
153
|
}
|
|
100
154
|
|
|
101
155
|
if (action === 'close') {
|
|
@@ -105,10 +159,28 @@ export function createWebAttachRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
105
159
|
// `close()` refuses to signal anything without a recorded PID, so a
|
|
106
160
|
// tunnel onto the user's own running instance stays hands-off.
|
|
107
161
|
const exec = (cmd) => poolForMachine(identityOf(machines.find((m) => m.id === machineId) || {})).exec(cmd, { timeoutMs: 10000 })
|
|
108
|
-
|
|
162
|
+
const managed = attach.remotePid > 0
|
|
163
|
+
const stop = await attach.close({ stopRemote, exec })
|
|
109
164
|
webAttaches.delete(machineId)
|
|
110
|
-
|
|
111
|
-
|
|
165
|
+
// Honest reporting, continuing the #271/#272 line (recursive remove
|
|
166
|
+
// reports incompleteness): `stoppedRemote` is what the stop command
|
|
167
|
+
// PROVED, never a restatement of the request. close() classifies the
|
|
168
|
+
// command's markers; the one legacy shape kept on purpose is the
|
|
169
|
+
// /proc-less remote, which cannot be checked either way — there the
|
|
170
|
+
// old `true` survives but is labelled unverified.
|
|
171
|
+
const report = !stopRemote
|
|
172
|
+
? { stoppedRemote: false, note: '' }
|
|
173
|
+
: managed
|
|
174
|
+
? stopRemoteReport(stop && stop.stopOutcome)
|
|
175
|
+
: { stoppedRemote: false, note: 'remote stop skipped: no pid of ours' }
|
|
176
|
+
const closeBody = { ok: true, closed: true, stoppedRemote: report.stoppedRemote }
|
|
177
|
+
if (report.note) closeBody.stoppedRemoteNote = report.note
|
|
178
|
+
// An honestly-failed stop is audited as a failure; the audit line
|
|
179
|
+
// used to claim "(remote stopped)" unconditionally.
|
|
180
|
+
const outcome = managed ? (stop && stop.stopOutcome) : null
|
|
181
|
+
const failedStop = outcome === 'failed' || outcome === 'refused' || outcome === 'error'
|
|
182
|
+
audit('web-attach', `close ${attach.cleanUrl}${stopRemote ? (report.note ? ` (${report.note})` : ' (remote stopped)') : ''}`, failedStop ? 1 : 0)
|
|
183
|
+
return sendJson(res, 200, closeBody)
|
|
112
184
|
}
|
|
113
185
|
|
|
114
186
|
return sendJson(res, 400, { ok: false, error: 'action must be open | close' })
|
package/lib/routes-workspace.js
CHANGED
|
@@ -24,6 +24,7 @@ import { createHostKeyGuard } from './hostkey.js'
|
|
|
24
24
|
* @param {(remotePath: string, host: string, user: string, port: number, extra?: object) => string} deps.ensureMirror
|
|
25
25
|
* @param {(m: object) => string} deps.aliasOf
|
|
26
26
|
* @param {() => object|null} deps.activeMachine
|
|
27
|
+
* @param {() => object} deps.activeMirrorOrigin
|
|
27
28
|
* @param {(localDir: string) => void} deps.startAutoPush
|
|
28
29
|
* @param {(body: object, res: object) => Promise<boolean>} deps.applyRequestedMachine - picker re-assertion (replies on mismatch).
|
|
29
30
|
* @param {(localDir: string, remotePath: string, machine: object) => Promise<void>} deps.registerMirroredWorkspace
|
|
@@ -35,7 +36,7 @@ import { createHostKeyGuard } from './hostkey.js'
|
|
|
35
36
|
* @param {() => string} deps.knownHostsFile
|
|
36
37
|
* @returns {Array<object>} route descriptors for registerHttpTransports.
|
|
37
38
|
*/
|
|
38
|
-
export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror, aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability, pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId }) {
|
|
39
|
+
export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, config, pool, backendFor, status, isRemoteDir, persistWorkspace, ensureMirror, aliasOf, activeMachine, activeMirrorOrigin, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability, pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId }) {
|
|
39
40
|
return [
|
|
40
41
|
{
|
|
41
42
|
kind: 'exact',
|
|
@@ -91,8 +92,9 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
91
92
|
const p = normalizeRemotePath(rawPath)
|
|
92
93
|
const okDir = await isRemoteDir(p)
|
|
93
94
|
if (!okDir) return sendJson(res, 400, { ok: false, error: `not a directory: ${p}` })
|
|
95
|
+
const { host, username, port, alias } = activeMirrorOrigin()
|
|
96
|
+
const local = ensureMirror(p, host, username, port, { alias })
|
|
94
97
|
persistWorkspace(p)
|
|
95
|
-
const local = ensureMirror(p, config.host, config.username, config.port, { alias: aliasOf(activeMachine()) })
|
|
96
98
|
startAutoPush(local)
|
|
97
99
|
return sendJson(res, 200, { ok: true, workspace: p, localMirror: local, ...status() })
|
|
98
100
|
} catch (err) {
|
|
@@ -106,11 +108,15 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
106
108
|
handler: async (req, res) => {
|
|
107
109
|
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
|
|
108
110
|
const controller = new AbortController()
|
|
111
|
+
const signal = req.signal ? AbortSignal.any([req.signal, controller.signal]) : controller.signal
|
|
109
112
|
const cancel = () => { if (!res.writableEnded) controller.abort() }
|
|
110
113
|
res.once?.('close', cancel)
|
|
111
114
|
req.once?.('aborted', cancel)
|
|
112
115
|
try {
|
|
113
|
-
|
|
116
|
+
if (signal.aborted) return
|
|
117
|
+
const raw = await readBody(req)
|
|
118
|
+
if (signal.aborted) return
|
|
119
|
+
const payload = JSON.parse(raw || '{}')
|
|
114
120
|
// Blank-only guard: a filesystem root is a legal workspace (issue
|
|
115
121
|
// #60); the real directory probe below answers everything else.
|
|
116
122
|
const rawPath = String(payload.path || '').trim()
|
|
@@ -120,13 +126,13 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
120
126
|
// switch made elsewhere between the listing and this commit cannot
|
|
121
127
|
// mirror onto a machine the user never looked at (the picker sends
|
|
122
128
|
// /current only once per machine now, so nothing else re-applies it).
|
|
123
|
-
if (!(await applyRequestedMachine(payload, res))) return
|
|
129
|
+
if (!(await applyRequestedMachine(payload, res)) || signal.aborted) return
|
|
124
130
|
if (!config.host) return sendJson(res, 400, { ok: false, error: 'no remote host configured/connected — connect first' })
|
|
125
131
|
const selected = payload.machineId && machineForId ? machineForId(String(payload.machineId)) : activeMachine()
|
|
126
132
|
const prepared = prepareMirrorTarget
|
|
127
|
-
? await prepareMirrorTarget(p, selected,
|
|
133
|
+
? await prepareMirrorTarget(p, selected, signal)
|
|
128
134
|
: { ok: await isRemoteDir(p), machine: selected, identity: { host: config.host, username: config.username, port: config.port } }
|
|
129
|
-
if (
|
|
135
|
+
if (signal.aborted) return
|
|
130
136
|
if (!prepared.ok) return sendJson(res, 400, { ok: false, error: prepared.error || `not a directory (or unreachable): ${p}` })
|
|
131
137
|
const { machine, identity } = prepared
|
|
132
138
|
const local = ensureMirror(p, identity.host, identity.username, identity.port, { alias: aliasOf(machine) })
|
|
@@ -139,11 +145,11 @@ export function createWorkspaceRoutes({ sendJson, readBody, parseJsonObject, con
|
|
|
139
145
|
// last segment. Callers that only pick a folder (settings page, Remote
|
|
140
146
|
// Files explorer) opt out with registerWorkspace:false, so no stray
|
|
141
147
|
// workspace appears in their flow.
|
|
142
|
-
if (payload.registerWorkspace !== false) await registerMirroredWorkspace(local, p, machine,
|
|
143
|
-
if (
|
|
148
|
+
if (payload.registerWorkspace !== false) await registerMirroredWorkspace(local, p, machine, signal)
|
|
149
|
+
if (signal.aborted) return
|
|
144
150
|
return sendJson(res, 200, { ok: true, ...status(), path: p, localMirror: local, machine: identity })
|
|
145
151
|
} catch (err) {
|
|
146
|
-
if (!
|
|
152
|
+
if (!signal.aborted) return sendJson(res, 500, { ok: false, error: friendlyMessage(err) })
|
|
147
153
|
} finally {
|
|
148
154
|
res.removeListener?.('close', cancel)
|
|
149
155
|
req.removeListener?.('aborted', cancel)
|