dsh-remote 1.5.0 → 1.6.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 +1 -1
- package/README.md +1 -1
- package/lib/binding.js +100 -84
- package/lib/client.js +107 -45
- package/lib/connect-summary.js +28 -0
- package/lib/file-reference.js +75 -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/main.js +279 -229
- package/lib/mirror-paths.js +107 -2
- package/lib/openssh.js +51 -1
- package/lib/pool.js +9 -0
- package/lib/registry.js +47 -7
- package/lib/remote-fs.js +43 -19
- package/lib/remote-git.js +53 -5
- package/lib/routes-fs.js +33 -17
- 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 +137 -20
- package/lib/workspace-cleanup.js +85 -60
- package/lib/workspace-files-remote.js +154 -3
- package/package.json +2 -2
package/lib/mirror-paths.js
CHANGED
|
@@ -1,8 +1,113 @@
|
|
|
1
1
|
// Files crossing between a remote workspace and its local mirror must obey
|
|
2
2
|
// both path grammars and must never traverse local symlinks.
|
|
3
|
-
import { lstatSync } from 'node:fs'
|
|
3
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
4
4
|
import path from 'node:path'
|
|
5
|
-
import { normalizeRemotePath } from './paths.js'
|
|
5
|
+
import { normalizeRemotePath, remotePathBase, shortHash } from './paths.js'
|
|
6
|
+
|
|
7
|
+
const MIRROR_META = '.dsh-remote-meta.json'
|
|
8
|
+
const lstat = (p) => lstatSync(p, { throwIfNoEntry: false })
|
|
9
|
+
|
|
10
|
+
function childDirectories(dir) {
|
|
11
|
+
try {
|
|
12
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
13
|
+
.filter(entry => entry.isDirectory())
|
|
14
|
+
.map(entry => entry.name)
|
|
15
|
+
.sort()
|
|
16
|
+
} catch { return [] }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function* mirrorDirectoriesUnder(root) {
|
|
20
|
+
for (const name of childDirectories(root)) {
|
|
21
|
+
const group = path.join(root, name)
|
|
22
|
+
for (const entry of childDirectories(group)) yield path.join(group, entry)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function readMirrorMeta(dir) {
|
|
27
|
+
try {
|
|
28
|
+
if (!lstat(path.dirname(dir))?.isDirectory() || !lstat(dir)?.isDirectory()) return null
|
|
29
|
+
const file = path.join(dir, MIRROR_META)
|
|
30
|
+
if (lstat(file)?.isFile()) return JSON.parse(readFileSync(file, 'utf8'))
|
|
31
|
+
} catch { /* occupied by something other than a readable mirror */ }
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function sameMirrorMachine(meta, { host, username, port, alias = '' }) {
|
|
36
|
+
if (!meta || typeof meta.host !== 'string' || !meta.host || typeof meta.username !== 'string') return false
|
|
37
|
+
const storedPort = typeof meta.port === 'string' && /^\d+$/.test(meta.port) ? Number(meta.port) : meta.port
|
|
38
|
+
if (!Number.isInteger(storedPort) || storedPort < 1 || storedPort > 65535) return false
|
|
39
|
+
// A saved SSH alias is the identity even when its resolved address changes.
|
|
40
|
+
// Literal connections use every component of the recorded endpoint.
|
|
41
|
+
const storedAlias = meta.alias === undefined ? '' : meta.alias
|
|
42
|
+
if (typeof storedAlias !== 'string') return false
|
|
43
|
+
if (alias || storedAlias) return alias === storedAlias
|
|
44
|
+
return meta.host === host && meta.username === username && storedPort === port
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function mirrorSegment(name, fallback) {
|
|
48
|
+
if (!name || name === '.' || name === '..' || name.includes('\0') || Buffer.byteLength(name) > 255) return fallback
|
|
49
|
+
if (process.platform === 'win32' && (/[<>:"|?*\\\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name))) return fallback
|
|
50
|
+
return name
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Claim a new directory without adopting an existing entry. Another allocator
|
|
54
|
+
// may have created it since the last lookup.
|
|
55
|
+
function claimDirectory(dir) {
|
|
56
|
+
try {
|
|
57
|
+
mkdirSync(dir)
|
|
58
|
+
return true
|
|
59
|
+
} catch (err) {
|
|
60
|
+
if (err.code !== 'EEXIST') throw err
|
|
61
|
+
return false
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function mirrorDirectory(root, remotePath, host, username, port, { alias = '', create = false } = {}) {
|
|
66
|
+
const origin = { host: String(host || ''), port: Number(port) || 22, username: String(username || ''), alias }
|
|
67
|
+
const remote = normalizeRemotePath(remotePath)
|
|
68
|
+
const tag = mirrorSegment([origin.host, origin.username, origin.port].filter(Boolean).join('-').replace(/[^a-zA-Z0-9._-]/g, '_'), 'machine')
|
|
69
|
+
const base = mirrorSegment(remotePathBase(remote), 'workspace')
|
|
70
|
+
const hash = shortHash(remote)
|
|
71
|
+
const suffix = mirrorSegment(base + '-' + hash, 'workspace-' + hash)
|
|
72
|
+
const preferred = path.join(root, tag)
|
|
73
|
+
const matches = (dir) => {
|
|
74
|
+
const meta = readMirrorMeta(dir)
|
|
75
|
+
return meta?.remotePath === remote && sameMirrorMachine(meta, origin)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Try both historical names first. A rebound mirror may live under its old
|
|
79
|
+
// machine directory, and a suffixed mirror still belongs to its workspace
|
|
80
|
+
// after a directory that once blocked the preferred name is removed.
|
|
81
|
+
for (const name of [base, suffix]) {
|
|
82
|
+
const dir = path.join(preferred, name)
|
|
83
|
+
if (matches(dir)) return dir
|
|
84
|
+
}
|
|
85
|
+
for (const dir of mirrorDirectoriesUnder(root)) {
|
|
86
|
+
if (matches(dir)) return dir
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (create) mkdirSync(root, { recursive: true })
|
|
90
|
+
let group
|
|
91
|
+
for (let n = 1; ; n++) {
|
|
92
|
+
group = path.join(root, n === 1 ? tag : mirrorSegment(tag + '-' + n, 'machine-' + n))
|
|
93
|
+
const entry = lstat(group)
|
|
94
|
+
if (entry?.isDirectory()) break
|
|
95
|
+
if (!entry && (!create || claimDirectory(group) || lstat(group)?.isDirectory())) break
|
|
96
|
+
}
|
|
97
|
+
for (let n = 0; ; n++) {
|
|
98
|
+
const name = n === 0 ? base : n === 1 ? suffix : mirrorSegment(suffix + '-' + n, 'workspace-' + hash + '-' + n)
|
|
99
|
+
const dir = path.join(group, name)
|
|
100
|
+
if (!lstat(dir) && (!create || claimDirectory(dir))) {
|
|
101
|
+
if (create) {
|
|
102
|
+
const meta = { host: origin.host, port: origin.port, username: origin.username, remotePath: remote, createdAt: new Date().toISOString() }
|
|
103
|
+
if (alias) meta.alias = alias
|
|
104
|
+
writeFileSync(path.join(dir, MIRROR_META), JSON.stringify(meta, null, 2), { flag: 'wx' })
|
|
105
|
+
}
|
|
106
|
+
return dir
|
|
107
|
+
}
|
|
108
|
+
if (matches(dir)) return dir
|
|
109
|
+
}
|
|
110
|
+
}
|
|
6
111
|
|
|
7
112
|
const unsafeDownload = () => Object.assign(new Error('The download destination must be a regular file inside this workspace mirror'), { httpStatus: 403 })
|
|
8
113
|
|
package/lib/openssh.js
CHANGED
|
@@ -562,6 +562,8 @@ export class SystemOpenSshPool {
|
|
|
562
562
|
/** The persistent `ssh -s ... sftp` session (kept across calls). */
|
|
563
563
|
this._sftpSession = null
|
|
564
564
|
this._sftpChild = null
|
|
565
|
+
/** Live `ssh` command children (_runSsh) for close()/invalidate() to reap. */
|
|
566
|
+
this._commandChildren = new Set()
|
|
565
567
|
/** Memoized askpass secret for this target (null = not resolved yet). */
|
|
566
568
|
this._secret = null
|
|
567
569
|
this._secretPromise = null
|
|
@@ -759,6 +761,12 @@ export class SystemOpenSshPool {
|
|
|
759
761
|
const sshBinary = resolveSshBinary(this.config)
|
|
760
762
|
const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
|
|
761
763
|
return new Promise((resolve) => {
|
|
764
|
+
// A pre-aborted signal must stop BEFORE the ssh child exists: the old
|
|
765
|
+
// order spawned first and killed after, so the command was already on
|
|
766
|
+
// its way to the host when the cancellation was honoured.
|
|
767
|
+
if (opts.signal?.aborted) {
|
|
768
|
+
return resolve({ code: -1, signal: 'ABORTED', stdout: '', stderr: '' })
|
|
769
|
+
}
|
|
762
770
|
let child
|
|
763
771
|
try {
|
|
764
772
|
child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
|
|
@@ -769,6 +777,13 @@ export class SystemOpenSshPool {
|
|
|
769
777
|
// after the command already exited (Git Bash); a broken pipe there must
|
|
770
778
|
// fail the call, not the process (issue #118).
|
|
771
779
|
guardChildStdin(child)
|
|
780
|
+
// Track the child for close()/invalidate(): a no-deadline call
|
|
781
|
+
// (timeoutMs 0, a promoted background job) arms NO timer, so without this
|
|
782
|
+
// bookkeeping a close() reported success while the command kept running.
|
|
783
|
+
this._commandChildren.add(child)
|
|
784
|
+
const reapChild = () => this._commandChildren.delete(child)
|
|
785
|
+
child.on('close', reapChild)
|
|
786
|
+
child.on('error', reapChild)
|
|
772
787
|
let stdout = ''
|
|
773
788
|
let stderr = ''
|
|
774
789
|
let settled = false
|
|
@@ -885,6 +900,12 @@ export class SystemOpenSshPool {
|
|
|
885
900
|
const sshBinary = resolveSshBinary(this.config)
|
|
886
901
|
const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
|
|
887
902
|
const child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
|
|
903
|
+
// Adopt the child BEFORE the handshake: `this._sftpChild` used to be assigned
|
|
904
|
+
// only once the handshake completed, so a close()/invalidate() while it was
|
|
905
|
+
// still pending killed nothing and the fresh `ssh -s sftp` child lived until
|
|
906
|
+
// its own commandTimeoutMs timer. _dropSftpSession() reaps this field, so a
|
|
907
|
+
// pending child now dies with the pool.
|
|
908
|
+
this._sftpChild = child
|
|
888
909
|
|
|
889
910
|
// ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
|
|
890
911
|
// and reads `_remoteIdentRaw` to pick its packet sizes.
|
|
@@ -977,7 +998,13 @@ export class SystemOpenSshPool {
|
|
|
977
998
|
if (settled) return
|
|
978
999
|
settled = true
|
|
979
1000
|
clearTimeout(timer)
|
|
980
|
-
if (err) {
|
|
1001
|
+
if (err) {
|
|
1002
|
+
// The handshake failed: drop the child adopted at spawn so a later
|
|
1003
|
+
// close() never mistakes a dead pid for a live session.
|
|
1004
|
+
if (this._sftpChild === child) this._sftpChild = null
|
|
1005
|
+
try { child.kill() } catch {}
|
|
1006
|
+
reject(err)
|
|
1007
|
+
} else resolve({ child, sftp })
|
|
981
1008
|
}
|
|
982
1009
|
const timer = setTimeout(() => {
|
|
983
1010
|
done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
|
|
@@ -1014,6 +1041,9 @@ export class SystemOpenSshPool {
|
|
|
1014
1041
|
// A target switch during the handshake must not adopt the old host's
|
|
1015
1042
|
// session (the same generational guard connect() uses).
|
|
1016
1043
|
if (this.epoch !== epoch) {
|
|
1044
|
+
// The epoch change already dropped the session; make sure the child
|
|
1045
|
+
// adopted at spawn does not linger as this pool's sftp child either.
|
|
1046
|
+
if (this._sftpChild === child) this._sftpChild = null
|
|
1017
1047
|
try { child.kill() } catch {}
|
|
1018
1048
|
throw new Error('ssh target changed while opening sftp')
|
|
1019
1049
|
}
|
|
@@ -1045,10 +1075,29 @@ export class SystemOpenSshPool {
|
|
|
1045
1075
|
this._secretPromise = null
|
|
1046
1076
|
if (client) { try { client.close() } catch {} }
|
|
1047
1077
|
this._dropSftpSession()
|
|
1078
|
+
this._killCommandChildren()
|
|
1048
1079
|
if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
|
|
1049
1080
|
if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
|
|
1050
1081
|
}
|
|
1051
1082
|
|
|
1083
|
+
/**
|
|
1084
|
+
* Reap every live command child. A no-deadline `ssh` child (timeoutMs 0, a
|
|
1085
|
+
* promoted background job) has NO timer of its own, so without this a
|
|
1086
|
+
* close()/invalidate() reported success while remote commands kept running
|
|
1087
|
+
* (the audit3 leak). Each child gets the escalation a timed-out command
|
|
1088
|
+
* gets: SIGTERM, backed by an unref'd SIGKILL backstop.
|
|
1089
|
+
*/
|
|
1090
|
+
_killCommandChildren() {
|
|
1091
|
+
const children = [...this._commandChildren]
|
|
1092
|
+
this._commandChildren.clear()
|
|
1093
|
+
for (const child of children) {
|
|
1094
|
+
try { child.kill() } catch { /* already gone */ }
|
|
1095
|
+
try {
|
|
1096
|
+
setTimeout(() => { try { child.kill('SIGKILL') } catch { /* already gone */ } }, 800).unref?.()
|
|
1097
|
+
} catch { /* timer allocation failed; the SIGTERM stands */ }
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1052
1101
|
_dropSftpSession() {
|
|
1053
1102
|
const session = this._sftpSession
|
|
1054
1103
|
this._sftpSession = null
|
|
@@ -1069,6 +1118,7 @@ export class SystemOpenSshPool {
|
|
|
1069
1118
|
this._secretPromise = null
|
|
1070
1119
|
if (client) { try { client.close() } catch {} }
|
|
1071
1120
|
this._dropSftpSession()
|
|
1121
|
+
this._killCommandChildren()
|
|
1072
1122
|
if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
|
|
1073
1123
|
if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
|
|
1074
1124
|
}
|
package/lib/pool.js
CHANGED
|
@@ -646,6 +646,15 @@ export class SshPool {
|
|
|
646
646
|
let onAbort = null
|
|
647
647
|
const cleanupAbort = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort) }
|
|
648
648
|
const runOn = (c) => {
|
|
649
|
+
// A pre-aborted signal must stop BEFORE the exec request leaves:
|
|
650
|
+
// the old code only noticed inside the callback below — after the
|
|
651
|
+
// dispatch had already gone out. Every (re)connect attempt enters
|
|
652
|
+
// here, so a cancel that lands during the retry window below is
|
|
653
|
+
// caught by this same check too.
|
|
654
|
+
if (signal?.aborted) {
|
|
655
|
+
cleanupAbort()
|
|
656
|
+
return resolve({ code: -1, signal: 'ABORTED', stdout: '', stderr: '' })
|
|
657
|
+
}
|
|
649
658
|
const execOpts = {}
|
|
650
659
|
if (opts && opts.pty) execOpts.pty = true
|
|
651
660
|
if (opts && opts.env && typeof opts.env === 'object') execOpts.env = opts.env
|
package/lib/registry.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// Keeping this logic in one module makes the guarantee unit-testable and
|
|
11
11
|
// shared between the HTTP routes and the tools (rw_connect).
|
|
12
12
|
|
|
13
|
-
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs'
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync, renameSync, rmSync, existsSync } from 'node:fs'
|
|
14
14
|
import path from 'node:path'
|
|
15
15
|
|
|
16
16
|
/** Load { list, currentId, explicitNone } from the registry file. */
|
|
@@ -30,7 +30,20 @@ export function loadMachines(file) {
|
|
|
30
30
|
const explicitNone = Object.prototype.hasOwnProperty.call(j, 'currentId') && j.currentId == null
|
|
31
31
|
return { list, currentId, explicitNone }
|
|
32
32
|
}
|
|
33
|
-
} catch {
|
|
33
|
+
} catch {
|
|
34
|
+
// An EXISTING file that fails to read or parse is corrupt — classically a
|
|
35
|
+
// machines.json torn by a crash mid-write (the atomic saveMachines below
|
|
36
|
+
// prevents fresh tears). Returning the fail-safe empty registry is right,
|
|
37
|
+
// but the corrupt bytes are the only evidence of what was lost, and the
|
|
38
|
+
// next save would silently overwrite them. Quarantine the file aside —
|
|
39
|
+
// same directory, original bytes, 0600 preserved by the rename — before
|
|
40
|
+
// failing safe. This continues the #171 machines.json hardening. A file
|
|
41
|
+
// that never existed is a fresh install, not corruption: nothing to
|
|
42
|
+
// preserve.
|
|
43
|
+
if (existsSync(file)) {
|
|
44
|
+
try { renameSync(file, file + '.corrupt-' + Date.now()) } catch { /* locked/unmovable — still fail safe below */ }
|
|
45
|
+
}
|
|
46
|
+
}
|
|
34
47
|
return { list: [], currentId: null, explicitNone: false }
|
|
35
48
|
}
|
|
36
49
|
|
|
@@ -55,7 +68,24 @@ export function saveMachines(file, list, currentId, keepCurrentKey = true) {
|
|
|
55
68
|
}
|
|
56
69
|
const payload = { list }
|
|
57
70
|
if (hasStored) payload.currentId = stored
|
|
58
|
-
|
|
71
|
+
// Atomic replace, continuing the #171 machines.json hardening: write a
|
|
72
|
+
// sibling temp file, then rename() it over the registry. The old bare
|
|
73
|
+
// writeFileSync() opened the LIVE file with O_TRUNC first, so a crash
|
|
74
|
+
// mid-write left a torn JSON that loadMachines() silently read as an empty
|
|
75
|
+
// registry — every saved machine vanished, and the next save erased the
|
|
76
|
+
// evidence. rename() within one directory is atomic, so a reader (or a
|
|
77
|
+
// crash) sees either the old bytes or the new ones, never a half-written
|
|
78
|
+
// file.
|
|
79
|
+
const tmp = file + '.tmp-' + process.pid + '-' + Date.now()
|
|
80
|
+
try {
|
|
81
|
+
// 0600 from the first byte: the temp file carries the same plaintext
|
|
82
|
+
// credentials as the registry, so it must never exist world-readable.
|
|
83
|
+
writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 })
|
|
84
|
+
renameSync(tmp, file)
|
|
85
|
+
} catch (err) {
|
|
86
|
+
try { rmSync(tmp, { force: true }) } catch { /* best-effort cleanup; never mask the real error */ }
|
|
87
|
+
throw err
|
|
88
|
+
}
|
|
59
89
|
// This file can carry plaintext credentials (password / passphrase under
|
|
60
90
|
// the default 'plain' backend), so keep it user-private — the same rule
|
|
61
91
|
// term-secret.json (main.js) and the ssh-config writer (routes-machines.js)
|
|
@@ -283,19 +313,29 @@ export function applyMachine(config, m) {
|
|
|
283
313
|
config.agentSocket = m.agentSocket || ''
|
|
284
314
|
config.identitiesOnly = !!m.identitiesOnly
|
|
285
315
|
config.workspace = m.workspace || (config.workspace || '')
|
|
286
|
-
|
|
316
|
+
// Continuing #206: an apply must fully own the per-machine policy fields.
|
|
317
|
+
// These assigns used to run only when the record carried the field, so a
|
|
318
|
+
// bare record — rw_connect's minimal {host, port} upsert, or a machines.json
|
|
319
|
+
// row saved before a field existed — left the PREVIOUS machine's values in
|
|
320
|
+
// the shared config: after machine A (backend openssh + hostKeyMode off) the
|
|
321
|
+
// next machine silently inherited A's backend and its DISABLED host-key
|
|
322
|
+
// verification. A record that omits one of these fields (or stores it empty
|
|
323
|
+
// — lib/hostkey.js and backendFor() already treat '' as the default) now
|
|
324
|
+
// resets it to the schema default declared in lib/main.js: hostKeyMode
|
|
325
|
+
// 'accept-new', backend 'native', shell '', sshBinary ''.
|
|
326
|
+
config.hostKeyMode = m.hostKeyMode || 'accept-new'
|
|
287
327
|
if (typeof m.useAgent === 'boolean') config.useAgent = m.useAgent
|
|
288
328
|
if (typeof m.keyboardInteractive === 'boolean') config.keyboardInteractive = m.keyboardInteractive
|
|
289
329
|
// Issue #51: the transport backend is PER MACHINE. An enterprise box that only
|
|
290
330
|
// accepts Kerberos must go through the system OpenSSH backend while every
|
|
291
331
|
// other machine can stay on the native one, so this cannot be a purely global
|
|
292
332
|
// default.
|
|
293
|
-
|
|
294
|
-
|
|
333
|
+
config.backend = m.backend || 'native'
|
|
334
|
+
config.sshBinary = typeof m.sshBinary === 'string' ? m.sshBinary : ''
|
|
295
335
|
// Issue #206: the per-machine `shell` (a bash.exe path or wrapper on Windows
|
|
296
336
|
// remotes) was declared in the schema and read by both backends' detection,
|
|
297
337
|
// but never copied here — a hand-edited value was dead on arrival.
|
|
298
|
-
|
|
338
|
+
config.shell = typeof m.shell === 'string' ? m.shell : ''
|
|
299
339
|
config.proxy = m.proxy && m.proxy.host ? m.proxy : undefined
|
|
300
340
|
}
|
|
301
341
|
|
package/lib/remote-fs.js
CHANGED
|
@@ -75,28 +75,52 @@ export async function listRemoteDrives(sshPool) {
|
|
|
75
75
|
return [...new Set(letters)].sort().map((l) => ({ name: l + ':\\', path: l + ':\\', type: 'dir', drive: true, size: 0, mtime: 0 }))
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
/**
|
|
79
|
-
export async function removeRemoteTree(sftp, p,
|
|
78
|
+
/** Remove entries bottom-up, budgeting each file or directory once, including the root. */
|
|
79
|
+
export async function removeRemoteTree(sftp, p, maxEntries = 2000) {
|
|
80
|
+
let visited = 0
|
|
80
81
|
let removed = 0
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
82
|
+
let failed = 0
|
|
83
|
+
let limited = false
|
|
84
|
+
let firstFailure = ''
|
|
85
|
+
const recordFailure = (op, target, error) => {
|
|
86
|
+
failed++
|
|
87
|
+
firstFailure ||= `${op} ${target} (${error?.message || error})`
|
|
88
|
+
return false
|
|
89
|
+
}
|
|
90
|
+
const remove = async (op, target) => {
|
|
91
|
+
try {
|
|
92
|
+
await sftp[op](target)
|
|
93
|
+
removed++
|
|
94
|
+
return true
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return recordFailure(op, target, error)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const walk = async (target, isDirectory) => {
|
|
100
|
+
if (visited >= maxEntries) {
|
|
101
|
+
limited = true
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
visited++
|
|
105
|
+
if (!isDirectory) return remove('unlink', target)
|
|
106
|
+
let entries
|
|
107
|
+
try { entries = await sftp.readdir(target) }
|
|
108
|
+
catch (error) { return recordFailure('readdir', target, error) }
|
|
109
|
+
let complete = true
|
|
110
|
+
for (const { filename, attrs } of entries) {
|
|
111
|
+
if (!filename || filename === '.' || filename === '..') continue
|
|
112
|
+
if (!await walk(joinRemotePath(target, filename), attrs?.isDirectory?.())) complete = false
|
|
113
|
+
if (limited) break
|
|
95
114
|
}
|
|
96
|
-
|
|
115
|
+
// An unfinished child already accounts for the failure or limit on this branch.
|
|
116
|
+
return complete && remove('rmdir', target)
|
|
97
117
|
}
|
|
98
|
-
await walk(p)
|
|
99
|
-
|
|
118
|
+
const complete = await walk(p, true)
|
|
119
|
+
const reasons = []
|
|
120
|
+
if (limited) reasons.push(`reached the ${maxEntries}-entry limit`)
|
|
121
|
+
if (failed) reasons.push(`${failed} SFTP ${failed === 1 ? 'operation' : 'operations'} failed. First failure was ${firstFailure}`)
|
|
122
|
+
const error = complete ? null : `incomplete removal of ${p} after removing ${removed} ${removed === 1 ? 'entry' : 'entries'}. ${reasons.join('. ')}`
|
|
123
|
+
return { removed, failed, limited, error }
|
|
100
124
|
}
|
|
101
125
|
|
|
102
126
|
/** MIME types for image formats the preview panel can render inline. */
|
package/lib/remote-git.js
CHANGED
|
@@ -37,6 +37,7 @@ async function runGit(pool, cwd, args, signal, limit = LIMIT) {
|
|
|
37
37
|
signal?.addEventListener('abort', abort, { once: true })
|
|
38
38
|
let output = [], size = 0, tapped = false, truncated = false
|
|
39
39
|
try {
|
|
40
|
+
cancel.signal.throwIfAborted()
|
|
40
41
|
const argv = [ '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args]
|
|
41
42
|
const options = { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
|
|
42
43
|
if (channel !== 'stdout') return
|
|
@@ -52,12 +53,14 @@ async function runGit(pool, cwd, args, signal, limit = LIMIT) {
|
|
|
52
53
|
} finally { signal?.removeEventListener('abort', abort) }
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
export async function inspectRemoteGit(binding, { action = 'status', path: relative, staged = false, signal, decodeBuf, encoding } = {}) {
|
|
56
|
+
export async function inspectRemoteGit(binding, { action = 'status', path: relative, staged = false, signal, decodeBuf, encoding, count = 50, branch = '' } = {}) {
|
|
56
57
|
const { pool, ws } = binding
|
|
57
58
|
if (!binding.bound || !ws) throw Object.assign(new Error('Git inspection requires a session bound to a remote workspace'), { httpStatus: 403 })
|
|
58
|
-
if (!['status', 'diff'].includes(action)) throw Object.assign(new Error('action must be status or
|
|
59
|
+
if (!['status', 'diff', 'graph'].includes(action)) throw Object.assign(new Error('action must be status, diff or graph'), { httpStatus: 400 })
|
|
59
60
|
if (action === 'diff' && !safeRelative(relative)) throw Object.assign(new Error('A repository-relative Git file path is required'), { httpStatus: 400 })
|
|
61
|
+
signal?.throwIfAborted()
|
|
60
62
|
await pool.detect()
|
|
63
|
+
signal?.throwIfAborted()
|
|
61
64
|
if (!pool.local && pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
|
|
62
65
|
const top = await runGit(pool, ws, ['rev-parse', '--show-toplevel', '--show-prefix'], signal, 8192)
|
|
63
66
|
if (top.code !== 0) {
|
|
@@ -78,6 +81,48 @@ export async function inspectRemoteGit(binding, { action = 'status', path: relat
|
|
|
78
81
|
return within === null ? null : within ? joinRemotePath(ws, within) : ws
|
|
79
82
|
}
|
|
80
83
|
if (signal?.aborted) throw new Error('Git inspection cancelled')
|
|
84
|
+
if (action === 'graph') {
|
|
85
|
+
// Issue #260: a read-only commit graph for the remote workspace. The UI
|
|
86
|
+
// (better-sidebar's Git tab) can render history only when the DATA comes
|
|
87
|
+
// from the remote — the local mirror deliberately never carries .git.
|
|
88
|
+
// parents drives fork/merge edges, refs drives the ref badges.
|
|
89
|
+
const limit = Math.min(Math.max(Number(count) || 50, 1), 200)
|
|
90
|
+
const branchArg = branch && /^refs\/heads\/[\w./-]+$/.test(branch) ? [branch] : ['--all']
|
|
91
|
+
const format = '%H%x1f%h%x1f%P%x1f%an%x1f%ad%x1f%D%x1f%s%x1e'
|
|
92
|
+
const log = await runGit(pool, repo, ['log', ...branchArg, `--max-count=${limit}`, '--date=iso-strict', `--pretty=format:${format}`], signal, 512 * 1024)
|
|
93
|
+
if (log.code !== 0 && !log.truncated) throw new Error(errorText(log))
|
|
94
|
+
const forEachRef = await runGit(pool, repo, ['for-each-ref', '--format=%(refname:short)%1f%(objectname)%1f%(refname)', 'refs/heads', 'refs/remotes'], signal, 256 * 1024)
|
|
95
|
+
if (forEachRef.code !== 0 && !forEachRef.truncated) throw new Error(errorText(forEachRef))
|
|
96
|
+
const head = await runGit(pool, repo, ['symbolic-ref', '--quiet', '--short', 'HEAD'], signal, 4096)
|
|
97
|
+
if (![0, 1].includes(head.code)) throw new Error(errorText(head))
|
|
98
|
+
const entries = []
|
|
99
|
+
for (const record of log.stdout.split('\x1e')) {
|
|
100
|
+
const fields = record.replace(/^[\r\n]+/, '').split('\x1f')
|
|
101
|
+
if (fields.length < 7) continue
|
|
102
|
+
const [hashFull, hash, parentsRaw, author, date, refsRaw, ...subjectRest] = fields
|
|
103
|
+
entries.push({
|
|
104
|
+
hashFull, hash,
|
|
105
|
+
parents: parentsRaw.trim() ? parentsRaw.trim().split(/\s+/) : [],
|
|
106
|
+
author, date,
|
|
107
|
+
refs: refsRaw.trim() ? refsRaw.trim().split(',').map((r) => r.trim()).filter(Boolean) : [],
|
|
108
|
+
subject: subjectRest.join('\x1f').trim(),
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
const branches = []
|
|
112
|
+
for (const line of forEachRef.stdout.split('\n')) {
|
|
113
|
+
if (!line.trim()) continue
|
|
114
|
+
const [name, hashFull, ref] = line.split('\x1f')
|
|
115
|
+
if (name && ref && /^refs\/(heads|remotes)\//.test(ref)) branches.push({ ref, name, hashFull })
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
ok: true, available: true, repo,
|
|
119
|
+
current: head.code === 0 ? head.stdout.trim() : '',
|
|
120
|
+
detached: head.code === 1,
|
|
121
|
+
entries,
|
|
122
|
+
branches,
|
|
123
|
+
truncated: log.truncated || forEachRef.truncated,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
81
126
|
if (action === 'status') {
|
|
82
127
|
const status = await runGit(pool, ws, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--', '.'], signal)
|
|
83
128
|
if (status.code !== 0 && !status.truncated) throw new Error(errorText(status))
|
|
@@ -116,14 +161,17 @@ export function createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, co
|
|
|
116
161
|
return [{ kind: 'exact', path: '/dsh-remote/git', async handler(req, res) {
|
|
117
162
|
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
118
163
|
const cancel = new AbortController(), close = () => cancel.abort()
|
|
164
|
+
const signal = req.signal ? AbortSignal.any([req.signal, cancel.signal]) : cancel.signal
|
|
119
165
|
res.on?.('close', close)
|
|
120
166
|
try {
|
|
167
|
+
signal.throwIfAborted()
|
|
121
168
|
const q = new URL(req.url, 'http://localhost').searchParams
|
|
122
169
|
if (!q.get('sessionId') && !q.get('local')) return sendJson(res, 400, { ok: false, error: 'sessionId or local workspace context is required' })
|
|
123
170
|
const binding = await resolveRequestBinding(req)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
171
|
+
signal.throwIfAborted()
|
|
172
|
+
const result = await inspectRemoteGit(binding, { action: q.get('action') || 'status', path: q.get('path'), staged: q.get('staged') === '1', count: q.get('count'), branch: q.get('branch') || '', signal, decodeBuf, encoding: config.encoding })
|
|
173
|
+
if (!signal.aborted) sendJson(res, 200, result)
|
|
174
|
+
} catch (error) { if (!signal.aborted) sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error) }) }
|
|
127
175
|
finally { res.off?.('close', close) }
|
|
128
176
|
} }]
|
|
129
177
|
}
|
package/lib/routes-fs.js
CHANGED
|
@@ -49,21 +49,16 @@ function responseDrained(res) {
|
|
|
49
49
|
})
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
*
|
|
55
|
-
* The SFTP surface exposes no read stream, and buffering the file would hold up
|
|
56
|
-
* to `maxFileBytes` in the host's memory per click, so read and write in 1 MiB
|
|
57
|
-
* steps and honour backpressure.
|
|
58
|
-
*/
|
|
59
|
-
async function streamFileToResponse(sftp, remotePath, size, res) {
|
|
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) {
|
|
60
55
|
const CHUNK = 1024 * 1024
|
|
61
56
|
if (typeof sftp.readPartial !== 'function') {
|
|
62
57
|
// Surface without bounded reads (tests, older adapters): one full read is
|
|
63
58
|
// still better than fastGet, which would park the bytes on the host's disk.
|
|
64
59
|
const buf = await sftp.readFile(remotePath)
|
|
65
|
-
if (
|
|
66
|
-
|
|
60
|
+
if (verifySize && (buf?.length || 0) !== size) throw new Error('file size changed during download')
|
|
61
|
+
if (buf && buf.length) yield buf
|
|
67
62
|
return
|
|
68
63
|
}
|
|
69
64
|
let offset = 0
|
|
@@ -71,7 +66,15 @@ async function streamFileToResponse(sftp, remotePath, size, res) {
|
|
|
71
66
|
const buf = await sftp.readPartial(remotePath, offset, Math.min(CHUNK, size - offset))
|
|
72
67
|
if (!buf || !buf.length) break
|
|
73
68
|
offset += buf.length
|
|
74
|
-
|
|
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)
|
|
75
78
|
}
|
|
76
79
|
res.end()
|
|
77
80
|
}
|
|
@@ -85,6 +88,7 @@ export function createFsRoutes({
|
|
|
85
88
|
audit,
|
|
86
89
|
config,
|
|
87
90
|
mirrorDirFor,
|
|
91
|
+
ensureBoundMirror,
|
|
88
92
|
onRemoteMutation = () => {},
|
|
89
93
|
openLocalPath,
|
|
90
94
|
mirrorRoot,
|
|
@@ -227,6 +231,9 @@ export function createFsRoutes({
|
|
|
227
231
|
// differs per browser, a plain field does not.
|
|
228
232
|
res.setHeader('X-Dsh-Download-Name', encodeURIComponent(name))
|
|
229
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))
|
|
230
237
|
streaming = true
|
|
231
238
|
await streamFileToResponse(sftp, p, size, res)
|
|
232
239
|
} catch (err) {
|
|
@@ -366,11 +373,18 @@ export function createFsRoutes({
|
|
|
366
373
|
if (op === 'remove') {
|
|
367
374
|
const p = normalizeRemotePath(String(body.path || ''))
|
|
368
375
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
369
|
-
const st = await sftp.
|
|
376
|
+
const st = await sftp.lstat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
|
|
370
377
|
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
371
|
-
if (st.isDirectory
|
|
378
|
+
if (st.isDirectory?.()) {
|
|
372
379
|
if (b.local) await b.pool.removeTree(p)
|
|
373
|
-
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
|
+
}
|
|
374
388
|
} else {
|
|
375
389
|
await sftp.unlink(p)
|
|
376
390
|
}
|
|
@@ -399,15 +413,17 @@ export function createFsRoutes({
|
|
|
399
413
|
const ws = b.ws
|
|
400
414
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
401
415
|
if (!ws) return sendJson(res, 400, { ok: false, error: 'no remote workspace set' })
|
|
402
|
-
const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port)
|
|
403
|
-
const
|
|
416
|
+
const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port, b.alias)
|
|
417
|
+
const target = mirrorDownloadTarget(base, ws, p)
|
|
404
418
|
const st = await sftp.stat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
|
|
405
419
|
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
406
420
|
if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
|
|
407
421
|
if (config.maxFileBytes > 0 && st.size > config.maxFileBytes) {
|
|
408
422
|
return sendJson(res, 400, { ok: false, error: `file is ${st.size} bytes (over ${config.maxFileBytes} cap)` })
|
|
409
423
|
}
|
|
410
|
-
|
|
424
|
+
const mirror = b.bound ? base : ensureBoundMirror(ws, b)
|
|
425
|
+
const local = mirror === base ? target : mirrorDownloadTarget(mirror, ws, p)
|
|
426
|
+
assertDownloadHasNoSymlinks(mirror, local)
|
|
411
427
|
mkdirSync(path.dirname(local), { recursive: true })
|
|
412
428
|
await sftp.fastGet(p, local)
|
|
413
429
|
if (!b.local) audit('download', `download ${p}`, 0, b)
|