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