fix(producer): startServer never listens without a token (#8655)

* fix(producer): startServer never listens without a token

Any local account, container or sandboxed program can reach a loopback port, and with no token
set every route but /health accepted a header-less caller. When neither authToken nor
PRODUCER_AUTH_TOKEN is set, startServer now makes a random token for the run, writes it to a
file only the server's account can read (~/.hyperframes/producer/<port>.token by default, or
authTokenFile, or PRODUCER_AUTH_TOKEN_FILE), logs that path, and requires it like a configured
token. The file is removed on shutdown. createProducerApp and createRenderHandlers keep their
behavior, and their docs now say they check no caller without a token.

* refactor(producer): keep server.ts at its comment share

* test(producer): call the started server through node:http on localhost

The unit lane refuses fetch and every lookup but localhost, so the startServer tests listen on
localhost and send their requests with node:http to the address it bound.

* refactor(producer): keep server.ts at its comment share
This commit is contained in:
Michael Wang
2026-11-24 20:34:56 +00:00
committed by GitHub
parent dd3f8440b1
commit 2b1fe6f313
4 changed files with 146 additions and 18 deletions
+11 -4
View File
@@ -223,10 +223,17 @@ 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.
The server listens on `127.0.0.1` unless you pass `hostname` or set `PRODUCER_HOST`. To
listen on any other address, also set `authToken` or `PRODUCER_AUTH_TOKEN`. Every route
except `/health` then requires `Authorization: Bearer <token>`, and the server refuses to
start without one. A request's `projectDir` must resolve, symlinks included, inside
Every route except `/health` requires `Authorization: Bearer <token>`. Set the token with
`authToken` or `PRODUCER_AUTH_TOKEN`. If you set none, `startServer` makes one for the run
and writes it to `~/.hyperframes/producer/<port>.token` (or `authTokenFile`, or
`PRODUCER_AUTH_TOKEN_FILE`), readable only by the account that runs the server, and logs
that path. Any local account, container or program can reach a loopback port, so the
server never listens without a token. It listens on `127.0.0.1` unless you pass
`hostname` or set `PRODUCER_HOST`, and it refuses any other address unless you set the
token yourself. `createProducerApp` without `authToken`, and `createRenderHandlers`
always, check no caller: serve them only behind your own authentication.
A request's `projectDir` must resolve, symlinks included, inside
`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
must stay inside that project, and `outputPath` must be inside `rendersDir`
(`PRODUCER_RENDERS_DIR`, default: a new private folder in the OS temp dir). `debug: true` is refused unless you set
+11 -4
View File
@@ -45,10 +45,17 @@ 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.
The server listens on `127.0.0.1` unless you pass `hostname` or set `PRODUCER_HOST`. To
listen on any other address, also set `authToken` or `PRODUCER_AUTH_TOKEN`. Every route
except `/health` then requires `Authorization: Bearer <token>`, and the server refuses to
start without one. A request's `projectDir` must resolve, symlinks included, inside
Every route except `/health` requires `Authorization: Bearer <token>`. Set the token with
`authToken` or `PRODUCER_AUTH_TOKEN`. If you set none, `startServer` makes one for the run
and writes it to `~/.hyperframes/producer/<port>.token` (or `authTokenFile`, or
`PRODUCER_AUTH_TOKEN_FILE`), readable only by the account that runs the server, and logs
that path. Any local account, container or program can reach a loopback port, so the
server never listens without a token. It listens on `127.0.0.1` unless you pass
`hostname` or set `PRODUCER_HOST`, and it refuses any other address unless you set the
token yourself. `createProducerApp` without `authToken`, and `createRenderHandlers`
always, check no caller: serve them only behind your own authentication.
A request's `projectDir` must resolve, symlinks included, inside
`projectsDir` (`PRODUCER_PROJECTS_DIR`, default: the working directory). Its `entryFile`
must stay inside that project, and `outputPath` must be inside `rendersDir`
(`PRODUCER_RENDERS_DIR`, default: a new private folder in the OS temp dir). `debug: true` is refused unless you set
+85 -1
View File
@@ -1,4 +1,14 @@
import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
statSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { request } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Hono } from "hono";
@@ -167,6 +177,80 @@ describe("createRenderHandlers: embedded contract", () => {
});
});
describe("startServer: callers on loopback", () => {
async function listening(options: Parameters<typeof startServer>[0]) {
process.env.PRODUCER_DISABLE_HEALTH_WORKER = "1";
// The unit lane refuses fetch and any lookup but "localhost", so listen there and call the bound address.
const server = startServer({ port: 0, hostname: "localhost", ...options });
if (!server.listening) await new Promise((done) => server.once("listening", done));
const { address, port } = server.address() as AddressInfo;
const close = () => new Promise((done) => server.close(done));
const status = (
path: string,
init: { method?: string; headers?: Record<string, string>; body?: string } = {},
) =>
new Promise<number>((done, fail) => {
const req = request(
{ host: address, port, path, method: init.method ?? "GET", headers: init.headers },
(res) => {
res.resume();
done(res.statusCode ?? 0);
},
);
req.on("error", fail);
req.end(init.body);
});
return { status, close };
}
it("with no token set, makes one only this account can read, and refuses a caller without it", async () => {
const { root, projectsDir, rendersDir } = setup();
const authTokenFile = join(root, "private", "producer.token");
// A file left at the path, readable by anyone, is replaced rather than reused.
mkdirSync(join(root, "private"));
writeFileSync(authTokenFile, "old\n", { mode: 0o644 });
const server = await listening({ projectsDir, rendersDir, authTokenFile });
try {
const token = readFileSync(authTokenFile, "utf8").trim();
expect(token).toMatch(/^[\w-]{43}$/);
if (process.platform !== "win32") expect(statSync(authTokenFile).mode & 0o077).toBe(0);
const plain = { "content-type": "application/json" };
for (const [method, path] of [
["POST", "/render"],
["POST", "/render/stream"],
["POST", "/lint"],
["GET", "/render/queue"],
["GET", "/outputs/any"],
] as const) {
const body = method === "POST" ? JSON.stringify({ projectDir: "demo" }) : undefined;
expect(
await server.status(path, { method, headers: plain, body }),
`${method} ${path}`,
).toBe(401);
}
expect(await server.status("/health")).toBe(200);
const authorization = `Bearer ${token}`;
expect(await server.status("/render/queue", { headers: { authorization } })).toBe(200);
} finally {
await server.close();
}
});
it("uses a configured token as it is and writes no file", async () => {
const { root, projectsDir, rendersDir } = setup();
const authTokenFile = join(root, "producer.token");
const server = await listening({ projectsDir, rendersDir, authTokenFile, authToken: "s3cret" });
try {
expect(existsSync(authTokenFile)).toBe(false);
expect(await server.status("/render/queue")).toBe(401);
const authorization = "Bearer s3cret";
expect(await server.status("/render/queue", { headers: { authorization } })).toBe(200);
} finally {
await server.close();
}
});
});
describe("startServer: listen address", () => {
it("refuses a non-loopback address without an auth token", () => {
expect(() => startServer({ hostname: "0.0.0.0", port: 0 })).toThrow(/auth token/);
+39 -9
View File
@@ -34,7 +34,7 @@ import {
createReadStream,
} from "node:fs";
import { basename, resolve, dirname, join } from "node:path";
import { tmpdir } from "node:os";
import { homedir, tmpdir } from "node:os";
import { parseArgs } from "node:util";
import { isIP } from "node:net";
import crypto from "node:crypto";
@@ -99,7 +99,7 @@ export interface HandlerOptions {
projectsDir?: string;
/** With `confineRequests`: let requests set `debug: true`, which keeps work dirs on disk. Defaults to PRODUCER_ALLOW_DEBUG=1. */
allowDebug?: boolean;
/** Bearer token `createProducerApp` requires on every route but /health. Defaults to PRODUCER_AUTH_TOKEN. */
/** Bearer token required on every route but /health. Defaults to PRODUCER_AUTH_TOKEN; without one no caller is checked. */
authToken?: string;
}
@@ -108,6 +108,8 @@ export interface ServerOptions extends HandlerOptions {
port?: number;
/** Address to listen on. Default: PRODUCER_HOST or 127.0.0.1. A non-loopback address requires `authToken`. */
hostname?: string;
/** Where a token made for a run without `authToken` is written. Default: PRODUCER_AUTH_TOKEN_FILE or ~/.hyperframes/producer/<port>.token. */
authTokenFile?: string;
}
// ---------------------------------------------------------------------------
@@ -912,7 +914,7 @@ export interface RenderHandlers {
/**
* Create route handler functions for the producer server.
*
* These can be mounted on any Hono app at any path prefix.
* Mount them on any Hono app at any path prefix, behind your own authentication: they check no caller.
*/
export function createRenderHandlers(options: HandlerOptions = {}): RenderHandlers {
const log = options.logger ?? defaultLogger;
@@ -1342,6 +1344,32 @@ export function createProducerApp(options: HandlerOptions = {}): Hono {
// Standalone server
// ---------------------------------------------------------------------------
interface ServerAuth {
token: string;
generatedFile?: string;
}
function serverAuth(options: ServerOptions, hostname: string, port: number): ServerAuth {
const configured = resolveAuthToken(options);
if (configured) return { token: configured };
if (!isLoopbackHostname(hostname)) {
throw new Error(
`Refusing to listen on ${hostname} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`,
);
}
const file = resolve(
options.authTokenFile?.trim() ||
process.env.PRODUCER_AUTH_TOKEN_FILE?.trim() ||
join(homedir(), ".hyperframes", "producer", `${port}.token`),
);
const token = crypto.randomBytes(32).toString("base64url");
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
// Removed first so the new file is created with its own mode, never through a link or an older file's mode.
rmSync(file, { force: true });
writeFileSync(file, `${token}\n`, { flag: "wx", mode: 0o600 });
return { token, generatedFile: file };
}
/**
* Start the producer HTTP server with graceful shutdown.
*/
@@ -1349,16 +1377,17 @@ export function startServer(options: ServerOptions = {}) {
const port = options.port ?? parseInt(process.env.PRODUCER_PORT ?? "9847", 10);
const hostname = options.hostname || process.env.PRODUCER_HOST || "127.0.0.1";
const log = options.logger ?? defaultLogger;
if (!isLoopbackHostname(hostname) && !resolveAuthToken(options)) {
throw new Error(
`Refusing to listen on ${hostname} without an auth token. Set authToken or PRODUCER_AUTH_TOKEN, or listen on a loopback address.`,
);
}
const app = createProducerApp(options);
const auth = serverAuth(options, hostname, port);
const app = createProducerApp({ ...options, authToken: auth.token });
const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
const address = info.family === "IPv6" ? `[${info.address}]` : info.address;
log.info(`Listening on http://${address}:${info.port}`);
if (auth.generatedFile) {
log.info(
`No auth token was set, so this run made one: send "Authorization: Bearer <token>" with the token in ${auth.generatedFile}`,
);
}
});
// Disable timeouts for long renders
@@ -1394,6 +1423,7 @@ export function startServer(options: ServerOptions = {}) {
async function shutdown(signal: string) {
log.info(`Received ${signal}, shutting down`);
if (auth.generatedFile) rmSync(auth.generatedFile, { force: true });
const { drainBrowserPool } = await import("@hyperframes/engine");
await drainBrowserPool().catch(() => {});
// Bounded await: if the worker hasn't come online within 1.5s of