Files
hyperframes/packages/engine/src/utils/loopbackOnly.ts
T
Michael Wang f891a30581 fix: answer only the loopback Host on the render and capture file servers (#7853)
The CLI static project server and the producer and engine file servers bind
127.0.0.1, but answered any Host header. They now refuse a request whose Host
is not 127.0.0.1, localhost or [::1] at their own port (or the in-process
origin the CLI hands out when listen is refused), and their responses carry
frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN so another site cannot
frame the served page.
2026-11-15 18:09:10 +00:00

24 lines
1006 B
TypeScript

import type { Hono } from "hono";
/** A page cannot forge Host, so a site that rebinds its own name to 127.0.0.1 is refused here. */
export function isOwnLoopbackHost(host: string | undefined, port: number): boolean {
const name = host?.toLowerCase();
return name === `127.0.0.1:${port}` || name === `localhost:${port}` || name === `[::1]:${port}`;
}
/** The runtime hands an editing port to its parent frame, so another site must not frame these pages. */
export const SAME_ORIGIN_FRAMING_HEADERS = {
"Content-Security-Policy": "frame-ancestors 'self'",
"X-Frame-Options": "SAMEORIGIN",
} as const;
export function answerOwnLoopbackHostOnly(app: Hono, boundPort: () => number): void {
app.use(async function refuseForeignHostAndFraming(c, next) {
if (!isOwnLoopbackHost(c.req.header("host"), boundPort())) return c.text("Forbidden", 403);
await next();
for (const [name, value] of Object.entries(SAME_ORIGIN_FRAMING_HEADERS)) {
c.res.headers.set(name, value);
}
});
}