Files
hyperframes/packages/studio-server/src/helpers/serverOrigin.ts
T
James RussoandClaude Opus 5.5 983e865ad7 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>
2026-11-10 14:30:10 +00:00

30 lines
1.2 KiB
TypeScript

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;
}