dsh-remote 1.1.1 → 1.2.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/index.js CHANGED
@@ -20,6 +20,8 @@
20
20
  // Plugin Config MUST be a schemastery schema (zod rejects the undefined row config).
21
21
  import { WorkspaceSearches, createSearchRoutes } from './workspace-search.js'
22
22
  import { createGitRoutes } from './remote-git.js'
23
+ import { createLocalWorkspacePool } from './local-workspace.js'
24
+ import { LOCAL_MUTATION_TOOLS, remoteLocalMutationDecision } from './local-mutation.js'
23
25
  import { fileChange, changeOutput, presentFileChange } from './file-changes.js'
24
26
  import { captureRemoteFile, atomicRemoteWrite } from './remote-write.js'
25
27
  import z from '@deepseek-ai/schemastery'
@@ -60,7 +62,7 @@ import { formatAuditLine, readAuditLines } from './audit.js'
60
62
  import { openLocalFolder } from './open-folder.js'
61
63
 
62
64
  import { selfDir, diskVersion, LOADED_VERSION, gtVersion, fetchLatestVersion, applyUpdate, persistUpdateMode, readUpdateMode, reloadSelf, scheduleSelfReload, lastSelfReload, isInstalledCopy, writeFileAtomic } from './update.js'
63
- import { sendHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath, telemetryAllowed } from './telemetry.js'
65
+ import { startHeartbeat, pseudonym, heartbeatUrl, hasPersistedId, installIdPath, telemetryAllowed } from './telemetry.js'
64
66
  import { loadMachines as _loadMachines, saveMachines as _saveMachines, sanitizeMachine as _sanitizeMachine, applyMachine as _applyMachine, machineId as _machineId, normalizeMachineGroup, filterMachinesByGroup, resolveProbeCredentials } from './registry.js'
65
67
  import { registerHttpTransports } from './http-transport.js'
66
68
  import { createHostApi } from './host-api.js'
@@ -487,10 +489,12 @@ export async function apply(ctx, config) {
487
489
 
488
490
  // ── 安装心跳(日活统计)─────────────────────────────────────────────────
489
491
  // 旁路:不 await、不阻塞加载、失败静默(见 lib/telemetry.js 的隐私与失败策略)。
490
- // 默认开启,但可以被关:profile 配置 `telemetry: false`(管理员)或设置页
491
- // 复选框(用户,持久化在 $DSH_HOME,优先于配置)。上报的是本插件专属 HMAC
492
+ // 默认开启;profile 配置 `telemetry: false` 或已持久化的用户选择可以关闭。
493
+ // 周期检查重新读取生效值,用户关闭后不继续发送。上报的是本插件专属 HMAC
492
494
  // 伪名,原始安装 id 与任何机器信息都不离开本机。
493
- if (telemetryAllowed(dshBase(), config.telemetry)) void sendHeartbeat(dshBase(), LOADED_VERSION)
495
+ ctx.effect(() => startHeartbeat(dshBase(), LOADED_VERSION, {
496
+ allowed: () => telemetryAllowed(dshBase(), config.telemetry),
497
+ }), 'dsh-remote.heartbeat')
494
498
 
495
499
  // ── terminal credential bridge (saved passwords for the `remote ssh` shell) ─
496
500
  // The generated terminal launcher spawns the OS ssh, which cannot receive the
@@ -1701,10 +1705,18 @@ export async function apply(ctx, config) {
1701
1705
  * a local (non-mirror) session is refused rather than falling back to the
1702
1706
  * active machine. Requests with no hint keep the picker/settings active pool.
1703
1707
  */
1704
- const resolveRequestBinding = async (req, body = {}) => {
1708
+ const localWorkspacePools = new Map()
1709
+ ctx.effect(() => () => localWorkspacePools.clear(), 'dsh-remote.local-workspaces')
1710
+ const resolveRequestBinding = async (req, body = {}, { allowLocal = false } = {}) => {
1705
1711
  const hint = requestSessionHint(req, body)
1706
1712
  let cwd = hint.local
1707
- if (!cwd && hint.sessionId) cwd = lookupSessionCwd(hint.sessionId, { sessions: sessionsSvc(), dshHome: dshBase() })
1713
+ if (hint.sessionId) {
1714
+ const recorded = lookupSessionCwd(hint.sessionId, { sessions: sessionsSvc(), dshHome: dshBase() })
1715
+ if (!recorded || hint.local && path.resolve(recorded) !== path.resolve(hint.local)) {
1716
+ throw Object.assign(new Error('Session workspace context is unavailable or mismatched; refusing to use another session or the active machine.'), { httpStatus: 403 })
1717
+ }
1718
+ cwd = recorded
1719
+ }
1708
1720
  if (cwd) {
1709
1721
  const { remotePath, machine, mirrorDir } = resolveMirrorForLocal(cwd)
1710
1722
  if (remotePath && machine) {
@@ -1720,6 +1732,15 @@ export async function apply(ctx, config) {
1720
1732
  local: false,
1721
1733
  }
1722
1734
  }
1735
+ if (allowLocal && hint.sessionId) {
1736
+ const root = path.resolve(cwd)
1737
+ let localPool = localWorkspacePools.get(root)
1738
+ if (!localPool) {
1739
+ localPool = await createLocalWorkspacePool(root)
1740
+ localWorkspacePools.set(root, localPool)
1741
+ }
1742
+ return { pool: localPool, ws: root, host: '', username: '', port: 0, mirrorDir: null, bound: true, local: true }
1743
+ }
1723
1744
  const err = new Error(
1724
1745
  'this session is LOCAL — its workspace is not a remote mirror, so there is no remote host to act on. '
1725
1746
  + 'Refusing rather than falling back to the active machine.',
@@ -1762,6 +1783,23 @@ export async function apply(ctx, config) {
1762
1783
  }
1763
1784
  }
1764
1785
 
1786
+ // Local workspace UI access is explicit and session-bound. Unmarked legacy
1787
+ // requests and all rw_* tools keep refusing local sessions, as before.
1788
+ const resolveWorkbenchBinding = async (req, body = {}) => {
1789
+ const q = new URL(req.url || '/', 'http://localhost').searchParams
1790
+ const local = q.get('workspace') === 'local' || body.workspace === 'local'
1791
+ const binding = await resolveRequestBinding(req, body, { allowLocal: local })
1792
+ if (local && !binding.local) throw Object.assign(new Error('Workspace execution context changed; reload before retrying'), { httpStatus: 409 })
1793
+ const route = new URL(req.url || '/', 'http://localhost').pathname
1794
+ if (binding.local && ['/dsh-remote/ls', '/dsh-remote/read', '/dsh-remote/write', '/dsh-remote/fs'].includes(route)) {
1795
+ for (const field of ['path', 'dest']) {
1796
+ const target = body[field] || q.get(field)
1797
+ if (target) await binding.pool.checkPath(String(target), { mutation: route === '/dsh-remote/write' || route === '/dsh-remote/fs' })
1798
+ }
1799
+ }
1800
+ return binding
1801
+ }
1802
+
1765
1803
  // ── session-bound remote binding (the authoritative tool path) ─────────────
1766
1804
 
1767
1805
  /**
@@ -1846,6 +1884,13 @@ export async function apply(ctx, config) {
1846
1884
  return b
1847
1885
  }
1848
1886
 
1887
+ if (typeof ctx.on === 'function') {
1888
+ ctx.on('tools/pre-execute', async (exec, next) => {
1889
+ if (!LOCAL_MUTATION_TOOLS.has(exec?.name)) return next()
1890
+ return remoteLocalMutationDecision(exec, bindingFor(exec)) || next()
1891
+ })
1892
+ }
1893
+
1849
1894
  // ── remote sandbox semantics ──────────────────────────────────────────────
1850
1895
  // A local session is confined by ctx.sandboxPolicy; a REMOTE command used to
1851
1896
  // run under no policy at all, so a read-only session could mutate any file on
@@ -1902,7 +1947,10 @@ export async function apply(ctx, config) {
1902
1947
  if (mode === 'danger-full-access') return
1903
1948
  const b = (() => { try { return bindingFor(exec) } catch { return null } })()
1904
1949
  const workspaceRoot = (b && b.ws) || ''
1905
- const verdict = checkRemoteSandbox({ mode, operation, path: opts.path, workspaceRoot })
1950
+ // Check the execution-world path the rw_* body will actually use. Raw
1951
+ // relative and mirror-local paths must resolve exactly as resolveRemoteArg.
1952
+ const targetPath = opts.path == null ? opts.path : resolveRemoteWorkspacePath(workspaceRoot, opts.path, b?.mirrorDir || '')
1953
+ const verdict = checkRemoteSandbox({ mode, operation, path: targetPath, workspaceRoot })
1906
1954
  if (verdict.allowed) return
1907
1955
  const err = remoteSandboxDenial(verdict)
1908
1956
  if (opts.tool) err.message = `${opts.tool}: ${err.message}`
@@ -3196,7 +3244,8 @@ export async function apply(ctx, config) {
3196
3244
  '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' +
3197
3245
  `\`@path\` mentions in this conversation name files under THAT remote root (\`@src/main.c\` = ${shown}/src/main.c). ` +
3198
3246
  'The rw_* tools take such paths as workspace-relative and resolve them against this root. ' +
3199
- `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.` +
3247
+ `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.\n` +
3248
+ 'Creating a file with local write/edit, a local shell, or Python does NOT save it on the remote host. Native write/edit mutations are refused in remote sessions: use rw_write_file / rw_edit or rw_exec to create and modify remote results. For an already-local artifact, explicitly use rw_push / rw_upload and verify it through rw_read_file or rw_stat before claiming it is saved remotely or giving a remote file link. run_code/PTC remains available for orchestration; its raw local filesystem IO is still LOCAL.\n' +
3200
3249
  extra
3201
3250
  )
3202
3251
  },
@@ -4196,6 +4245,17 @@ export async function apply(ctx, config) {
4196
4245
 
4197
4246
  // ── route helpers ─────────────────────────────────────────────────────────
4198
4247
  const routes = [
4248
+ {
4249
+ kind: 'exact', path: '/dsh-remote/workspace-context',
4250
+ handler: async (req, res) => {
4251
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
4252
+ try {
4253
+ if (!requestSessionHint(req).sessionId) return sendJson(res, 400, { ok: false, error: 'sessionId is required' })
4254
+ const b = await resolveRequestBinding(req, {}, { allowLocal: true })
4255
+ return sendJson(res, 200, { ok: true, kind: b.local ? 'local' : 'remote', root: b.ws, host: b.host, username: b.username, port: b.port, connected: b.local || !!b.pool.client })
4256
+ } catch (error) { return sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error) }) }
4257
+ },
4258
+ },
4199
4259
  {
4200
4260
  kind: 'exact',
4201
4261
  path: '/dsh-remote/status',
@@ -4352,10 +4412,10 @@ export async function apply(ctx, config) {
4352
4412
  aliasOf, activeMachine, startAutoPush, applyRequestedMachine, registerMirroredWorkspace, localPickCapability,
4353
4413
  pickLocalNative, listLocalDrives, probeMachineRecord, setCurrent, knownHostsFile, prepareMirrorTarget, machineForId: (id) => machines.find((m) => m.id === id),
4354
4414
  }),
4355
- ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding, isIgnoredFor: searchIgnoreMatcher }),
4356
- ...createGitRoutes({ sendJson, resolveRequestBinding, decodeBuf, config }),
4415
+ ...createSearchRoutes({ searches: workspaceSearches, sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, isIgnoredFor: searchIgnoreMatcher }),
4416
+ ...createGitRoutes({ sendJson, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, config }),
4357
4417
  ...createFsRoutes({
4358
- sendJson, readBody, resolveRequestBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4418
+ sendJson, readBody, resolveRequestBinding: resolveWorkbenchBinding, decodeBuf, encodeText, audit, config, mirrorDirFor,
4359
4419
  onRemoteMutation: () => { if (remoteSkills) remoteSkills.invalidate() },
4360
4420
  }),
4361
4421
 
@@ -0,0 +1,129 @@
1
+ // Recovery for an explicitly identified local mirror copy. A remote read never
2
+ // substitutes these bytes, and publishing uses SFTP exclusive creation.
3
+ import { open, lstat, realpath } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
6
+ import { requestSessionHint } from './binding.js'
7
+ import { remoteRevision, missingRemoteFile } from './remote-write.js'
8
+ import { normalizeRemotePath, remoteDirname, mkdirRemoteDirs, joinRemotePath } from './paths.js'
9
+
10
+ const HARD_CAP = 2 * 1024 * 1024
11
+ const failure = (message, httpStatus, code) => Object.assign(new Error(message), { httpStatus, code })
12
+ const changed = () => failure('本地副本已变化,请重新查看后再上传。', 409, 'LOCAL_COPY_CHANGED')
13
+ const unsupported = () => failure('仅支持查看和上传完整的 UTF-8 文本副本;此文件不是受支持的文本。', 415, 'LOCAL_COPY_UNSUPPORTED')
14
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs
15
+
16
+ async function checkRemoteParents(sftp, binding, target, allowMissing) {
17
+ const root = normalizeRemotePath(binding.ws)
18
+ const grammar = /^(?:[a-z]:[\\/]|\\\\)/i.test(root) ? path.win32 : path.posix
19
+ const relative = grammar.relative(root, remoteDirname(target))
20
+ let current = root
21
+ for (const part of ['', ...relative.split(grammar.sep).filter(Boolean)]) {
22
+ if (part) current = joinRemotePath(current, part)
23
+ let stat
24
+ try { stat = await sftp.lstat(current) }
25
+ catch (error) { if (allowMissing && missingRemoteFile(error)) return; throw error }
26
+ if (stat.isSymbolicLink?.() || !stat.isDirectory?.()) throw failure('远端父路径不是普通目录或含符号链接,未上传。', 403, 'LOCAL_COPY_UNSAFE_REMOTE_PATH')
27
+ }
28
+ }
29
+
30
+ async function resolveCopy(binding, target) {
31
+ if (!binding.bound || !binding.ws || !binding.mirrorDir) throw failure('An explicitly bound remote session is required', 403, 'LOCAL_COPY_UNBOUND')
32
+ const local = mirrorDownloadTarget(binding.mirrorDir, binding.ws, target)
33
+ assertDownloadHasNoSymlinks(binding.mirrorDir, local)
34
+ const root = await realpath(binding.mirrorDir), physical = await realpath(local)
35
+ const within = path.relative(root, physical)
36
+ if (!within || path.isAbsolute(within) || within.split(path.sep).includes('..')) throw failure('The local copy is outside this session workspace mirror', 403, 'LOCAL_COPY_UNSAFE')
37
+ const stat = await lstat(local)
38
+ if (!stat.isFile() || stat.isSymbolicLink()) throw failure('The local copy must be a regular file without symbolic links', 403, 'LOCAL_COPY_UNSAFE')
39
+ return { local, stat, relativePath: path.relative(path.resolve(binding.mirrorDir), local).split(path.sep).join('/') }
40
+ }
41
+
42
+ export async function localCopyInfo(binding, target) {
43
+ if (!binding.bound || !binding.mirrorDir) return null
44
+ try {
45
+ const copy = await resolveCopy(binding, target)
46
+ return { available: true, source: 'local-mirror', relativePath: copy.relativePath, size: copy.stat.size, mtime: Math.floor(copy.stat.mtimeMs / 1000) }
47
+ } catch (error) {
48
+ // A remote missing-file response is still truthful when a local candidate
49
+ // cannot be offered safely. Do not disclose files behind links/outside root.
50
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR' || error.httpStatus === 403) return null
51
+ throw error
52
+ }
53
+ }
54
+
55
+ export async function readLocalCopy(binding, target, { maxFileBytes = 0 } = {}) {
56
+ let copy
57
+ try { copy = await resolveCopy(binding, target) }
58
+ catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw failure('本地副本已不存在。', 404, 'LOCAL_COPY_NOT_FOUND'); throw error }
59
+ const cap = maxFileBytes > 0 ? Math.min(maxFileBytes, HARD_CAP) : HARD_CAP
60
+ if (copy.stat.size > cap) throw failure(`本地副本超过 ${cap} bytes 的文本恢复上限。`, 413, 'LOCAL_COPY_TOO_LARGE')
61
+ if (/\.(?:png|jpe?g|gif|webp|bmp|ico|avif|pdf)$/i.test(target)) throw unsupported()
62
+ const handle = await open(copy.local, 'r')
63
+ let bytes
64
+ try {
65
+ const before = await handle.stat()
66
+ if (!sameFile(copy.stat, before)) throw changed()
67
+ // Resolve and recheck after opening; a replaced file or parent link must
68
+ // never turn an apparent mirror read into an unrelated local read.
69
+ const verified = await resolveCopy(binding, target)
70
+ if (!sameFile(copy.stat, verified.stat)) throw changed()
71
+ const buffer = Buffer.alloc(copy.stat.size + 1)
72
+ let offset = 0
73
+ while (offset < buffer.length) {
74
+ const result = await handle.read(buffer, offset, buffer.length - offset, offset)
75
+ if (!result.bytesRead) break
76
+ offset += result.bytesRead
77
+ }
78
+ if (offset !== copy.stat.size || !sameFile(copy.stat, await handle.stat())) throw changed()
79
+ bytes = buffer.subarray(0, offset)
80
+ } finally { await handle.close() }
81
+ if (bytes.includes(0)) throw unsupported()
82
+ let text
83
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes) } catch { throw unsupported() }
84
+ return { bytes, preview: { ok: true, source: 'local-mirror', readOnly: true, path: target,
85
+ relativePath: copy.relativePath, content: text.replace(/\r\n/g, '\n'), localRevision: remoteRevision(bytes),
86
+ size: bytes.length, mtime: Math.floor(copy.stat.mtimeMs / 1000), binary: false, image: false, truncated: false } }
87
+ }
88
+
89
+ export async function publishLocalCopy(binding, target, expectedLocalRevision, options = {}) {
90
+ if (typeof expectedLocalRevision !== 'string' || !/^[a-f0-9]{64}$/.test(expectedLocalRevision)) throw failure('A localRevision from the complete local-copy preview is required', 400, 'LOCAL_COPY_REVISION_REQUIRED')
91
+ const { bytes, preview } = await readLocalCopy(binding, target, options)
92
+ if (preview.localRevision !== expectedLocalRevision) throw changed()
93
+ const sftp = await binding.pool.sftp()
94
+ const existing = await sftp.lstat(target).catch(error => { if (missingRemoteFile(error)) return null; throw error })
95
+ if (existing) throw failure('远端已有同名文件,未覆盖。请重新读取并比较。', 409, 'REMOTE_FILE_EXISTS')
96
+ await checkRemoteParents(sftp, binding, target, true)
97
+ await mkdirRemoteDirs(sftp, remoteDirname(target))
98
+ await checkRemoteParents(sftp, binding, target, false)
99
+ try {
100
+ // This flag is forwarded to SSH_FXP_OPEN as CREAT|EXCL. A concurrent file
101
+ // appearing after lstat MUST fail at the server; no replace/rename follows.
102
+ await sftp.createFileExclusive(target, bytes)
103
+ } catch (error) {
104
+ if (error.exclusiveFileCreated) throw failure('上传未完整完成,远端可能留下新建的不完整文件;请检查远端后再重试。', 502, 'LOCAL_COPY_UPLOAD_INCOMPLETE')
105
+ if (error.exclusiveOpenFailed && [4, 11, 'EEXIST'].includes(error.code)) {
106
+ const appeared = await sftp.lstat(target).catch(probe => { if (missingRemoteFile(probe)) return null; throw error })
107
+ if (appeared) throw failure('远端已出现同名文件,上传未覆盖该文件;请重新读取并检查。', 409, 'REMOTE_FILE_EXISTS')
108
+ }
109
+ throw error
110
+ }
111
+ return { ok: true, source: 'remote', path: target, bytes: bytes.length, revision: remoteRevision(bytes) }
112
+ }
113
+
114
+ export function createLocalCopyRoutes({ sendJson, readBody, resolveRequestBinding, config, audit, onRemoteMutation = () => {} }) {
115
+ return ['read', 'publish'].map(action => ({ kind: 'exact', path: '/dsh-remote/local-copy/' + action, async handler(req, res) {
116
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
117
+ try {
118
+ const body = JSON.parse((await readBody(req)) || '{}'), hint = requestSessionHint(req, body)
119
+ if (!hint.sessionId && !hint.local) throw failure('An explicit sessionId or local workspace context is required', 403, 'LOCAL_COPY_UNBOUND')
120
+ if (typeof body.path !== 'string' || !body.path.trim()) throw failure('path is required', 400, 'LOCAL_COPY_PATH_REQUIRED')
121
+ const target = normalizeRemotePath(body.path), binding = await resolveRequestBinding(req, body)
122
+ if (action === 'read') return sendJson(res, 200, (await readLocalCopy(binding, target, config)).preview)
123
+ const result = await publishLocalCopy(binding, target, body.expectedLocalRevision, config)
124
+ audit?.('publish-local-copy', `publish ${target}`, 0, binding)
125
+ onRemoteMutation()
126
+ return sendJson(res, 200, result)
127
+ } catch (error) { return sendJson(res, error.httpStatus || 500, { ok: false, error: error.message || String(error), ...(error.code ? { code: error.code } : {}) }) }
128
+ } }))
129
+ }
@@ -0,0 +1,8 @@
1
+ // Native filesystem tools operate on the host mirror, not its SSH origin.
2
+ // Use the same gate for root native calls and nested PTC dispatches.
3
+ export const LOCAL_MUTATION_TOOLS = new Set(['write', 'edit', 'str_replace_editor'])
4
+ export function remoteLocalMutationDecision(exec, binding) {
5
+ if (!binding?.bound || !LOCAL_MUTATION_TOOLS.has(exec?.name)) return null
6
+ if (exec.name === 'str_replace_editor' && exec.arguments?.command === 'view') return null
7
+ return { kind: 'deny', reason: `${exec.name} was not executed: this session is a REMOTE workspace, but this tool writes only the LOCAL mirror. Use rw_write_file to create remote files or rw_edit to modify them; workspace-relative paths and local-mirror paths are accepted. A local write does not publish a remote file or make a remote file link valid. If a local artifact already exists, explicitly upload it with rw_push/rw_upload and verify it remotely before reporting a remote link.` }
8
+ }
@@ -0,0 +1,103 @@
1
+ // Local execution-world adapter for the shared workspace UI. Never used by rw_*
2
+ // Agent tools. Every filesystem operation is rooted in a server-resolved session
3
+ // directory; neither an active SSH machine nor a client-supplied root is used.
4
+ import fs from 'node:fs/promises'
5
+ import path from 'node:path'
6
+ import { spawn } from 'node:child_process'
7
+
8
+ export const sameLocalPath = (a, b, grammar = path) => grammar.relative(a, b) === ''
9
+ const denied = () => Object.assign(new Error('Path is outside this local workspace (including symlink targets)'), { httpStatus: 403, code: 'LOCAL_WORKSPACE_PATH' })
10
+ const inside = (root, target) => { const rel = path.relative(root, target); return !path.isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + path.sep) }
11
+ const attrs = stat => ({
12
+ size: stat.size, mtime: stat.mtimeMs / 1000, mode: stat.mode,
13
+ isDirectory: () => stat.isDirectory(), isFile: () => stat.isFile(), isSymbolicLink: () => stat.isSymbolicLink(),
14
+ })
15
+
16
+ export async function createLocalWorkspacePool(directory) {
17
+ const root = path.resolve(directory), canonical = await fs.realpath(root)
18
+ if (!(await fs.stat(canonical)).isDirectory()) throw Object.assign(new Error('Local workspace directory is unavailable'), { httpStatus: 404 })
19
+ const resolve = async (input, { mutation = false } = {}) => {
20
+ if (typeof input !== 'string' || !input || input.includes('\0') || !path.isAbsolute(input)) throw denied()
21
+ const target = path.resolve(input)
22
+ if (!inside(root, target) && !inside(canonical, target)) throw denied()
23
+ if (mutation && (sameLocalPath(root, target) || sameLocalPath(canonical, target))) throw denied()
24
+ // Missing children may be created, but their nearest existing ancestor must
25
+ // still be inside the canonical project. No symlink escape on read or save.
26
+ let ancestor = target
27
+ for (;;) {
28
+ try { if (!inside(canonical, await fs.realpath(ancestor))) throw denied(); break }
29
+ catch (error) {
30
+ if (error.code !== 'ENOENT') throw error
31
+ const parent = path.dirname(ancestor)
32
+ if (parent === ancestor) throw denied()
33
+ // A dangling symlink must not be treated as an ordinary missing child.
34
+ try { if ((await fs.lstat(ancestor)).isSymbolicLink()) throw denied() } catch (e) { if (e.code !== 'ENOENT') throw e }
35
+ ancestor = parent
36
+ }
37
+ }
38
+ return target
39
+ }
40
+ const regularFile = async p => {
41
+ const target = await resolve(p)
42
+ if (!(await fs.stat(target)).isFile()) throw Object.assign(new Error('Only regular local files can be previewed'), { httpStatus: 415 })
43
+ return target
44
+ }
45
+ const sftp = {
46
+ async stat(p) { return attrs(await fs.stat(await resolve(p))) },
47
+ async lstat(p) { return attrs(await fs.lstat(await resolve(p))) },
48
+ async realpath(p) { return fs.realpath(await resolve(p)) },
49
+ async readdir(p) {
50
+ const dir = await resolve(p), names = await fs.readdir(dir)
51
+ return Promise.all(names.map(async filename => ({ filename, attrs: attrs(await fs.lstat(path.join(dir, filename))) })))
52
+ },
53
+ async readFile(p) { return fs.readFile(await regularFile(p)) },
54
+ async readPartial(p, offset, length) {
55
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > 4 * 1024 * 1024) throw new Error('Invalid bounded read')
56
+ const file = await fs.open(await regularFile(p), 'r')
57
+ try { const buffer = Buffer.alloc(length); const { bytesRead } = await file.read(buffer, 0, length, offset); return buffer.subarray(0, bytesRead) }
58
+ finally { await file.close() }
59
+ },
60
+ async mkdir(p) { return fs.mkdir(await resolve(p, { mutation: true })) },
61
+ async rmdir(p) { return fs.rmdir(await resolve(p, { mutation: true })) },
62
+ async unlink(p) { return fs.unlink(await resolve(p, { mutation: true })) },
63
+ async writeFile(p, bytes, options) { return fs.writeFile(await resolve(p, { mutation: true }), bytes, options) },
64
+ async setstat(p, data) { if (data.mode != null) await fs.chmod(await resolve(p, { mutation: true }), data.mode) },
65
+ async rename(from, to) {
66
+ const source = await resolve(from, { mutation: true }), dest = await resolve(to, { mutation: true })
67
+ const stat = await fs.lstat(source)
68
+ if (stat.isFile()) { await fs.link(source, dest); await fs.unlink(source); return }
69
+ try { await fs.lstat(dest); throw Object.assign(new Error('Destination already exists'), { code: 'EEXIST' }) }
70
+ catch (error) { if (error.code !== 'ENOENT') throw error }
71
+ return fs.rename(source, dest)
72
+ },
73
+ async renameOverwrite(from, to) { return fs.rename(await resolve(from, { mutation: true }), await resolve(to, { mutation: true })) },
74
+ }
75
+ return {
76
+ checkPath: resolve,
77
+ async mkdirTree(p) { return fs.mkdir(await resolve(p, { mutation: true }), { recursive: true }) },
78
+ async removeTree(p) { return fs.rm(await resolve(p, { mutation: true }), { recursive: true }) },
79
+ config: { local: true }, platform: process.platform === 'win32' ? 'windows' : 'posix', local: true,
80
+ async detect() {}, async sftp() { return sftp },
81
+ // Git receives an argv array, never a POSIX command string on Windows.
82
+ execFile(file, args, { signal, timeoutMs = 15000, onData } = {}) {
83
+ if (file !== 'git') throw new Error('Only read-only Git inspection is available through this adapter')
84
+ return new Promise(resolveResult => {
85
+ let stdout = '', stderr = '', timedOut = false, settled = false
86
+ const env = { ...process.env }
87
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_PREFIX']) delete env[key]
88
+ const child = spawn(file, args, { cwd: root, env, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
89
+ const append = (channel, chunk) => { const text = chunk.toString(); if (channel === 'stdout') stdout = (stdout + text).slice(0, 256 * 1024); else stderr = (stderr + text).slice(0, 256 * 1024); onData?.(channel, text) }
90
+ child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8')
91
+ child.stdout.on('data', data => append('stdout', data)); child.stderr.on('data', data => append('stderr', data))
92
+ const stop = () => child.kill()
93
+ const timer = setTimeout(() => { timedOut = true; stop() }, timeoutMs)
94
+ const done = (code, error) => {
95
+ if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener('abort', stop)
96
+ resolveResult({ code: code ?? 1, stdout, stderr: error ? String(error.message || error) : stderr, ...(timedOut ? { signal: 'TIMEOUT' } : {}) })
97
+ }
98
+ child.on('error', error => done(error.code === 'ENOENT' ? 127 : 1, error)); child.on('close', code => done(code))
99
+ if (signal?.aborted) stop(); else signal?.addEventListener('abort', stop, { once: true })
100
+ })
101
+ },
102
+ }
103
+ }
@@ -0,0 +1,34 @@
1
+ // Files crossing between a remote workspace and its local mirror must obey
2
+ // both path grammars and must never traverse local symlinks.
3
+ import { lstatSync } from 'node:fs'
4
+ import path from 'node:path'
5
+ import { normalizeRemotePath } from './paths.js'
6
+
7
+ const unsafeDownload = () => Object.assign(new Error('The download destination must be a regular file inside this workspace mirror'), { httpStatus: 403 })
8
+
9
+ // Remote POSIX names may contain backslashes that become separators on a
10
+ // Windows host. Resolve in each filesystem's own grammar, never by prefix.
11
+ export function mirrorDownloadTarget(base, workspace, remote, localPath = path) {
12
+ const remotePath = /^(?:[a-z]:[\\/]|\\\\)/i.test(workspace) ? path.win32 : path.posix
13
+ const relative = remotePath.relative(normalizeRemotePath(workspace), normalizeRemotePath(remote))
14
+ if (!relative || remotePath.isAbsolute(relative) || relative.split(remotePath.sep).some(part => part === '..') || relative.includes('\0')) throw unsafeDownload()
15
+ const parts = relative.split(remotePath.sep)
16
+ // This local-only record determines the session's remote identity.
17
+ if (parts.length === 1 && (localPath.sep === '\\' ? parts[0].toLowerCase() : parts[0]) === '.dsh-remote-meta.json') throw unsafeDownload()
18
+ if (localPath.sep === '\\' && parts.some(part => /[<>:"|?*\\\x00-\x1f]/.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw unsafeDownload()
19
+ const root = localPath.resolve(base), target = localPath.resolve(root, ...parts)
20
+ const within = localPath.relative(root, target)
21
+ if (!within || localPath.isAbsolute(within) || within.split(localPath.sep).some(part => part === '..')) throw unsafeDownload()
22
+ return target
23
+ }
24
+
25
+ export function assertDownloadHasNoSymlinks(base, target) {
26
+ const root = path.resolve(base)
27
+ let current = root
28
+ for (const segment of ['', ...path.relative(root, target).split(path.sep)]) {
29
+ if (segment) current = path.join(current, segment)
30
+ try { if (lstatSync(current).isSymbolicLink()) throw unsafeDownload() }
31
+ catch (error) { if (error.code !== 'ENOENT') throw error }
32
+ }
33
+ }
34
+
package/lib/remote-git.js CHANGED
@@ -37,15 +37,16 @@ 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
- const command = ['git', '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args].map(shq).join(' ')
41
- const result = await pool.exec(command, { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
40
+ const argv = [ '--no-pager', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', '-c', 'color.ui=false', '-C', gitPath(cwd), ...args]
41
+ const options = { timeoutMs: 15000, signal: cancel.signal, onData(channel, chunk) {
42
42
  if (channel !== 'stdout') return
43
43
  tapped = true
44
44
  const bytes = Buffer.from(chunk)
45
45
  if (size < limit) output.push(bytes.subarray(0, limit - size))
46
46
  size += bytes.length
47
47
  if (size > limit) { truncated = true; cancel.abort() }
48
- } })
48
+ } }
49
+ const result = pool.local ? await pool.execFile('git', argv, options) : await pool.exec(['git', ...argv].map(shq).join(' '), options)
49
50
  const stdout = tapped ? Buffer.concat(output).toString('utf8') : String(result.stdout || '').slice(0, limit)
50
51
  return { ...result, stdout, truncated: truncated || !tapped && String(result.stdout || '').length > limit }
51
52
  } finally { signal?.removeEventListener('abort', abort) }
@@ -57,7 +58,7 @@ export async function inspectRemoteGit(binding, { action = 'status', path: relat
57
58
  if (!['status', 'diff'].includes(action)) throw Object.assign(new Error('action must be status or diff'), { httpStatus: 400 })
58
59
  if (action === 'diff' && !safeRelative(relative)) throw Object.assign(new Error('A repository-relative Git file path is required'), { httpStatus: 400 })
59
60
  await pool.detect()
60
- if (pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
61
+ if (!pool.local && pool.platform === 'windows' && !pool.gitBashPath) return { ok: true, available: false, reason: 'unsupported-shell' }
61
62
  const top = await runGit(pool, ws, ['rev-parse', '--show-toplevel', '--show-prefix'], signal, 8192)
62
63
  if (top.code !== 0) {
63
64
  if (top.code === 127 || /not recognized|command not found/i.test(top.stderr || '')) return { ok: true, available: false, reason: 'git-unavailable' }
@@ -71,6 +72,7 @@ export async function inspectRemoteGit(binding, { action = 'status', path: relat
71
72
  // Git canonicalizes symlinked workspace roots. Keep filtering in that same
72
73
  // world, but return navigation paths under the user's original workspace.
73
74
  const gitWorkspace = prefix ? joinRemotePath(repo, prefix) : repo
75
+ if (pool.local) await pool.checkPath(gitWorkspace)
74
76
  const navigationPath = target => {
75
77
  const within = relPathUnder(gitWorkspace, target)
76
78
  return within === null ? null : within ? joinRemotePath(ws, within) : ws