import { afterAll, describe, expect, it } from 'vitest' import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { renameWorkspaceEntry, removeWorkspaceEntry, mkdirWorkspaceEntry, writeWorkspaceUpload } from '../src/fs-operations.ts' import { removeTree } from './temp-tree.ts' /** The test workspace root (each suite gets its own temp tree). */ const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-')) /** Symlink creation needs privileges on Windows; the link cases skip there. */ const canSymlink = (() => { const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-probe-')) try { symlinkSync(dir, join(dir, 'probe-link')) return true } catch { return false } finally { removeTree(dir) } })() afterAll(() => { removeTree(root) }) /** Names of leftover temp files under `dir` (must be empty after every run). */ function tmpLeftovers(dir: string): string[] { return readdirSync(dir).filter(name => name.includes('.dsh-upload-')) } /** Turn a string into the async-iterable chunk shape the route receives. */ function chunksOf(text: string): AsyncIterable { return { async *[Symbol.asyncIterator]() { // Split on two-byte boundaries so UTF-8 multi-byte sequences cross // chunk edges (streaming must reassemble them as raw bytes, not text). for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2) }, } } /** `count` copies of one buffer, generated lazily: the payload is never held in memory. */ function repeatedChunks(chunk: Uint8Array, count: number): AsyncIterable { return { async *[Symbol.asyncIterator]() { for (let i = 0; i < count; i++) yield chunk }, } } /** A body that yields `text` in chunks and then DIES, as a dropped upload does. */ function dyingChunks(text: string): AsyncIterable { return { async *[Symbol.asyncIterator]() { for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2) throw new Error('stream died') }, } } /** * A body that is only COMPLETE once `parties` uploads have reached its end. * * A concurrency case that merely starts its uploads together proves nothing: * each spends its time in the write stream, and they may well reach their * renames milliseconds apart — the case then passes while never exercising the * race it names. Holding every body at the end until the whole set is there forces * the renames into the same instant, which is the overlap the case is about. */ function bodiesThatMeet(parties: number) { let arrived = 0 let release!: () => void const allArrived = new Promise((resolve) => { release = resolve }) const chunks = (text: string): AsyncIterable => ({ async *[Symbol.asyncIterator]() { for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2) if (++arrived >= parties) release() await allArrived }, }) return chunks } /** * A temp project whose root directory carries letters, so a lowercase variant * of its path is a real spelling of the SAME directory (the win32 cases) and a * link to it stands for the project itself. */ function makeProject(): { ws: string; inner: string } { const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-root-')) const inner = join(ws, 'ProjDir') mkdirSync(join(inner, 'src'), { recursive: true }) writeFileSync(join(inner, 'src', 'keep.ts'), 'x') return { ws, inner } } describe('writeWorkspaceUpload', () => { it('writes a file under the upload directory and returns its size', async () => { const { path, size } = await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'a.txt', chunks: chunksOf('hello 世界'), }) expect(path).toBe(join(root, 'a.txt')) expect(size).toBe(Buffer.byteLength('hello 世界')) expect(readFileSync(path, 'utf8')).toBe('hello 世界') }) it('creates nested directories on demand (folder uploads)', async () => { const { path } = await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'docs/nested/deep.txt', chunks: chunksOf('x'), }) expect(existsSync(path)).toBe(true) }) it('resolves relativePaths against the chosen directory', async () => { const { path } = await writeWorkspaceUpload({ cwd: root, dir: join(root, 'docs'), relativePath: 'b.txt', chunks: chunksOf('y'), }) expect(path).toBe(join(root, 'docs', 'b.txt')) }) it('refuses traversal, empty segments, and absolute relativePaths', async () => { await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: '../evil.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: './a.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'a/../b.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: '//', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) // Empty segments are refused, not silently collapsed. await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'a//b.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'a/b/', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) // Absolute paths (POSIX and Windows separators) are refused, not re-anchored. await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: '/x.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: '\\x.txt', chunks: chunksOf('x'), })).rejects.toMatchObject({ code: 'bad-request' }) }) it('uploads into a directory outside the workspace (containment was removed)', async () => { const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-outside-')) try { // ⚠️ PERMISSION CHANGE: the workspace fence is gone, so an absolute // directory the host user can write is a valid upload target. const result = await writeWorkspaceUpload({ cwd: root, dir: outside, relativePath: 'x.txt', chunks: chunksOf('x'), }) expect(result).toEqual({ path: join(outside, 'x.txt'), size: 1 }) expect(readFileSync(join(outside, 'x.txt'), 'utf8')).toBe('x') } finally { removeTree(outside) } }) it('follows an upload directory symlink outside the workspace (no realpath guard)', async () => { if (!canSymlink) return const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-symlink-outside-')) const link = join(root, 'upload-link') try { symlinkSync(outside, link) const viaLink = await writeWorkspaceUpload({ cwd: root, dir: link, relativePath: 'a.txt', chunks: chunksOf('a'), }) expect(viaLink.path).toBe(join(link, 'a.txt')) // …and a relative path that walks through the link lands there too. const viaRelative = await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'upload-link/b.txt', chunks: chunksOf('b'), }) expect(viaRelative.path).toBe(join(root, 'upload-link', 'b.txt')) expect(readFileSync(join(outside, 'a.txt'), 'utf8')).toBe('a') expect(readFileSync(join(outside, 'b.txt'), 'utf8')).toBe('b') } finally { rmSync(link, { force: true }) removeTree(outside) } }) it('streams a body well past the removed size cap and leaves nothing behind', async () => { const target = join(root, 'big.bin') // 16 KiB × 12288 = 192 MiB: half again the cap this case used to trip (the // client pre-check and the host's per-request byte cap both refused at // 128 MiB). Large bodies must simply flow through the same temp-file + // rename path. const chunk = Buffer.alloc(16 * 1024, 7) const count = 12288 const expected = chunk.length * count expect(expected).toBeGreaterThan(128 * 1024 * 1024) const { path, size } = await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'big.bin', chunks: repeatedChunks(chunk, count), }) expect(path).toBe(target) expect(size).toBe(expected) expect(statSync(target).size).toBe(expected) expect(tmpLeftovers(root)).toEqual([]) // Assertions are done; keep 192 MiB out of tmp for the rest of the run. rmSync(target, { force: true }) }) it('keeps concurrent uploads to the same target independent', async () => { const target = join(root, 'race.txt') // Eight parties on purpose. With two, a bare rename loses the collision in // roughly one round out of ten; with eight EVERY round has losers (measured: // 1–5 of them, and never zero), so a dropped retry cannot slip through on // luck. const parties = 8 const rounds = 4 for (let round = 0; round < rounds; round++) { // Every body is held open until ALL of them are complete, so the eight // renames land on the target at the same instant (see bodiesThatMeet). const meet = bodiesThatMeet(parties) const bodies = Array.from({ length: parties }, (_, index) => `body-${round}-${index}`) await Promise.all(bodies.map(body => writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: meet(body), }))) // Every upload SUCCEEDS. Unique temp names keep the bodies from crossing // — but they do not make the renames independent: renames naming the same // target in the same instant are mutually exclusive on Windows, and every // rename that does not win is refused. Losing must cost the caller a // retry, not the upload. The last rename to land wins, and no party // leaves a temp file behind. expect(bodies).toContain(readFileSync(target, 'utf8')) expect(tmpLeftovers(root)).toEqual([]) } }) it('does not overwrite an existing file when a retry dies mid-stream', async () => { const target = join(root, 'keep.txt') await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'keep.txt', chunks: chunksOf('original') }) // The retry fails part-way (a dead body stream, not a size refusal): the // bytes already spilled into the temp sibling are discarded with it, so the // committed target keeps its original content. await expect(writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'keep.txt', chunks: dyingChunks('0123456789'), })).rejects.toThrow('stream died') expect(readFileSync(target, 'utf8')).toBe('original') expect(tmpLeftovers(root)).toEqual([]) }) }) describe('renameWorkspaceEntry', () => { it('renames a file within its directory', async () => { writeFileSync(join(root, 'old-name.txt'), 'x') const { path } = await renameWorkspaceEntry({ cwd: root, path: join(root, 'old-name.txt'), name: 'new-name.txt' }) // The returned path is CANONICAL (realpath-resolved ancestors — on macOS // the tmpdir's /var becomes /private/var), so assert the shape, not the // lexical spelling. expect(path.endsWith('new-name.txt')).toBe(true) expect(existsSync(join(root, 'old-name.txt'))).toBe(false) expect(existsSync(join(root, 'new-name.txt'))).toBe(true) }) it('renames a directory (recursive content moves with it)', async () => { mkdirSync(join(root, 'olddir/nested'), { recursive: true }) writeFileSync(join(root, 'olddir/nested/deep.txt'), 'x') await renameWorkspaceEntry({ cwd: root, path: join(root, 'olddir'), name: 'newdir' }) expect(readFileSync(join(root, 'newdir/nested/deep.txt'), 'utf8')).toBe('x') }) it('is a no-op for the same name (destination-exists refusal must not bite)', async () => { writeFileSync(join(root, 'same.txt'), 'x') await renameWorkspaceEntry({ cwd: root, path: join(root, 'same.txt'), name: 'same.txt' }) expect(existsSync(join(root, 'same.txt'))).toBe(true) }) it('refuses single-segment violations (empty, dot, traversal, separators)', async () => { writeFileSync(join(root, 'r.txt'), 'x') for (const name of ['', '.', '..', 'a/b', 'a\\b']) { await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'r.txt'), name })) .rejects.toMatchObject({ code: 'bad-request' }) } }) it('refuses an existing destination instead of clobbering it', async () => { writeFileSync(join(root, 'src.txt'), 'src') writeFileSync(join(root, 'dst.txt'), 'dst') await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'src.txt'), name: 'dst.txt' })) .rejects.toMatchObject({ code: 'fs-error', status: 409 }) expect(readFileSync(join(root, 'dst.txt'), 'utf8')).toBe('dst') }) it('refuses the workspace root and missing sources', async () => { await expect(renameWorkspaceEntry({ cwd: root, path: root, name: 'nope' })) .rejects.toMatchObject({ code: 'fs-error' }) await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'missing.txt'), name: 'x' })) .rejects.toMatchObject({ code: 'fs-error' }) }) it('renames a symlink ROW, not its target', async () => { writeFileSync(join(root, 'target.txt'), 't') symlinkSync(join(root, 'target.txt'), join(root, 'alias.txt')) await renameWorkspaceEntry({ cwd: root, path: join(root, 'alias.txt'), name: 'alias2.txt' }) expect(existsSync(join(root, 'alias.txt'))).toBe(false) expect(existsSync(join(root, 'alias2.txt'))).toBe(true) expect(readFileSync(join(root, 'target.txt'), 'utf8')).toBe('t') }) }) describe('removeWorkspaceEntry', () => { it('unlinks a file', async () => { writeFileSync(join(root, 'gone.txt'), 'x') await removeWorkspaceEntry({ cwd: root, path: join(root, 'gone.txt') }) expect(existsSync(join(root, 'gone.txt'))).toBe(false) }) it('removes a directory recursively', async () => { mkdirSync(join(root, 'tree/sub'), { recursive: true }) writeFileSync(join(root, 'tree/sub/leaf.txt'), 'x') await removeWorkspaceEntry({ cwd: root, path: join(root, 'tree') }) expect(existsSync(join(root, 'tree'))).toBe(false) }) it('unlinks a symlink row without touching (or recursing into) its target', async () => { mkdirSync(join(root, 'realdir'), { recursive: true }) writeFileSync(join(root, 'realdir/keep.txt'), 'x') symlinkSync(join(root, 'realdir'), join(root, 'linkdir')) await removeWorkspaceEntry({ cwd: root, path: join(root, 'linkdir') }) expect(existsSync(join(root, 'linkdir'))).toBe(false) expect(readFileSync(join(root, 'realdir/keep.txt'), 'utf8')).toBe('x') }) it('refuses the workspace root and missing paths', async () => { await expect(removeWorkspaceEntry({ cwd: root, path: root })) .rejects.toMatchObject({ code: 'fs-error' }) await expect(removeWorkspaceEntry({ cwd: root, path: join(root, 'no-such.txt') })) .rejects.toMatchObject({ code: 'fs-error' }) }) it.runIf(canSymlink)('unlinks a symlink aimed AT the root, leaving the project intact', async () => { // The guard compares the ENTRY's own identity (the same `lstat` the // removal below uses), never what the link resolves to: the link goes and // the project behind it stays — the behaviour the string compare had. const { ws, inner } = makeProject() symlinkSync(inner, join(ws, 'link-to-proj')) try { await removeWorkspaceEntry({ cwd: inner, path: join(ws, 'link-to-proj') }) expect(existsSync(join(ws, 'link-to-proj'))).toBe(false) expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true) } finally { removeTree(ws) } }) }) describe('session-relative targets (the shared resolution contract, #646)', () => { it('uploads into a session-relative directory', async () => { const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relupload-')) try { const { path, size } = await writeWorkspaceUpload({ cwd: ws, dir: '.', relativePath: 'up/rel.txt', chunks: chunksOf('rel'), }) expect(path).toBe(join(ws, 'up', 'rel.txt')) expect(size).toBe(3) expect(readFileSync(path, 'utf8')).toBe('rel') expect(tmpLeftovers(ws)).toEqual([]) } finally { removeTree(ws) } }) it('renames a session-relative row', async () => { const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relrename-')) try { writeFileSync(join(ws, 'a.txt'), 'x') const renamed = await renameWorkspaceEntry({ cwd: ws, path: 'a.txt', name: 'b.txt' }) expect(renamed.path).toBe(join(ws, 'b.txt')) expect(existsSync(join(ws, 'b.txt'))).toBe(true) } finally { removeTree(ws) } }) it('removes a session-relative row', async () => { const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relremove-')) try { writeFileSync(join(ws, 'gone.txt'), 'x') const removed = await removeWorkspaceEntry({ cwd: ws, path: 'gone.txt' }) expect(removed.path).toBe(join(ws, 'gone.txt')) expect(existsSync(join(ws, 'gone.txt'))).toBe(false) } finally { removeTree(ws) } }) it('mkdirs under a session-relative parent', async () => { const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relmkdir-')) try { const made = await mkdirWorkspaceEntry({ cwd: ws, path: '.', name: 'sub' }) expect(made.path).toBe(join(ws, 'sub')) expect(existsSync(join(ws, 'sub'))).toBe(true) } finally { removeTree(ws) } }) }) /** * One directory has many SPELLINGS — a case variant, a `\\?\` prefix, an 8.3 * short name, a mapped drive. The root guard compared the two strings, so any * of them walked past it and "delete this row" became a recursive delete of * the whole project. The guard compares what the filesystem itself compares * (`dev`+`ino`), which does not care how a path is spelled. * * Windows-only: on Linux the variant is a different directory, not a spelling * of this one, and a case variant of a real path does not exist. */ describe.runIf(process.platform === 'win32')('workspace-root guard across path spellings', () => { it('refuses a case variant of the root', async () => { const { ws, inner } = makeProject() try { const variant = inner.toLowerCase() // `ProjDir` carries capitals, so the lowercase spelling always differs — // this does not depend on how the temp directory itself is spelled. expect(variant).not.toBe(inner) await expect(removeWorkspaceEntry({ cwd: inner, path: variant })) .rejects.toMatchObject({ code: 'fs-error' }) expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true) } finally { removeTree(ws) } }) it('refuses the extended-length spelling of the root', async () => { const { ws, inner } = makeProject() try { await expect(removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${inner}` })) .rejects.toMatchObject({ code: 'fs-error' }) expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true) } finally { removeTree(ws) } }) it('refuses a case variant for rename too', async () => { const { ws, inner } = makeProject() try { await expect(renameWorkspaceEntry({ cwd: inner, path: inner.toLowerCase(), name: 'moved' })) .rejects.toMatchObject({ code: 'fs-error' }) expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true) } finally { removeTree(ws) } }) it('still removes a SUBdirectory reached through a spelled-out path', async () => { const { ws, inner } = makeProject() try { mkdirSync(join(inner, 'Sub')) // A spelled-out path that is NOT the root passes the guard — and unlike a // case variant this holds on a case-SENSITIVE volume too. await removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${join(inner, 'Sub')}` }) expect(existsSync(join(inner, 'Sub'))).toBe(false) expect(existsSync(inner)).toBe(true) } finally { removeTree(ws) } }) })