Skip to content
11 changes: 10 additions & 1 deletion packages/cli/src/server/shareBoundary.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { randomBytes, timingSafeEqual } from "node:crypto";

export function localShareRequestAllowed(request: Request): boolean {
const isLoopbackSocketPeer = (address: string | undefined): boolean => {
const ip = address?.replace(/^::ffff:/i, "") ?? "";
return ip === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip);
};

export function localShareRequestAllowed(
request: Request,
socketPeer: string | undefined,
): boolean {
if (!isLoopbackSocketPeer(socketPeer)) return false;
const host = request.headers.get("host");
if (!host || request.headers.get("sec-fetch-site") !== "same-origin") return false;
try {
Expand Down
33 changes: 26 additions & 7 deletions packages/cli/src/server/shareRoutes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,30 @@ function fixture() {
mountShareRoutes(app, "/fixed/project", create, login, track);
return { app, service, create, login, track };
}
const LOCAL_PEER = { incoming: { socket: { remoteAddress: "127.0.0.1" } } };
const headers = {
host: "localhost:3000",
origin: "http://localhost:3000",
"sec-fetch-site": "same-origin",
};
async function token(app: Hono) {
const response = await app.request("/api/share/bootstrap", { headers });
const response = await app.request("/api/share/bootstrap", { headers }, LOCAL_PEER);
expect(response.status).toBe(200);
const body: unknown = await response.json();
if (!body || typeof body !== "object" || !("csrf" in body) || typeof body.csrf !== "string")
throw new Error("missing token");
return body.csrf;
}
function request(app: Hono, path: string, csrf: string, body?: unknown) {
return app.request(`/api/share/${path}`, {
method: body ? "POST" : "GET",
headers: { ...headers, "x-hyperframes-share-csrf": csrf, "content-type": "application/json" },
...(body ? { body: JSON.stringify(body) } : {}),
});
return app.request(
`/api/share/${path}`,
{
method: body ? "POST" : "GET",
headers: { ...headers, "x-hyperframes-share-csrf": csrf, "content-type": "application/json" },
...(body ? { body: JSON.stringify(body) } : {}),
},
LOCAL_PEER,
);
}
describe("local share boundary", () => {
it.each([
Expand All @@ -72,7 +77,19 @@ describe("local share boundary", () => {
{ ...headers, host: "localhost:3000@evil.example" },
])("denies foreign, LAN and missing-origin requests before authentication %j", async (input) => {
const { app, create } = fixture();
expect((await app.request("/api/share/bootstrap", { headers: input })).status).toBe(403);
expect((await app.request("/api/share/bootstrap", { headers: input }, LOCAL_PEER)).status).toBe(
403,
);
expect(create).not.toHaveBeenCalled();
});
it.each([
["a LAN peer", { incoming: { socket: { remoteAddress: "192.168.1.20" } } }],
["a mapped LAN peer", { incoming: { socket: { remoteAddress: "::ffff:10.0.0.5" } } }],
["an unknown peer", {}],
["no server bindings", undefined],
])("denies %s even with local headers", async (_, peer) => {
const { app, create } = fixture();
expect((await app.request("/api/share/bootstrap", { headers }, peer)).status).toBe(403);
expect(create).not.toHaveBeenCalled();
});
it("allows same-origin browser GET Referer and IPv6 loopback", () => {
Expand All @@ -85,6 +102,7 @@ describe("local share boundary", () => {
"sec-fetch-site": "same-origin",
},
}),
"127.0.0.1",
),
).toBe(true);
expect(
Expand All @@ -96,6 +114,7 @@ describe("local share boundary", () => {
"sec-fetch-site": "same-origin",
},
}),
"::1",
),
).toBe(true);
});
Expand Down
5 changes: 3 additions & 2 deletions packages/cli/src/server/shareRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { Hono } from "hono";
import type { HttpBindings } from "@hono/node-server";
import { bodyLimit } from "hono/body-limit";
import type {
LocalShareAction,
Expand Down Expand Up @@ -93,7 +94,7 @@ export function mountShareRoutes(
login: () => Promise<void> = defaultLogin,
track: typeof trackShareInteraction = trackShareInteraction,
): void {
const routes = new Hono();
const routes = new Hono<{ Bindings: Partial<HttpBindings> }>();
let job: LocalShareJob | null = null;
const hasRunningJob = () => job?.state === "running";
let jobOwner: string | null = null;
Expand All @@ -112,7 +113,7 @@ export function mountShareRoutes(
};
routes.use("*", async (c, next) => {
c.header("Cache-Control", "no-store");
if (!localShareRequestAllowed(c.req.raw))
if (!localShareRequestAllowed(c.req.raw, c.env?.incoming?.socket.remoteAddress))
return c.json({ code: "forbidden", message: "Open sharing from this local Studio." }, 403);
if (
c.req.path !== "/api/share/bootstrap" &&
Expand Down
55 changes: 55 additions & 0 deletions packages/core/src/compiler/htmlBundler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,61 @@ describe("bundleToSingleHtml", () => {
expect(reads).not.toContain(join(dir, "notes.md"));
});

it("never inlines git metadata or env files, spelled directly or through a link", async () => {
const secret = "SECRET_TOKEN_VALUE";
const dir = makeTempProject({
"index.html": `<!doctype html><html><head>
<link rel="stylesheet" href=".env"><link rel="stylesheet" href="style.css">
</head><body>
<div data-composition-id="root" data-width="320" data-height="180" data-start="0" data-duration="2">
<img src=".git/config">
<div data-composition-id="intro" data-composition-src="scenes/intro.html" data-start="0" data-duration="1"></div>
<div data-composition-id="env" data-composition-src=".env.html" data-start="0" data-duration="1"></div>
</div>
<script src=".git/config"></script>
<script src="linked.js"></script>
</body></html>`,
"style.css": '@import ".env.local"; .a { color: red; }',
"scenes/intro.html": `<template><div data-composition-id="intro" data-width="320" data-height="180">
<p>intro</p><script src="../.env"></script></div></template>`,
".env": `TOKEN=${secret}`,
".env.local": `TOKEN=${secret}`,
".env.html": `<template><div data-composition-id="env">${secret}</div></template>`,
".git/config": `[remote "origin"] url = https://${secret}@example.com/repo.git`,
});
symlinkSync(join(dir, ".env"), join(dir, "linked.js"));
try {
const bundled = await bundleToSingleHtml(dir, { inlineAssets: true });
expect(bundled).not.toContain(secret);
expect(bundled).not.toContain(Buffer.from(`TOKEN=${secret}`).toString("base64"));
expect(bundled).toContain(".a { color: red; }");
expect(bundled).toContain("<p>intro</p>");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it("refuses the app's records only under the studio private-file policy", async () => {
const dir = makeTempProject({
"index.html": `<!doctype html><html><head>
<link rel="stylesheet" href=".hyperframes/handoff.css">
<link rel="stylesheet" href=".hyperframes/prepared-assets/fonts.css">
</head><body><div data-composition-id="root" data-width="320" data-height="180"></div></body></html>`,
".hyperframes/handoff.css": ".app-record { color: red; }",
".hyperframes/prepared-assets/fonts.css": ".prepared { color: blue; }",
});
try {
const studio = await bundleToSingleHtml(dir, { privateFiles: "studio" });
expect(studio).not.toContain(".app-record");
expect(studio).toContain('href=".hyperframes/handoff.css"');
expect(studio).toContain(".prepared { color: blue; }");
const plain = await bundleToSingleHtml(dir);
expect(plain).toContain(".app-record { color: red; }");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it.each([
[
"UTF-16LE",
Expand Down
52 changes: 41 additions & 11 deletions packages/core/src/compiler/htmlBundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ import {
isLibraryCopy,
refuseSwapsReachedByRootScripts,
} from "./inlineSubCompositions";
import { isSafePath, resolveWithinProject } from "../safePath.js";
import {
isPrivateFileUnder,
isSafePath,
isStudioPrivatePath,
isVcsOrSecretPath,
resolveWithinProject,
} from "../safePath.js";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { readTextFile } from "@hyperframes/parsers/asset-resolution";
import { HF_COLOR_GRADING_ATTR } from "../colorGrading";
Expand Down Expand Up @@ -111,15 +117,28 @@ function isRelativeUrl(url: string): boolean {
return !isNonRelativeUrl(url) && !isAbsolute(url);
}

const bundleReads = new AsyncLocalStorage<(filePath: string) => void>();
interface BundleReadScope {
projectDir: string;
privateFiles: BundlePrivateFiles;
noteRead: (filePath: string) => void;
}

const bundleReads = new AsyncLocalStorage<BundleReadScope>();

function noteRead(filePath: string): void {
bundleReads.getStore()?.(filePath);
bundleReads.getStore()?.noteRead(filePath);
}

function readAllowed(filePath: string): boolean {
const scope = bundleReads.getStore();
if (!scope) return true;
const isPrivate = scope.privateFiles === "studio" ? isStudioPrivatePath : isVcsOrSecretPath;
return !isPrivateFileUnder(scope.projectDir, filePath, isPrivate);
}

function safeReadFile(filePath: string): string | null {
noteRead(filePath);
if (!existsSync(filePath)) return null;
if (!readAllowed(filePath) || !existsSync(filePath)) return null;
try {
return readTextFile(filePath);
} catch {
Expand Down Expand Up @@ -290,7 +309,7 @@ function inlineCssFile(

function safeReadFileBuffer(filePath: string): Buffer | null {
noteRead(filePath);
if (!existsSync(filePath)) return null;
if (!readAllowed(filePath) || !existsSync(filePath)) return null;
try {
return readFileSync(filePath);
} catch {
Expand Down Expand Up @@ -912,8 +931,16 @@ export interface BundleOptions {
staticGuard?: boolean;
/** Called once per build for each project file the build reads or looks for. */
onRead?: (filePath: string) => void;
/**
* Project files the build never reads; a refused file keeps its authored reference. Git metadata and env files
* always; `"studio"` also refuses the app's records under `.hyperframes/`, as Studio's file routes do.
*/
privateFiles?: BundlePrivateFiles;
}

/** Plain data, so the option crosses to a build thread and keys a shared build. */
export type BundlePrivateFiles = "vcs-and-secrets" | "studio";

/**
* Bundle a project's index.html into a single self-contained HTML file.
*
Expand Down Expand Up @@ -1038,16 +1065,19 @@ function hoistCompositionScripts(
}

export function bundleToSingleHtml(projectDir: string, options?: BundleOptions): Promise<string> {
const bundle = () => bundleProject(projectDir, options);
const onRead = options?.onRead;
if (!onRead) return bundle();
const noted = new Set<string>();
const noteOnce = (filePath: string) => {
const noteRead = (filePath: string) => {
if (noted.has(filePath)) return;
noted.add(filePath);
onRead(filePath);
onRead?.(filePath);
};
const scope: BundleReadScope = {
projectDir,
privateFiles: options?.privateFiles ?? "vcs-and-secrets",
noteRead,
};
return bundleReads.run(noteOnce, bundle);
return bundleReads.run(scope, () => bundleProject(projectDir, options));
}

// A <template> scene has no root or GSAP of its own: bundle it inside the index that mounts it, as render does.
Expand All @@ -1066,7 +1096,7 @@ function readMountedSceneShell(
async function bundleProject(projectDir: string, options?: BundleOptions): Promise<string> {
const entryFile = options?.entryFile ?? "index.html";
const indexPath = resolveWithinProject(projectDir, entryFile);
if (!indexPath || !existsSync(indexPath)) {
if (!indexPath || !readAllowed(indexPath) || !existsSync(indexPath)) {
throw new Error(`${entryFile} not found in project directory`);
}
noteRead(indexPath);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export {
type BundledHostCompositionIdentity,
bundleToSingleHtml,
type BundleOptions,
type BundlePrivateFiles,
type BundleScriptProvenance,
prepareFlattenedInnerRoot,
FLATTENED_INNER_ROOT_STRIP_ATTRS,
Expand Down
55 changes: 55 additions & 0 deletions packages/core/src/safePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,61 @@ export function resolveWithinProject(base: string, relativePath: string): string
return isSafePath(base, resolved) ? resolved : null;
}

/** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
export function projectPathSegments(relPath: string): string[] {
return relPath
.toLowerCase()
.split(/[\\/]/)
.map((segment) => withoutTrailingDotsOrSpaces(segment.split(":", 1)[0] ?? ""));
}

function withoutTrailingDotsOrSpaces(segment: string): string {
let end = segment.length;
while (end > 0 && (segment[end - 1] === "." || segment[end - 1] === " ")) end--;
return segment.slice(0, end);
}

// Git metadata and env files hold commands other tools run and secrets: nothing serves or inlines them.
export function isVcsOrSecretPath(relPath: string): boolean {
return projectPathSegments(relPath).some(
(segment) => segment === ".git" || segment.startsWith(".env"),
);
}

// `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): Studio
// reaches none of it, the folder itself included, but its own files and the app's request pictures.
const STUDIO_FILES = new Set([
".hyperframes/studio-motion.json",
".hyperframes/studio-manual-edits.json",
]);
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];

/** Studio's private files, for a project-relative path with `/` separators: git, env, and the app's records. */
export function isStudioPrivatePath(relPath: string): boolean {
const path = relPath.toLowerCase();
if (isVcsOrSecretPath(path)) return true;
return (
(path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
!STUDIO_FILES.has(path) &&
!STUDIO_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`))
);
}

/** Whether `isPrivate` holds for a file under `projectDir`, spelled as given or with its links resolved. */
export function isPrivateFileUnder(
projectDir: string,
filePath: string,
isPrivate: (relPath: string) => boolean,
): boolean {
const rel = (from: string, to: string) => relative(from, to).split(sep).join("/");
if (isPrivate(rel(resolve(projectDir), resolve(filePath)))) return true;
try {
return isPrivate(rel(realpath(resolve(projectDir)), realpath(filePath)));
} catch {
return false;
}
}

/** The project folder is gone, renamed or deleted while open; a write must not bring it back. */
export class ProjectRootMissingError extends Error {
constructor(readonly root: string) {
Expand Down
15 changes: 15 additions & 0 deletions packages/producer/src/services/htmlCompiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,21 @@ describe("detectRenderModeHints", () => {
}
});

it("compileForRender refuses to inline an env file named as a data-composition-src", async () => {
const projectDir = makeSubCompProject(
"hf-env-subcomp-",
[{ id: "intro", src: "compositions/.env.html" }],
{ ".env.html": validSubCompHtml("intro", "ENV_SECRET_VALUE") },
);
try {
await expect(
compileForRender(projectDir, join(projectDir, "index.html"), projectDir),
).rejects.toThrow(/compositions\/\.env\.html[\s\S]*git metadata or an env file/);
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});

it("compileForRender aborts when a data-composition-src reference points at a missing file", async () => {
const projectDir = makeSubCompProject(
"hf-missing-subcomp-",
Expand Down
Loading
Loading