fix(cli): play and present answer unknown paths with an inert refusal (SECOPS-2642 part 3) (#8160)

* fix(cli): play and present answer unknown paths with an inert refusal (SECOPS-2642 part 3)

An OAuth return that lands on the play or present port was a 404 document on
the same origin as the composition frame, so project script could read its
?code=&state= through a frame, a popup or the authorize redirect. Unknown
paths, missing composition files and any request carrying code or state now
get a fixed text/plain 404 on an opaque origin (CSP sandbox) that cannot be
framed and drops its opener (COOP same-origin).

play's app setup moves into an exported buildPlayApp so tests can serve it.

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

* fix(cli): trim the inert refusal's comments to the package share

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:
Wenbo Zhu
2026-11-18 14:55:42 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent a82ee10c68
commit fc289b0dfc
7 changed files with 289 additions and 30 deletions
+4
View File
@@ -1156,6 +1156,10 @@ setting `preview` uses:
HYPERFRAMES_PREVIEW_ALLOWED_HOSTS=demo.tunnels.example hyperframes present
```
Any path they have no page for, and any address carrying a `code` or `state`
parameter, gets a plain-text `Not found` that cannot be framed or scripted, so a
sign-in that returns to their port leaves nothing the project's own script can read.
### `publish`
For new video reviews, use [`share`](#share). Legacy source publishing stays
@@ -0,0 +1,139 @@
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createAdaptorServer } from "@hono/node-server";
import type { Hono } from "hono";
import puppeteer, { type Browser } from "puppeteer-core";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { ensureBrowser } from "../browser/manager.js";
import { buildPlayApp } from "./play.js";
import { buildPresentApp } from "./present.js";
// SECOPS-2642 part 3. HeyGen's sign-in returns a CLI code to any loopback port, and the play and
// present pages share their origin with the composition frame (`sandbox-origin="same-origin"`), so
// anything those pages can read, project script can read through `parent`. Each probe runs on the
// server's own page and tries to read a return address that landed on that server.
let browser: Browser;
let dir: string;
const servers: Server[] = [];
async function listen(server: Server, host: string): Promise<number> {
servers.push(server);
await new Promise<void>((done) => server.listen(0, host, done));
return (server.address() as AddressInfo).port;
}
/** Stands in for the authorize endpoint: another origin that always redirects to `returnTo`. */
async function redirector(returnTo: string): Promise<string> {
const server = createServer((_req, res) => {
res.writeHead(302, { Location: returnTo });
res.end();
});
return `http://localhost:${await listen(server, "127.0.0.1")}/authorize`;
}
async function serve(app: Hono): Promise<string> {
const server = createAdaptorServer({ fetch: app.fetch }) as Server;
return `http://127.0.0.1:${await listen(server, "127.0.0.1")}`;
}
async function readReturnAddress(origin: string): Promise<Record<string, string>> {
const back = `${origin}/oauth/callback?code=SECRET&state=s`;
const viaAuthorize = await redirector(back);
const page = await browser.newPage();
try {
await page.goto(`${origin}/`);
expect(await page.evaluate(() => location.origin)).toBe(origin);
return await page.evaluate(
async (back, viaAuthorize) => {
const settle = () => new Promise((done) => setTimeout(done, 1000));
const read = (w: Window | null) => {
if (!w) return "no window";
if (w.closed) return "severed";
try {
return w.location.href;
} catch {
return "unreadable";
}
};
const framed = (src: string) => {
const frame = document.createElement("iframe");
frame.src = src;
document.body.append(frame);
return frame;
};
const frame = framed(back);
const frameViaAuthorize = framed(viaAuthorize);
const popup = open(back);
const popupViaAuthorize = open(viaAuthorize);
await settle();
const seen = {
frame: read(frame.contentWindow),
frameViaAuthorize: read(frameViaAuthorize.contentWindow),
popup: read(popup),
popupViaAuthorize: read(popupViaAuthorize),
};
popup?.close();
popupViaAuthorize?.close();
return seen;
},
back,
viaAuthorize,
);
} finally {
// A popup the probe closed itself can still be listed for a moment.
for (const other of await browser.pages()) await other.close().catch(() => undefined);
}
}
beforeAll(async () => {
const { executablePath } = await ensureBrowser();
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--no-sandbox"] });
dir = mkdtempSync(join(tmpdir(), "hf-oauth-return-"));
writeFileSync(join(dir, "index.html"), "<html><head></head><body></body></html>");
for (const bundle of ["player.js", "runtime.js", "slideshow.js"]) {
writeFileSync(join(dir, bundle), "");
}
}, 60_000);
afterAll(async () => {
await browser?.close();
for (const server of servers) server.close();
rmSync(dir, { recursive: true, force: true });
});
// Fails without the fix: on main every probe reads `…/oauth/callback?code=SECRET&state=s`.
describe("an OAuth return that lands on the server's port", () => {
// A blocked popup ("no window") would pass a looser check without proving anything.
const unreadable = expect.stringMatching(/^(severed|unreadable)$/);
const expected = {
frame: unreadable,
frameViaAuthorize: unreadable,
popup: unreadable,
popupViaAuthorize: unreadable,
};
const project = () => ({ dir, name: "deck", indexPath: join(dir, "index.html") });
it("cannot be read from the play page", async () => {
const origin = await serve(
await buildPlayApp(project(), false, {
playerPath: join(dir, "player.js"),
runtimePath: join(dir, "runtime.js"),
}),
);
expect(await readReturnAddress(origin)).toEqual(expected);
}, 30_000);
it("cannot be read from the present page", async () => {
const origin = await serve(
await buildPresentApp(project(), "{}", {
playerPath: join(dir, "player.js"),
slideshowPath: join(dir, "slideshow.js"),
}),
);
expect(await readReturnAddress(origin)).toEqual(expected);
}, 30_000);
});
+43 -1
View File
@@ -122,7 +122,8 @@ vi.mock("../utils/compositionServer.js", async (importOriginal) => ({
listenOnFreePort: async () => 3003,
}));
const { default: play, registerCompositionRoute } = await import("./play.js");
const { default: play, buildPlayApp, registerCompositionRoute } = await import("./play.js");
const { INERT_REFUSAL_HEADERS } = await import("../utils/strayRequestRefusal.js");
let dir: string | undefined;
@@ -606,3 +607,44 @@ it.skipIf(process.platform === "win32")(
}
},
);
describe("a request the play server has no page for", () => {
async function playApp() {
const project = tmpProject();
writeFileSync(join(project.dir, "index.html"), "<html><head></head><body></body></html>");
writeFileSync(join(project.dir, "player.js"), "");
writeFileSync(join(project.dir, "runtime.js"), "");
return buildPlayApp(project, false, {
playerPath: join(project.dir, "player.js"),
runtimePath: join(project.dir, "runtime.js"),
});
}
// fails without the fix: these were a 404 document on the play page's own origin, readable by
// composition script in a frame or popup, or (for `/` and composition files) the page itself.
it.each([
"/oauth/callback?code=c0de&state=st4te",
"/callback?code=c0de&state=st4te",
"/?code=c0de&state=st4te",
"/composition/index.html?code=c0de",
"/no-such-page",
"/composition/missing.html",
])("gets an inert plain-text refusal: %s", async (path) => {
const app = await playApp();
const res = await app.request(path, { headers: { "Sec-Fetch-Site": "cross-site" } });
expect(res.status).toBe(404);
expect(Object.fromEntries(res.headers)).toEqual(
Object.fromEntries(
Object.entries(INERT_REFUSAL_HEADERS).map(([name, value]) => [name.toLowerCase(), value]),
),
);
expect(await res.text()).toBe("Not found");
});
it("leaves the player page and its bundles as they were", async () => {
const app = await playApp();
for (const path of ["/", "/player.js", "/runtime.js", "/composition/index.html"]) {
const res = await app.request(path, { headers: { "Sec-Fetch-Site": "same-origin" } });
expect(res.status).toBe(200);
}
});
});
+35 -29
View File
@@ -49,6 +49,7 @@ import {
} from "../utils/compositionServer.js";
import { isPrivateCompositionFile } from "../utils/privateProjectFile.js";
import { escapeHtml } from "../utils/escapeHtml.js";
import { refuseStrayRequestsInertly } from "../utils/strayRequestRefusal.js";
import {
resolveProxy,
ProxyCapacityError,
@@ -147,37 +148,9 @@ export default defineCommand({
return;
}
const { Hono } = await import("hono");
const { createAdaptorServer } = await import("@hono/node-server");
const app = new Hono();
refuseUnknownHosts(app);
// Serve the player JS
app.get("/player.js", (ctx) =>
revalidatedResponse(
readFileSync(playerPath, "utf-8"),
"application/javascript",
ctx.req.header("If-None-Match"),
),
);
// Serve the runtime JS
app.get("/runtime.js", (ctx) =>
revalidatedResponse(
readFileSync(runtimePath, "utf-8"),
"application/javascript",
ctx.req.header("If-None-Match"),
),
);
const autoProxy = resolveAutoProxy(project.dir, args.proxy as boolean | undefined);
await registerCompositionRoute(app, project, autoProxy);
// Main page — the player wrapper
app.get("/", (ctx) => {
return ctx.html(buildPlayerPage(project.name));
});
const app = await buildPlayApp(project, autoProxy, { playerPath, runtimePath });
clack.intro(c.bold("hyperframes play"));
const s = clack.spinner();
@@ -210,6 +183,39 @@ export default defineCommand({
},
});
/** The player page, its two bundles and the project's files, on one loopback origin. */
export async function buildPlayApp(
project: ProjectDir,
autoProxy: boolean,
bundles: { playerPath: string; runtimePath: string },
): Promise<Hono> {
const { Hono } = await import("hono");
const app = new Hono();
refuseStrayRequestsInertly(app);
refuseUnknownHosts(app);
app.get("/player.js", (ctx) =>
revalidatedResponse(
readFileSync(bundles.playerPath, "utf-8"),
"application/javascript",
ctx.req.header("If-None-Match"),
),
);
app.get("/runtime.js", (ctx) =>
revalidatedResponse(
readFileSync(bundles.runtimePath, "utf-8"),
"application/javascript",
ctx.req.header("If-None-Match"),
),
);
await registerCompositionRoute(app, project, autoProxy);
// Main page — the player wrapper
app.get("/", (ctx) => ctx.html(buildPlayerPage(project.name)));
return app;
}
/**
* Registers the `/composition/*` route: serves composition HTML (runtime +
* `__HF_MEDIA_CODEC_MAP__` injected) and asset files, with byte-Range support
+31
View File
@@ -4,6 +4,7 @@ import { consumeCommandResult } from "../utils/commandResult.js";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { INERT_REFUSAL_HEADERS } from "../utils/strayRequestRefusal.js";
vi.mock("@hono/node-server", async (importOriginal) => ({
...(await importOriginal<typeof import("@hono/node-server")>()),
@@ -141,3 +142,33 @@ it.skipIf(process.platform === "win32")(
}
},
);
describe("a request the present server has no page for", () => {
it.each([
"/oauth/callback?code=c0de&state=st4te",
"/callback?code=c0de&state=st4te",
"/?code=c0de&state=st4te",
"/?mode=audience&state=st4te",
"/composition/index.html?code=c0de",
"/no-such-page",
"/composition/missing.html",
])("gets an inert plain-text refusal: %s", async (path) => {
const app = await presentApp();
const res = await app.request(path, { headers: { "Sec-Fetch-Site": "cross-site" } });
expect(res.status).toBe(404);
expect(Object.fromEntries(res.headers)).toEqual(
Object.fromEntries(
Object.entries(INERT_REFUSAL_HEADERS).map(([name, value]) => [name.toLowerCase(), value]),
),
);
expect(await res.text()).toBe("Not found");
});
it("leaves the presenter and audience pages as they were", async () => {
const app = await presentApp();
for (const path of ["/", "/?mode=audience"]) {
const res = await app.request(path, { headers: { "Sec-Fetch-Site": "same-origin" } });
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toMatch(/^text\/html/);
}
});
});
+2
View File
@@ -36,6 +36,7 @@ import {
} from "../utils/compositionServer.js";
import { isPrivateCompositionFile } from "../utils/privateProjectFile.js";
import { escapeHtml } from "../utils/escapeHtml.js";
import { refuseStrayRequestsInertly } from "../utils/strayRequestRefusal.js";
export default defineCommand({
meta: {
@@ -177,6 +178,7 @@ export async function buildPresentApp(
): Promise<Hono> {
const { Hono } = await import("hono");
const app = new Hono();
refuseStrayRequestsInertly(app);
refuseUnknownHosts(app);
refuseFramingByOtherSites(app);
@@ -0,0 +1,35 @@
import type { Hono } from "hono";
// Opaque origin, unframeable, opener dropped: same-origin project script cannot read a `?code=` return.
const OAUTH_RETURN_PARAMS = ["code", "state"] as const;
export const INERT_REFUSAL_HEADERS = {
"Content-Type": "text/plain; charset=utf-8",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
"Cross-Origin-Opener-Policy": "same-origin",
"Content-Security-Policy": "sandbox; default-src 'none'; frame-ancestors 'none'",
"X-Frame-Options": "DENY",
} as const;
function inertRefusal(): Response {
return new Response("Not found", { status: 404, headers: INERT_REFUSAL_HEADERS });
}
function carriesOAuthReturn(url: string): boolean {
const params = new URL(url).searchParams;
return OAUTH_RETURN_PARAMS.some((name) => params.has(name));
}
/** Register before any other middleware: the refusal replaces whatever headers the others add. */
export function refuseStrayRequestsInertly(app: Hono): void {
app.use(async function refuseStrayRequest(c, next) {
if (carriesOAuthReturn(c.req.url)) return inertRefusal();
await next();
if (c.res.status !== 404) return;
// Clear first: assigning over an existing response would carry its headers across.
c.res = undefined;
c.res = inertRefusal();
});
}