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/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
|
|
@@ -587,7 +589,7 @@ export class SystemOpenSshPool {
|
|
|
587
589
|
return String(this.config.host || '')
|
|
588
590
|
}
|
|
589
591
|
|
|
590
|
-
setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
|
|
592
|
+
setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary, shell }, previous) {
|
|
591
593
|
const base = previous || this.config
|
|
592
594
|
const wanted = []
|
|
593
595
|
if (host !== undefined) wanted.push(['host', String(host)])
|
|
@@ -606,6 +608,9 @@ export class SystemOpenSshPool {
|
|
|
606
608
|
// a field one of them diffs must not be silently ignored by the other.
|
|
607
609
|
if (backend !== undefined) wanted.push(['backend', String(backend)])
|
|
608
610
|
if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
|
|
611
|
+
// Issue #206: kept in step with the native pool's setTarget (same contract
|
|
612
|
+
// as sshBinary above) — a shell change resets the cached detection.
|
|
613
|
+
if (shell !== undefined) wanted.push(['shell', String(shell)])
|
|
609
614
|
const differs = ([k, v]) => (k === 'proxy'
|
|
610
615
|
? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
|
|
611
616
|
: base[k] !== v)
|
|
@@ -756,6 +761,12 @@ export class SystemOpenSshPool {
|
|
|
756
761
|
const sshBinary = resolveSshBinary(this.config)
|
|
757
762
|
const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
|
|
758
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
|
+
}
|
|
759
770
|
let child
|
|
760
771
|
try {
|
|
761
772
|
child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
|
|
@@ -766,6 +777,13 @@ export class SystemOpenSshPool {
|
|
|
766
777
|
// after the command already exited (Git Bash); a broken pipe there must
|
|
767
778
|
// fail the call, not the process (issue #118).
|
|
768
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)
|
|
769
787
|
let stdout = ''
|
|
770
788
|
let stderr = ''
|
|
771
789
|
let settled = false
|
|
@@ -882,6 +900,12 @@ export class SystemOpenSshPool {
|
|
|
882
900
|
const sshBinary = resolveSshBinary(this.config)
|
|
883
901
|
const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
|
|
884
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
|
|
885
909
|
|
|
886
910
|
// ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
|
|
887
911
|
// and reads `_remoteIdentRaw` to pick its packet sizes.
|
|
@@ -974,7 +998,13 @@ export class SystemOpenSshPool {
|
|
|
974
998
|
if (settled) return
|
|
975
999
|
settled = true
|
|
976
1000
|
clearTimeout(timer)
|
|
977
|
-
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 })
|
|
978
1008
|
}
|
|
979
1009
|
const timer = setTimeout(() => {
|
|
980
1010
|
done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
|
|
@@ -1011,6 +1041,9 @@ export class SystemOpenSshPool {
|
|
|
1011
1041
|
// A target switch during the handshake must not adopt the old host's
|
|
1012
1042
|
// session (the same generational guard connect() uses).
|
|
1013
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
|
|
1014
1047
|
try { child.kill() } catch {}
|
|
1015
1048
|
throw new Error('ssh target changed while opening sftp')
|
|
1016
1049
|
}
|
|
@@ -1042,10 +1075,29 @@ export class SystemOpenSshPool {
|
|
|
1042
1075
|
this._secretPromise = null
|
|
1043
1076
|
if (client) { try { client.close() } catch {} }
|
|
1044
1077
|
this._dropSftpSession()
|
|
1078
|
+
this._killCommandChildren()
|
|
1045
1079
|
if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
|
|
1046
1080
|
if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
|
|
1047
1081
|
}
|
|
1048
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
|
+
|
|
1049
1101
|
_dropSftpSession() {
|
|
1050
1102
|
const session = this._sftpSession
|
|
1051
1103
|
this._sftpSession = null
|
|
@@ -1066,6 +1118,7 @@ export class SystemOpenSshPool {
|
|
|
1066
1118
|
this._secretPromise = null
|
|
1067
1119
|
if (client) { try { client.close() } catch {} }
|
|
1068
1120
|
this._dropSftpSession()
|
|
1121
|
+
this._killCommandChildren()
|
|
1069
1122
|
if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
|
|
1070
1123
|
if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
|
|
1071
1124
|
}
|
package/lib/pool.js
CHANGED
|
@@ -272,7 +272,7 @@ export class SshPool {
|
|
|
272
272
|
return p
|
|
273
273
|
}
|
|
274
274
|
|
|
275
|
-
setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
|
|
275
|
+
setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary, shell }, previous) {
|
|
276
276
|
// Collect the requested changes first: an UNCHANGED target is a no-op. The
|
|
277
277
|
// old behavior closed the live connection and re-ran platform detection
|
|
278
278
|
// even for an identical target, so every picker keystroke
|
|
@@ -303,6 +303,10 @@ export class SshPool {
|
|
|
303
303
|
// it must close the live connection exactly like changing the host does.
|
|
304
304
|
if (backend !== undefined) wanted.push(['backend', String(backend)])
|
|
305
305
|
if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
|
|
306
|
+
// Issue #206: the shell participates in the target identity so a machine
|
|
307
|
+
// switch that only changes it still resets detection (gitBashPath/shellMode
|
|
308
|
+
// are cached per target and would otherwise outlive the switch).
|
|
309
|
+
if (shell !== undefined) wanted.push(['shell', String(shell)])
|
|
306
310
|
const differs = ([k, v]) => (k === 'proxy'
|
|
307
311
|
? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
|
|
308
312
|
: base[k] !== v)
|
|
@@ -456,6 +460,15 @@ export class SshPool {
|
|
|
456
460
|
}
|
|
457
461
|
this.client = client
|
|
458
462
|
this._sftpTimeouts = 0
|
|
463
|
+
// Issue #211: ssh2 writes each SSH packet's length/payload/padding as
|
|
464
|
+
// separate socket writes; with Nagle on, every burst waits for the
|
|
465
|
+
// previous ACK (plus delayed-ACK) — on a 72ms WireGuard link that made
|
|
466
|
+
// every command take ~6x (measured: `echo ok` 370ms → 146ms). Called
|
|
467
|
+
// from 'ready' because the socket only exists once connected (an
|
|
468
|
+
// earlier call is a silent no-op on a null _sock). It is a no-op for
|
|
469
|
+
// non-socket transports (a proxied channel), and the system-OpenSSH
|
|
470
|
+
// backend runs its own `ssh`, which sets NODELAY itself.
|
|
471
|
+
if (typeof client.setNoDelay === 'function') { try { client.setNoDelay(true) } catch { /* best effort */ } }
|
|
459
472
|
resolve(client)
|
|
460
473
|
if (this.onReady) { try { this.onReady(client) } catch {} }
|
|
461
474
|
})
|
|
@@ -633,6 +646,15 @@ export class SshPool {
|
|
|
633
646
|
let onAbort = null
|
|
634
647
|
const cleanupAbort = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort) }
|
|
635
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
|
+
}
|
|
636
658
|
const execOpts = {}
|
|
637
659
|
if (opts && opts.pty) execOpts.pty = true
|
|
638
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,15 +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 : ''
|
|
335
|
+
// Issue #206: the per-machine `shell` (a bash.exe path or wrapper on Windows
|
|
336
|
+
// remotes) was declared in the schema and read by both backends' detection,
|
|
337
|
+
// but never copied here — a hand-edited value was dead on arrival.
|
|
338
|
+
config.shell = typeof m.shell === 'string' ? m.shell : ''
|
|
295
339
|
config.proxy = m.proxy && m.proxy.host ? m.proxy : undefined
|
|
296
340
|
}
|
|
297
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
|
}
|
|
@@ -150,6 +150,7 @@ function isWindowsRemotePath(p) {
|
|
|
150
150
|
*
|
|
151
151
|
* @param {object} target - `{ host, port, username, alias, remotePath }`
|
|
152
152
|
* @param {object} [machine] - saved connection, for the key and transport hints
|
|
153
|
+
* (`terminalNoCommand` — issue #212 — makes the launcher dial a plain login)
|
|
153
154
|
* @returns {string[]}
|
|
154
155
|
*/
|
|
155
156
|
function buildSshArgs(target, machine) {
|
|
@@ -169,7 +170,14 @@ function buildSshArgs(target, machine) {
|
|
|
169
170
|
// default shell may be cmd or PowerShell, and picking one would be a guess.
|
|
170
171
|
// Opening ssh with no command leaves the remote's own default shell in charge,
|
|
171
172
|
// so the terminal still works; only the automatic `cd` is given up.
|
|
172
|
-
|
|
173
|
+
//
|
|
174
|
+
// Issue #212: the same no-command shape is available per machine for
|
|
175
|
+
// JumpServer-class gateways, which allocate a remote PTY only for a plain
|
|
176
|
+
// LOGIN — a session carrying a command comes up with no line discipline
|
|
177
|
+
// (no ICRNL, no ZLE: keys look dead, or a `script` wrapper doubles the
|
|
178
|
+
// terminal). A plain login gets a REAL pty from the gateway; the automatic
|
|
179
|
+
// `cd` is traded for a working terminal.
|
|
180
|
+
if (!isWindowsRemotePath(target.remotePath) && !(machine && machine.terminalNoCommand)) args.push(remoteCommand(target.remotePath))
|
|
173
181
|
return args
|
|
174
182
|
}
|
|
175
183
|
|