dsh-remote 1.4.0 → 1.5.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/lib/main.js CHANGED
@@ -151,6 +151,17 @@ export function pickWorkspaceNextStep(localSession) {
151
151
  : 'Run rw_sync to download its files into the local mirror.'
152
152
  }
153
153
 
154
+ /** Issue #205: the closing note when the picking session is ALREADY bound to a
155
+ * different workspace. rw_pick_workspace does not rebind the current session
156
+ * — a model that assumes "paths now resolve against the new pick" silently
157
+ * operates on the old workspace — so the success text must say so explicitly.
158
+ * The parallel-worktree flow (pick each worktree once, one session per
159
+ * mirror) is the documented answer. */
160
+ export function pickWorkspaceRebindNote(currentWs, pickedWs, display) {
161
+ if (!currentWs || currentWs === pickedWs) return null
162
+ return `NOTE: this session is still bound to ${display(currentWs)} — relative paths, rw_exec's working directory and rw_sync keep resolving against IT. To work inside the newly picked workspace, open a session whose workspace is the local mirror path above (for parallel git worktrees: pick each worktree once, one session per mirror), or pass absolute paths / an explicit cd in commands.`
163
+ }
164
+
154
165
  // Web and Desktop share the SSH tools; each optional UI transport is attached
155
166
  // reactively below, so service startup order does not drop the JSON routes.
156
167
  export const inject = ['tools', 'systemPrompt']
@@ -849,6 +860,9 @@ export async function apply(ctx, config) {
849
860
  // Issue #51: the backend is part of the target identity, so a machine switch
850
861
  // between backends must be seen as a change by setTarget.
851
862
  backend: c.backend, sshBinary: c.sshBinary,
863
+ // Issue #206: the per-machine shell is part of the target identity too —
864
+ // a switch that only changes it must reset the cached platform detection.
865
+ shell: c.shell,
852
866
  })
853
867
 
854
868
  /** Fingerprint of the machine record last applied to the shared pool config.
@@ -1844,7 +1858,7 @@ export async function apply(ctx, config) {
1844
1858
  const binding = await resolveRequestBinding(req, body, { allowLocal: local })
1845
1859
  if (local && !binding.local) throw Object.assign(new Error('Workspace execution context changed; reload before retrying'), { httpStatus: 409 })
1846
1860
  const route = new URL(req.url || '/', 'http://localhost').pathname
1847
- if (binding.local && ['/dsh-remote/ls', '/dsh-remote/read', '/dsh-remote/write', '/dsh-remote/fs'].includes(route)) {
1861
+ if (binding.local && ['/dsh-remote/ls', '/dsh-remote/read', '/dsh-remote/download', '/dsh-remote/write', '/dsh-remote/fs'].includes(route)) {
1848
1862
  for (const field of ['path', 'dest']) {
1849
1863
  const target = body[field] || q.get(field)
1850
1864
  if (target) await binding.pool.checkPath(String(target), { mutation: route === '/dsh-remote/write' || route === '/dsh-remote/fs' })
@@ -2259,6 +2273,7 @@ export async function apply(ctx, config) {
2259
2273
  hostKeyMode: { type: 'string', description: 'Host-key policy for this machine: ask | strict | off (default from config)' },
2260
2274
  backend: { type: 'string', description: 'SSH transport backend (issue #51): "native" (default) uses the built-in ssh2 client (password / private key / agent / keyboard-interactive); "openssh" drives the LOCAL ssh command, which is the only way to reach hosts that require GSSAPI/Kerberos (log in once with kinit) and which honours the whole of ~/.ssh/config (ProxyCommand, PKCS11Provider, Match blocks). Prefer "openssh" together with useSshConfig=true so the alias and its settings stay the single source of truth.' },
2261
2275
  sshBinary: { type: 'string', description: 'Path (or PATH name) of the ssh executable the "openssh" backend drives — default "ssh"' },
2276
+ shell: { type: 'string', description: 'Windows remotes: the bash.exe path (or a wrapper script) to use as the remote shell, overriding auto-detection (where bash) — e.g. when auto-detect finds the WSL launcher stub, or Git Bash needs a wrapper to survive sshd. Leave empty to auto-detect.' },
2262
2277
  name: { type: 'string', description: 'Display name for a newly saved machine (default: the host)' },
2263
2278
  useSshConfig: { type: 'boolean', description: 'Treat `host` as a ~/.ssh/config Host alias; resolve host/user/port/key/proxy from that file (issue #38)' },
2264
2279
  save: { type: 'boolean', description: 'Save this machine to the registry and make it current (default true)' },
@@ -2330,6 +2345,9 @@ export async function apply(ctx, config) {
2330
2345
  // handed to ssh verbatim so ~/.ssh/config stays the single source.
2331
2346
  if (args.backend) rec.backend = args.backend === 'openssh' ? 'openssh' : 'native'
2332
2347
  if (args.sshBinary !== undefined) rec.sshBinary = String(args.sshBinary)
2348
+ // Issue #206: the per-machine shell is settable at connect time too,
2349
+ // mirroring sshBinary (it is honored by both backends' detection).
2350
+ if (args.shell !== undefined) rec.shell = String(args.shell)
2333
2351
  // Issue #54: the per-machine `dsh web` command is settable by hand too,
2334
2352
  // not only by the deploy flow (the README told users to set it and the
2335
2353
  // settings UI offered nowhere to type it).
@@ -2388,6 +2406,7 @@ export async function apply(ctx, config) {
2388
2406
  proxy: ct.proxy,
2389
2407
  backend: backendFor(rec, config),
2390
2408
  sshBinary: rec.sshBinary !== undefined ? rec.sshBinary : config.sshBinary,
2409
+ shell: rec.shell !== undefined ? rec.shell : config.shell,
2391
2410
  workspace: config.workspace,
2392
2411
  })
2393
2412
  appliedMachineId = ephemeral.id || null
@@ -2490,7 +2509,7 @@ export async function apply(ctx, config) {
2490
2509
  defineTool({
2491
2510
  name: 'rw_pick_workspace',
2492
2511
  description:
2493
- 'Set the remote workspace directory this session should treat as its working root on the connected remote. Verifies it exists (a directory). Use rw_list_dir to browse first if unsure. Accepts POSIX (/home/dev/project) or Windows (C:\\Users\\dev\\project) paths.',
2512
+ 'Set the remote workspace directory for this machine: verifies it exists (a directory), creates its LOCAL MIRROR (auto-push starts watching the mirror), and records it as the machine\'s workspace. Use rw_list_dir to browse first if unsure. SCOPE (issue #205): this does NOT change the current session\'s working directory — a session already bound to another workspace keeps resolving relative paths, rw_exec\'s cwd and rw_sync against ITS OWN workspace until a session is opened inside the new mirror. For parallel git worktrees: pick each worktree once, then open one session per mirror; within a single session use absolute paths or an explicit cd. Accepts POSIX (/home/dev/project) or Windows (C:\\Users\\dev\\project) paths.',
2494
2513
  parameters: {
2495
2514
  path: { type: 'string', required: true, description: 'Absolute remote directory path, e.g. /home/dev/code/project or C:\\Users\\dev\\project' },
2496
2515
  },
@@ -2531,8 +2550,13 @@ export async function apply(ctx, config) {
2531
2550
  // The closing hint depends on where THIS session stands (issue #63):
2532
2551
  // in a LOCAL session "Run rw_sync" is a dead instruction — rw_sync
2533
2552
  // refuses a local session — so say the mirror must be OPENED first.
2553
+ // Issue #205: a session that picks a workspace DIFFERENT from its own
2554
+ // binding must be told the pick does not rebind it — the old text
2555
+ // ("Remote workspace set to …" + "Run rw_sync") read as "paths now
2556
+ // resolve against the new pick", which is not what happens.
2557
+ const rebindNote = pickWorkspaceRebindNote(b.ws, p, (x) => toDisplayPath(x, b.pool.platform))
2534
2558
  return {
2535
- text: `Remote workspace set to ${shown} on ${b.username}@${b.host}.\nLocal mirror (native workspace path): ${local}\n\n${pickWorkspaceNextStep(b.local)}`,
2559
+ text: `Remote workspace set to ${shown} on ${b.username}@${b.host}.\nLocal mirror (native workspace path): ${local}\n\n${rebindNote || pickWorkspaceNextStep(b.local)}`,
2536
2560
  }
2537
2561
  },
2538
2562
  }),
@@ -3772,6 +3796,12 @@ export async function apply(ctx, config) {
3772
3796
  const prev = i >= 0 ? machines[i] : null
3773
3797
  const credBackend = body.credentialBackend === 'plain' ? 'plain'
3774
3798
  : (body.encryptPassword ? platformBackend() : (prev && prev.credentialBackend ? prev.credentialBackend : 'plain'))
3799
+ // Issue #212: the per-machine plain-login terminal flag. An omitted flag
3800
+ // keeps the stored one (older clients, partial API updates); an explicit
3801
+ // boolean wins — including false, which clears it.
3802
+ const keepNoCommand = body.terminalNoCommand === undefined
3803
+ ? !!(prev && prev.terminalNoCommand)
3804
+ : !!body.terminalNoCommand
3775
3805
  const rec = {
3776
3806
  id,
3777
3807
  name: String(body.name || '').trim() || host,
@@ -3816,6 +3846,14 @@ export async function apply(ctx, config) {
3816
3846
  credentialBackend: prev && prev.credentialBackend,
3817
3847
  }, config),
3818
3848
  sshBinary: String(body.sshBinary || '').trim(),
3849
+ ...(keepNoCommand ? { terminalNoCommand: true } : {}),
3850
+ // Issue #206: the per-machine shell. A form that omits it (or an older
3851
+ // client) keeps the stored value — a rebuild that dropped the field used
3852
+ // to wipe a hand-edited shell on the next save (picking a workspace was
3853
+ // enough); an explicit '' clears it.
3854
+ shell: body.shell === undefined
3855
+ ? String((prev && prev.shell) || '')
3856
+ : String(body.shell || '').trim(),
3819
3857
  // Issue #54: the per-machine `dsh web` launch command was only
3820
3858
  // ever writable by the deploy flow or by hand-editing
3821
3859
  // machines.json — the README told users to set it and the
@@ -4098,7 +4136,9 @@ export async function apply(ctx, config) {
4098
4136
  const started = Date.now()
4099
4137
  try {
4100
4138
  await probe.connect()
4101
- await probe.exec('true', { timeoutMs: 10000 })
4139
+ // `echo ok`, not `true`: cmd.exe (default shell of a stock Windows OpenSSH
4140
+ // server) has no `true`, which made a healthy host probe as "unavailable".
4141
+ await probe.exec('echo ok', { timeoutMs: 10000 })
4102
4142
  } finally {
4103
4143
  probe.close()
4104
4144
  }
@@ -4514,6 +4554,7 @@ export async function apply(ctx, config) {
4514
4554
  ...createFsRoutes({
4515
4555
  sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4516
4556
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4557
+ openLocalPath, mirrorRoot: remoteWorkspacesRoot,
4517
4558
  }),
4518
4559
 
4519
4560
  // Embedded terminal (P1): one host-owned PTY session per machine, polled.
package/lib/openssh.js CHANGED
@@ -64,6 +64,7 @@ import path from 'node:path'
64
64
  import { Duplex } from 'node:stream'
65
65
  import { setTimeout as delay } from 'node:timers/promises'
66
66
  import { buildSftpSurface } from './sftp-surface.js'
67
+ import { detectPlatform } from './detect-platform.js'
67
68
  import { truncate } from './paths.js'
68
69
 
69
70
  // The SFTP protocol engine lives at lib/protocol/SFTP.js inside ssh2 and is not
@@ -586,7 +587,7 @@ export class SystemOpenSshPool {
586
587
  return String(this.config.host || '')
587
588
  }
588
589
 
589
- setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
590
+ setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary, shell }, previous) {
590
591
  const base = previous || this.config
591
592
  const wanted = []
592
593
  if (host !== undefined) wanted.push(['host', String(host)])
@@ -605,6 +606,9 @@ export class SystemOpenSshPool {
605
606
  // a field one of them diffs must not be silently ignored by the other.
606
607
  if (backend !== undefined) wanted.push(['backend', String(backend)])
607
608
  if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
609
+ // Issue #206: kept in step with the native pool's setTarget (same contract
610
+ // as sshBinary above) — a shell change resets the cached detection.
611
+ if (shell !== undefined) wanted.push(['shell', String(shell)])
608
612
  const differs = ([k, v]) => (k === 'proxy'
609
613
  ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
610
614
  : base[k] !== v)
@@ -711,7 +715,10 @@ export class SystemOpenSshPool {
711
715
  // Native semantics are "connect() throws when the SSH connection fails", and
712
716
  // a probe also gives the settings page a real latency number. The CLI has no
713
717
  // socket to keep, so this is the only point where the target is proven.
714
- const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
718
+ // `echo ok` rather than a bare `true`: cmd.exe (the default shell of a
719
+ // stock Windows OpenSSH server) has no `true`, so the probe failed on
720
+ // healthy Windows hosts. `echo ok` works under cmd.exe, PowerShell and POSIX shells.
721
+ const probe = await this._runSsh(['--', this.destination(), 'echo ok'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
715
722
  if (!isCurrent()) throw new Error('ssh target changed during connect')
716
723
  if (probe.code !== 0) {
717
724
  // dsh-remote-fix3: _runSsh reports its own timer as code -1 / signal
@@ -845,58 +852,16 @@ export class SystemOpenSshPool {
845
852
  }
846
853
 
847
854
  async _detect() {
848
- let res
849
- try {
850
- res = await this._runSsh(['--', this.destination(), 'cmd /c ver'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
851
- } catch {
852
- this.platform = 'unknown'
853
- this.shellMode = 'native'
854
- return
855
- }
856
- const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
857
- if (res.code === 0 && /microsoft windows/i.test(out)) {
858
- this.platform = 'windows'
859
- await this._resolveGitBash()
860
- return
861
- }
862
- try {
863
- const u = await this._runSsh(['--', this.destination(), 'uname -s'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
864
- if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
865
- this.platform = 'windows'
866
- await this._resolveGitBash()
867
- return
868
- }
869
- } catch { /* inconclusive — fall through to posix */ }
870
- this.platform = 'posix'
871
- this.shellMode = 'native'
872
- this.gitBashPath = ''
873
- }
874
-
875
- async _resolveGitBash() {
876
- const cfg = String(this.config.shell || '').trim()
877
- const exists = async (p) => {
878
- const r = await this._runSsh(['--', this.destination(), `cmd /c if exist "${p}" (echo Y) else (echo N)`], { timeoutMs: 8000 })
879
- return /Y/.test(String(r.stdout || ''))
880
- }
881
- if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
882
- if (await exists(cfg)) { this.gitBashPath = cfg; this.shellMode = 'git-bash'; return }
883
- }
884
- if (cfg === 'native') { this.shellMode = 'native'; this.gitBashPath = ''; return }
885
- try {
886
- const r = await this._runSsh(['--', this.destination(), 'cmd /c where bash'], { timeoutMs: 8000 })
887
- const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
888
- if (first) { this.gitBashPath = first; this.shellMode = 'git-bash'; return }
889
- } catch { /* fall through to the candidate list */ }
890
- const candidates = [
891
- 'C:\\Program Files\\Git\\bin\\bash.exe',
892
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
893
- ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
894
- ]
895
- for (const c of candidates) {
896
- if (await exists(c)) { this.gitBashPath = c; this.shellMode = 'git-bash'; return }
897
- }
898
- this.shellMode = 'git-bash'
899
- this.gitBashPath = ''
855
+ // The probes live in lib/detect-platform.js — the single implementation
856
+ // shared with the native ssh2 backend (see the header comment there for
857
+ // the issue #197 / #199 probe-order and quoting rules).
858
+ const r = await detectPlatform(
859
+ (cmd, timeoutMs) => this._runSsh(['--', this.destination(), cmd], { timeoutMs }),
860
+ { commandTimeoutMs: this.config.commandTimeoutMs, shell: this.config.shell },
861
+ )
862
+ this.platform = r.platform
863
+ this.shellMode = r.shellMode
864
+ this.gitBashPath = r.gitBashPath
900
865
  }
901
866
 
902
867
  /** Run one remote command (Windows + Git Bash is wrapped exactly as native). */
package/lib/pool.js CHANGED
@@ -6,6 +6,7 @@ import path from 'node:path'
6
6
  import { truncate } from './paths.js'
7
7
  import { createHostKeyGuard } from './hostkey.js'
8
8
  import { buildSftpSurface } from './sftp-surface.js'
9
+ import { detectPlatform } from './detect-platform.js'
9
10
  import { friendlyMessage } from './errors.js'
10
11
  import { setTimeout as delay } from 'node:timers/promises'
11
12
  import { SystemOpenSshPool, isSystemOpenSshBackend } from './openssh.js'
@@ -271,7 +272,7 @@ export class SshPool {
271
272
  return p
272
273
  }
273
274
 
274
- 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) {
275
276
  // Collect the requested changes first: an UNCHANGED target is a no-op. The
276
277
  // old behavior closed the live connection and re-ran platform detection
277
278
  // even for an identical target, so every picker keystroke
@@ -302,6 +303,10 @@ export class SshPool {
302
303
  // it must close the live connection exactly like changing the host does.
303
304
  if (backend !== undefined) wanted.push(['backend', String(backend)])
304
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)])
305
310
  const differs = ([k, v]) => (k === 'proxy'
306
311
  ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
307
312
  : base[k] !== v)
@@ -455,6 +460,15 @@ export class SshPool {
455
460
  }
456
461
  this.client = client
457
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 */ } }
458
472
  resolve(client)
459
473
  if (this.onReady) { try { this.onReady(client) } catch {} }
460
474
  })
@@ -578,84 +592,16 @@ export class SshPool {
578
592
  }
579
593
 
580
594
  async _detect() {
581
- let res
582
- try {
583
- // `cmd /c ver` works under cmd.exe, PowerShell AND Git Bash (all print
584
- // "Microsoft Windows …"); on POSIX hosts `cmd` simply doesn't exist.
585
- res = await this._execRaw('cmd /c ver', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
586
- } catch (err) {
587
- this.platform = 'unknown'
588
- this.shellMode = 'native'
589
- return
590
- }
591
- const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
592
- if (res.code === 0 && /microsoft windows/i.test(out)) {
593
- this.platform = 'windows'
594
- await this._resolveGitBash()
595
- return
596
- }
597
- // inconclusive — probe for a Git-Bash/MSYS remote (uname prints MINGW64_NT…)
598
- try {
599
- const u = await this._execRaw('uname -s', { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
600
- if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
601
- this.platform = 'windows'
602
- await this._resolveGitBash()
603
- return
604
- }
605
- } catch {}
606
- this.platform = 'posix'
607
- this.shellMode = 'native'
608
- this.gitBashPath = ''
609
- }
610
-
611
- /** On a Windows remote, locate Git Bash (config path → PATH → common installs). */
612
- async _resolveGitBash() {
613
- const cfg = String(this.config.shell || '').trim()
614
- if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
615
- if (await this._cmdExists(cfg)) {
616
- this.gitBashPath = cfg
617
- this.shellMode = 'git-bash'
618
- return
619
- }
620
- }
621
- if (cfg === 'native') {
622
- this.shellMode = 'native'
623
- this.gitBashPath = ''
624
- return
625
- }
626
- try {
627
- const r = await this._execRaw('cmd /c where bash', { timeoutMs: 8000 })
628
- const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
629
- if (first) {
630
- this.gitBashPath = first
631
- this.shellMode = 'git-bash'
632
- return
633
- }
634
- } catch {}
635
- const candidates = [
636
- 'C:\\Program Files\\Git\\bin\\bash.exe',
637
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
638
- ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
639
- '%LOCALAPPDATA%\\Programs\\Git\\bin\\bash.exe',
640
- ]
641
- for (const c of candidates) {
642
- if (await this._cmdExists(c)) {
643
- this.gitBashPath = c
644
- this.shellMode = 'git-bash'
645
- return
646
- }
647
- }
648
- this.shellMode = 'git-bash' // wanted but not found — commands fall back to raw
649
- this.gitBashPath = ''
650
- }
651
-
652
- async _cmdExists(p) {
653
- try {
654
- const r = await this._execRaw(`cmd /c if exist "${p}" (echo Y) else (echo N)`, { timeoutMs: 8000 })
655
- return /Y/.test(String(r.stdout || ''))
656
- } catch {
657
- return false
658
- }
595
+ // The probes live in lib/detect-platform.js — the single implementation
596
+ // shared with the system-OpenSSH backend (see the header comment there for
597
+ // the issue #197 / #199 probe-order and quoting rules).
598
+ const r = await detectPlatform(
599
+ (cmd, timeoutMs) => this._execRaw(cmd, { timeoutMs }),
600
+ { commandTimeoutMs: this.config.commandTimeoutMs, shell: this.config.shell },
601
+ )
602
+ this.platform = r.platform
603
+ this.shellMode = r.shellMode
604
+ this.gitBashPath = r.gitBashPath
659
605
  }
660
606
 
661
607
  /** Run one remote command; resolves { code, signal, stdout, stderr }.
package/lib/registry.js CHANGED
@@ -292,6 +292,10 @@ export function applyMachine(config, m) {
292
292
  // default.
293
293
  if (m.backend) config.backend = m.backend
294
294
  if (typeof m.sshBinary === 'string') config.sshBinary = m.sshBinary
295
+ // Issue #206: the per-machine `shell` (a bash.exe path or wrapper on Windows
296
+ // remotes) was declared in the schema and read by both backends' detection,
297
+ // but never copied here — a hand-edited value was dead on arrival.
298
+ if (typeof m.shell === 'string') config.shell = m.shell
295
299
  config.proxy = m.proxy && m.proxy.host ? m.proxy : undefined
296
300
  }
297
301
 
@@ -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
- if (!isWindowsRemotePath(target.remotePath)) args.push(remoteCommand(target.remotePath))
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
 
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,64 @@ 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
+ /**
53
+ * Copy a remote (or local-workspace) file into the HTTP response.
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) {
60
+ const CHUNK = 1024 * 1024
61
+ if (typeof sftp.readPartial !== 'function') {
62
+ // Surface without bounded reads (tests, older adapters): one full read is
63
+ // still better than fastGet, which would park the bytes on the host's disk.
64
+ const buf = await sftp.readFile(remotePath)
65
+ if (buf && buf.length) res.write(buf)
66
+ res.end()
67
+ return
68
+ }
69
+ let offset = 0
70
+ while (offset < size) {
71
+ const buf = await sftp.readPartial(remotePath, offset, Math.min(CHUNK, size - offset))
72
+ if (!buf || !buf.length) break
73
+ offset += buf.length
74
+ if (!res.write(buf)) await responseDrained(res)
75
+ }
76
+ res.end()
77
+ }
78
+
21
79
  export function createFsRoutes({
22
80
  sendJson,
23
81
  readBody,
@@ -28,6 +86,8 @@ export function createFsRoutes({
28
86
  config,
29
87
  mirrorDirFor,
30
88
  onRemoteMutation = () => {},
89
+ openLocalPath,
90
+ mirrorRoot,
31
91
  }) {
32
92
  const bindOrReply = async (req, res, body = {}) => {
33
93
  try {
@@ -119,6 +179,62 @@ export function createFsRoutes({
119
179
  }
120
180
  },
121
181
  },
182
+ {
183
+ // Bytes for the machine running the BROWSER, not for the harness host.
184
+ //
185
+ // `fs op=download` writes the file into the DSH host's local mirror, which
186
+ // is the wrong machine as soon as the page is opened from another desktop:
187
+ // the file lands next to the harness and the browser is handed a path. This
188
+ // route answers the bytes themselves — GET, so the browser's own download
189
+ // manager owns progress, resume and cancel.
190
+ //
191
+ // The binding is the usual session one (query `sessionId`, plus
192
+ // `workspace=local` for a local workspace) and resolveWorkbenchBinding
193
+ // fences this route like /read, so a click in one session's explorer can
194
+ // never pull a file from another session's host, nor read outside a local
195
+ // workspace's root.
196
+ kind: 'exact',
197
+ path: '/dsh-remote/download',
198
+ handler: async (req, res) => {
199
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
200
+ let streaming = false
201
+ try {
202
+ const q = new URL(req.url, 'http://localhost').searchParams
203
+ const requested = q.get('path') || ''
204
+ if (!requested) return sendJson(res, 400, { ok: false, error: 'path is required' })
205
+ const b = await bindOrReply(req, res, {})
206
+ if (!b) return
207
+ const p = normalizeRemotePath(requested)
208
+ if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path is required' })
209
+ const sftp = await b.pool.sftp()
210
+ const st = await sftp.stat(p).catch((error) => {
211
+ if (missingRemoteFile(error)) return null
212
+ throw error
213
+ })
214
+ if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
215
+ if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
216
+ const size = Number(st.size) || 0
217
+ if (config.maxFileBytes > 0 && size > config.maxFileBytes) {
218
+ return sendJson(res, 400, { ok: false, error: `file is ${size} bytes (over ${config.maxFileBytes} cap)` })
219
+ }
220
+ const name = String(p).split(/[\\/]/).filter(Boolean).pop() || 'download'
221
+ res.statusCode = 200
222
+ res.setHeader('Content-Type', 'application/octet-stream')
223
+ res.setHeader('Content-Disposition', contentDisposition(name))
224
+ res.setHeader('Content-Length', String(size))
225
+ res.setHeader('Cache-Control', 'no-store')
226
+ // Read by the UI to name the saved file: Content-Disposition parsing
227
+ // differs per browser, a plain field does not.
228
+ res.setHeader('X-Dsh-Download-Name', encodeURIComponent(name))
229
+ if (!b.local) audit('download', `download ${p} (to browser)`, 0, b)
230
+ streaming = true
231
+ await streamFileToResponse(sftp, p, size, res)
232
+ } catch (err) {
233
+ if (streaming) { try { res.destroy(err) } catch { /* already gone */ } return }
234
+ return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err) })
235
+ }
236
+ },
237
+ },
122
238
  {
123
239
  kind: 'exact',
124
240
  path: '/dsh-remote/read',
@@ -208,6 +324,26 @@ export function createFsRoutes({
208
324
  const b = await bindOrReply(req, res, body)
209
325
  if (!b) return
210
326
  if (b.local && op === 'download') return sendJson(res, 400, { ok: false, error: 'Local files are already on this host; no mirror download is needed' })
327
+ if (op === 'revealLocal') {
328
+ // Issue #207: "download to local mirror" used to end in a file the
329
+ // user could not find — no path picker is involved by design, and
330
+ // the explorer discarded the response entirely. The UI now offers
331
+ // "show in folder", backed by this op. The target is ALWAYS fenced
332
+ // to the plugin's own mirror tree; arbitrary local paths are
333
+ // refused (this is not a file launcher).
334
+ if (typeof openLocalPath !== 'function' || typeof mirrorRoot !== 'function') {
335
+ return sendJson(res, 501, { ok: false, error: 'reveal is not available on this host' })
336
+ }
337
+ const resolved = path.resolve(String(body.path || ''))
338
+ const rootDir = path.resolve(mirrorRoot())
339
+ if (!resolved.startsWith(rootDir + path.sep)) {
340
+ return sendJson(res, 400, { ok: false, error: 'revealLocal only accepts paths inside the local mirror tree' })
341
+ }
342
+ if (!existsSync(resolved)) return sendJson(res, 404, { ok: false, error: 'not found' })
343
+ const r = await openLocalPath(resolved, 'reveal')
344
+ if (!r.ok) return sendJson(res, r.httpStatus || 500, { ok: false, error: r.error, path: resolved })
345
+ return sendJson(res, 200, { ok: true, path: resolved, how: r.how })
346
+ }
211
347
  const sftp = await b.pool.sftp()
212
348
  if (op === 'mkdir') {
213
349
  const p = normalizeRemotePath(String(body.path || ''))
@@ -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
- privateKeyPath: '',
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
- // ~/.ssh/config defines this machine, and the user's own `ssh`
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: [],