fix(producer): tighten resource lifecycle and harden file server

This commit is contained in:
Vance Ingalls
2026-04-23 03:37:08 +00:00
committed by Vance Ingalls
parent 3ddf3984d9
commit d7ead447a2
3 changed files with 1091 additions and 866 deletions
@@ -1,8 +1,12 @@
import { describe, expect, it } from "bun:test";
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import {
HF_BRIDGE_SCRIPT,
HF_EARLY_STUB,
injectScriptsAtHeadStart,
isPathInside,
VIRTUAL_TIME_SHIM,
} from "./fileServer.js";
@@ -40,6 +44,76 @@ describe("injectScriptsIntoHtml", () => {
});
});
describe("isPathInside", () => {
it("returns true when the child equals the parent", () => {
expect(isPathInside("/tmp/project", "/tmp/project")).toBe(true);
});
it("returns true for direct children", () => {
expect(isPathInside("/tmp/project/index.html", "/tmp/project")).toBe(true);
});
it("returns true for deeply nested descendants", () => {
expect(isPathInside("/tmp/project/a/b/c/file.html", "/tmp/project")).toBe(true);
});
it("rejects siblings with a shared name prefix", () => {
// The classic prefix-bug: "/foo" should NOT contain "/foobar/x". A naive
// startsWith check without a trailing separator would incorrectly accept
// this as nested.
expect(isPathInside("/tmp/projectile/a", "/tmp/project")).toBe(false);
expect(isPathInside("/tmp/project-other/a", "/tmp/project")).toBe(false);
});
it("rejects paths outside the parent entirely", () => {
expect(isPathInside("/etc/passwd", "/tmp/project")).toBe(false);
expect(isPathInside("/tmp/other/file.html", "/tmp/project")).toBe(false);
});
it("rejects path-traversal attempts that escape the parent", () => {
// path.join("/tmp/project", "../etc/passwd") normalizes to "/tmp/etc/passwd"
// — outside the project root. The whole point of isPathInside is to catch
// exactly this after the join.
expect(isPathInside("/tmp/etc/passwd", "/tmp/project")).toBe(false);
expect(isPathInside("/tmp/project/../etc/passwd", "/tmp/project")).toBe(false);
});
it("accepts traversal that resolves back inside the parent", () => {
expect(isPathInside("/tmp/project/sub/../index.html", "/tmp/project")).toBe(true);
});
it("treats parents with and without trailing slashes the same", () => {
expect(isPathInside("/tmp/project/index.html", "/tmp/project/")).toBe(true);
expect(isPathInside("/tmp/project/index.html", "/tmp/project")).toBe(true);
});
it("resolves relative paths against the current working directory", () => {
// Both sides resolve against cwd, so a relative file under a relative dir
// should be considered nested. We don't assert the absolute path; we just
// check the containment relationship holds after resolution.
expect(isPathInside("a/b/c.html", "a/b")).toBe(true);
expect(isPathInside("a/b/../../c.html", "a/b")).toBe(false);
});
it("rejects symlink escapes when realpath enforcement is enabled", () => {
const rootDir = mkdtempSync(join(tmpdir(), "hf-file-server-root-"));
const outsideDir = mkdtempSync(join(tmpdir(), "hf-file-server-outside-"));
const outsideFile = join(outsideDir, "secret.txt");
const symlinkPath = join(rootDir, "escaped.txt");
try {
writeFileSync(outsideFile, "secret");
symlinkSync(outsideFile, symlinkPath);
expect(isPathInside(symlinkPath, rootDir)).toBe(true);
expect(isPathInside(symlinkPath, rootDir, { resolveSymlinks: true })).toBe(false);
} finally {
rmSync(rootDir, { recursive: true, force: true });
rmSync(outsideDir, { recursive: true, force: true });
}
});
});
describe("HF_EARLY_STUB + HF_BRIDGE_SCRIPT integration", () => {
/**
* Simulates the real injection order in a Puppeteer page:
+68 -8
View File
@@ -10,10 +10,47 @@
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import type { IncomingMessage } from "node:http";
import { readFileSync, existsSync, statSync } from "node:fs";
import { join, extname } from "node:path";
import { readFileSync, existsSync, realpathSync, statSync } from "node:fs";
import { join, extname, resolve, sep } from "node:path";
import { getVerifiedHyperframeRuntimeSource } from "./hyperframeRuntimeLoader.js";
type IsPathInsideOptions = {
resolveSymlinks?: boolean;
};
/**
* Returns true iff `child` is the same as, or nested inside, `parent` after
* symlink-free path normalization. Used to reject path-traversal attempts
* (e.g. GET `/../etc/passwd`) before opening any file.
*
* `path.join(root, "..")` normalizes traversal segments and can escape `root`
* entirely, so the join return value alone is not a safe guard. Callers must
* resolve both sides and compare prefixes with the platform separator
* appended to `parent` to avoid `/foo` matching `/foobar`.
*
* Exported for unit tests; not part of the public package surface.
*/
export function isPathInside(
child: string,
parent: string,
options: IsPathInsideOptions = {},
): boolean {
const { resolveSymlinks = false } = options;
const resolvedChild = resolve(child);
const resolvedParent = resolve(parent);
const normalizedChild =
resolveSymlinks && existsSync(resolvedChild)
? realpathSync.native(resolvedChild)
: resolvedChild;
const normalizedParent =
resolveSymlinks && existsSync(resolvedParent)
? realpathSync.native(resolvedParent)
: resolvedParent;
if (normalizedChild === normalizedParent) return true;
const parentWithSep = normalizedParent.endsWith(sep) ? normalizedParent : normalizedParent + sep;
return normalizedChild.startsWith(parentWithSep);
}
const MIME_TYPES: Record<string, string> = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
@@ -479,13 +516,36 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
// Remove leading slash
const relativePath = requestPath.replace(/^\//, "");
const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;
const hasCompiledFile = Boolean(
compiledPath && existsSync(compiledPath) && statSync(compiledPath).isFile(),
);
const filePath = hasCompiledFile ? (compiledPath as string) : join(projectDir, relativePath);
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
// Resolve against compiledDir first (preferred — overrides project files
// for compositions emitted by the build), then projectDir as fallback.
// Each candidate is rejected if `..` segments push it outside the
// intended root: `path.join` normalizes traversal but does not enforce
// containment, so a request like `GET /../etc/passwd` would otherwise
// be served straight off the filesystem.
let filePath: string | null = null;
if (compiledDir) {
const candidate = join(compiledDir, relativePath);
if (
existsSync(candidate) &&
isPathInside(candidate, compiledDir, { resolveSymlinks: true }) &&
statSync(candidate).isFile()
) {
filePath = candidate;
}
}
if (!filePath) {
const candidate = join(projectDir, relativePath);
if (
existsSync(candidate) &&
isPathInside(candidate, projectDir, { resolveSymlinks: true }) &&
statSync(candidate).isFile()
) {
filePath = candidate;
}
}
if (!filePath) {
if (!/favicon\.ico$/i.test(requestPath)) {
console.warn(`[FileServer] 404 Not Found: ${requestPath}`);
}
File diff suppressed because it is too large Load Diff