DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(worktree): 防止清理越过托管目录边界 (#851)
SkanderBot5a1d964fc84e
diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree-safety.test.ts b/packages/dsh-tauri-worktree/src/host/service/worktree-safety.test.tsnew file mode 100644index 00000000..7757949a--- /dev/null+++ b/packages/dsh-tauri-worktree/src/host/service/worktree-safety.test.ts@@ -0,0 +1,180 @@+import type { Binding } from '../types'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import process from 'node:process'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const home = vi.hoisted(() => ({ value: '' }))+vi.mock('dsh-tauri', async (importOriginal) => {+ const actual = await importOriginal<typeof import('dsh-tauri')>()+ return { ...actual, get DSH_HOME() {+ return home.value+ } }+})++let scratch: string+let worktree: typeof import('./worktree')['worktree']+let binding: Binding+const protectedFiles = ['sessions/project/turn.json', 'profiles/web/package.json', 'storages/workspace.json', '.credentials.yaml']++beforeEach(async () => {+ vi.resetModules()+ scratch = mkdtempSync(join(tmpdir(), 'dsh-cleanup-safety-'))+ home.value = join(scratch, 'dsh-home')+ for (const name of protectedFiles) {+ const path = join(home.value, name)+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, `preserve ${name}`)+ }+ binding = {+ sessionId: 'session',+ hash: 'hash',+ dirname: 'project',+ worktreePath: join(home.value, 'worktrees/hash/project'),+ projectPath: '',+ branchName: '(detached)',+ ownsBranch: false,+ } as Binding+ ;({ worktree } = await import('./worktree'))+})++afterEach(() => {+ rmSync(scratch, { recursive: true, force: true })+ vi.restoreAllMocks()+})++function saveBinding() {+ const directory = join(home.value, 'ledger')+ mkdirSync(directory, { recursive: true })+ writeFileSync(join(directory, 'session.json'), JSON.stringify(binding))+}++function expectProtectedData() {+ for (const name of protectedFiles) {+ const path = join(home.value, name)+ expect(existsSync(path), `cleanup must preserve ${name}`).toBe(true)+ expect(readFileSync(path, 'utf8')).toBe(`preserve ${name}`)+ }+}++function linkDirectory(target: string, link: string) {+ mkdirSync(join(link, '..'), { recursive: true })+ symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir')+}++describe('worktree deletion boundaries', () => {+ it.each(['home', 'sessions', 'external'])('preserves user data when a saved binding points at %s', async (target) => {+ const external = join(scratch, 'external')+ mkdirSync(external)+ writeFileSync(join(external, 'keep.txt'), 'outside data')+ binding.worktreePath = target === 'home' ? home.value : target === 'sessions' ? join(home.value, 'sessions') : external+ saveBinding()+ const result = await worktree.remove('session')+ expectProtectedData()+ expect(readFileSync(join(external, 'keep.txt'), 'utf8')).toBe('outside data')+ expect(result.ok).toBe(false)+ expect(existsSync(join(home.value, 'ledger/session.json'))).toBe(true)+ })++ it('rejects a damaged binding before scheduling asynchronous deletion', async () => {+ binding.worktreePath = home.value+ saveBinding()+ const result = await worktree.discard('session', 'hash/project')+ expect(result.ok).toBe(false)+ expectProtectedData()+ })++ it('preserves an external alias and its binding instead of reporting successful removal', async () => {+ const managed = binding.worktreePath+ mkdirSync(managed, { recursive: true })+ writeFileSync(join(managed, 'keep.txt'), 'worktree data')+ const alias = join(scratch, 'external-alias')+ linkDirectory(managed, alias)+ binding.worktreePath = alias+ saveBinding()+ const result = await worktree.remove('session')+ expect(result.ok).toBe(false)+ expect(existsSync(alias)).toBe(true)+ expect(readFileSync(join(managed, 'keep.txt'), 'utf8')).toBe('worktree data')+ expect(existsSync(join(home.value, 'ledger/session.json'))).toBe(true)+ expectProtectedData()+ })++ it.each(['..', '.. ', '', null, {}])('rejects a saved binding with malformed hash %j', async (hash) => {+ Object.assign(binding, { hash })+ mkdirSync(binding.worktreePath, { recursive: true })+ writeFileSync(join(binding.worktreePath, 'keep.txt'), 'worktree data')+ saveBinding()+ const result = await worktree.remove('session')+ expect(result.ok).toBe(false)+ expectProtectedData()+ expect(readFileSync(join(binding.worktreePath, 'keep.txt'), 'utf8')).toBe('worktree data')+ })++ it('rejects a damaged binding before checkout can change the repository', async () => {+ binding.worktreePath = home.value+ saveBinding()+ const result = await worktree.checkout({ sessionId: 'session', branch_name: 'main' })+ expect(result).toEqual({ ok: false, error: '工作树路径不安全,已保留数据' })+ expectProtectedData()+ })++ it('rejects an orphan cleanup through a worktree parent link', async () => {+ linkDirectory(home.value, join(home.value, 'worktrees/hash'))+ const result = await worktree.remove('', 'hash/sessions')+ expectProtectedData()+ expect(result.ok).toBe(false)+ })++ it('preserves sessions when a trash parent link redirects pre-deletion cleanup', async () => {+ binding.dirname = 'sessions'+ binding.worktreePath = join(home.value, 'worktrees/hash/sessions')+ mkdirSync(binding.worktreePath, { recursive: true })+ writeFileSync(join(binding.worktreePath, 'keep.txt'), 'worktree data')+ saveBinding()+ linkDirectory(home.value, join(home.value, '.trash/hash'))+ const result = await worktree.remove('session')+ expectProtectedData()+ expect(readFileSync(join(binding.worktreePath, 'keep.txt'), 'utf8')).toBe('worktree data')+ expect(result.ok).toBe(false)+ })++ it('does not sweep a trash root that redirects into DSH_HOME', async () => {+ linkDirectory(home.value, join(home.value, '.trash'))+ const result = await worktree.recover()+ expectProtectedData()+ expect(result.ok).toBe(false)+ })++ it.each(['../..', '.. /.. ', 'hash/..\\..', 'hash/C:'])('rejects unsafe orphan key %s', async (key) => {+ const result = await worktree.remove('', key)+ expect(result.ok).toBe(false)+ expectProtectedData()+ })++ it('removes an ordinary managed orphan while preserving user data', async () => {+ mkdirSync(binding.worktreePath, { recursive: true })+ writeFileSync(join(binding.worktreePath, 'remove.txt'), 'orphan worktree')+ const result = await worktree.remove('', 'hash/project')+ expect(result.ok).toBe(true)+ expect(existsSync(binding.worktreePath)).toBe(false)+ expectProtectedData()+ })++ it.each(['configured', 'canonical', 'original'])('allows a linked DSH_HOME with a %s binding path', async (pathKind) => {+ const realHome = home.value+ const alias = join(scratch, 'home-alias')+ linkDirectory(realHome, alias)+ home.value = alias+ const managed = join(alias, 'worktrees/hash/project')+ mkdirSync(managed, { recursive: true })+ writeFileSync(join(managed, 'remove.txt'), 'orphan worktree')+ binding.worktreePath = pathKind === 'configured' ? managed : pathKind === 'canonical' ? realpathSync(managed) : join(realHome, 'worktrees/hash/project')+ saveBinding()+ const result = await worktree.remove('session')+ expect(result.ok).toBe(true)+ expect(existsSync(managed)).toBe(false)+ expectProtectedData()+ })+})diff --git a/packages/dsh-tauri-worktree/src/host/service/worktree.ts b/packages/dsh-tauri-worktree/src/host/service/worktree.tsindex fc727f76..9cc9b16a 100644--- a/packages/dsh-tauri-worktree/src/host/service/worktree.ts+++ b/packages/dsh-tauri-worktree/src/host/service/worktree.ts@@ -66,6 +66,8 @@ export const worktree = defineService({const hash = computeHash(projectPath, sessionId)const dirname = projectDirname(projectPath)const path = worktreePath(hash, dirname)+ if (!isSafeRemovalTarget(path, hash, dirname))+ return { ok: false, error: '工作树路径不安全,已保留数据' }const linkDirectories = normalizeLinkDirectories(options.linkDependencyDirectories)const linkDependencies = options.linkDependencies ?? LINK_DEPENDENCIES@@ -206,6 +208,8 @@ export const worktree = defineService({const binding = resolveBinding(params.sessionId, params.worktreeHashDirname ?? params.worktree_hash_dirname)if (!binding)return { ok: false, error: '未找到绑定的工作树' }+ if (!isSafeRemovalTarget(binding.worktreePath, binding.hash, binding.dirname))+ return { ok: false, error: '工作树路径不安全,已保留数据' }if (!existsSync(binding.worktreePath))return { ok: false, error: `工作树目录不存在:${binding.worktreePath}` }@@ -572,6 +576,8 @@ async function removeWorktreeOnDisk(linkDirectories: readonly string[] = [],signal?: AbortSignal,): Promise<OperationResult> {+ if (!isSafeRemovalTarget(path, hash, dirname))+ return { ok: false, error: '工作树路径不安全,已保留数据' }await stopWorktreeProcesses(sessionId, path)if (linkDirectories.length > 0)@@ -658,14 +664,19 @@ interface RemovalTarget {*/async function removalTarget(sessionId: string, key: string): Promise<RemovalTarget | null> {const binding = resolveBinding(sessionId, key)- if (binding)+ if (binding) {+ if (!isSafeRemovalTarget(binding.worktreePath, binding.hash, binding.dirname))+ return nullreturn { ...binding, binding, bound: true }+ }const parsed = parseWorktreeKey(key)// 未绑定的 key 直接来自请求体:任一段越出 `worktrees/<hash>/<dirname>` 都拒绝,// 否则 `../..` 这类 key 会被 join() 归一化到工作树根之外再被递归删除if (!parsed || !isSafeKeySegment(parsed.hash) || !isSafeKeySegment(parsed.dirname))return nullconst path = worktreePath(parsed.hash, parsed.dirname)+ if (!isSafeRemovalTarget(path, parsed.hash, parsed.dirname))+ return nullreturn {sessionId,hash: parsed.hash,@@ -678,8 +689,31 @@ async function removalTarget(sessionId: string, key: string): Promise<RemovalTar}/** key 的每一段都必须是单一目录名:不接受空串、`.`、`..` 与任何路径分隔符。 */-function isSafeKeySegment(segment: string): boolean {- return Boolean(segment) && segment !== '.' && segment !== '..' && !segment.includes('/') && !segment.includes('\\')+function isSafeKeySegment(segment: unknown): segment is string {+ return typeof segment === 'string' && Boolean(segment.trim())+ && segment.trim() !== '.' && segment.trim() !== '..'+ && !/[\\/:\0]/.test(segment)+}++// issue #848:落盘绑定也可能损坏;源目录和回收站都必须匹配 DSH_HOME 内的固定路径。+function isSafeRemovalTarget(path: unknown, hash: unknown, dirname: unknown): boolean {+ return isSafeKeySegment(hash) && isSafeKeySegment(dirname)+ && isManagedPath(path, WORKTREES_DIR, hash, dirname)+ && isManagedPath(worktreeTrashPath(hash, dirname), TRASH_DIR, hash, dirname)+}++function isManagedPath(path: unknown, ...parts: string[]): boolean {+ if (typeof path !== 'string' || !path)+ return false+ const normalize = (value: string) => process.platform === 'win32' ? resolve(value).toLowerCase() : resolve(value)+ const home = canonicalPath(DSH_HOME)+ const expected = normalize(join(home, ...parts))+ const source = normalize(path)+ const root = parts.reduce(parent => dirname(parent), resolve(path))+ // 根目录允许链接和 Windows 短路径,受管子路径必须原样匹配,不能用外部别名替代。+ if (source !== normalize(join(root, ...parts)) || normalize(canonicalPath(root)) !== normalize(home))+ return false+ return normalize(canonicalPath(path)) === expected}function projectFromWorktree(path: string): string {@@ -720,19 +754,27 @@ async function worktreeOccupant(root: string, branch: string, worktreePath: striasync function sweepAbandoned(): Promise<number> {let swept = 0const trashRoot = join(DSH_HOME, TRASH_DIR)+ const worktreesRoot = join(DSH_HOME, WORKTREES_DIR)+ if (!isManagedPath(trashRoot, TRASH_DIR) || !isManagedPath(worktreesRoot, WORKTREES_DIR))+ throw new Error('工作树清理目录不安全,已保留数据')for (const hash of listDirectoryNames(trashRoot)) {const container = join(trashRoot, hash)+ if (!isSafeKeySegment(hash) || !isManagedPath(container, TRASH_DIR, hash))+ throw new Error('工作树回收站目录不安全,已保留数据')await removeDirectoryTree(container)if (!existsSync(container))swept += 1}- const worktreesRoot = join(DSH_HOME, WORKTREES_DIR)for (const hash of listDirectoryNames(worktreesRoot)) {const container = join(worktreesRoot, hash)+ if (!isSafeKeySegment(hash) || !isManagedPath(container, WORKTREES_DIR, hash))+ throw new Error('工作树目录不安全,已保留数据')const staleContainer = isSweepable(container)for (const name of listDirectoryNames(container)) {const path = join(container, name)+ if (!isSafeKeySegment(name) || !isManagedPath(path, WORKTREES_DIR, hash, name))+ throw new Error('工作树目录不安全,已保留数据')if (isSweepable(path))await removeEmptyDirectories([path])if (!existsSync(path))