diff --git a/docs/packages/producer.mdx b/docs/packages/producer.mdx index 1519d24109..ff3fc4b806 100644 --- a/docs/packages/producer.mdx +++ b/docs/packages/producer.mdx @@ -188,6 +188,13 @@ import { startServer } from "@hyperframes/producer"; await startServer({ port: 8080 }); ``` +A browser request (one that carries an `Origin` or `Sec-Fetch-Site` header) is accepted +only under an IP address, `localhost` or a `*.localhost` name, so a page that points its +own domain at the server cannot start renders or lint. If browsers reach the server +through a proxy name, list that name in `allowedHosts` or in the comma-separated +`PRODUCER_ALLOWED_HOSTS` variable. Requests without those headers, such as curl or +another service, are unaffected. + For larger workloads, the `@hyperframes/producer/distributed` entry exposes the three rendering activities—`plan`, `renderChunk`, and `assemble`. Your orchestrator remains responsible for dispatch, retries, storage, and networking. diff --git a/packages/producer/README.md b/packages/producer/README.md index 1489164ad9..a007501e1e 100644 --- a/packages/producer/README.md +++ b/packages/producer/README.md @@ -38,6 +38,13 @@ await startServer({ port: 8080 }); // POST /render or /render/stream with projectDir, html, or previewUrl (public HTTPS only) and render options ``` +A browser request (one that carries an `Origin` or `Sec-Fetch-Site` header) is accepted +only under an IP address, `localhost` or a `*.localhost` name, so a page that points its +own domain at the server cannot start renders or lint. If browsers reach the server +through a proxy name, list that name in `allowedHosts` or in the comma-separated +`PRODUCER_ALLOWED_HOSTS` variable. Requests without those headers, such as curl or +another service, are unaffected. + Both HTTP routes accept optional `pageMotionBlur: "off"` to disable authored page motion blur. Omit it to preserve the composition's behavior. Other explicit values are rejected before a render starts. This is separate from engine sub-frame diff --git a/packages/producer/src/server.crossOrigin.test.ts b/packages/producer/src/server.crossOrigin.test.ts index 5dad287e68..8b2727bf8e 100644 --- a/packages/producer/src/server.crossOrigin.test.ts +++ b/packages/producer/src/server.crossOrigin.test.ts @@ -22,10 +22,10 @@ vi.mock("./services/renderOrchestrator.js", () => { }; }); -import { createProducerApp } from "./server.js"; +import { createProducerApp, type HandlerOptions } from "./server.js"; -function postRender(headers: Record) { - return createProducerApp().request("http://localhost:9847/render", { +function postRender(headers: Record, options: HandlerOptions = {}) { + return createProducerApp(options).request("http://localhost:9847/render", { method: "POST", headers: { host: "localhost:9847", ...headers }, body: JSON.stringify({ html: "" }), @@ -58,12 +58,88 @@ describe("createProducerApp: cross-origin browser requests", () => { it.each([ ["no Origin (curl, server-to-server)", {}], ["a same-origin page", { origin: "http://localhost:9847" }], - [ - "a same-origin page behind a proxy that rewrites Host", - { origin: "https://render.example.com", "sec-fetch-site": "same-origin" }, - ], ])("renders for %s", async (_label, headers) => { const res = await postRender({ "content-type": "application/json", ...headers }); expect(res.status).toBe(200); }); + + it("renders for a same-origin page behind a proxy that rewrites Host once its name is allowed", async () => { + const headers = { + "content-type": "application/json", + origin: "https://render.example.com", + "sec-fetch-site": "same-origin", + }; + expect((await postRender(headers)).status).toBe(403); + expect((await postRender(headers, { allowedHosts: ["render.example.com"] })).status).toBe(200); + }); +}); + +describe("createProducerApp: browser requests under a rebound host name", () => { + const rebound = { host: "attacker.example:9847", origin: "http://attacker.example:9847" }; + + function request(path: string, headers: Record, options: HandlerOptions = {}) { + const method = path === "/render" ? "POST" : "GET"; + return createProducerApp(options).request(`http://localhost:9847${path}`, { + method, + headers: { "content-type": "application/json", ...headers }, + body: method === "POST" ? JSON.stringify({ html: "" }) : undefined, + }); + } + + it.each([ + ["with Sec-Fetch-Site: same-origin", { ...rebound, "sec-fetch-site": "same-origin" }], + ["without Sec-Fetch-Site", rebound], + ])("refuses a render %s and starts nothing", async (_label, headers) => { + const before = started.count; + const res = await request("/render", headers); + expect(res.status).toBe(403); + expect(started.count).toBe(before); + }); + + it("refuses an output download and a queue read the same way", async () => { + const headers = { ...rebound, "sec-fetch-site": "same-origin" }; + expect((await request("/outputs/some-token", headers)).status).toBe(403); + expect((await request("/render/queue", headers)).status).toBe(403); + }); + + it("refuses a page whose own origin is a rebindable name even when Host is loopback", async () => { + const res = await request("/render", { + host: "localhost:9847", + origin: "http://attacker.example:9847", + "sec-fetch-site": "same-origin", + }); + expect(res.status).toBe(403); + }); + + it.each([ + ["127.0.0.1", "127.0.0.1:9847"], + ["a LAN address", "192.168.1.20:9847"], + ["IPv6 loopback", "[::1]:9847"], + ["a *.localhost name", "studio.localhost:9847"], + ])("serves a same-origin page on %s", async (_label, host) => { + const res = await request("/render", { + host, + origin: `http://${host}`, + "sec-fetch-site": "same-origin", + }); + expect(res.status).toBe(200); + }); + + it("serves a listed name, from options or PRODUCER_ALLOWED_HOSTS, matched without port or case", async () => { + const headers = { ...rebound, "sec-fetch-site": "same-origin" }; + expect((await request("/render", headers, { allowedHosts: ["Attacker.Example"] })).status).toBe( + 200, + ); + vi.stubEnv("PRODUCER_ALLOWED_HOSTS", " other.example , attacker.example:443"); + try { + expect((await request("/render", headers)).status).toBe(200); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("leaves non-browser callers alone whatever Host they send", async () => { + const res = await request("/render", { host: "producer.internal:9847" }); + expect(res.status).toBe(200); + }); }); diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.ts index 62e4854ea7..4eab1bea01 100644 --- a/packages/producer/src/server.ts +++ b/packages/producer/src/server.ts @@ -25,6 +25,7 @@ import { import { resolve, dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { parseArgs } from "node:util"; +import { isIP } from "node:net"; import crypto from "node:crypto"; import { Hono, type Context } from "hono"; import { streamSSE } from "hono/streaming"; @@ -76,6 +77,8 @@ export interface HandlerOptions { artifactTtlMs?: number; /** Max renders that execute simultaneously. Queued requests wait FIFO. Default: 2. */ maxConcurrentRenders?: number; + /** Extra browser-facing host names (e.g. a proxy's); merged with PRODUCER_ALLOWED_HOSTS. */ + allowedHosts?: readonly string[]; } export interface ServerOptions extends HandlerOptions { @@ -1033,12 +1036,65 @@ function isCrossOriginBrowserRequest(c: Context): boolean { } } +function hostnameOf(host: string): string | null { + try { + return new URL(`http://${host}`).hostname.toLowerCase(); + } catch { + return null; + } +} + +/** A rebound page arrives under its own DNS name; IP literals and localhost can't be rebound. */ +function isAllowedBrowserHostname(hostname: string | null, allowed: ReadonlySet): boolean { + if (!hostname) return false; + if (hostname === "localhost" || hostname.endsWith(".localhost")) return true; + if (isIP(hostname.replace(/^\[|\]$/g, "")) !== 0) return true; + return allowed.has(hostname); +} + +function allowedHostnames(options: HandlerOptions): Set { + const fromEnv = (process.env.PRODUCER_ALLOWED_HOSTS ?? "").split(","); + const names = new Set(); + for (const entry of [...(options.allowedHosts ?? []), ...fromEnv]) { + const hostname = entry.trim() ? hostnameOf(entry.trim()) : null; + if (hostname) names.add(hostname); + } + return names; +} + +/** Header-less callers (curl, services) pass; a page's POST always carries Origin. */ +function isDisallowedBrowserHost(c: Context, allowed: ReadonlySet): boolean { + const origin = c.req.header("origin"); + if (!origin && !c.req.header("sec-fetch-site")) return false; + if (!isAllowedBrowserHostname(hostnameOf(c.req.header("host") ?? ""), allowed)) return true; + if (!origin) return false; + try { + return !isAllowedBrowserHostname(new URL(origin).hostname.toLowerCase(), allowed); + } catch { + return true; + } +} + /** * Create a Hono app with clean public routes for OSS use. */ export function createProducerApp(options: HandlerOptions = {}): Hono { const app = new Hono(); const handlers = createRenderHandlers(options); + const allowed = allowedHostnames(options); + + app.use("*", async (c, next) => { + if (isDisallowedBrowserHost(c, allowed)) { + return c.json( + { + success: false, + error: "Host not allowed. Add it to allowedHosts or PRODUCER_ALLOWED_HOSTS.", + }, + 403, + ); + } + await next(); + }); app.post("*", async (c, next) => { if (isCrossOriginBrowserRequest(c)) {