diff --git a/packages/studio/vite.config.files.test.ts b/packages/studio/vite.config.files.test.ts new file mode 100644 index 0000000000..8a1b51dc02 --- /dev/null +++ b/packages/studio/vite.config.files.test.ts @@ -0,0 +1,83 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { createServer, type ViteDevServer } from "vite"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const fsUrl = (path: string) => `/@fs/${path.replace(/\\/g, "/").replace(/^\/+/, "")}`; + +const SECRET = "registry-token-for-test"; +const project = realpathSync(mkdtempSync(join(tmpdir(), "hf-linked-project-"))); +const link = resolve(__dirname, "data", "projects", `linked-${process.pid}`); +const studioDotfile = resolve(__dirname, `.hf-dev-secret-${process.pid}`); +let server: ViteDevServer; +let origin = ""; + +beforeAll(async () => { + writeFileSync(join(project, ".npmrc"), SECRET); + writeFileSync(studioDotfile, SECRET); + mkdirSync(dirname(link), { recursive: true }); + symlinkSync(project, link); + server = await createServer({ + configFile: resolve(__dirname, "vite.config.ts"), + logLevel: "silent", + server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false }, + // Dependency discovery would hold the first module request on a cold server; file serving does not need it. + optimizeDeps: { noDiscovery: true, include: [] }, + }); + await server.listen(); + const address = server.httpServer?.address(); + if (!address || typeof address === "string") throw new Error("dev server has no port"); + origin = `http://127.0.0.1:${address.port}`; + await server.warmupRequest("/src/main.tsx"); +}, 60_000); + +afterAll(async () => { + rmSync(link, { force: true }); + rmSync(studioDotfile, { force: true }); + rmSync(project, { recursive: true, force: true }); + await server?.close(); +}, 30_000); + +// fails without the fix: the dev server's own file serving answered for linked projects and checkout files. +describe("the dev Studio's file serving", { timeout: 30_000 }, () => { + it("serves no byte of a linked project's or the checkout's private file", async () => { + const name = link.split(/[\\/]/).pop(); + const dotfile = studioDotfile.split(/[\\/]/).pop(); + for (const path of [ + `/data/projects/${name}/.npmrc`, + `/data/projects/${name}/.npmrc?raw`, + `/data/projects/${name}/.npmrc?import&raw`, + `/data/projects/${name}/.npmrc?url`, + `/data/projects/${name}/.npmrc?inline`, + fsUrl(`${project}/.npmrc?raw`), + `/${dotfile}`, + `/${dotfile}?raw`, + fsUrl(`${studioDotfile}?raw`), + ]) { + const response = await fetch(`${origin}${path}`); + expect(await response.text(), path).not.toContain(SECRET); + } + }); + + it("still serves Studio's own modules", async () => { + for (const path of ["/src/main.tsx", "/@vite/client"]) + expect((await fetch(`${origin}${path}`)).status, path).toBe(200); + }); + + it("answers with the CLI Studio's framing rule, so another site cannot frame it", async () => { + for (const path of ["/", "/src/main.tsx"]) { + const response = await fetch(`${origin}${path}`); + expect(response.headers.get("content-security-policy"), path).toBe("frame-ancestors 'self'"); + expect(response.headers.get("x-frame-options"), path).toBe("SAMEORIGIN"); + } + }); + + it("lets no other loopback origin read what it serves", async () => { + const response = await fetch(`${origin}/src/main.tsx`, { + headers: { Origin: "http://127.0.0.1:4444" }, + }); + expect(response.headers.get("access-control-allow-origin")).toBeNull(); + }); +}); diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts index e781803d33..3a5f9e1d20 100644 --- a/packages/studio/vite.config.ts +++ b/packages/studio/vite.config.ts @@ -19,7 +19,13 @@ import { previewConfigPayload } from "./vite.preview-config"; import { loadStudioServerDevModule } from "./vite.studio-server-module"; import type { openProjectHistory } from "@hyperframes/studio-server"; import { previewChangeOwner } from "./vite.preview-watch"; -import { carriesOAuthReturn, refuseOAuthReturn } from "../studio-server/src/helpers/inertRefusal"; +import { + carriesOAuthReturn, + inertRefusal, + refuseOAuthReturn, +} from "../studio-server/src/helpers/inertRefusal"; +import { devServesUrl } from "./vite.private-files"; +import { SAME_ORIGIN_FRAMING_HEADERS } from "../engine/src/utils/loopbackOnly"; import { hostHeaderAllowed, PREVIEW_ALLOWED_HOSTS_ENV, @@ -229,6 +235,14 @@ export function devProjectApi(): Plugin { if (!carriesOAuthReturn(req.url ?? "/")) return next(); void bridgeHonoResponse(refuseOAuthReturn(), res); }); + // Plugin middlewares run before Vite's file serving; project files reach the page only through /api, as built. + const servedRoots = { studio: __dirname, checkout: resolve(__dirname, "../..") }; + server.middlewares.use((req, res, next) => { + const url = req.url ?? "/"; + if (url === "/__hyperframes_config" || url.startsWith("/api/")) return next(); + if (devServesUrl(url, servedRoots)) return next(); + void bridgeHonoResponse(inertRefusal(404, "Not found."), res); + }); server.middlewares.use((req, res, next) => { const url = req.url ?? ""; if (url !== "/__hyperframes_config" && !url.startsWith("/api/")) return next(); @@ -402,6 +416,10 @@ export default defineConfig({ }, server: { port: 5190, + // The built Studio answers no other origin; Vite's default would let any loopback page read what it serves. + cors: false, + // The same framing rule as the CLI Studio's shell, so another site cannot frame this one. + headers: { ...SAME_ORIGIN_FRAMING_HEADERS }, // Vite's defaults (localhost, IP literals) still apply on top of this list. allowedHosts: previewAllowedHostsFromEnv(), watch: { diff --git a/packages/studio/vite.private-files.test.ts b/packages/studio/vite.private-files.test.ts new file mode 100644 index 0000000000..1dbdf11d87 --- /dev/null +++ b/packages/studio/vite.private-files.test.ts @@ -0,0 +1,83 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { devServesUrl } from "./vite.private-files"; + +const fsUrl = (path: string) => `/@fs/${path.replace(/\\/g, "/").replace(/^\/+/, "")}`; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "hf-dev-files-"))); +const checkout = join(base, "checkout"); +const studio = join(checkout, "packages", "studio"); +const elsewhere = join(base, "my-project"); +const roots = { studio, checkout }; + +function file(path: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, "x"); +} + +for (const project of [join(studio, "data", "projects", "real"), elsewhere]) + for (const name of [".npmrc", "id_rsa", "sub/.hyperframes/chat.json", ".claude/settings.json"]) + file(join(project, name)); +symlinkSync(elsewhere, join(studio, "data", "projects", "linked")); +file(join(studio, "src", "main.tsx")); +file(join(checkout, ".npmrc")); +file(join(checkout, "node_modules", ".bun", "react@19", "node_modules", "react", "index.js")); + +afterAll(() => rmSync(base, { recursive: true, force: true })); + +// fails without the fix: the dev server answered every URL outside /api from its own file serving. +describe("the dev server serves no project or private file", () => { + const PRIVATE = [".npmrc", "id_rsa", "sub/.hyperframes/chat.json", ".claude/settings.json"]; + const QUERIES = ["", "?raw", "?url", "?inline", "?import", "?import&raw"]; + + it.each(["real", "linked"])("refuses every %s project file, private or not", (project) => { + for (const name of [...PRIVATE, "index.html"]) + for (const query of QUERIES) + expect(devServesUrl(`/data/projects/${project}/${name}${query}`, roots)).toBe(false); + }); + + it("refuses a linked project's files by their real path", () => { + for (const name of PRIVATE) + expect(devServesUrl(fsUrl(`${elsewhere}/${name}`), roots)).toBe(false); + }); + + it.each([ + "/data/sessions/s.json", + "/data/renders/r.mp4", + "/DATA/projects/real/.npmrc", + "/data/projects/real/%2Enpmrc", + "/src/../data/projects/real/.npmrc", + "/src/%2e%2e/data/projects/real/.npmrc", + fsUrl(`${checkout}/.npmrc`), + `/@id/${checkout}/.npmrc?raw`, + `${checkout}/.npmrc?raw`, + "/%E0%A4%A", + ])("refuses %s", (url) => { + expect(devServesUrl(url, roots)).toBe(false); + }); + + it.each([ + "/", + "/index.html", + "/src/main.tsx", + "/src/main.tsx?t=1", + "/@vite/client", + "/@react-refresh", + "/node_modules/.vite/deps/react.js?v=1", + fsUrl(`${checkout}/node_modules/.bun/react@19/node_modules/react/index.js`), + fsUrl(`${checkout}/packages/core/src/index.ts`), + ])("still serves Studio's own %s", (url) => { + expect(devServesUrl(url, roots)).toBe(true); + }); + + it("still serves a checkout's modules when the checkout sits in a hidden folder", () => { + const hidden = { + studio: join(base, ".cache", "co", "packages", "studio"), + checkout: join(base, ".cache", "co"), + }; + expect(devServesUrl(fsUrl(`${hidden.checkout}/packages/core/src/index.ts`), hidden)).toBe(true); + expect(devServesUrl(fsUrl(`${hidden.checkout}/.npmrc`), hidden)).toBe(false); + }); +}); diff --git a/packages/studio/vite.private-files.ts b/packages/studio/vite.private-files.ts new file mode 100644 index 0000000000..31546d0656 --- /dev/null +++ b/packages/studio/vite.private-files.ts @@ -0,0 +1,65 @@ +import { readdirSync, realpathSync } from "node:fs"; +import { isAbsolute, join, relative, resolve } from "node:path"; +import { + isCredentialOrToolStatePath, + isStudioPrivatePath, + isVcsOrSecretPath, + projectPathSegments, +} from "../parsers/src/privatePath"; + +export interface DevServedRoots { + /** The Vite root: Studio's own package, with linked projects under `data/projects`. */ + studio: string; + /** The source checkout Vite serves under `/@fs/`. */ + checkout: string; +} + +const inside = (rel: string) => rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); + +function realOrSelf(path: string): string { + try { + return realpathSync.native(path); + } catch { + return path; + } +} + +function linkedProjects(studio: string): string[] { + const dir = join(studio, "data", "projects"); + try { + return readdirSync(dir).map((name) => realOrSelf(join(dir, name))); + } catch { + return []; + } +} + +// `/@fs/` names a file-system path; any other URL Vite may read from its root or, as an id, from the file system. +function filesNamedBy(url: string, studio: string): string[] | null { + let pathname: string; + try { + pathname = decodeURIComponent(new URL(url, "http://dev").pathname); + } catch { + return null; + } + if (pathname.startsWith("/@fs/")) return [resolve("/", pathname.slice("/@fs/".length))]; + const path = pathname.replace(/^\/@id(?=\/)/, ""); + return [resolve(studio, `.${path}`), resolve("/", path.replace(/^\/+/, ""))]; +} + +function refused(file: string, roots: DevServedRoots, projects: string[]): boolean { + if (projectPathSegments(relative(roots.studio, file))[0] === "data") return true; + if (projects.some((project) => project === file || inside(relative(project, file)))) return true; + const rel = relative(roots.checkout, file).split("\\").join("/"); + if (!projectPathSegments(rel).includes("node_modules")) return isStudioPrivatePath(rel); + return isVcsOrSecretPath(rel) || isCredentialOrToolStatePath(rel); +} + +/** Whether the dev server may answer `url` from a file: never a project's, `data/`'s, or a private one. */ +export function devServesUrl(url: string, roots: DevServedRoots): boolean { + const files = filesNamedBy(url, roots.studio); + if (!files) return false; + const projects = linkedProjects(roots.studio); + return !files.some( + (file) => refused(file, roots, projects) || refused(realOrSelf(file), roots, projects), + ); +}