Files
Agent-Workbench/tests/local-files.test.mjs

99 lines
6.8 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { fixture, launchWorkbench, until } from './helpers.mjs';
import { localDirectories } from '../src/server/local-directories.mjs';
import { LocalFilePreviews } from '../src/core/preview/local-file-preview.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
function html(f) {
fs.mkdirSync(path.join(f.projectRoot, 'pages'));
fs.mkdirSync(path.join(f.projectRoot, 'assets'));
fs.writeFileSync(path.join(f.projectRoot, 'pages', '页面.html'), '<!doctype html><html><script type="module" src="../assets/app.mjs"></script><body>Preview</body></html>');
fs.writeFileSync(path.join(f.projectRoot, 'assets', 'app.mjs'), 'document.body.dataset.ready="yes";');
fs.writeFileSync(path.join(f.projectRoot, '.env'), 'TEST_SECRET=never-served');
}
test('directory picker reads one level, preserves empty folders, skips credential and linked folders', async t => {
const f = fixture(t);
for (const name of ['empty', '中文 工程', '.ssh', '.git']) fs.mkdirSync(path.join(f.projectRoot, name));
fs.symlinkSync(f.root, path.join(f.projectRoot, 'external-link'), process.platform === 'win32' ? 'junction' : 'dir');
const result = await localDirectories(f.projectRoot);
assert.equal(result.current, fs.realpathSync.native(f.projectRoot));
assert.equal(result.parent, f.root);
assert.deepEqual(result.directories.map(item => item.name).sort(), ['empty', '中文 工程'].sort());
assert.ok(result.bookmarks.length);
await assert.rejects(localDirectories('relative-folder'));
await assert.rejects(localDirectories(path.join(f.root, 'missing')), /不存在/);
await assert.rejects(localDirectories(path.join(f.projectRoot, 'README.md')), /无法访问/);
});
test('HTML preview serves encoded names and relative modules on an isolated loopback origin; closing revokes it', async t => {
const f = fixture(t); html(f);
const manager = new LocalFilePreviews(f.store); f.onCleanup(() => manager.stopAll());
const result = await manager.start(f.project, 'pages/页面.html');
assert.equal(manager.access(result.url).projectId, f.project.id);
const response = await fetch(result.url);
assert.equal(response.status, 200); assert.match(await response.text(), /Preview/);
assert.match(response.headers.get('content-security-policy'), /sandbox allow-scripts/);
assert.equal(response.headers.get('access-control-allow-origin'), 'null');
const script = await fetch(new URL('../assets/app.mjs', result.url));
assert.equal(script.status, 200); assert.match(await script.text(), /dataset.ready/);
const wrong = new URL(result.url); wrong.pathname = '/invalid/pages/页面.html';
assert.equal(manager.access(wrong.href).allowed, false);
assert.equal((await fetch(wrong)).status, 404);
assert.equal((await fetch(result.url, { method: 'POST' })).status, 405);
await assert.rejects(manager.close('other-project', result.id), /不属于/);
await manager.close(f.project.id, result.id);
assert.equal(manager.access(result.url).allowed, false);
await assert.rejects(fetch(result.url));
});
test('HTML preview refuses credentials, hidden inventories, traversal, external junctions, hardlinks and unsupported file types', async t => {
const f = fixture(t); html(f);
fs.writeFileSync(path.join(f.root, 'outside.html'), '<h1>Outside project</h1>');
fs.symlinkSync(f.root, path.join(f.projectRoot, 'escape'), process.platform === 'win32' ? 'junction' : 'dir');
fs.linkSync(path.join(f.projectRoot, 'pages', '页面.html'), path.join(f.projectRoot, 'aliased.html'));
const manager = new LocalFilePreviews(f.store); f.onCleanup(() => manager.stopAll());
await assert.rejects(manager.start(f.project, 'aliased.html'), /硬链接/);
fs.unlinkSync(path.join(f.projectRoot, 'aliased.html'));
const result = await manager.start(f.project, 'pages/页面.html'), url = new URL(result.url), base = url.origin + url.pathname.split('/').slice(0, 2).join('/') + '/';
for (const relative of ['.env', '.git/config', 'README.md', 'escape/outside.html', '%2e%2e%2fproject/pages/页面.html', '%2eenv.json', 'pages/%00.html']) {
const response = await fetch(base + relative); assert.ok(response.status >= 400, relative);
}
const wrongHostStatus = await new Promise((resolve, reject) => {
http.get(result.url, { headers: { Host: 'evil.example' } }, response => { response.resume(); resolve(response.statusCode); }).on('error', reject);
});
assert.equal(wrongHostStatus, 421);
});
test('runtime shutdown closes local preview ports and pending starts cannot escape shutdown', async t => {
const f = fixture(t); html(f);
const runtime = new Runtime(f.store, new Provider());
const result = await runtime.localFilePreviews().start(f.project, 'pages/页面.html');
await runtime.stopAll(); assert.equal(runtime.filePreviews.active.size, 0);
await assert.rejects(fetch(result.url));
await assert.rejects(runtime.localFilePreviews().start(f.project, 'pages/页面.html'), /已关闭/);
});
test('idle file previews expire and release their loopback servers', async t => {
const f = fixture(t); html(f);
const manager = new LocalFilePreviews(f.store, { ttl: 60 }); f.onCleanup(() => manager.stopAll());
const result = await manager.start(f.project, 'pages/页面.html');
await until(() => !manager.access(result.url).allowed);
await assert.rejects(fetch(result.url));
});
test('directory and preview HTTP controls require workbench authentication; project pages cannot read bootstrap', async t => {
const f = fixture(t); html(f);
const server = await launchWorkbench(t, f.data);
assert.equal((await fetch(server.url + '/api/local-directories')).status, 403);
const before = (await server.api('/bootstrap')).projects.length;
assert.equal((await server.api('/local-directories?path=' + encodeURIComponent(f.projectRoot))).current, f.projectRoot);
assert.equal((await server.api('/bootstrap')).projects.length, before);
const result = await server.api('/projects/' + f.project.id + '/file-previews', { path: 'pages/页面.html' });
assert.notEqual(new URL(result.url).origin, server.url);
assert.equal((await fetch(server.url + '/api/bootstrap', { headers: { Origin: 'null' } })).status, 403);
assert.equal((await server.api('/local-file-preview-access?url=' + encodeURIComponent(result.url))).allowed, true);
await assert.rejects(server.api('/projects/' + f.project.id + '/file-previews', { path: '../escape.html' }));
const response = await fetch(server.url + '/api/projects/' + f.project.id + '/file-previews/' + result.id, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': server.bootstrap.token }, body: '{}' });
assert.equal(response.status, 200); await assert.rejects(fetch(result.url));
});