mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(studio): the dev Studio serves project files only through its API (#8721)
* fix(studio): the dev Studio serves no project or private file outside its API * fix(studio): the dev Studio shell sends the CLI Studio's framing headers * test(studio): the dev file-serving test does not wait on dependency discovery * test(studio): dev file-serving tests build /@fs/ URLs the way Vite does on Windows * test(studio): the dev file-serving test warms Studio's entry module before timing requests * test(studio): dev file-serving tests get a dev-server time budget
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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: {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user