fix(studio-server): thumbnail origin from the server, sandbox previews from other sites (#7492)

* fix(studio-server): thumbnail origin from the server, sandbox previews from other sites

The thumbnail route builds the headless browser's URL from the server's own
listening origin (a new optional `serverOrigin` on the adapter, wired in the CLI
preview server and the Vite dev host) instead of the request's Host header.
Hosts that report no origin fall back to a loopback Host only.

Preview responses (bundled, sub-composition and project files) opened from
another site carry `Content-Security-Policy: sandbox allow-scripts` and
`Vary: Sec-Fetch-Site`. Studio's same-origin iframe, browser automation and
non-browser clients are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(studio): build the thumbnail origin from a hostname bind name

With HYPERFRAMES_PREVIEW_HOST set to a hostname, the listening address is
the IP it resolved to, and the Host check accepts the bind name, not that
IP. The thumbnail browser then loaded a 403 page. Use the bind name when it
is a hostname; IP and wildcard binds keep the listening address.

— Rames Jusso

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(studio): drop the serverOrigin comment that put it over the package's comment share

The hostname-bind rule is stated by its test name in serverOrigin.test.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-10 14:30:10 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 5c57999756
commit 983e865ad7
13 changed files with 275 additions and 4 deletions
@@ -22,6 +22,7 @@ vi.mock("@clack/prompts", async (importOriginal) => {
vi.mock("../server/studioServer.js", () => ({
resolveStudioBundle: () => ({ available: true, checkedPaths: [] }),
loadPreviewServerBuildSignature: async () => "test",
originForListeningAddress: () => undefined,
createStudioServer: () => ({
app: { fetch: () => new Response() },
watcher: { close: vi.fn() },
+12 -3
View File
@@ -1589,8 +1589,12 @@ export async function runEmbeddedMode(
startPort: number,
options?: EmbeddedStudioOptions,
): Promise<void> {
const { createStudioServer, loadPreviewServerBuildSignature, resolveStudioBundle } =
await import("../server/studioServer.js");
const {
createStudioServer,
loadPreviewServerBuildSignature,
originForListeningAddress,
resolveStudioBundle,
} = await import("../server/studioServer.js");
const pName = options?.projectName ?? basename(dir);
const studioBundle = resolveStudioBundle();
@@ -1687,7 +1691,12 @@ export async function runEmbeddedMode(
}
const url = `http://localhost:${result.port}`;
listening = `http://127.0.0.1:${result.port}`;
listening =
originForListeningAddress(
result.server.address(),
"http",
process.env.HYPERFRAMES_PREVIEW_HOST,
) ?? `http://127.0.0.1:${result.port}`;
if (options?.json) {
writeLifecycleJson(foregroundPreviewReadyPayload(pName, url, dir, process.pid));
} else {
@@ -795,6 +795,14 @@ describe("host guarding on identity-bearing responses", () => {
expect(await res.text()).not.toContain('distinctId":"');
});
it("gives the thumbnail browser the origin it listens on, not the request's", async () => {
let listening: string | undefined;
server = createStudioServer({ projectDir: tmpProject(), origin: () => listening });
expect(server.adapter.serverOrigin?.()).toBeUndefined();
listening = "http://127.0.0.1:3002";
expect(server.adapter.serverOrigin?.()).toBe("http://127.0.0.1:3002");
});
it("serves the identity endpoint on a loopback Host", async () => {
server = createStudioServer({ projectDir: tmpProject() });
const res = await server.app.request("/api/telemetry-identity", {
+3
View File
@@ -94,6 +94,8 @@ import {
} from "../browser/gpuPolicy.js";
import { loadSharpInBackground } from "../utils/optionalPackages.js";
export { originForListeningAddress } from "@hyperframes/studio-server";
const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
// Under preview.ts's 3s process-exit watchdog, so shutdown() always returns
@@ -605,6 +607,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
runtimeUrl: "/api/runtime.js",
gsapLocalRoot: gsapVendorDir ? GSAP_LOCAL_ROOT : undefined,
serverOrigin: () => options.origin?.(),
rendersDir: () => join(projectDir, "renders"),
@@ -38,6 +38,15 @@ async function answerRefusedFrameWithPage(c: Context, next: Next) {
});
}
async function sandboxPreviewOpenedFromAnotherSite(c: Context, next: Next) {
await next();
c.header("Vary", "Sec-Fetch-Site", { append: true });
const site = c.req.header("sec-fetch-site");
if (site === "cross-site" || site === "same-site") {
c.header("Content-Security-Policy", "sandbox allow-scripts");
}
}
function urlHost(url: string): string | undefined {
try {
return new URL(url).host || undefined;
@@ -60,6 +69,7 @@ export interface StudioApiOptions {
export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOptions = {}): Hono {
const api = new Hono();
api.use("/projects/:id/preview/*", sandboxPreviewOpenedFromAnotherSite);
// This API is unauthenticated and simple cross-origin POSTs need no
// preflight, so the guard rejects writes the shared predicate refuses.
api.use(async function rejectCrossOriginWrites(c, next) {
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { originForListeningAddress } from "./serverOrigin";
describe("originForListeningAddress", () => {
it.each([
[{ address: "127.0.0.1", family: "IPv4", port: 3002 }, "http://127.0.0.1:3002"],
[{ address: "0.0.0.0", family: "IPv4", port: 3002 }, "http://127.0.0.1:3002"],
[{ address: "::", family: "IPv6", port: 3002 }, "http://127.0.0.1:3002"],
[{ address: "::1", family: "IPv6", port: 3002 }, "http://[::1]:3002"],
[{ address: "192.168.1.20", family: "IPv4", port: 5190 }, "http://192.168.1.20:5190"],
])("reaches %o at %s", (address, origin) => {
expect(originForListeningAddress(address)).toBe(origin);
});
it("reaches a hostname bind by that name, which the Host check accepts", () => {
const address = { address: "192.168.1.20", family: "IPv4", port: 5190 };
expect(originForListeningAddress(address, "http", "mybox.lan")).toBe("http://mybox.lan:5190");
expect(originForListeningAddress(address, "http", " mybox.lan ")).toBe("http://mybox.lan:5190");
});
it.each(["192.168.1.20", "0.0.0.0", "::", "*", "", undefined])(
"keeps the listening address for bind %s",
(bindHost) => {
const address = { address: "192.168.1.20", family: "IPv4", port: 5190 };
expect(originForListeningAddress(address, "http", bindHost)).toBe("http://192.168.1.20:5190");
},
);
it("has no origin for a pipe or a server that is not listening", () => {
expect(originForListeningAddress("/tmp/studio.sock")).toBeUndefined();
expect(originForListeningAddress(null)).toBeUndefined();
});
});
@@ -0,0 +1,29 @@
import { isIP, type AddressInfo } from "node:net";
export function originForListeningAddress(
address: AddressInfo | string | null | undefined,
protocol: "http" | "https" = "http",
bindHost?: string,
): string | undefined {
if (!address || typeof address === "string") return undefined;
const bindName = bindHost?.trim() ?? "";
if (bindName !== "" && bindName !== "*" && isIP(bindName) === 0) {
return `${protocol}://${bindName}:${address.port}`;
}
const unspecified = address.address === "0.0.0.0" || address.address === "::";
const host = unspecified ? "127.0.0.1" : address.address;
return `${protocol}://${host.includes(":") ? `[${host}]` : host}:${address.port}`;
}
// Anchored at both ends: a `user@host` or path after the port would move the URL built from it.
const LOOPBACK_HOST_HEADER = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d{1,5})?$/i;
const IN_PROCESS_ORIGIN = "http://localhost";
export function thumbnailPreviewOrigin(
serverOrigin: string | undefined,
hostHeader: string | undefined,
): string | null {
if (serverOrigin) return serverOrigin;
if (hostHeader === undefined) return IN_PROCESS_ORIGIN;
return LOOPBACK_HOST_HEADER.test(hostHeader) ? `http://${hostHeader}` : null;
}
+1
View File
@@ -48,6 +48,7 @@ export { PREVIEW_BUNDLE_OPTIONS } from "./routes/preview.js";
export { createPreviewDocumentStore } from "./helpers/previewDocumentStore.js";
export { getMimeType, MIME_TYPES } from "./helpers/mime.js";
export { decodeWellFormedEscapes, requestSubPath } from "./helpers/requestSubPath.js";
export { originForListeningAddress } from "./helpers/serverOrigin.js";
export { MAX_OPEN_MEDIA_RANGE_BYTES, openRangeEnd } from "./helpers/mediaRange.js";
export {
consumeFileWriteReceipt,
@@ -0,0 +1,78 @@
// @vitest-environment node
import { afterAll, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createStudioApi } from "../createStudioApi";
import type { StudioApiAdapter } from "../types";
const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-sandbox-"));
writeFileSync(
join(projectDir, "index.html"),
'<div data-composition-id="main" data-width="320" data-height="180"></div>',
);
writeFileSync(join(projectDir, "page.html"), "<script>document.title = 'ran'</script>");
writeFileSync(
join(projectDir, "icon.svg"),
'<svg xmlns="http://www.w3.org/2000/svg"><script>void 0</script></svg>',
);
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
const adapter: StudioApiAdapter = {
listProjects: () => [],
resolveProject: async (id: string) => ({ id, dir: projectDir }),
bundle: async () => null,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(projectDir, "renders"),
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
};
const api = createStudioApi(adapter);
const SANDBOX = "sandbox allow-scripts";
const routes = [
["a project HTML file", "/projects/demo/preview/page.html", "text/html"],
["a project SVG file", "/projects/demo/preview/icon.svg", "image/svg+xml"],
["the bundled preview", "/projects/demo/preview", "text/html"],
["a sub-composition preview", "/projects/demo/preview/comp/page.html", "text/html"],
] as const;
async function get(path: string, site?: string) {
return api.request(`http://localhost${path}`, {
headers: site === undefined ? {} : { "sec-fetch-site": site },
});
}
describe.each(routes)("%s", (_name, path, type) => {
it.each(["cross-site", "same-site"])("is sandboxed when the request is %s", async (site) => {
const res = await get(path, site);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain(type);
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
});
it.each([["same-origin"], ["none"], [undefined]])(
"keeps its origin when Sec-Fetch-Site is %s",
async (site) => {
const res = await get(path, site);
expect(res.status).toBe(200);
expect(res.headers.get("content-security-policy")).toBeNull();
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
},
);
});
describe("a revalidated preview", () => {
it("still names Sec-Fetch-Site in Vary and carries the sandbox on a 304", async () => {
const first = await get("/projects/demo/preview", "same-origin");
const etag = first.headers.get("etag");
expect(etag).toBeTruthy();
const res = await api.request("http://localhost/projects/demo/preview", {
headers: { "sec-fetch-site": "cross-site", "if-none-match": etag! },
});
expect(res.status).toBe(304);
expect(res.headers.get("vary")).toBe("Sec-Fetch-Site");
expect(res.headers.get("content-security-policy")).toBe(SANDBOX);
});
});
@@ -0,0 +1,88 @@
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerThumbnailRoutes } from "./thumbnail";
import type { StudioApiAdapter } from "../types";
vi.mock("../helpers/proxyTranscoder.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../helpers/proxyTranscoder.js")>()),
proxyActivityMark: vi.fn(() => "0"),
}));
const dirs: string[] = [];
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
function setup(serverOrigin?: string) {
const projectDir = mkdtempSync(join(tmpdir(), "hf-thumbnail-origin-"));
dirs.push(projectDir);
writeFileSync(join(projectDir, "index.html"), '<div data-width="320" data-height="180"></div>');
const visited: string[] = [];
const adapter: StudioApiAdapter = {
listProjects: () => [],
resolveProject: async (id: string) => ({ id, dir: projectDir }),
bundle: async () => null,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(projectDir, "renders"),
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/o.mp4" }),
...(serverOrigin !== undefined && { serverOrigin: () => serverOrigin }),
generateThumbnail: async ({ previewUrl }) => {
visited.push(previewUrl);
return Buffer.from("thumb");
},
};
const app = new Hono();
registerThumbnailRoutes(app, adapter);
// Each request a fresh `t`, so none is answered from the previous one's cache.
let seek = 0;
const request = (host: string) =>
app.request(`http://localhost/projects/demo/thumbnail/index.html?t=${(seek += 0.25)}`, {
headers: { host },
});
return { request, visited };
}
describe("the thumbnail browser's destination", () => {
it("is the server's own origin, whatever Host the request names", async () => {
const { request, visited } = setup("http://127.0.0.1:3002");
const res = await request("other.example:3002");
expect(res.status).toBe(200);
expect(visited).toHaveLength(1);
expect(new URL(visited[0]!).origin).toBe("http://127.0.0.1:3002");
expect(visited[0]).toMatch(/^http:\/\/127\.0\.0\.1:3002\/api\/projects\/demo\/preview\?/);
});
it("never comes from a non-loopback Host when the host reports no origin", async () => {
const { request, visited } = setup();
for (const host of [
"other.example:3002",
"127.0.0.1:3002@other.example",
"localhost.other.example",
"127.0.0.1.other.example:3002",
]) {
expect((await request(host)).status).toBe(400);
}
expect(visited).toEqual([]);
});
it("is a loopback Host as given when the host reports no origin", async () => {
const { request, visited } = setup();
for (const host of ["localhost:3002", "127.0.0.1:4100", "[::1]:3002"]) {
expect((await request(host)).status).toBe(200);
}
expect(visited.map((url) => new URL(url).host)).toEqual([
"localhost:3002",
"127.0.0.1:4100",
"[::1]:3002",
]);
});
});
@@ -31,6 +31,7 @@ import {
} from "../helpers/safePath.js";
import { proxyActivityMark } from "../helpers/proxyTranscoder.js";
import { PREVIEW_CAPTURE_PARAM } from "./preview.js";
import { thumbnailPreviewOrigin } from "../helpers/serverOrigin.js";
const THUMBNAIL_CACHE_VERSION = "v5";
const THUMBNAIL_MAX_OUTPUT_WIDTH = 240;
@@ -186,7 +187,9 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const motion = manifestKey(join(project.dir, STUDIO_MOTION_PATH));
sourceMtime = Math.max(sourceMtime, manualEdits.mtimeMs, motion.mtimeMs);
const projectUrl = `http://${c.req.header("host")}/api/projects/${encodeURIComponent(project.id)}`;
const origin = thumbnailPreviewOrigin(adapter.serverOrigin?.(), c.req.header("host"));
if (!origin) return c.json({ error: "thumbnail needs a loopback Host" }, 400);
const projectUrl = `${origin}/api/projects/${encodeURIComponent(project.id)}`;
const previewPath =
compPath === "index.html"
? `${projectUrl}/preview`
+2
View File
@@ -229,6 +229,8 @@ export interface StudioApiAdapter {
jobId: string;
}) => MediaProcessingJobState;
serverOrigin?: () => string | undefined;
/** Optional: generate a thumbnail at the route's explicit output dimensions. */
generateThumbnail?: (opts: {
project: ResolvedProject;
+6
View File
@@ -23,6 +23,7 @@ import {
DEFAULT_HISTORY_ROOT,
openProjectHistory,
historyCache,
originForListeningAddress,
} from "@hyperframes/studio-server";
import { encoderJobOptions } from "@hyperframes/studio-server/encoder-options";
import type { RegistryItem } from "@hyperframes/core/registry";
@@ -306,6 +307,11 @@ export function createViteAdapter(
},
runtimeUrl: "/api/runtime.js",
serverOrigin: () =>
originForListeningAddress(
server.httpServer?.address(),
server.config.server.https ? "https" : "http",
),
rendersDir: () => resolve(dataDir, "../renders"),