From a243169f8a10fa26fe9e9d1d1623d68445e2a3c7 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Wed, 11 Nov 2026 19:31:24 +0000 Subject: [PATCH] fix: keep private project files out of preview bundles and local sharing (#7563) * fix(core): keep git metadata and env files out of bundled HTML The bundler now checks every file it reads against the project's private paths (git metadata and env files, spelled directly or through a link) and leaves a refused reference as authored instead of inlining it. Bundle options gain a canRead predicate; Studio's preview passes its own private-file rule so the preview document matches what the file routes serve. Co-Authored-By: Claude Opus 5.5 * fix(studio-server): check capture read grants against the decoded path A capture page's read grant now looks at the path the way the static preview route decodes it, including encoded separators, so a URL that resolves to a dotfile or into a dot-folder gets no CORS grant. Ordinary project files keep loading in thumbnails. Co-Authored-By: Claude Opus 5.5 * fix(cli): accept local share requests only from loopback connections The local share routes already require loopback Host and same-origin headers. They now also require the connection itself to come from this machine, so a Studio bound to a network address still keeps sharing local to the person running it. Co-Authored-By: Claude Opus 5.5 * fix(studio-server): ask the bundler for Studio's private-file rule as plain data The preview route passed a fresh `canRead` callback on every build. A host that builds on a worker thread cannot send a function across, so it built on its own thread, and it could no longer share one build between two same-content requests. The bundler now takes `privateFiles: "studio"`, a plain string, and applies Studio's private-file rule itself. That rule (git metadata, env files, and the app's records under `.hyperframes/`) now lives in `@hyperframes/core/safe-path`, and studio-server reuses it. The `canRead` option is removed. Co-Authored-By: Claude Opus 5.5 * fix(studio-server): do not serve a preview main file linked to a private file When index.html (or .html) is a link to an env file or into git metadata, the bundler refuses it and the route falls back to reading the main file from disk. That fallback now skips a candidate that is a private project file, by the same rule the file routes use. A main file linked from outside the project is still served. Co-Authored-By: Claude Opus 5.5 * fix(producer): never inline git or env files as render sub-compositions The render compiler resolved data-composition-src and inlined the file it named, so `data-composition-src=".env"` put the env file's text into the render page. It now refuses git metadata and env files with the same shared rule the bundler uses. The pre-render check names the refused reference and stops the render. Co-Authored-By: Claude Opus 5.5 * chore: raise the inspector unpacked size budget to 3,722,000 bytes The inspector already sat about 36.8 KB over its 3,684,092 budget, just inside the 1% tolerance. Moving Studio's private-file rule into core added a few hundred bytes to the bundles it ships, which pushed it to 3,721,419 bytes and over the tolerance. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- packages/cli/src/server/shareBoundary.ts | 11 +- packages/cli/src/server/shareRoutes.test.ts | 33 ++++-- packages/cli/src/server/shareRoutes.ts | 5 +- .../core/src/compiler/htmlBundler.test.ts | 55 +++++++++ packages/core/src/compiler/htmlBundler.ts | 52 ++++++-- packages/core/src/compiler/index.ts | 1 + packages/core/src/safePath.ts | 55 +++++++++ .../src/services/htmlCompiler.test.ts | 15 +++ .../producer/src/services/htmlCompiler.ts | 16 ++- .../src/helpers/captureLoads.test.ts | 5 + .../studio-server/src/helpers/captureLoads.ts | 13 +- .../studio-server/src/helpers/safePath.ts | 41 +------ .../studio-server/src/routes/preview.test.ts | 111 ++++++++++++++++++ packages/studio-server/src/routes/preview.ts | 7 +- packages/studio-server/src/types.ts | 2 +- scripts/package-size-budgets.json | 2 +- 16 files changed, 356 insertions(+), 68 deletions(-) diff --git a/packages/cli/src/server/shareBoundary.ts b/packages/cli/src/server/shareBoundary.ts index 9765927696..99f36f9490 100644 --- a/packages/cli/src/server/shareBoundary.ts +++ b/packages/cli/src/server/shareBoundary.ts @@ -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 { diff --git a/packages/cli/src/server/shareRoutes.test.ts b/packages/cli/src/server/shareRoutes.test.ts index e8a6916d33..7638f91c9e 100644 --- a/packages/cli/src/server/shareRoutes.test.ts +++ b/packages/cli/src/server/shareRoutes.test.ts @@ -41,13 +41,14 @@ 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") @@ -55,11 +56,15 @@ async function token(app: Hono) { 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([ @@ -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", () => { @@ -85,6 +102,7 @@ describe("local share boundary", () => { "sec-fetch-site": "same-origin", }, }), + "127.0.0.1", ), ).toBe(true); expect( @@ -96,6 +114,7 @@ describe("local share boundary", () => { "sec-fetch-site": "same-origin", }, }), + "::1", ), ).toBe(true); }); diff --git a/packages/cli/src/server/shareRoutes.ts b/packages/cli/src/server/shareRoutes.ts index ede794699e..c5c963459a 100644 --- a/packages/cli/src/server/shareRoutes.ts +++ b/packages/cli/src/server/shareRoutes.ts @@ -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, @@ -93,7 +94,7 @@ export function mountShareRoutes( login: () => Promise = defaultLogin, track: typeof trackShareInteraction = trackShareInteraction, ): void { - const routes = new Hono(); + const routes = new Hono<{ Bindings: Partial }>(); let job: LocalShareJob | null = null; const hasRunningJob = () => job?.state === "running"; let jobOwner: string | null = null; @@ -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" && diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.ts index 00e1570ab1..4fddfaf3e5 100644 --- a/packages/core/src/compiler/htmlBundler.test.ts +++ b/packages/core/src/compiler/htmlBundler.test.ts @@ -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": ` + + +
+ +
+
+
+ + + `, + "style.css": '@import ".env.local"; .a { color: red; }', + "scenes/intro.html": ``, + ".env": `TOKEN=${secret}`, + ".env.local": `TOKEN=${secret}`, + ".env.html": ``, + ".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("

intro

"); + } 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": ` + + +
`, + ".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", diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.ts index 4f6e87b962..867ecbb374 100644 --- a/packages/core/src/compiler/htmlBundler.ts +++ b/packages/core/src/compiler/htmlBundler.ts @@ -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"; @@ -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(); 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 { @@ -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 { @@ -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. * @@ -1038,16 +1065,19 @@ function hoistCompositionScripts( } export function bundleToSingleHtml(projectDir: string, options?: BundleOptions): Promise { - const bundle = () => bundleProject(projectDir, options); const onRead = options?.onRead; - if (!onRead) return bundle(); const noted = new Set(); - const noteOnce = (filePath: string) => { + const noteRead = (filePath: string) => { if (noted.has(filePath)) return; noted.add(filePath); - onRead(filePath); + onRead?.(filePath); }; - return bundleReads.run(noteOnce, bundle); + const scope: BundleReadScope = { + projectDir, + privateFiles: options?.privateFiles ?? "vcs-and-secrets", + noteRead, + }; + return bundleReads.run(scope, () => bundleProject(projectDir, options)); } // A