import fs from 'fs/promises'; import os from 'os'; import path from 'path'; import zlib from 'zlib'; import * as tarStream from 'tar-stream'; import Limrun from '@limrun/api'; /** tar builds an archive the way the guest agent writes one: entries relative to the folder. */ async function tar( entries: Array<{ name: string; body?: string; link?: string; dir?: boolean; mode?: number }>, ) { const pack = tarStream.pack(); const chunks: Buffer[] = []; pack.on('data', (chunk) => chunks.push(chunk as Buffer)); const done = new Promise((resolve) => pack.on('end', () => resolve())); for (const e of entries) { if (e.dir) pack.entry({ name: e.name, type: 'directory', mode: e.mode ?? 0o755 }); else if (e.link) pack.entry({ name: e.name, type: 'symlink', linkname: e.link }); else pack.entry({ name: e.name, mode: e.mode ?? 0o644 }, e.body ?? ''); } pack.finalize(); await done; return Buffer.concat(chunks); } // Node has zstd from 22.15; on an older Node the client asks for and sends nothing compressed. const zstd = typeof (zlib as any).createZstdDecompress === 'function'; const pullQuery = zstd ? 'archive=tar&compression=zstd' : 'archive=tar'; describe('macOS files', () => { let server: import('http').Server; let signaling: import('ws').WebSocketServer; let apiUrl: string; let dir: string; const requests: Array<{ method: string; url: string; encoding?: string; body: Buffer }> = []; let project: Buffer; let evil: Buffer; beforeAll(async () => { project = await tar([ { name: 'src/', dir: true }, { name: 'src/main.swift', body: 'print(1)', mode: 0o755 }, { name: 'entry', link: 'src/main.swift' }, { name: 'abs', link: '/etc/hosts' }, { name: 'Package.swift', body: '// swift-tools-version:6.0' }, ]); evil = await tar([{ name: '../escape', body: 'x' }]); const http = await import('http'); const { WebSocketServer } = await import('ws'); server = http.createServer((req, res) => { const chunks: Buffer[] = []; req.on('data', (chunk: Buffer) => chunks.push(chunk)); req.on('end', () => { let body = Buffer.concat(chunks); const encoding = req.headers['content-encoding']; if (encoding === 'zstd') body = (zlib as any).zstdDecompressSync(body); if (encoding === 'gzip') body = zlib.gunzipSync(body); requests.push({ method: req.method!, url: req.url!, ...(encoding && { encoding }), body }); const url = new URL(req.url!, 'http://guest'); const json = (status: number, value: unknown) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(value)); }; if (url.pathname === '/folder-sync') return json(200, { ok: true }); if (url.pathname === '/files/list') { return json(200, { entries: [ { name: 'a', path: 'Desktop/a', isDirectory: true }, { name: 'b.txt', path: 'Desktop/b.txt', isDirectory: false, size: 3 }, ], }); } if (req.method === 'PUT') return json(200, { path: '/Users/limrun/Desktop/notes.txt' }); if (req.method === 'DELETE') return json(200, { ok: true }); switch (url.searchParams.get('path')) { case 'sync/project': // Compressed only when asked, as the guest agent does. if (url.searchParams.get('compression') === 'zstd') { res.writeHead(200, { 'Content-Type': 'application/x-tar', 'X-Limrun-Compression': 'zstd' }); return res.end((zlib as any).zstdCompressSync(project)); } res.writeHead(200, { 'Content-Type': 'application/x-tar' }); return res.end(project); case 'evil': res.writeHead(200, { 'Content-Type': 'application/x-tar' }); return res.end(evil); case 'missing': return json(404, { reason: 'no such file' }); default: // As an instance that predates compression answers: the body as it is. res.writeHead(200, { 'Content-Type': 'application/octet-stream' }); return res.end('log line'); } }); }); signaling = new WebSocketServer({ server, path: '/signaling' }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); apiUrl = `http://127.0.0.1:${(server.address() as import('net').AddressInfo).port}`; }); afterAll(async () => { for (const client of signaling.clients) client.terminate(); await new Promise((resolve) => signaling.close(() => resolve())); await new Promise((resolve) => server.close(() => resolve())); }); beforeEach(async () => { requests.length = 0; dir = await fs.mkdtemp(path.join(os.tmpdir(), 'lim-macos-files-')); }); afterEach(async () => { await fs.rm(dir, { recursive: true, force: true }); }); async function client() { const limrun = new Limrun({ apiKey: 'key', baseURL: 'https://api.example.test' }); return limrun.macosInstances.createClient({ apiUrl, token: 'control', logLevel: 'none' }); } test('pushes compressed, lists and deletes by guest path', async () => { const mac = await client(); try { const local = path.join(dir, 'notes.txt'); await fs.writeFile(local, 'hello '.repeat(1000)); await expect(mac.pushFile(local, 'Desktop/notes.txt')).resolves.toBe('/Users/limrun/Desktop/notes.txt'); expect(requests[0]).toMatchObject({ method: 'PUT', url: '/files?path=Desktop%2Fnotes.txt', }); expect(requests[0]!.encoding).toBe(zstd ? 'zstd' : undefined); expect(requests[0]!.body.toString()).toBe('hello '.repeat(1000)); await expect(mac.listFiles('Desktop')).resolves.toEqual([ { name: 'a', path: 'Desktop/a', isDirectory: true }, { name: 'b.txt', path: 'Desktop/b.txt', isDirectory: false, size: 3 }, ]); await mac.listFiles(); await mac.deleteFile('/tmp/old dir'); expect(requests.slice(1).map((r) => `${r.method} ${r.url}`)).toEqual([ 'GET /files/list?path=Desktop', 'GET /files/list', 'DELETE /files?path=%2Ftmp%2Fold+dir', ]); } finally { mac.disconnect(); } }); test('pulls a file, and a compressed folder into an existing folder', async () => { const mac = await client(); try { const file = path.join(dir, 'out.log'); await expect(mac.pull('Library/Logs/app.log', file)).resolves.toEqual({ path: file, isDirectory: false, }); expect(await fs.readFile(file, 'utf8')).toBe('log line'); await expect(mac.pull('sync/project', dir)).resolves.toEqual({ path: path.join(dir, 'project'), isDirectory: true, }); const root = path.join(dir, 'project'); expect(await fs.readFile(path.join(root, 'src/main.swift'), 'utf8')).toBe('print(1)'); expect((await fs.stat(path.join(root, 'src/main.swift'))).mode & 0o777).toBe(0o755); expect(await fs.readlink(path.join(root, 'entry'))).toBe('src/main.swift'); // A link keeps its target, as tar keeps it; nothing is written through it. expect(await fs.readlink(path.join(root, 'abs'))).toBe('/etc/hosts'); expect(requests.map((r) => r.url)).toEqual([ `/files?path=Library%2FLogs%2Fapp.log&${pullQuery}`, `/files?path=sync%2Fproject&${pullQuery}`, ]); } finally { mac.disconnect(); } }); test('refuses a tar entry outside the folder and reports a missing path', async () => { const mac = await client(); try { await expect(mac.pull('evil', path.join(dir, 'evil'))).rejects.toThrow('outside its folder'); await expect(fs.stat(path.join(dir, 'escape'))).rejects.toThrow(); await expect(mac.pull('missing', path.join(dir, 'missing'))).rejects.toThrow(/404.*no such file/); } finally { mac.disconnect(); } }); test('syncs a folder into the guest folder it names', async () => { const mac = await client(); try { const local = path.join(dir, 'MyApp'); await fs.mkdir(path.join(local, 'Sources'), { recursive: true }); await fs.writeFile(path.join(local, 'Sources/main.swift'), 'print(1)'); await fs.symlink('Sources/main.swift', path.join(local, 'entry')); const cache = path.join(dir, 'cache'); const result = await mac.sync(local, { basisCacheDir: cache }); expect(result.destination).toBe('MyApp'); await mac.sync(local, { destination: '/Users/limrun/Projects/App/', basisCacheDir: path.join(dir, 'c2'), }); expect(requests.map((r) => r.url)).toEqual([ '/folder-sync?path=MyApp', '/folder-sync?path=%2FUsers%2Flimrun%2FProjects%2FApp', ]); const meta = (body: Buffer) => JSON.parse(body.subarray(4, 4 + body.readUInt32BE(0)).toString()); const first = meta(requests[0]!.body); expect(first.rootName).toBe('MyApp'); expect(first.install).toBe(false); expect(first.files).toEqual( expect.arrayContaining([ expect.objectContaining({ path: 'Sources/main.swift' }), expect.objectContaining({ path: 'entry', link: 'Sources/main.swift' }), ]), ); expect(meta(requests[1]!.body).rootName).toBe('App'); // A shared cache still keeps each destination's basis apart: a new destination gets every file. const shared = path.join(dir, 'shared'); await mac.sync(local, { destination: 'one', basisCacheDir: shared }); const second = await mac.sync(local, { destination: 'two', basisCacheDir: shared }); expect(second.bytesSent).toBe('print(1)'.length); // A cache inside the synced folder stays out of the walk, every destination's folder in it. const inside = path.join(local, '.limsync'); await mac.sync(local, { destination: 'three', basisCacheDir: inside }); requests.length = 0; await mac.sync(local, { destination: 'four', basisCacheDir: inside }); expect( meta(requests[0]!.body) .files.map((f: { path: string }) => f.path) .sort(), ).toEqual(['Sources/main.swift', 'entry']); await expect(mac.sync(local, { destination: '~' })).rejects.toThrow('folder of its own'); } finally { mac.disconnect(); } }); });