mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-17 15:24:19 +00:00
* fix(server): contain static file requests within their served roots
Static asset handlers joined the raw request path onto their root
directory without checking where it landed. Hono decodes percent
escapes while routing, so an encoded backslash (%5c) arrives as a real
separator on Windows and dot segments arrive already collapsed —
"/assets/..%5c..%5csecret" and "/%2e%2e%2fsecret" could read files
above the studio bundle root (embedded Studio server) and above
compiledDir/projectDir (engine render file server). Browsers never
request those shapes, but anything that can reach the bound port can:
raw local clients, LAN peers when the preview binds 0.0.0.0, and a
shared-machine process hitting the render server.
Both handlers now resolve the request path first and refuse anything
that collapses outside its root, using the same lexical containment
the preview asset route already applies — bundle/project assets behind
symlinked directories keep being served, only dot-segment escapes are
rejected. Route-level pathSafety tests pin the behavior in both
packages, including the Windows backslash shape and the
symlinked-asset cases from the descriptor-pinning regressions.
Validated: new containment suites fail on the prior handlers (200 +
marker file content served from outside the root) and pass with the
guards; cli server (140), engine services (1024+, matching the main
baseline incl. pre-existing browserManager failures), typecheck,
oxlint, oxfmt and the full workspace build all clean.
* fix: close fallow audit findings, prove containment cross-platform
Fallow audit (health/complexity): createFileServer's request handler
exceeded the CRAP-score threshold once the new containment checks were
added. Extracted resolveContainedPaths, a small pure function that
resolves and validates both roots, cutting the handler's own branching
back down.
Fallow audit (duplication): the new pathSafety test files copied their
temp-root/studioDir setup and teardown from the existing staticAssets
test wholesale. Extracted the shared parts into
studioServerTestFixture.ts (makeStudioServerRoot, writeStudioIndexHtml,
cleanupStudioServerRoot); only the per-file vi.mock("node:path", ...)
call stays duplicated, since Vitest requires it declared statically in
each test file and it cannot be moved behind a shared function -- that
one block keeps a narrow, targeted ignore comment instead of a
file-wide one.
Security claim: isWithinProjectRoot's %5c-decoded-backslash escape is
real, but only on Windows -- POSIX never treats a literal backslash as
a separator, and Hono leaves %2f undecoded in c.req.path, so none of
the new tests' encoded-traversal payloads produce an actual escape on
Linux (verified empirically: they pass identically with the fix
reverted). isWithinProjectRoot now takes an optional path-module
override (defaulting to the host's native node:path, so every existing
caller is unchanged) so its win32 and posix branches can be unit
tested directly from one OS, the same pattern already used by
producer/fileServer.ts's isPathInside. New tests cover a backslash
traversal, a mixed backslash/forward-slash traversal, and a
drive-letter path escaping the root under path.win32, plus the
existing posix case -- confirmed each one fails when the check is
removed. The HTTP-level tests stay as-is: real regression coverage for
them comes from the windows-latest CI job, which runs both new
pathSafety suites unfiltered.
---------
Co-authored-by: Miguel Ángel <miguel.sierra@heygen.com>
Co-authored-by: orphan4183 <kingenmaww@gmail.com>
160 lines
5.3 KiB
TypeScript
160 lines
5.3 KiB
TypeScript
/**
|
|
* File Server
|
|
*
|
|
* Lightweight HTTP server that serves a project directory to headless Chrome.
|
|
* Optionally injects scripts into index.html on-the-fly (e.g. runtime, bridge).
|
|
* Framework-agnostic — the caller decides what scripts to inject.
|
|
*/
|
|
|
|
import { Hono } from "hono";
|
|
import { serve } from "@hono/node-server";
|
|
import { readFileSync, openSync, fstatSync, closeSync, statSync, constants } from "node:fs";
|
|
import { join, extname } from "node:path";
|
|
import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";
|
|
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
|
|
|
|
const MIME_TYPES: Record<string, string> = {
|
|
".html": "text/html; charset=utf-8",
|
|
".css": "text/css; charset=utf-8",
|
|
".js": "application/javascript; charset=utf-8",
|
|
".mjs": "application/javascript; charset=utf-8",
|
|
".json": "application/json; charset=utf-8",
|
|
".png": "image/png",
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".gif": "image/gif",
|
|
".svg": "image/svg+xml",
|
|
".webp": "image/webp",
|
|
".avif": "image/avif",
|
|
".ico": "image/vnd.microsoft.icon",
|
|
".mp4": "video/mp4",
|
|
".mov": "video/quicktime",
|
|
".webm": "video/webm",
|
|
".mp3": "audio/mpeg",
|
|
".wav": "audio/wav",
|
|
".ogg": "audio/ogg",
|
|
".aac": "audio/aac",
|
|
".flac": "audio/flac",
|
|
".m4a": "audio/mp4",
|
|
".woff": "font/woff",
|
|
".woff2": "font/woff2",
|
|
".ttf": "font/ttf",
|
|
".otf": "font/otf",
|
|
};
|
|
|
|
export interface FileServerOptions {
|
|
projectDir: string;
|
|
compiledDir?: string;
|
|
port?: number;
|
|
/** Scripts injected into <head> of index.html. Default: none. */
|
|
headScripts?: string[];
|
|
/** Scripts injected before </body> of index.html. Default: none. */
|
|
bodyScripts?: string[];
|
|
/** Strip embedded runtime scripts from HTML before injection. Default: true. */
|
|
stripEmbeddedRuntime?: boolean;
|
|
}
|
|
|
|
export interface FileServerHandle {
|
|
url: string;
|
|
port: number;
|
|
close: () => void;
|
|
}
|
|
|
|
function readRegularFile(filePath: string): Buffer<ArrayBuffer> | null {
|
|
let fd: number;
|
|
try {
|
|
// Do not block on a named pipe before fstat can reject non-regular files.
|
|
fd = openSync(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
} catch (error) {
|
|
if (
|
|
error instanceof Error &&
|
|
"code" in error &&
|
|
(error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
)
|
|
return null;
|
|
// Platforms report different open errors for directories and sockets.
|
|
// This check only classifies a failed open; no read follows it.
|
|
if (!statSync(filePath, { throwIfNoEntry: false })?.isFile()) return null;
|
|
throw error;
|
|
}
|
|
try {
|
|
if (!fstatSync(fd).isFile()) return null;
|
|
return readFileSync(fd);
|
|
} finally {
|
|
closeSync(fd);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolves the request path against both roots and rejects the pair the
|
|
* moment either escapes -- lexically, so a symlinked asset directory still
|
|
* resolves (see the containment note at the call site).
|
|
*/
|
|
function resolveContainedPaths(
|
|
projectDir: string,
|
|
compiledDir: string | undefined,
|
|
relativePath: string,
|
|
): { projectPath: string; compiledPath: string | null } | null {
|
|
const projectPath = join(projectDir, relativePath);
|
|
if (!isWithinProjectRoot(projectDir, projectPath)) return null;
|
|
if (!compiledDir) return { projectPath, compiledPath: null };
|
|
const compiledPath = join(compiledDir, relativePath);
|
|
if (!isWithinProjectRoot(compiledDir, compiledPath)) return null;
|
|
return { projectPath, compiledPath };
|
|
}
|
|
|
|
export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
|
|
const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;
|
|
|
|
const headScripts = options.headScripts ?? [];
|
|
const bodyScripts = options.bodyScripts ?? [];
|
|
|
|
const app = new Hono();
|
|
|
|
app.get("/*", (c) => {
|
|
let requestPath = c.req.path;
|
|
if (requestPath === "/") requestPath = "/index.html";
|
|
|
|
// Remove leading slash
|
|
const relativePath = requestPath.replace(/^\//, "");
|
|
// Percent escapes can decode into separators and dot segments before the
|
|
// join, so a hostile request can name files above either root -- see
|
|
// resolveContainedPaths for why the check stays lexical, not realpath.
|
|
const resolved = resolveContainedPaths(projectDir, compiledDir, relativePath);
|
|
if (!resolved) return c.text("Not found", 404);
|
|
const content =
|
|
(resolved.compiledPath ? readRegularFile(resolved.compiledPath) : null) ??
|
|
readRegularFile(resolved.projectPath);
|
|
if (content === null) return c.text("Not found", 404);
|
|
|
|
const ext = extname(relativePath).toLowerCase();
|
|
const contentType = MIME_TYPES[ext] || "application/octet-stream";
|
|
|
|
if (ext === ".html") {
|
|
const rawHtml = content.toString("utf-8");
|
|
const html =
|
|
relativePath === "index.html"
|
|
? injectScriptsIntoHtml(rawHtml, headScripts, bodyScripts, stripEmbeddedRuntime)
|
|
: rawHtml;
|
|
return c.text(html, 200, { "Content-Type": contentType });
|
|
}
|
|
|
|
return new Response(content, {
|
|
status: 200,
|
|
headers: { "Content-Type": contentType },
|
|
});
|
|
});
|
|
|
|
return new Promise((resolve) => {
|
|
const server = serve({ fetch: app.fetch, port }, (info) => {
|
|
const actualPort = info.port;
|
|
const url = `http://localhost:${actualPort}`;
|
|
resolve({
|
|
url,
|
|
port: actualPort,
|
|
close: () => server.close(),
|
|
});
|
|
});
|
|
});
|
|
}
|