From 249968f48c364cb3b0ea1406012b895c41bba373 Mon Sep 17 00:00:00 2001 From: HuanLinOTO Date: Thu, 1 Oct 2026 17:10:47 +0800 Subject: [PATCH] =?UTF-8?q?fix(paths):=20=E8=AF=86=E5=88=AB=20remote-mirro?= =?UTF-8?q?r=20=E5=B7=A5=E4=BD=9C=E5=8C=BA=E5=91=BD=E5=90=8D=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E6=8A=95=E5=BD=B1=EF=BC=88#744=20=E6=91=98=E5=8F=96?= =?UTF-8?q?=20remote-mirror=20=E5=8D=8A=E8=BE=B9=EF=BC=8C#788=20#703?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 摘取 PR #744 中 remote-mirror 命名空间投影这一半:resolveSessionPath 在 win32 上识别 dsh-remote 镜像会话的 cwd(\.dsh\remote-workspaces\ \),读取镜像根的 .dsh-remote-meta.json 拿到远端 POSIX 工作区路径(mtime 失效的同步缓存),把命名空间下的远端绝对路径 (/srv/app/src/a.ts)投影到本地镜像目录(mirrorRoot\src\a.ts)——否则 win32 把它盘符根化成 C:\srv\... 导致交付物 ENOENT(#788 / #703 的 Windows 远程会话症状)。只投影落在远端工作区内的路径;区外路径 (/etc/hosts)刻意不投影。无元数据/元数据损坏/非 POSIX remotePath 时 一律放行原路径,不破坏请求。 相对 PR 原版的基线适配:main 的 path-security 重写已删除工作区围栏 (resolve-only),因此「区外路径不投影」的后果从「403 containment 拒绝」 变为「保持斜杠根化 → resolve() 盘符根化 → stat 失败报缺失本地文件」, 文档与测试注释已按此改写;投影决策本身不变。 明确丢弃的另一半(html 路由 cwd hint + $c/$r marker + media 路由 resolveWorkspaceRelative + intercept.tsx 取 cwd): - cwd hint 半边已被 main 的 d71261ac(PR #372)缓解——sessionCwdOf 现有 header → clientCwd → persistence → process.cwd 回退链,覆盖 detach 场景; - resolveWorkspaceRelative 与 main 的 resolveTarget 语义重复(后者已把 会话相对目标 join 到 cwd); - src/client/intercept.tsx 在 main 上已整体删除(turnTail 交还宿主); - path-security 报错文案子改动随 5c95002 重写失去载体。 PR 中的 html-route / paths / sandbox-views / smoke 测试改动同属该半边, 一并不取。html 路由 clientCwd 入口仍缺(#819,另由 #754 客户端侧覆盖), 不在本提交范围。 测试:tests/session-path.spec.ts 移植 dsh-remote mirror describe 块 (10 例:区内/根/嵌套会话投影、区外与同名前缀不投影、dot 段归一、盘符 路径保留、无/坏元数据放行、非 win32 不重释),18/18 绿。 --- src/session-path.ts | 122 +++++++++++++++++++++++++++++++++---- tests/session-path.spec.ts | 85 +++++++++++++++++++++++++- 2 files changed, 193 insertions(+), 14 deletions(-) diff --git a/src/session-path.ts b/src/session-path.ts index 040058e0..4978936a 100644 --- a/src/session-path.ts +++ b/src/session-path.ts @@ -1,22 +1,102 @@ +import { readFileSync, statSync } from 'node:fs' import { win32 } from 'node:path' /** `\\wsl.localhost\` root of a Windows-hosted WSL workspace. */ const WSL_LOCALHOST_ROOT = /^\\\\wsl\.localhost\\([^\\]+)(?:\\|$)/i +/** + * `<...>\.dsh\remote-workspaces\\` mirror root of a + * dsh-remote session. The captured group is the mirror root itself: the + * local directory that mirrors one remote workspace. + */ +const REMOTE_MIRROR_ROOT = /^(.*\\\.dsh\\remote-workspaces\\[^\\]+\\[^\\]+)(?:\\|$)/i + +/** Metadata file dsh-remote writes at the root of every mirror directory. */ +const REMOTE_META_FILE = '.dsh-remote-meta.json' + +/** One cached mirror metadata read, invalidated by the file's mtime. */ +interface RemoteMetaEntry { + mtimeMs: number + /** The remote workspace path (POSIX), or undefined when unusable. */ + remotePath: string | undefined +} + +/** + * Mirror metadata cache. `resolveSessionPath` is synchronous and sits on + * every filesystem request, so the metadata is read synchronously and + * memoized per mirror root; an mtime change re-reads it. + */ +const remoteMetaCache = new Map() + +/** + * The remote workspace path a mirror root stands for, or undefined when the + * directory carries no usable metadata. Failures are swallowed on purpose: + * an unreadable or malformed meta file must leave the caller's path alone + * rather than break the request. + */ +function remotePathOf(mirrorRoot: string): string | undefined { + const metaFile = win32.join(mirrorRoot, REMOTE_META_FILE) + let mtimeMs: number + try { + mtimeMs = statSync(metaFile).mtimeMs + } catch { + remoteMetaCache.delete(mirrorRoot) + return undefined + } + const cached = remoteMetaCache.get(mirrorRoot) + if (cached !== undefined && cached.mtimeMs === mtimeMs) return cached.remotePath + + let remotePath: string | undefined + try { + const parsed: unknown = JSON.parse(readFileSync(metaFile, 'utf8')) + const value = (parsed as { remotePath?: unknown } | null)?.remotePath + // Only POSIX-rooted remote paths can be projected; a Windows remote + // (drive path) needs no reinterpretation and is left to the caller. + remotePath = typeof value === 'string' && value.startsWith('/') ? value : undefined + } catch { + remotePath = undefined + } + remoteMetaCache.set(mirrorRoot, { mtimeMs, remotePath }) + return remotePath +} + +/** + * The POSIX path segments of `target` relative to `base`, or undefined when + * `target` does not lie under `base`. Both are remote (POSIX) paths, so the + * comparison is case-SENSITIVE and separator handling is plain '/'. + */ +function relativeUnderPosix(base: string, target: string): string | undefined { + const normalize = (value: string): string => value.replace(/\/+$/, '') + const root = normalize(base) + if (target === root) return '' + if (!target.startsWith(`${root}/`)) return undefined + return target.slice(root.length + 1) +} + /** * Reinterpret an already-absolute path in the namespace of one session. * * Windows treats `/foo` as rooted on the current drive, so `path.resolve()` * turns it into e.g. `C:\\foo`. That is wrong for a session whose cwd is a * WSL UNC path: in that namespace `/foo` means the distro's Linux `/foo`. - * Project only that unambiguous combination onto the matching distro root; - * drive paths, UNC paths, ordinary Windows sessions and non-Windows hosts - * keep their existing semantics. + * It is equally wrong for a dsh-remote mirror session, whose cwd is a local + * directory (`...\\.dsh\\remote-workspaces\\\\`) standing in + * for a remote POSIX workspace: there `/srv/app/src/a.ts` means the mirrored + * file, not `C:\\srv\\app\\src\\a.ts` (which does not exist — the symptom is + * `ENOENT ... realpath 'C:\\Users\\...'`). * - * Workspace containment is intentionally NOT handled here. A projected path - * such as `/tmp/x` can still be rejected later for lying outside the session - * workspace; the important part is that it is checked as WSL `/tmp/x`, not - * silently redirected to `C:\\tmp\\x`. + * Project only those unambiguous combinations onto the matching root; drive + * paths, UNC paths, ordinary Windows sessions and non-Windows hosts keep + * their existing semantics. + * + * What happens AFTER projection is the caller's business (the old workspace + * fence is gone; `resolveTarget` only normalizes). The important part for a + * WSL session is that `/tmp/x` is read as WSL `/tmp/x`, not silently + * redirected to `C:\\tmp\\x`. For a mirror session a remote path OUTSIDE the + * mirrored workspace (e.g. `/etc/hosts`) is deliberately left unprojected: + * it stays slash-rooted, `resolve()` then drive-roots it and the request + * fails as a missing local file — it is never mapped onto an unrelated file + * inside the mirror. */ export function resolveSessionPath( cwd: string, @@ -26,12 +106,28 @@ export function resolveSessionPath( if (platform !== 'win32' || !/^\/(?!\/)/.test(target)) return target // Session cwd can be spelled with either separator style. Normalize only - // for detection; the returned host path is always canonical win32 UNC. + // for detection; the returned host path is always canonical win32. const normalizedCwd = cwd.replace(/\//g, '\\') - const match = WSL_LOCALHOST_ROOT.exec(normalizedCwd) - if (match === null) return target + const wsl = WSL_LOCALHOST_ROOT.exec(normalizedCwd) + if (wsl !== null) { + const distroRoot = `\\\\wsl.localhost\\${wsl[1]}` + const relative = target.slice(1).replace(/\//g, '\\') + return win32.resolve(distroRoot, relative) + } - const distroRoot = `\\\\wsl.localhost\\${match[1]}` - const relative = target.slice(1).replace(/\//g, '\\') - return win32.resolve(distroRoot, relative) + // A dsh-remote mirror: map the remote workspace path onto the local mirror + // root. Only paths inside the mirrored workspace are projected. + const mirror = REMOTE_MIRROR_ROOT.exec(normalizedCwd) + if (mirror !== null) { + const mirrorRoot = mirror[1]! + const remotePath = remotePathOf(mirrorRoot) + if (remotePath !== undefined) { + const relative = relativeUnderPosix(remotePath, target) + if (relative !== undefined) { + return relative === '' ? win32.resolve(mirrorRoot) : win32.resolve(mirrorRoot, relative.replace(/\//g, '\\')) + } + } + } + + return target } diff --git a/tests/session-path.spec.ts b/tests/session-path.spec.ts index 07508f89..c71793f0 100644 --- a/tests/session-path.spec.ts +++ b/tests/session-path.spec.ts @@ -1,4 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { resolveSessionPath } from '../src/session-path.ts' const WSL_CWD = '\\\\wsl.localhost\\archlinux\\home\\zdaar\\project' @@ -48,3 +51,83 @@ describe('resolveSessionPath', () => { .toBe('\\\\wsl.localhost\\Ubuntu\\home\\me\\project\\a.ts') }) }) + +/** + * dsh-remote mirror sessions: the session cwd is a LOCAL directory standing + * in for a remote POSIX workspace. A remote path must land inside the mirror, + * never on the current drive (the `ENOENT ... realpath 'C:\\...'` symptom). + */ +describe('resolveSessionPath (dsh-remote mirror)', () => { + let dshHome: string + let mirrorRoot: string + const REMOTE_PATH = '/Users/yangheng/Project/claude/CBI_CT/civiapp_main' + + beforeAll(() => { + dshHome = mkdtempSync(join(tmpdir(), 'dsh-session-path-')) + mirrorRoot = join(dshHome, '.dsh', 'remote-workspaces', '192.168.8.6-yangheng-22', 'civiapp_main') + mkdirSync(mirrorRoot, { recursive: true }) + writeFileSync( + join(mirrorRoot, '.dsh-remote-meta.json'), + JSON.stringify({ host: '192.168.8.6', port: 22, username: 'yangheng', remotePath: REMOTE_PATH }), + ) + }) + + afterAll(() => { + rmSync(dshHome, { recursive: true, force: true }) + }) + + it('maps a remote workspace file onto the local mirror', () => { + expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/a.ts`, 'win32')) + .toBe(join(mirrorRoot, 'src', 'a.ts')) + }) + + it('maps the remote workspace root itself onto the mirror root', () => { + expect(resolveSessionPath(mirrorRoot, REMOTE_PATH, 'win32')).toBe(mirrorRoot) + }) + + it('maps for a session nested inside the mirror', () => { + const nested = join(mirrorRoot, 'packages', 'api') + expect(resolveSessionPath(nested, `${REMOTE_PATH}/src/a.ts`, 'win32')) + .toBe(join(mirrorRoot, 'src', 'a.ts')) + }) + + it('leaves a remote path OUTSIDE the mirrored workspace unprojected', () => { + // Deliberately NOT mapped: projecting it would invent an unrelated local + // file. It stays a slash-rooted path — downstream `resolve()` drive-roots + // it (`C:\etc\hosts`) and the request fails as a missing local file. + expect(resolveSessionPath(mirrorRoot, '/etc/hosts', 'win32')).toBe('/etc/hosts') + }) + + it('does not treat a workspace whose name merely prefixes another as inside it', () => { + expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}_backup/a.ts`, 'win32')) + .toBe(`${REMOTE_PATH}_backup/a.ts`) + }) + + it('normalizes dot segments without escaping the mirror root', () => { + expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/../lib/a.ts`, 'win32')) + .toBe(join(mirrorRoot, 'lib', 'a.ts')) + }) + + it('preserves Windows drive paths in a mirror session', () => { + const target = 'C:\\Users\\yangheng\\file.md' + expect(resolveSessionPath(mirrorRoot, target, 'win32')).toBe(target) + }) + + it('leaves paths alone when the mirror has no metadata file', () => { + const bare = join(dshHome, '.dsh', 'remote-workspaces', 'host-key', 'no-meta') + mkdirSync(bare, { recursive: true }) + expect(resolveSessionPath(bare, '/srv/app/a.ts', 'win32')).toBe('/srv/app/a.ts') + }) + + it('leaves paths alone when the metadata is malformed', () => { + const broken = join(dshHome, '.dsh', 'remote-workspaces', 'host-key', 'broken-meta') + mkdirSync(broken, { recursive: true }) + writeFileSync(join(broken, '.dsh-remote-meta.json'), '{ not json') + expect(resolveSessionPath(broken, '/srv/app/a.ts', 'win32')).toBe('/srv/app/a.ts') + }) + + it('does not reinterpret paths for a mirror session on non-Windows hosts', () => { + expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/a.ts`, 'linux')) + .toBe(`${REMOTE_PATH}/src/a.ts`) + }) +})