mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 04:30:00 +08:00
Download responses built the header in five places. Studio's render download and the shared studio host stripped quotes and non-ASCII from the plain parameter, but the diagnostics, integration-guide, asset, brand-kit and project-archive downloads did not, and the two sanitised sites disagreed on the delimiter set: one escaped ! alongside '()* and the other did not. Node rejects CRLF with ERR_INVALID_CHAR, so this was never response splitting, but a bare quote passed straight through into a header value. Add shared/http-header.ts with the reasoning and route every site through it, including the render download, which keeps its portable OpenMotion<extension> plain name through the helper's override. The override is sanitised inside the helper, so passing a plain name explicitly cannot bypass the rule. RFC 5987 attr-char technically allows !, and the shared encoder escapes the whole delimiter set anyway: percent-encoding an allowed character stays valid, and one predictable rule is easier to trust than a per-site choice. Two sites still built their own header when this change first landed: the scenario bundle download ran a second sanitizer over the plain name and the Design Studio project download interpolated the raw name with only quotes removed. Both now use attachmentDisposition, with the scenario caller defaulting its name first, so no download response keeps a private rule that can drift from the shared one. Covered by a unit test for the sanitiser and encoder, including an explicit override and the attr-char rationale, and by the server suite. The scenario bundle, scenario run, design project and archive suites run in CI; locally they need FFmpeg, symlink privileges and the refreshed dependency tree this checkout does not carry. Validation: - node --experimental-strip-types --test tests/server.test.ts - npm run check - node --test tests/ci-scope.test.mjs
71 lines
4.3 KiB
TypeScript
71 lines
4.3 KiB
TypeScript
import { renderFilenameStem } from './shared/render-name.ts';
|
|
import { attachmentDisposition } from './shared/http-header.ts';
|
|
import { request } from 'node:http';
|
|
import { readFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
import { pluginRoot } from './hyperframes.ts';
|
|
import { resolveDesignSystemFile } from './packages/design-system/index.js';
|
|
import { isSpaRoutePath } from './shared/spa-routes.ts';
|
|
|
|
const mime: Record<string, string> = { '.mp4': 'video/mp4', '.m4a': 'audio/mp4', '.jpg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.map': 'application/json', '.ttf': 'font/ttf', '.woff2': 'font/woff2', '.txt': 'text/plain', '.md': 'text/plain; charset=utf-8' };
|
|
|
|
/** Only application bundle and design-system files are exposed, never Studio source or project files. */
|
|
export async function serveEditorFile(url: URL, res: ServerResponse): Promise<boolean> {
|
|
let relative: string;
|
|
const designFile = resolveDesignSystemFile(url.pathname);
|
|
if (isSpaRoutePath(url.pathname)) relative = 'studio/build/index.html';
|
|
else if (designFile) relative = 'packages/design-system/' + designFile;
|
|
else if (url.pathname === '/favicon.svg') relative = 'packages/design-system/brand/favicon.svg';
|
|
else if (/^\/editor-assets\/[a-zA-Z0-9_.-]+$/.test(url.pathname)) relative = 'studio/build' + url.pathname;
|
|
else if (/^\/guide-assets\/viewer\.(js|css)$/.test(url.pathname)) relative = 'studio/build' + url.pathname;
|
|
else if (/^\/web\/catalog\/(?:hyperframes|template-frames|provenance|covers)\.json$/.test(url.pathname) || /^\/web\/catalog\/(?:template-frames|covers)\/[a-f0-9]{24}\.(?:jpg|webp)$/.test(url.pathname)) relative = url.pathname.slice(1);
|
|
else return false;
|
|
const type = mime[path.extname(relative)];
|
|
if (!type) return false;
|
|
try {
|
|
const data = await readFile(path.join(pluginRoot, relative));
|
|
res.writeHead(200, { 'Content-Type': type, 'Content-Length': data.length,
|
|
...(designFile && /\.(?:ttf|woff2?)$/.test(designFile) ? { 'Access-Control-Allow-Origin': '*' } : {}) }); res.end(data);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
res.end(relative.endsWith('index.html') ? '编辑器尚未构建。请运行 npm run build:studio。' : '编辑器资源不存在,请刷新页面。');
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** Suggest a portable name without changing the immutable render's storage path. */
|
|
export function renderDownloadDisposition(title: string | undefined, extension: string): string {
|
|
return attachmentDisposition(renderFilenameStem(title) + extension, `OpenMotion${extension}`);
|
|
}
|
|
|
|
/** Preserve native HTTP semantics (SSE, byte ranges, multipart uploads and optimistic file writes). */
|
|
export function proxyStudio(req: IncomingMessage, res: ServerResponse, url: URL, studioUrl: string, downloadDisposition?: string): Promise<void> {
|
|
const target = new URL(studioUrl);
|
|
target.pathname = url.pathname; target.search = url.search; target.hash = '';
|
|
const headers = { ...req.headers, host: target.host };
|
|
if (headers.origin) headers.origin = target.origin;
|
|
if (headers.referer) headers.referer = target.origin + '/';
|
|
delete headers.connection;
|
|
return new Promise(resolve => {
|
|
const upstream = request(target, { method: req.method, headers }, response => {
|
|
const outgoing = { ...response.headers };
|
|
delete outgoing.connection;
|
|
if (downloadDisposition && response.statusCode === 200) outgoing['content-disposition'] = downloadDisposition;
|
|
res.writeHead(response.statusCode || 502, outgoing);
|
|
response.on('error', () => { res.destroy(); resolve(); });
|
|
response.pipe(res);
|
|
});
|
|
upstream.on('error', () => {
|
|
if (!res.headersSent) { res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: '原生编辑服务连接中断,请刷新重试' })); }
|
|
else res.destroy();
|
|
resolve();
|
|
});
|
|
res.on('close', () => { upstream.destroy(); resolve(); });
|
|
res.on('finish', resolve);
|
|
req.on('error', () => upstream.destroy());
|
|
req.pipe(upstream);
|
|
});
|
|
}
|