dsh-remote 0.8.80 → 0.8.82

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/index.js CHANGED
@@ -21,14 +21,15 @@
21
21
  import z from '@deepseek-ai/schemastery'
22
22
  import { defineTool } from '@deepseek-ai/dsh-tools'
23
23
  import { execFile } from 'node:child_process'
24
- import { readFileSync, mkdirSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, copyFileSync, appendFileSync, watch, rmSync } from 'node:fs'
24
+ import { readFileSync, mkdirSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, copyFileSync, appendFileSync, watch, rmSync, chmodSync } from 'node:fs'
25
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
25
26
  import { homedir } from 'node:os'
26
27
  import path from 'node:path'
27
28
  import { fileURLToPath } from 'node:url'
28
29
  import iconv from 'iconv-lite'
29
30
 
30
31
  import {
31
- shq, normalizeRemotePath, joinRemotePath, remoteDirname, mkdirRemoteDirs,
32
+ shq, normalizeRemotePath, joinRemotePath, joinRemoteRel, resolveRemoteWorkspacePath, remoteDirname, mkdirRemoteDirs,
32
33
  toShellPath, toDisplayPath, remotePathBase, remoteWorkspaceTitle, truncate, shortHash,
33
34
  } from './paths.js'
34
35
  import { createHostKeyGuard, isHostKeyKnown as _isHostKeyKnown } from './hostkey.js'
@@ -51,8 +52,9 @@ import { TaskManager } from './tasks.js'
51
52
  import { ForwardManager } from './forwards.js'
52
53
  import { WebAttach } from './web-attach.js'
53
54
  import { formatAuditLine, readAuditLines } from './audit.js'
55
+ import { openLocalFolder } from './open-folder.js'
54
56
 
55
- import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy } from './update.js'
57
+ import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy, writeFileAtomic } from './update.js'
56
58
  import { sendHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath, telemetryAllowed, persistTelemetryOpt } from './telemetry.js'
57
59
  import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
58
60
  import { registerHttpTransports } from './http-transport.js'
@@ -474,6 +476,34 @@ export async function apply(ctx, config) {
474
476
  // 伪名,原始安装 id 与任何机器信息都不离开本机。
475
477
  if (telemetryAllowed(dshBase(), config.telemetry)) void sendHeartbeat(dshBase(), LOADED_VERSION)
476
478
 
479
+ // ── terminal credential bridge (saved passwords for the `remote ssh` shell) ─
480
+ // The generated terminal launcher spawns the OS ssh, which cannot receive the
481
+ // plugin's saved passwords by itself. Bridge: a per-boot bearer token in
482
+ // $DSH_HOME/remote-terminal/term-secret.json (0600) + a POST route that
483
+ // resolves the machine through the SAME credential chain a real connect uses.
484
+ // The askpass helper (written next to the launcher) is the only reader.
485
+ const termSecretFile = () => path.join(remoteTerminalRoot(), 'term-secret.json')
486
+ const termSecretToken = randomBytes(24).toString('hex')
487
+ // A stale payload from a previous boot would name a dead port with a dead
488
+ // token — and with SSH_ASKPASS_REQUIRE=force a failing bridge means NO tty
489
+ // prompt at all. Always boot from absent; only a live webServer re-creates it
490
+ // (Desktop compositions have no HTTP listener, so the bridge stays off there
491
+ // and the terminal keeps its interactive prompt).
492
+ try { rmSync(termSecretFile(), { force: true }) } catch { /* absent is fine */ }
493
+ const writeTermSecretPayload = (origin) => {
494
+ if (!origin) return false
495
+ try {
496
+ mkdirSync(remoteTerminalRoot(), { recursive: true })
497
+ writeFileAtomic(termSecretFile(), JSON.stringify({ version: 1, url: String(origin).replace(/\/+$/, ''), token: termSecretToken }))
498
+ try { chmodSync(termSecretFile(), 0o600) } catch { /* Windows: dir is already user-private */ }
499
+ return true
500
+ } catch { return false }
501
+ }
502
+ const termSecretOk = (presented) => {
503
+ const dig = (s) => createHash('sha256').update(String(s)).digest()
504
+ return timingSafeEqual(dig(presented), dig(termSecretToken))
505
+ }
506
+
477
507
  // The update marker means "a newer version landed on disk but is not the code
478
508
  // running yet". Reaching apply() with a marker naming the version we just
479
509
  // loaded means the swap already happened (or this is a plain boot into the
@@ -617,6 +647,46 @@ export async function apply(ctx, config) {
617
647
  }
618
648
  }
619
649
 
650
+ /**
651
+ * Does this machine carry a credential the NATIVE (ssh2) backend can use?
652
+ *
653
+ * The native backend authenticates only through a password, a private key, an
654
+ * agent or keyboard-interactive. A `~/.ssh/config` machine whose Host block
655
+ * carries just HostName/User relies on OpenSSH's own default-identity
656
+ * discovery (id_rsa/id_ed25519, the agent, AddKeysToAgent/UseKeychain), which
657
+ * ssh2 does not implement — so dialing it with native reports "no credentials"
658
+ * for a host that `ssh <alias>` reaches fine. The system-OpenSSH backend hands
659
+ * the name to the user's own `ssh`, which authenticates exactly like that
660
+ * command.
661
+ *
662
+ * @param {object} m - a machine record or request body carrying the fields.
663
+ * @returns {boolean} true when native has something to authenticate with.
664
+ */
665
+ const nativeUsableCredential = (m) => !!(
666
+ (m && String(m.password || '').trim())
667
+ || (m && String(m.privateKeyPath || '').trim())
668
+ || (m && m.useAgent)
669
+ || (m && m.keyboardInteractive)
670
+ // A keychain-backed machine stores an empty `password` by design.
671
+ || (m && (m.secretStored || (m.credentialBackend && m.credentialBackend !== 'plain')))
672
+ )
673
+
674
+ /**
675
+ * The backend a machine must dial with. Native stays whenever it has a usable
676
+ * credential (or the machine explicitly asks for openssh); otherwise openssh,
677
+ * because native provably cannot connect and would only report a missing
678
+ * credential the user never needed.
679
+ *
680
+ * @param {object} m - machine record or request body.
681
+ * @param {object} cfg - the plugin Config (its `backend` is the fallback).
682
+ * @returns {string} 'openssh' | 'native'.
683
+ */
684
+ const backendFor = (m, cfg) => {
685
+ const chosen = String((m && m.backend) || (cfg && cfg.backend) || 'native')
686
+ if (chosen === 'openssh') return 'openssh'
687
+ return nativeUsableCredential(m) ? 'native' : 'openssh'
688
+ }
689
+
620
690
  /** The alias a machine was saved as ('' for a machine with literal values). */
621
691
  const aliasOf = (m) => (m && m.sshAlias) || (m && m.useSshConfig ? String(m.host || '') : '')
622
692
 
@@ -905,7 +975,7 @@ export async function apply(ctx, config) {
905
975
  // Issue #51: the transport backend is a per-machine choice — an
906
976
  // enterprise Kerberos host needs `openssh` while its neighbours stay on
907
977
  // the native backend.
908
- backend: (eff && eff.backend) || config.backend,
978
+ backend: backendFor(eff, config),
909
979
  sshBinary: (eff && typeof eff.sshBinary === 'string') ? eff.sshBinary : config.sshBinary,
910
980
  // Identity-pinned pools never carry the shared active workspace: a
911
981
  // session passes its own mirror-resolved remote path explicitly.
@@ -1822,17 +1892,6 @@ export async function apply(ctx, config) {
1822
1892
  // Everything below is glue: which remote root an agent is bound to, and how a
1823
1893
  // workspace-relative directory is listed over the machine's own pool.
1824
1894
 
1825
- /** Join a workspace-relative directory onto a remote root, segment by
1826
- * segment, so the root's separator style is preserved on Windows hosts. */
1827
- const joinRemoteRel = (base, rel) => {
1828
- let out = base
1829
- for (const segment of String(rel || '').split('/')) {
1830
- if (!segment || segment === '.') continue
1831
- out = joinRemotePath(out, segment)
1832
- }
1833
- return out
1834
- }
1835
-
1836
1895
  const fileReferenceLog = (msg) => {
1837
1896
  try {
1838
1897
  const logger = typeof ctx.get === 'function' ? ctx.get('logger') : undefined
@@ -1907,28 +1966,17 @@ export async function apply(ctx, config) {
1907
1966
 
1908
1967
  /**
1909
1968
  * Resolve a PATH ARGUMENT a tool received against the session's remote
1910
- * workspace root when it is not already absolute (issue #39).
1969
+ * workspace root when it is not already a remote absolute path (issue #39).
1911
1970
  *
1912
- * An `@path` mention in a remote session is workspace-relative — the same
1913
- * shape the local provider produces — so `rw_read_file("src/main.c")` must
1914
- * mean `<remote workspace>/src/main.c`, not the filesystem root's `/src`.
1915
- * Absolute POSIX (`/a/b`), Windows (`D:\a`, `/D:/a`) and UNC (`\\host\share`)
1916
- * forms pass through normalizeRemotePath() unchanged, so behaviour for every
1917
- * existing caller is preserved. `..` segments collapse inside the joined path
1918
- * exactly as normalizeRemotePath() already did.
1971
+ * Also maps paths inside `b.mirrorDir` onto `b.ws` when the model passes the
1972
+ * local mirror cwd reported by the harness's runtime context to an `rw_*` tool.
1919
1973
  *
1920
- * @param {{ws: string}} b - the binding resolved for this call.
1974
+ * @param {{ws: string, mirrorDir?: string|null}} b - the binding resolved for this call.
1921
1975
  * @param {unknown} raw - the raw argument value.
1922
1976
  * @returns {string} a normalized remote path.
1923
1977
  */
1924
- const resolveRemoteArg = (b, raw) => {
1925
- const s = String(raw ?? '').trim()
1926
- const absolute = s.startsWith('/') || s.startsWith('\\\\') || /^[a-zA-Z]:[\\/]/.test(s)
1927
- if (absolute) return normalizeRemotePath(s)
1928
- const rel = s.replace(/^\.\//, '').replace(/^[\\/]+/, '')
1929
- if (!rel) return normalizeRemotePath(b.ws || '')
1930
- return normalizeRemotePath(b.ws ? joinRemoteRel(b.ws, rel.replace(/\\/g, '/')) : rel)
1931
- }
1978
+ const resolveRemoteArg = (b, raw) =>
1979
+ resolveRemoteWorkspacePath((b && b.ws) || '', raw, (b && b.mirrorDir) || '')
1932
1980
 
1933
1981
  // ── tools ─────────────────────────────────────────────────────────────────
1934
1982
 
@@ -2135,7 +2183,7 @@ export async function apply(ctx, config) {
2135
2183
  keyboardInteractive: !!rec.keyboardInteractive,
2136
2184
  hostKeyMode: rec.hostKeyMode || config.hostKeyMode,
2137
2185
  proxy: ct.proxy,
2138
- backend: rec.backend || config.backend,
2186
+ backend: backendFor(rec, config),
2139
2187
  sshBinary: rec.sshBinary !== undefined ? rec.sshBinary : config.sshBinary,
2140
2188
  workspace: config.workspace,
2141
2189
  })
@@ -2294,7 +2342,7 @@ export async function apply(ctx, config) {
2294
2342
  const depth = Math.min(Math.max(Number(args.depth) || 8, 1), 16)
2295
2343
  const maxFiles = Math.min(Math.max(Number(args.maxFiles) || 2000, 1), 20000)
2296
2344
  const isIgnored = ignoreMatcher(p)
2297
- const body = { depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2345
+ const body = { depth, maxDepth: depth, maxFiles, dryRun: !!args.dryRun, force: !!args.force, isIgnored }
2298
2346
  const runSync = async () => {
2299
2347
  let sftp
2300
2348
  try {
@@ -2303,9 +2351,16 @@ export async function apply(ctx, config) {
2303
2351
  throw new Error('sftp unavailable: ' + ((err && err.message) || err))
2304
2352
  }
2305
2353
  const state = loadSyncState(local)
2306
- const { stats, nextState } = await syncTree(sftp, p, local, { ...body, state, maxFileBytes: config.maxFileBytes })
2354
+ const { stats, nextState } = await syncTree(sftp, p, local, {
2355
+ ...body,
2356
+ state,
2357
+ maxFileBytes: config.maxFileBytes,
2358
+ getSftp: () => b.pool.sftp(),
2359
+ })
2307
2360
  if (!args.dryRun) saveSyncState(local, nextState)
2308
2361
  let text = `${args.dryRun ? 'WOULD download' : 'Downloaded'} ${stats.files} file(s) from ${p} → ${local}.`
2362
+ if (stats.abortedError) text += ` ABORTED early (${stats.abortedError}; re-run rw_sync to resume incremental sync, or use rw_download for a specific file).`
2363
+ else if (stats.failed) text += ` ${stats.failed} failed.`
2309
2364
  if (stats.truncated || stats.files >= maxFiles) text += ` TRUNCATED (hit depth=${depth} or maxFiles=${maxFiles} cap; raise maxFiles/depth and re-run).`
2310
2365
  if (stats.skippedUnchanged) text += ` ${stats.skippedUnchanged} unchanged.`
2311
2366
  if (stats.skippedLarge) text += ` ${stats.skippedLarge} too large (over ${config.maxFileBytes} bytes).`
@@ -3031,13 +3086,14 @@ export async function apply(ctx, config) {
3031
3086
  // Issue #39: `@` mentions are resolved from the REMOTE tree by
3032
3087
  // lib/file-reference.js, so the model must know they are remote-relative
3033
3088
  // and that the built-in read tool sees only the local mirror.
3089
+ const mirrorNote = mirrorDir ? ` (${mirrorDir})` : ''
3034
3090
  return (
3035
3091
  '## Remote workspace\n' +
3036
3092
  `Current remote workspace: ${who}:${shown}\n` +
3037
- 'Use the rw_* tools (rw_list_dir / rw_read_file / rw_write_file / rw_edit / rw_exec / rw_search / rw_sync / rw_push) to inspect and act on files on the remote host. Treat this directory as the working root for this task.\n' +
3093
+ 'Use the rw_* tools (rw_list_dir / rw_read_file / rw_write_file / rw_edit / rw_exec / rw_search / rw_sync / rw_push / rw_download / rw_upload) to inspect and act on files on the remote host. Treat this directory as the working root for this task.\n' +
3038
3094
  `\`@path\` mentions in this conversation name files under THAT remote root (\`@src/main.c\` = ${shown}/src/main.c). ` +
3039
3095
  'The rw_* tools take such paths as workspace-relative and resolve them against this root. ' +
3040
- 'The harness\'s built-in read/list tools only see the LOCAL mirror of this directory, which stays empty until rw_sync — use rw_read_file for remote files.' +
3096
+ `The harness's built-in local tools (read / write / edit / grep / glob / working_directory / local shell) only see the LOCAL mirror of this directory${mirrorNote}, which stays empty until rw_sync — use rw_read_file / rw_list_dir / rw_search / rw_exec for remote files, or rw_download to fetch a specific remote file locally.` +
3041
3097
  extra
3042
3098
  )
3043
3099
  },
@@ -3436,9 +3492,20 @@ export async function apply(ctx, config) {
3436
3492
  hostKeyMode: body.hostKeyMode || '',
3437
3493
  useAgent: !!body.useAgent,
3438
3494
  keyboardInteractive: !!body.keyboardInteractive,
3439
- // Issue #51: the transport backend is per machine. `native` is
3440
- // the default, so an unknown value is not persisted as-is.
3441
- backend: body.backend === 'openssh' ? 'openssh' : 'native',
3495
+ // Issue #51: the transport backend is per machine. Native stays when it
3496
+ // has a credential to authenticate with; otherwise openssh, so saving a
3497
+ // credential-less machine (the normal shape of a ~/.ssh/config alias) can
3498
+ // actually connect instead of reporting a missing credential the user
3499
+ // never needed. An unknown value is not persisted as-is.
3500
+ backend: backendFor({
3501
+ backend: body.backend,
3502
+ password: body.password || (prev && prev.password),
3503
+ privateKeyPath: body.privateKeyPath === undefined ? (prev && prev.privateKeyPath) : body.privateKeyPath,
3504
+ useAgent: !!body.useAgent,
3505
+ keyboardInteractive: !!body.keyboardInteractive,
3506
+ secretStored: prev && prev.secretStored,
3507
+ credentialBackend: prev && prev.credentialBackend,
3508
+ }, config),
3442
3509
  sshBinary: String(body.sshBinary || '').trim(),
3443
3510
  // Issue #54: the per-machine `dsh web` launch command was only
3444
3511
  // ever writable by the deploy flow or by hand-editing
@@ -3643,7 +3710,15 @@ export async function apply(ctx, config) {
3643
3710
  const cred = resolveProbeCredentials(body, savedRec, savedPassword)
3644
3711
  // Issue #38: "test" on an ssh-config ALIAS resolves the alias first —
3645
3712
  // the form holds the alias name, not the host it points at.
3646
- const probeBackend = String(cred.backend || config.backend || 'native')
3713
+ const probeBackend = backendFor({
3714
+ backend: cred.backend,
3715
+ password: cred.password,
3716
+ privateKeyPath: cred.privateKeyPath,
3717
+ useAgent: cred.useAgent,
3718
+ keyboardInteractive: cred.keyboardInteractive,
3719
+ secretStored: savedRec && savedRec.secretStored,
3720
+ credentialBackend: savedRec && savedRec.credentialBackend,
3721
+ }, config)
3647
3722
  const probeIsOpenssh = isSystemOpenSshBackend({ backend: probeBackend })
3648
3723
  const aliasTarget = body.useSshConfig
3649
3724
  ? resolveMachineSshConfig({
@@ -3840,6 +3915,19 @@ export async function apply(ctx, config) {
3840
3915
  return { ...p, machineId: rec && rec.id ? String(rec.id) : null }
3841
3916
  })
3842
3917
 
3918
+ /** 在系统文件管理器里打开本机 dsh-remote 的镜像根目录
3919
+ * (`$DSH_HOME/remote-workspaces`,里面按机器分目录存放所有工作区镜像)。
3920
+ * 只打开已存在的目录,不创建任何东西。 */
3921
+ const revealMirrorFolderForApi = async () => {
3922
+ const dir = remoteWorkspacesRoot()
3923
+ if (!existsSync(dir)) {
3924
+ throw codedError('VALIDATION', '还没有任何远程工作区镜像目录:先浏览远程目录并按 w 建一个工作区')
3925
+ }
3926
+ // spawn 失败(例如 Linux 没有 xdg-open)必须让调用方看到错误,不能先报成功。
3927
+ await openLocalFolder(dir)
3928
+ return { path: dir }
3929
+ }
3930
+
3843
3931
  /** SSH `stat` validation used by pickRemoteWorkspace. With a machineId it
3844
3932
  * runs on that machine's OWN pool (validation must not switch the active
3845
3933
  * machine); without one it behaves like the /mirror route (active pool). */
@@ -4099,6 +4187,10 @@ export async function apply(ctx, config) {
4099
4187
  password: payload.password !== undefined && payload.password !== '' ? payload.password : undefined,
4100
4188
  privateKeyPath: payload.privateKeyPath,
4101
4189
  workspace: payload.workspace,
4190
+ // A credential-less target — including an alias from ~/.ssh/config
4191
+ // whose Host block relies on OpenSSH's default keys — cannot connect
4192
+ // on native; dial it through the user's own ssh instead.
4193
+ backend: backendFor(payload, config),
4102
4194
  })
4103
4195
  await pool.exec('echo ok', { timeoutMs: Math.min(config.commandTimeoutMs, 8000) })
4104
4196
  return sendJson(res, 200, { ok: true, ...status() })
@@ -4323,7 +4415,12 @@ export async function apply(ctx, config) {
4323
4415
  hostKeyMode: '',
4324
4416
  useAgent: false,
4325
4417
  keyboardInteractive: false,
4326
- backend: 'native',
4418
+ // ~/.ssh/config defines this machine, and the user's own `ssh`
4419
+ // is what interprets that file (default identity discovery,
4420
+ // agent/keychain, ProxyJump, GSSAPI). Native cannot see any of
4421
+ // it, so a Host block with no IdentityFile would be reported as
4422
+ // "no credentials".
4423
+ backend: 'openssh',
4327
4424
  sshBinary: '',
4328
4425
  credentialBackend: 'plain',
4329
4426
  recentWorkspaces: [],
@@ -4332,6 +4429,12 @@ export async function apply(ctx, config) {
4332
4429
  }
4333
4430
  machines.push(rec)
4334
4431
  saveMachines(machines, store.currentId, false)
4432
+ } else if (String(rec.backend || 'native') !== 'openssh' && !nativeUsableCredential(rec)) {
4433
+ // A record adopted before this fix carries `native` with no
4434
+ // credential: upgrade it in place, so clicking Connect dials what
4435
+ // `ssh <alias>` already does.
4436
+ rec.backend = 'openssh'
4437
+ saveMachines(machines, store.currentId, false)
4335
4438
  }
4336
4439
  // Making it current is the whole point of the click: the picker and
4337
4440
  // every session route then act on this machine.
@@ -4723,10 +4826,63 @@ export async function apply(ctx, config) {
4723
4826
  }
4724
4827
  },
4725
4828
  },
4829
+ {
4830
+ kind: 'exact',
4831
+ path: '/dsh-remote/term-secret',
4832
+ // Owns its bearer token (per boot, 0600 file): the caller is a local
4833
+ // PROCESS (the askpass helper), not a browser, so the Connection cookie
4834
+ // fence would 401 it. The fallback fence still locks out cross-site pages
4835
+ // (they cannot read the token file).
4836
+ fence: 'bearer',
4837
+ handler: async (req, res) => {
4838
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4839
+ // Self-heal: a caller exists but the payload was never published (the
4840
+ // origin arrived after the first write attempts).
4841
+ if (!existsSync(termSecretFile())) {
4842
+ try {
4843
+ const ws = ctx.get('webServer')
4844
+ if (ws && typeof ws.getOrigin === 'function') writeTermSecretPayload(ws.getOrigin())
4845
+ } catch { /* still no listener: the 403 below answers honestly */ }
4846
+ }
4847
+ // Malformed bodies are a 400 with a reason even before the token check
4848
+ // (the routes matrix pins that readability contract for every POST).
4849
+ let body = {}
4850
+ try { body = JSON.parse((await readBody(req)) || '{}') } catch { return sendJson(res, 400, { ok: false, error: 'invalid JSON body' }) }
4851
+ const presented = String((req.headers && req.headers.authorization) || '').replace(/^Bearer\s+/i, '')
4852
+ if (!presented || !termSecretOk(presented)) return sendJson(res, 403, { ok: false, error: 'forbidden' })
4853
+ const alias = String(body.alias || '')
4854
+ let m = null
4855
+ if (alias) m = machines.find((x) => x && x.useSshConfig && String(x.host) === alias) || null
4856
+ if (!m) {
4857
+ const host = String(body.host || '')
4858
+ const port = Number(body.port) || 22
4859
+ const user = String(body.username || '')
4860
+ m = machines.find((x) => x && !x.useSshConfig && String(x.host) === host && (Number(x.port) || 22) === port && String(x.username || '') === user) || null
4861
+ }
4862
+ if (!m) return sendJson(res, 404, { ok: false, error: 'unknown machine' })
4863
+ const password = await machinePassword(m)
4864
+ return sendJson(res, 200, { ok: true, password })
4865
+ },
4866
+ },
4726
4867
  ]
4727
4868
 
4728
4869
  registerHttpTransports(ctx, routes)
4729
4870
 
4871
+ // Publish the credential-bridge payload as soon as the loopback origin is
4872
+ // known (the listener may still be binding at apply time — retry once).
4873
+ ctx.inject(['webServer'], (inner) => {
4874
+ const ws = inner.get('webServer')
4875
+ const publish = () => {
4876
+ try {
4877
+ return writeTermSecretPayload(typeof ws.getOrigin === 'function' ? ws.getOrigin() : '')
4878
+ } catch { return false } // listener not bound yet
4879
+ }
4880
+ if (!publish()) {
4881
+ const timer = setTimeout(publish, 2000)
4882
+ if (typeof timer.unref === 'function') timer.unref()
4883
+ }
4884
+ })
4885
+
4730
4886
  // ── remote terminal: one extra shell in the host terminal's own list ──────
4731
4887
  // Additive and optional: a composition without `terminalController` simply
4732
4888
  // keeps the terminal it already had.
@@ -4804,6 +4960,7 @@ export async function apply(ctx, config) {
4804
4960
  statusSnapshot: () => status(),
4805
4961
  resolveDirBinding: listDirBindingForApi,
4806
4962
  listRemoteProjects: listRemoteProjectsForApi,
4963
+ revealMirrorFolderRecord: revealMirrorFolderForApi,
4807
4964
  resolveMachine: resolveMachineForApi,
4808
4965
  ensureMirror,
4809
4966
  registerMirroredWorkspace,
@@ -0,0 +1,56 @@
1
+ // 在系统默认文件管理器里打开一个本地目录。
2
+ //
3
+ // 插件跑在 dsh-tui 进程里,所以“打开本机文件夹”就是一个本地动作:
4
+ // · macOS → `open <dir>`
5
+ // · Windows → `explorer <dir>`
6
+ // · 其它 → `xdg-open <dir>`
7
+ // 只做一次 spawn,不读输出、不等待、不阻塞;spawn 的异步 `error` 必须被吃掉,
8
+ // 否则一个不存在的 `xdg-open` 会以未处理事件把宿主进程带崩。
9
+
10
+ import { spawn } from 'node:child_process'
11
+
12
+ /** 当前平台对应的“打开文件夹”命令。 */
13
+ export function folderOpenCommand(platform = process.platform) {
14
+ if (platform === 'darwin') return 'open'
15
+ if (platform === 'win32') return 'explorer'
16
+ return 'xdg-open'
17
+ }
18
+
19
+ /**
20
+ * 用系统默认文件管理器打开 `target`。
21
+ *
22
+ * 返回的 Promise 在子进程真的 spawn 成功时 resolve、spawn 失败(如 Linux 没有
23
+ * `xdg-open`、权限不足)时 reject —— 调用方不能先报“已打开”再吞掉失败。
24
+ * 子进程本身仍然 detached + ignore,且从不 await 退出码:`explorer` 对目录参数
25
+ * 返回非零退出码是常态。
26
+ *
27
+ * @param {string} target - 本地绝对路径。
28
+ * @param {object} [options]
29
+ * @param {string} [options.platform] - 覆盖平台(测试用)。
30
+ * @param {Function} [options.spawnImpl] - 覆盖 spawn(测试用)。
31
+ * @returns {Promise<string>} resolve 实际使用的命令名。
32
+ */
33
+ export function openLocalFolder(target, options = {}) {
34
+ const platform = options.platform || process.platform
35
+ const spawnImpl = typeof options.spawnImpl === 'function' ? options.spawnImpl : spawn
36
+ const directory = String(target == null ? '' : target)
37
+ if (!directory) return Promise.reject(new Error('openLocalFolder: target is required'))
38
+ const command = folderOpenCommand(platform)
39
+ return new Promise((resolve, reject) => {
40
+ let child
41
+ try {
42
+ child = spawnImpl(command, [directory], { detached: true, stdio: 'ignore' })
43
+ } catch (error) {
44
+ reject(error)
45
+ return
46
+ }
47
+ if (!child || typeof child.on !== 'function') {
48
+ // 极小化的 spawn 替身:没有事件可等,按成功处理。
49
+ resolve(command)
50
+ return
51
+ }
52
+ child.on('spawn', () => resolve(command))
53
+ child.on('error', reject)
54
+ if (typeof child.unref === 'function') child.unref()
55
+ })
56
+ }
package/lib/paths.js CHANGED
@@ -213,11 +213,12 @@ export function remoteWorkspaceTitle(remotePath, machine) {
213
213
 
214
214
  /** Relative path of `p` under `root` (POSIX form, no leading slash), or null
215
215
  * when `p` is not inside `root`. Both POSIX and Windows drive paths work
216
- * (Windows is compared in its `/D:/…` POSIX-equivalent form). */
216
+ * (Windows is compared in its `/d:/…` POSIX-equivalent form, including `/D:/…`
217
+ * SFTP paths). */
217
218
  export function relPathUnder(root, p) {
218
219
  const posix = (x) => {
219
220
  let n = normalizeRemotePath(x).replace(/[\\/]+$/, '')
220
- const m = n.match(/^([a-zA-Z]):(.*)$/s)
221
+ const m = n.match(/^\/?([a-zA-Z]):(.*)$/s)
221
222
  if (m) return '/' + m[1].toLowerCase() + ':/' + (m[2] ? m[2].replace(/\\/g, '/').replace(/^\/+/, '') : '')
222
223
  return n.replace(/\\/g, '/')
223
224
  }
@@ -229,6 +230,45 @@ export function relPathUnder(root, p) {
229
230
  return null
230
231
  }
231
232
 
233
+ /**
234
+ * Join a workspace-relative path onto a remote root, segment by segment, so the
235
+ * root's separator style (`/` on POSIX, `\` on Windows) is preserved.
236
+ */
237
+ export function joinRemoteRel(base, rel) {
238
+ let out = base
239
+ for (const segment of String(rel || '').split(/[\\/]+/)) {
240
+ if (!segment || segment === '.') continue
241
+ out = joinRemotePath(out, segment)
242
+ }
243
+ return out
244
+ }
245
+
246
+ /**
247
+ * Resolve a tool's `path` argument against a session's remote workspace root `ws`.
248
+ *
249
+ * - Relative paths (`src/main.c`, `./a`, empty) resolve under `ws` (issue #39).
250
+ * - If `mirrorDir` is given and `raw` points at `mirrorDir` itself or a child
251
+ * under `mirrorDir` (because the harness reports the local mirror as the
252
+ * session's working directory), the mirror prefix is stripped and mapped
253
+ * onto `ws` instead of being sent to SFTP as a literal local path.
254
+ * - Any other absolute POSIX (`/a/b`), Windows (`D:\a`, `/D:/a`) or UNC
255
+ * (`\\host\share`) path passes through `normalizeRemotePath()` unchanged.
256
+ */
257
+ export function resolveRemoteWorkspacePath(ws, raw, mirrorDir = '') {
258
+ const s = String(raw ?? '').trim()
259
+ if (mirrorDir && ws && s) {
260
+ const mirrorRel = relPathUnder(mirrorDir, s)
261
+ if (mirrorRel !== null) {
262
+ return normalizeRemotePath(mirrorRel ? joinRemoteRel(ws, mirrorRel) : ws)
263
+ }
264
+ }
265
+ const absolute = s.startsWith('/') || s.startsWith('\\\\') || /^[a-zA-Z]:[\\/]/.test(s)
266
+ if (absolute) return normalizeRemotePath(s)
267
+ const rel = s.replace(/^\.\//, '').replace(/^[\\/]+/, '')
268
+ if (!rel) return normalizeRemotePath(ws || '')
269
+ return normalizeRemotePath(ws ? joinRemoteRel(ws, rel.replace(/\\/g, '/')) : rel)
270
+ }
271
+
232
272
  export function truncate(s, max) {
233
273
  // A missing/NaN cap is a CONFIG BUG (measured: a bare `new SshPool({...})`
234
274
  // with no maxOutputChars turned EVERY exec result into a 29-char truncation
@@ -266,14 +266,59 @@ function stdinIsInteractive(deps = {}) {
266
266
  }
267
267
  }
268
268
 
269
+ /**
270
+ * Whether the machine's password auth needs (and can use) the credential
271
+ * bridge. Keys, agents and ssh-config aliases authenticate without us;
272
+ * keyboard-interactive (OTP) prompts are per-login and must stay on the tty;
273
+ * everything else with a stored credential (plaintext registry or OS keychain)
274
+ * goes through the bridge.
275
+ *
276
+ * @param {object|undefined} machine - the matched registry record.
277
+ * @returns {boolean}
278
+ */
279
+ function needsAskpass(machine) {
280
+ if (!machine) return false
281
+ if (machine.useAgent || machine.useSshConfig || machine.keyboardInteractive) return false
282
+ if (String(machine.privateKeyPath || '')) return false
283
+ if (String(machine.password || '')) return true
284
+ return Boolean(machine.credentialBackend && machine.credentialBackend !== 'plain')
285
+ }
286
+
287
+ /**
288
+ * Environment additions that route ssh's password prompt to the bridge helper.
289
+ * Only applied when needsAskpass() held AND the payload file exists.
290
+ *
291
+ * `SSH_ASKPASS_REQUIRE=force` (OpenSSH ≥ 8.4) is what makes askpass run at all
292
+ * on a tty; DISPLAY feeds prehistoric ssh builds. DSH_TS_* carries the machine
293
+ * identity to the helper through the process environment.
294
+ *
295
+ * @param {object} machine
296
+ * @param {string} termDir - the launcher's directory (DSH_TERM_DIR).
297
+ * @param {string} [platform]
298
+ * @returns {object} env entries to merge over process.env
299
+ */
300
+ function askpassEnv(machine, termDir, platform = process.platform) {
301
+ const wrapper = path.join(termDir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
302
+ return {
303
+ SSH_ASKPASS: wrapper,
304
+ SSH_ASKPASS_REQUIRE: 'force',
305
+ DISPLAY: process.env.DISPLAY || 'dsh-remote:0',
306
+ DSH_TS_HOST: String(machine.host || ''),
307
+ DSH_TS_PORT: String(Number(machine.port) || 22),
308
+ DSH_TS_USERNAME: String(machine.username || ''),
309
+ DSH_TS_ALIAS: String(machine.alias || ''),
310
+ }
311
+ }
312
+
269
313
  /**
270
314
  * Hand the current process over to `file args…`, propagating the exit code.
271
315
  * @param {string} file
272
316
  * @param {string[]} args
317
+ * @param {object} [extraEnv] - env entries merged over process.env (askpass).
273
318
  * @returns {import('node:child_process').ChildProcess}
274
319
  */
275
- function handover(file, args) {
276
- const child = spawn(file, args, { stdio: 'inherit' })
320
+ function handover(file, args, extraEnv) {
321
+ const child = spawn(file, args, { stdio: 'inherit', env: extraEnv ? { ...process.env, ...extraEnv } : process.env })
277
322
  child.on('error', (error) => {
278
323
  process.stderr.write(`[dsh-remote] cannot run ${file}: ${error && error.message}\n`)
279
324
  process.exit(127)
@@ -322,13 +367,24 @@ function main(argv = process.argv.slice(2), deps = {}) {
322
367
  process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
323
368
  process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
324
369
  }
370
+ // Saved-password bridge: when the machine needs password auth and the host
371
+ // wrote the bridge payload (Web composition only), answer ssh's password
372
+ // prompt through the plugin's credential chain instead of the tty.
373
+ const termDir = env.DSH_TERM_DIR || ''
374
+ if (termDir && needsAskpass(resolved.machine) && existsSync(path.join(termDir, 'term-secret.json'))) {
375
+ process.stderr.write('[dsh-remote] using the saved password via the local credential bridge.\n')
376
+ process.stderr.write('[dsh-remote] 已保存的密码将通过本机凭据桥自动应答。\n')
377
+ return handover(ssh, args, askpassEnv(resolved.machine, termDir, platform))
378
+ }
325
379
  return handover(ssh, args)
326
380
  }
327
381
 
328
382
  module.exports = {
329
383
  META_FILE,
384
+ askpassEnv,
330
385
  buildSshArgs,
331
386
  findMirror,
387
+ needsAskpass,
332
388
  isWindowsRemotePath,
333
389
  localShell,
334
390
  main,