fix: add web project folder picker and isolated HTML file previews

This commit is contained in:
Agent Workbench Dev
2026-11-02 08:54:31 +08:00
parent bfd2f213a5
commit 70ac4c40b5
28 changed files with 515 additions and 20 deletions
+7
View File
@@ -40,6 +40,13 @@ export class DesktopBridge {
const error = await this.shell.openPath(project.root); if (error) throw desktopError('系统无法打开所属项目目录。');
return { opened: true, projectId: project.id, root: project.root };
}
if (action === 'openFilePreview') {
const access = await this.controller.api('/local-file-preview-access?url=' + encodeURIComponent(value.url));
if (!access.allowed || access.projectId !== value.projectId) throw desktopError('此预览已关闭或不属于当前项目。');
assertDesktopFrame(event, this.getWindow(), this.controller.url);
await this.shell.openExternal(value.url);
return { opened: true };
}
if (action === 'reviewTask') {
const session = await this.task(value); await this.project(value.projectId);
return { projectId: session.projectId, sessionId: session.id, taskId: value.taskId, eventSeq: session.eventSeq };
+89
View File
@@ -0,0 +1,89 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomBytes, randomUUID } from 'node:crypto';
import { safePath, readText, excludedFromInventory } from '../../server/files.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
const types = new Map(Object.entries({ '.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
'.avif': 'image/avif', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.mp4': 'video/mp4', '.webm': 'video/webm', '.wasm': 'application/wasm' }));
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
export function localPreviewAddress(value) {
try {
const url = new URL(value);
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && !!url.port && !url.username && !url.password
&& /^\/[a-f0-9]{48}\//.test(url.pathname);
} catch { return false; }
}
export class LocalFilePreviews {
constructor(store, { ttl = 30 * 60 * 1000 } = {}) {
this.store = store; this.ttl = ttl; this.active = new Map(); this.pending = 0; this.disposed = false;
this.sweep = setInterval(() => { for (const entry of this.active.values()) if (Date.now() - entry.lastRead > this.ttl) void this.close(entry.projectId, entry.id); }, Math.min(ttl, 60000));
this.sweep.unref();
}
access(value) {
if (!localPreviewAddress(value)) return { allowed: false };
const url = new URL(value);
const entry = [...this.active.values()].find(item => url.origin === item.origin && url.pathname.startsWith(item.prefix));
return entry ? { allowed: true, projectId: entry.projectId } : { allowed: false };
}
async start(project, relative) {
if (this.disposed) throw fail('文件预览已关闭,请重新打开文件。', 409);
if (this.active.size + this.pending >= 8) throw fail('已打开较多文件预览,请先关闭一个预览再试。', 409);
this.pending++;
try {
await verifyWorkspaceProject(this.store, project);
if (typeof relative !== 'string' || !/\.html?$/i.test(relative)) throw fail('请选择 HTML 文件进行预览。');
if (excludedFromInventory(relative)) throw fail('此目录不用于文件预览。', 403);
readText(project, relative); // Same verified project/file boundary as the source view.
const entry = { id: randomUUID(), projectId: project.id, prefix: '/' + randomBytes(24).toString('hex') + '/', lastRead: Date.now() };
entry.server = http.createServer(async (request, response) => {
response.setHeader('Cache-Control', 'no-store');
response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('Access-Control-Allow-Origin', 'null'); // Sandboxed module scripts, without credentials.
// Applies to both the embedded frame and a separately opened preview.
response.setHeader('Content-Security-Policy', "sandbox allow-scripts; default-src 'self' data: blob:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'");
try {
if (request.headers.host !== '127.0.0.1:' + entry.server.address()?.port) throw fail('文件预览仅接受原本机地址。', 421);
if (!['GET', 'HEAD'].includes(request.method)) throw fail('文件预览只支持读取。', 405);
// Parse the raw path before URL normalization so encoded traversal
// cannot silently turn into a different project file.
const raw = request.url.split('?')[0];
if (!raw.startsWith(entry.prefix)) throw fail('预览地址已失效,请重新打开文件预览。', 404);
let resource;
try { resource = decodeURIComponent(raw.slice(entry.prefix.length)); } catch { throw fail('资源路径无效。'); }
if (excludedFromInventory(resource)) throw fail('此资源不在预览范围内。', 403);
const mediaType = types.get(path.extname(resource).toLowerCase());
if (!mediaType) throw fail('此文件类型不用于网页预览。', 403);
await verifyWorkspaceProject(this.store, project);
const file = safePath(project, resource), stat = fs.statSync(file);
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) throw fail('资源不存在或超过 20 MB 预览上限。', 413);
const bytes = fs.readFileSync(file);
entry.lastRead = Date.now();
response.writeHead(200, { 'Content-Type': mediaType, 'Content-Length': bytes.length });
response.end(request.method === 'HEAD' ? undefined : bytes);
} catch (error) { response.writeHead(error.status || 403, { 'Content-Type': 'text/plain; charset=utf-8' }); response.end('无法预览:' + error.message); }
});
entry.server.requestTimeout = 15000;
await new Promise((resolve, reject) => { entry.server.once('error', reject); entry.server.listen(0, '127.0.0.1', resolve); });
if (this.disposed) { entry.server.close(); throw fail('文件预览已关闭。', 409); }
entry.origin = 'http://127.0.0.1:' + entry.server.address().port;
this.active.set(entry.id, entry);
return { id: entry.id, projectId: project.id, path: relative, url: entry.origin + entry.prefix + relative.replaceAll('\\', '/').split('/').map(encodeURIComponent).join('/') };
} finally { this.pending--; }
}
async close(projectId, id) {
const entry = this.active.get(id);
if (!entry) return { closed: true };
if (entry.projectId !== projectId) throw fail('预览不属于当前项目。', 403);
this.active.delete(id);
await new Promise(resolve => { entry.server.close(resolve); entry.server.closeAllConnections(); });
return { closed: true };
}
async stopAll() { this.disposed = true; clearInterval(this.sweep); await Promise.all([...this.active.values()].map(entry => this.close(entry.projectId, entry.id))); }
}