mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 07:50:13 +00:00
* wip: paused before review * test: cover credential files on the preview routes and the deploy notice * refactor: name the inspector's file lookup for what it serves * fix(cli): a link to a private file outside the project keeps its own left-out reason * fix: escape the upload notice and skip private files from old manifests
826 lines
32 KiB
TypeScript
826 lines
32 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
mkdirSync,
|
|
mkdtempSync,
|
|
rmSync,
|
|
symlinkSync,
|
|
writeFileSync,
|
|
type ReadStream,
|
|
} from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import fs from "node:fs";
|
|
import { get, Server } from "node:http";
|
|
import { syncBuiltinESMExports } from "node:module";
|
|
import {
|
|
inProcessAnswer,
|
|
serveStaticProjectHtml,
|
|
type StaticProjectServer,
|
|
} from "./staticProjectServer.js";
|
|
import { injectMediaCodecMapIntoHtml } from "@hyperframes/studio-server/media-proxy-preview";
|
|
import { MAX_OPEN_MEDIA_RANGE_BYTES } from "@hyperframes/studio-server";
|
|
|
|
// `serveStaticProjectHtml` reaches these two studio-server helpers via a
|
|
// absolute module regardless of which file's relative specifier reaches it).
|
|
//
|
|
// The error class lives inside this `vi.hoisted` block (not a plain top-level
|
|
// `class`) because `vi.mock` factories run during static-import resolution —
|
|
// before any of this file's own top-level statements execute — so a `class`
|
|
// declared below would still be in its temporal dead zone.
|
|
const mocks = vi.hoisted(() => {
|
|
class FakeProxyTranscodeError extends Error {
|
|
readonly exitCode: number | null;
|
|
readonly stderrTail: string;
|
|
constructor(message: string, exitCode: number | null = null, stderrTail = "") {
|
|
super(message);
|
|
this.name = "ProxyTranscodeError";
|
|
this.exitCode = exitCode;
|
|
this.stderrTail = stderrTail;
|
|
}
|
|
}
|
|
class FakeProxyCapacityError extends FakeProxyTranscodeError {
|
|
constructor(message = "media proxy queue is full") {
|
|
super(message);
|
|
this.name = "ProxyCapacityError";
|
|
}
|
|
}
|
|
return {
|
|
resolveProxy: vi.fn<
|
|
(
|
|
projectDir: string,
|
|
absoluteSourcePath: string,
|
|
variant?: string,
|
|
box?: unknown,
|
|
options?: { signal?: AbortSignal },
|
|
) => Promise<string>
|
|
>(
|
|
// Benign default so `injectMediaCodecMap`'s fire-and-forget pre-warm
|
|
// (called for every hostile map entry) always gets a promise to
|
|
// `.catch()`, even in tests that don't care about the proxy path.
|
|
async () => "/unused-prewarm-proxy-path",
|
|
),
|
|
scanProjectMediaCodecMap: vi.fn<
|
|
(
|
|
...args: unknown[]
|
|
) => Promise<
|
|
Record<
|
|
string,
|
|
{ codecName: string; browserHostile: boolean; representativeMime: string | null }
|
|
>
|
|
>
|
|
>(async () => ({})),
|
|
probeAssetCodec: vi.fn(async () => ({
|
|
codecName: "hevc",
|
|
hasAlpha: false,
|
|
browserHostile: true,
|
|
representativeMime: null,
|
|
})),
|
|
decideMediaProxyEligibility: vi.fn<
|
|
() => { eligible: true } | { eligible: false; reason: "browser_safe_codec" }
|
|
>(() => ({ eligible: true })),
|
|
ProxyTranscodeError: FakeProxyTranscodeError,
|
|
ProxyCapacityError: FakeProxyCapacityError,
|
|
};
|
|
});
|
|
const FakeProxyTranscodeError = mocks.ProxyTranscodeError;
|
|
|
|
vi.mock("@hyperframes/studio-server/proxy-transcoder", () => ({
|
|
resolveProxy: mocks.resolveProxy,
|
|
ProxyTranscodeError: mocks.ProxyTranscodeError,
|
|
ProxyCapacityError: mocks.ProxyCapacityError,
|
|
}));
|
|
|
|
vi.mock("@hyperframes/studio-server/media-codec-map", () => ({
|
|
probeAssetCodec: mocks.probeAssetCodec,
|
|
decideMediaProxyEligibility: mocks.decideMediaProxyEligibility,
|
|
isProxyVariant: (value: string) => value === "h264" || value === "vp8",
|
|
isProxyVariantRequest: (value: string) => value === "auto" || value === "h264" || value === "vp8",
|
|
recordProxyRequest: () => {},
|
|
proxyVariantFor: (facts: { hasAlpha?: boolean }) => (facts.hasAlpha ? "vp8" : "h264"),
|
|
resolveProxyVariantRequest: (request: "auto" | "h264" | "vp8", facts: { hasAlpha?: boolean }) => {
|
|
const expected = facts.hasAlpha ? "vp8" : "h264";
|
|
return request === "auto" || request === expected ? expected : null;
|
|
},
|
|
PROXY_VARIANT_CONFIG: {
|
|
h264: { extension: ".mp4", contentType: "video/mp4" },
|
|
vp8: { extension: ".webm", contentType: "video/webm" },
|
|
},
|
|
}));
|
|
|
|
// The shared injection helper ships as a self-contained dist bundle (its copy
|
|
// of scanProjectMediaCodecMap is inlined), so it must be mocked wholesale —
|
|
// mocking the media-codec-map subpath can't reach inside it. The fake mirrors
|
|
// the real contract (scan → inject tag) via this file's scan mock so the
|
|
// injection assertions stay meaningful. Mirrors commands/play.test.ts.
|
|
vi.mock("@hyperframes/studio-server/media-proxy-preview", () => ({
|
|
injectMediaCodecMapIntoHtml: vi.fn(
|
|
async (html: string, projectDir: string, htmlSources: unknown[]) => {
|
|
const map = await mocks.scanProjectMediaCodecMap(projectDir, htmlSources);
|
|
const tag = `<script data-hf-media-codec-map>window.__HF_MEDIA_CODEC_MAP__=${JSON.stringify(map)};</script>`;
|
|
return html.includes("</head>")
|
|
? html.replace("</head>", `${tag}\n</head>`)
|
|
: `${tag}\n${html}`;
|
|
},
|
|
),
|
|
}));
|
|
|
|
let server: StaticProjectServer | undefined;
|
|
let dir: string | undefined;
|
|
|
|
afterEach(async () => {
|
|
await server?.close();
|
|
server = undefined;
|
|
if (dir) rmSync(dir, { recursive: true, force: true });
|
|
dir = undefined;
|
|
mocks.resolveProxy.mockReset();
|
|
mocks.resolveProxy.mockResolvedValue("/unused-prewarm-proxy-path");
|
|
mocks.scanProjectMediaCodecMap.mockReset();
|
|
mocks.scanProjectMediaCodecMap.mockResolvedValue({});
|
|
mocks.probeAssetCodec.mockClear();
|
|
mocks.decideMediaProxyEligibility.mockClear();
|
|
mocks.decideMediaProxyEligibility.mockReturnValue({ eligible: true });
|
|
});
|
|
|
|
const TAGGED_PNG = Buffer.from(
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGNJQ1ABAQABlXPCVgAAAAxJREFUeJxj0NfXBwABHgCOTp25kgAAAABJRU5ErkJggg==",
|
|
"base64",
|
|
);
|
|
|
|
async function serveWith(bytes: Buffer, name = "tone.wav"): Promise<{ url: string }> {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-"));
|
|
writeFileSync(join(dir, name), bytes);
|
|
server = await serveStaticProjectHtml(dir, "<html></html>");
|
|
return { url: server.url };
|
|
}
|
|
|
|
describe("serveStaticProjectHtml colour-tagged PNGs", () => {
|
|
it("serves a BT.709-tagged PNG without the tag, so check and snapshot see the file's values", async () => {
|
|
const { url } = await serveWith(TAGGED_PNG, "tagged.png");
|
|
|
|
const res = await fetch(`${url}tagged.png`);
|
|
const body = Buffer.from(await res.arrayBuffer());
|
|
|
|
expect(body.includes("cICP")).toBe(false);
|
|
expect(body.includes("IDAT")).toBe(true);
|
|
expect(res.headers.get("content-length")).toBe(String(body.length));
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml content types", () => {
|
|
it("tells the browser not to sniff a type, so an image cannot load as a script or stylesheet", async () => {
|
|
const { url } = await serveWith(Buffer.from("window.ran = true;"), "scene.png");
|
|
for (const path of ["", "scene.png", "missing.js"]) {
|
|
const response = await fetch(`${url}${path}`);
|
|
expect(response.headers.get("x-content-type-options"), path).toBe("nosniff");
|
|
}
|
|
expect((await fetch(`${url}scene.png`)).headers.get("content-type")).toBe("image/png");
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml range support", () => {
|
|
it("answers a Range request with 206 + the requested byte slice", async () => {
|
|
// Chromium needs byte-range seekability or WAV `.duration` reports Infinity,
|
|
// which makes `hyperframes validate` falsely warn it cannot read the duration.
|
|
const body = Buffer.from("0123456789", "utf-8");
|
|
const { url } = await serveWith(body);
|
|
|
|
const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=2-5" } });
|
|
expect(res.status).toBe(206);
|
|
expect(res.headers.get("accept-ranges")).toBe("bytes");
|
|
expect(res.headers.get("content-range")).toBe(`bytes 2-5/${body.length}`);
|
|
expect(await res.text()).toBe("2345");
|
|
});
|
|
|
|
it("advertises Accept-Ranges even on a full 200 response", async () => {
|
|
const { url } = await serveWith(Buffer.from("abcdef", "utf-8"));
|
|
const res = await fetch(`${url}tone.wav`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get("accept-ranges")).toBe("bytes");
|
|
expect(await res.text()).toBe("abcdef");
|
|
});
|
|
|
|
it.each([undefined, "invalid", "items=0-1"])(
|
|
"serves an empty asset with Range %j and keeps serving the project",
|
|
async (range) => {
|
|
const { url } = await serveWith(Buffer.alloc(0));
|
|
const res = await fetch(`${url}tone.wav`, {
|
|
headers: range === undefined ? {} : { Range: range },
|
|
signal: AbortSignal.timeout(1500),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get("content-length")).toBe("0");
|
|
expect(res.headers.get("accept-ranges")).toBe("bytes");
|
|
expect(res.headers.get("content-range")).toBeNull();
|
|
expect(await res.text()).toBe("");
|
|
const project = await fetch(url);
|
|
expect(project.status).toBe(200);
|
|
expect(await project.text()).toContain("<html></html>");
|
|
},
|
|
);
|
|
|
|
it.each(["bytes=0-", "bytes=0-0", "bytes=-1"])(
|
|
"rejects the unsatisfiable range %s on an empty asset",
|
|
async (range) => {
|
|
const { url } = await serveWith(Buffer.alloc(0));
|
|
const res = await fetch(`${url}tone.wav`, { headers: { Range: range } });
|
|
expect(res.status).toBe(416);
|
|
expect(res.headers.get("content-range")).toBe("bytes */0");
|
|
expect(await res.text()).toBe("");
|
|
},
|
|
);
|
|
|
|
it("streams a small slice out of a large file without buffering the whole thing", async () => {
|
|
// 8MB file, ask for 4 bytes deep inside it. The handler must createReadStream
|
|
// the [start,end] window only, not readFileSync the whole 8MB and slice.
|
|
const size = 8 * 1024 * 1024;
|
|
const big = Buffer.alloc(size, 0x61); // 'a' everywhere...
|
|
big.write("WXYZ", 5_000_000); // ...except a 4-byte marker
|
|
const { url } = await serveWith(big);
|
|
|
|
const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=5000000-5000003" } });
|
|
expect(res.status).toBe(206);
|
|
expect(res.headers.get("content-range")).toBe(`bytes 5000000-5000003/${size}`);
|
|
expect(res.headers.get("content-length")).toBe("4");
|
|
expect(await res.text()).toBe("WXYZ");
|
|
});
|
|
|
|
it("returns 416 for an unsatisfiable range", async () => {
|
|
const body = Buffer.from("abc", "utf-8");
|
|
const { url } = await serveWith(body);
|
|
const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=99-200" } });
|
|
expect(res.status).toBe(416);
|
|
expect(res.headers.get("content-range")).toBe(`bytes */${body.length}`);
|
|
});
|
|
|
|
it("answers an open-ended media range with a bounded piece, not the rest of the file", async () => {
|
|
// A media element reads `bytes=N-` until its buffer is full, then leaves the response open.
|
|
// Served to EOF, each <video> held one of Chrome's six connections, so seven clips on one
|
|
// file left every other request queued and `hyperframes check` hung (#6029).
|
|
const size = 8 * 1024 * 1024;
|
|
const { url } = await serveWith(Buffer.alloc(size, 0x61), "clip.mp4");
|
|
const res = await fetch(`${url}clip.mp4`, { headers: { Range: "bytes=1000-" } });
|
|
expect(res.status).toBe(206);
|
|
expect(res.headers.get("content-range")).toBe(
|
|
`bytes 1000-${1000 + MAX_OPEN_MEDIA_RANGE_BYTES - 1}/${size}`,
|
|
);
|
|
expect(res.headers.get("content-length")).toBe(String(MAX_OPEN_MEDIA_RANGE_BYTES));
|
|
expect((await res.arrayBuffer()).byteLength).toBe(MAX_OPEN_MEDIA_RANGE_BYTES);
|
|
});
|
|
|
|
it("serves an open-ended media range to EOF when the rest is under one piece", async () => {
|
|
const { url } = await serveWith(Buffer.from("0123456789", "utf-8"), "clip.mp4");
|
|
const res = await fetch(`${url}clip.mp4`, { headers: { Range: "bytes=2-" } });
|
|
expect(res.status).toBe(206);
|
|
expect(res.headers.get("content-range")).toBe("bytes 2-9/10");
|
|
expect(await res.text()).toBe("23456789");
|
|
});
|
|
|
|
it("serves an open-ended range of a file that isn't media to EOF", async () => {
|
|
const size = 8 * 1024 * 1024;
|
|
const { url } = await serveWith(Buffer.alloc(size, 0x61), "data.bin");
|
|
const res = await fetch(`${url}data.bin`, { headers: { Range: "bytes=1000-" } });
|
|
expect(res.status).toBe(206);
|
|
expect(res.headers.get("content-range")).toBe(`bytes 1000-${size - 1}/${size}`);
|
|
expect((await res.arrayBuffer()).byteLength).toBe(size - 1000);
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml asset stream lifetime", () => {
|
|
it.each([
|
|
{ label: "full", range: undefined, proxy: false },
|
|
{ label: "open-ended range", range: "bytes=1048576-", proxy: false },
|
|
{ label: "bounded range", range: "bytes=0-16777215", proxy: false },
|
|
{ label: "proxy", range: undefined, proxy: true },
|
|
])("closes a $label asset when its client disconnects", async ({ range, proxy }) => {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-disconnect-"));
|
|
const assetPath = join(dir, "large.mp4");
|
|
writeFileSync(assetPath, "x");
|
|
fs.truncateSync(assetPath, 32 * 1024 * 1024);
|
|
mocks.resolveProxy.mockResolvedValue(assetPath);
|
|
server = await serveStaticProjectHtml(dir, "<html></html>");
|
|
|
|
const createStream = fs.createReadStream;
|
|
const streams: ReadStream[] = [];
|
|
const spy = vi.spyOn(fs, "createReadStream").mockImplementation((...args) => {
|
|
const stream = createStream(...args);
|
|
streams.push(stream);
|
|
return stream;
|
|
});
|
|
syncBuiltinESMExports();
|
|
|
|
try {
|
|
const status = await new Promise<number | undefined>((resolve, reject) => {
|
|
const req = get(
|
|
`${server?.url}large.mp4${proxy ? "?hf-proxy=h264" : ""}`,
|
|
{ headers: range ? { Range: range } : {} },
|
|
(response) => {
|
|
response.on("data", () => {
|
|
response.destroy();
|
|
req.destroy();
|
|
resolve(response.statusCode);
|
|
});
|
|
response.on("error", reject);
|
|
},
|
|
);
|
|
req.on("error", reject);
|
|
});
|
|
|
|
expect(status).toBe(range ? 206 : 200);
|
|
expect(streams).toHaveLength(1);
|
|
await expect.poll(() => streams[0]?.closed, { timeout: 1500, interval: 10 }).toBe(true);
|
|
expect(streams[0]?.destroyed).toBe(true);
|
|
expect((await fetch(server.url)).status).toBe(200);
|
|
} finally {
|
|
await Promise.all(
|
|
streams.map(
|
|
(stream) =>
|
|
new Promise<void>((resolve) => {
|
|
if (stream.closed) resolve();
|
|
else {
|
|
stream.once("close", resolve);
|
|
stream.destroy();
|
|
}
|
|
}),
|
|
),
|
|
);
|
|
spy.mockRestore();
|
|
syncBuiltinESMExports();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml asset roots", () => {
|
|
const extraDirs: string[] = [];
|
|
const mk = (): string => {
|
|
const d = mkdtempSync(join(tmpdir(), "hf-static-root-"));
|
|
extraDirs.push(d);
|
|
return d;
|
|
};
|
|
afterEach(() => {
|
|
for (const d of extraDirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
|
});
|
|
|
|
it("serves files from an extra asset root when the project dir lacks them", async () => {
|
|
// extra root (e.g. localized-assets temp dir) resolves same-origin
|
|
const projectDir = mk();
|
|
const assetDir = mk();
|
|
mkdirSync(join(assetDir, "_remote_media"), { recursive: true });
|
|
writeFileSync(join(assetDir, "_remote_media", "img.jpg"), "PIXELS");
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>", undefined, [assetDir]);
|
|
|
|
const res = await fetch(`${server.url}_remote_media/img.jpg`);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.text()).toBe("PIXELS");
|
|
});
|
|
|
|
it("labels the page and its scripts UTF-8 so text without a meta charset is not misread", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "scene.js"), 'document.title = "太阳系";');
|
|
server = await serveStaticProjectHtml(projectDir, "<h1>太阳系科普动画</h1>");
|
|
|
|
const page = await fetch(server.url);
|
|
const script = await fetch(`${server.url}scene.js`);
|
|
expect(page.headers.get("content-type")).toBe("text/html; charset=utf-8");
|
|
expect(script.headers.get("content-type")).toBe("text/javascript; charset=utf-8");
|
|
});
|
|
|
|
it("prefers the project dir over an asset root for the same path", async () => {
|
|
const projectDir = mk();
|
|
const assetDir = mk();
|
|
writeFileSync(join(projectDir, "a.txt"), "PROJECT");
|
|
writeFileSync(join(assetDir, "a.txt"), "ASSET");
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>", undefined, [assetDir]);
|
|
|
|
const res = await fetch(`${server.url}a.txt`);
|
|
expect(await res.text()).toBe("PROJECT");
|
|
});
|
|
|
|
it("serves a file whose name has a bare percent sign", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "100%.png"), "PERCENT");
|
|
writeFileSync(join(projectDir, "50% off.png"), "SALE");
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>", undefined, []);
|
|
|
|
const bare = await fetch(`${server.url}100%.png`);
|
|
expect(bare.status).toBe(200);
|
|
expect(await bare.text()).toBe("PERCENT");
|
|
expect(await (await fetch(`${server.url}50%%20off.png`)).text()).toBe("SALE");
|
|
});
|
|
|
|
it("404s a path present in no root", async () => {
|
|
const projectDir = mk();
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>", undefined, [mk()]);
|
|
const res = await fetch(`${server.url}nope.txt`);
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml transparent media proxies", () => {
|
|
const dirs: string[] = [];
|
|
const mk = (): string => {
|
|
const d = mkdtempSync(join(tmpdir(), "hf-static-proxy-"));
|
|
dirs.push(d);
|
|
return d;
|
|
};
|
|
afterEach(() => {
|
|
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
|
});
|
|
|
|
it("injects __HF_MEDIA_CODEC_MAP__ into the served HTML", async () => {
|
|
mocks.scanProjectMediaCodecMap.mockResolvedValue({
|
|
"/clip.mp4": { codecName: "hevc", browserHostile: true, representativeMime: null },
|
|
});
|
|
const projectDir = mk();
|
|
server = await serveStaticProjectHtml(projectDir, "<html><head></head><body></body></html>");
|
|
|
|
const res = await fetch(server.url);
|
|
const html = await res.text();
|
|
expect(html).toContain("__HF_MEDIA_CODEC_MAP__");
|
|
expect(html).toContain("/clip.mp4");
|
|
});
|
|
|
|
it("lets an explicit proxy override win over hyperframes.json", async () => {
|
|
mocks.scanProjectMediaCodecMap.mockResolvedValue({
|
|
"/clip.mp4": { codecName: "hevc", browserHostile: true, representativeMime: null },
|
|
});
|
|
const projectDir = mk();
|
|
writeFileSync(
|
|
join(projectDir, "hyperframes.json"),
|
|
JSON.stringify({ media: { autoProxy: false } }),
|
|
);
|
|
server = await serveStaticProjectHtml(
|
|
projectDir,
|
|
"<html><head></head><body></body></html>",
|
|
undefined,
|
|
[],
|
|
true,
|
|
);
|
|
|
|
const html = await (await fetch(server.url)).text();
|
|
expect(html).toContain("__HF_MEDIA_CODEC_MAP__");
|
|
});
|
|
|
|
it("lets an explicit --no-proxy override suppress config-enabled proxying", async () => {
|
|
mocks.scanProjectMediaCodecMap.mockResolvedValue({
|
|
"/clip.mp4": { codecName: "hevc", browserHostile: true, representativeMime: null },
|
|
});
|
|
const projectDir = mk();
|
|
server = await serveStaticProjectHtml(
|
|
projectDir,
|
|
"<html><head></head><body></body></html>",
|
|
undefined,
|
|
[],
|
|
false,
|
|
);
|
|
|
|
const html = await (await fetch(server.url)).text();
|
|
expect(html).not.toContain("__HF_MEDIA_CODEC_MAP__");
|
|
expect(mocks.scanProjectMediaCodecMap).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("serves the resolved proxy's bytes for ?hf-proxy=h264 on a hostile video asset", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
const proxyPath = join(projectDir, "proxy.mp4");
|
|
writeFileSync(proxyPath, "transcoded-h264-bytes");
|
|
mocks.resolveProxy.mockResolvedValue(proxyPath);
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.mp4?hf-proxy=h264`);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.text()).toBe("transcoded-h264-bytes");
|
|
expect(mocks.resolveProxy).toHaveBeenCalledWith(
|
|
projectDir,
|
|
join(projectDir, "clip.mp4"),
|
|
"h264",
|
|
undefined,
|
|
{ signal: expect.any(AbortSignal) },
|
|
);
|
|
});
|
|
|
|
it("pre-warms the copy the page will ask for, not the source-size one", async () => {
|
|
const projectDir = mk();
|
|
const html =
|
|
'<html><body><div data-composition-id="root" data-width="1920" data-height="1080"></div></body></html>';
|
|
const { injectMediaCodecMapIntoHtml } =
|
|
await import("@hyperframes/studio-server/media-proxy-preview");
|
|
|
|
server = await serveStaticProjectHtml(projectDir, html);
|
|
|
|
expect(injectMediaCodecMapIntoHtml).toHaveBeenLastCalledWith(
|
|
html,
|
|
projectDir,
|
|
[{ html }],
|
|
undefined,
|
|
true,
|
|
expect.any(AbortSignal),
|
|
{ width: 2048, height: 1218 },
|
|
);
|
|
});
|
|
|
|
it("resolves the copy named by hf-proxy-box, the one check made before the page opened", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
const proxyPath = join(projectDir, "proxy.mp4");
|
|
writeFileSync(proxyPath, "boxed-h264-bytes");
|
|
mocks.resolveProxy.mockResolvedValue(proxyPath);
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.mp4?hf-proxy=h264&hf-proxy-box=2048x1448`);
|
|
|
|
expect(await res.text()).toBe("boxed-h264-bytes");
|
|
expect(mocks.resolveProxy).toHaveBeenCalledWith(
|
|
projectDir,
|
|
join(projectDir, "clip.mp4"),
|
|
"h264",
|
|
{ width: 2048, height: 1448 },
|
|
{ signal: expect.any(AbortSignal) },
|
|
);
|
|
});
|
|
|
|
it.each(["clip.mp4?hf-proxy=h264&hf-proxy-box=1000x1000", "clip.mp4?hf-proxy-box=2048x1448"])(
|
|
"answers 404 without a copy for %s, as the Studio preview does",
|
|
async (path) => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
expect((await fetch(`${server.url}${path}`)).status).toBe(404);
|
|
expect(mocks.resolveProxy).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it.each(["mxf", "mts", "m2ts", "ts", "mkv", "m4v"])(
|
|
"serves a proxy for .%s camera/container media",
|
|
async (extension) => {
|
|
const projectDir = mk();
|
|
const sourcePath = join(projectDir, `clip.${extension}`);
|
|
writeFileSync(sourcePath, "original-hostile-bytes");
|
|
const proxyPath = join(projectDir, "proxy.mp4");
|
|
writeFileSync(proxyPath, "transcoded-h264-bytes");
|
|
mocks.resolveProxy.mockResolvedValue(proxyPath);
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.${extension}?hf-proxy=h264`);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.text()).toBe("transcoded-h264-bytes");
|
|
expect(mocks.resolveProxy).toHaveBeenCalledWith(projectDir, sourcePath, "h264", undefined, {
|
|
signal: expect.any(AbortSignal),
|
|
});
|
|
},
|
|
);
|
|
|
|
it("serves an alpha-bearing video through a VP8 WebM proxy", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mov"), "prores-4444-alpha-bytes");
|
|
mocks.probeAssetCodec.mockResolvedValueOnce({
|
|
codecName: "prores",
|
|
hasAlpha: true,
|
|
browserHostile: true,
|
|
representativeMime: null,
|
|
});
|
|
const proxyPath = join(projectDir, "proxy.webm");
|
|
writeFileSync(proxyPath, "vp8-alpha-proxy");
|
|
mocks.resolveProxy.mockResolvedValueOnce(proxyPath);
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.mov?hf-proxy=auto`);
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get("content-type")).toBe("video/webm");
|
|
expect(mocks.probeAssetCodec).toHaveBeenCalledWith(join(projectDir, "clip.mov"));
|
|
expect(mocks.resolveProxy).toHaveBeenCalledWith(
|
|
projectDir,
|
|
join(projectDir, "clip.mov"),
|
|
"vp8",
|
|
undefined,
|
|
{ signal: expect.any(AbortSignal) },
|
|
);
|
|
});
|
|
|
|
it("answers 502 when the proxy transcode fails", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
mocks.resolveProxy.mockRejectedValue(
|
|
new FakeProxyTranscodeError("ffmpeg exited with code 1", 1),
|
|
);
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.mp4?hf-proxy=h264`);
|
|
expect(res.status).toBe(502);
|
|
});
|
|
|
|
it("answers a retryable 503 when the proxy queue is full", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
mocks.resolveProxy.mockRejectedValue(new mocks.ProxyCapacityError());
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}clip.mp4?hf-proxy=h264`);
|
|
expect(res.status).toBe(503);
|
|
expect(res.headers.get("retry-after")).toBe("1");
|
|
});
|
|
|
|
it("404s ?hf-proxy=h264 for a non-video asset without attempting a transcode", async () => {
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "image.png"), "not-a-video");
|
|
server = await serveStaticProjectHtml(projectDir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}image.png?hf-proxy=h264`);
|
|
expect(res.status).toBe(404);
|
|
expect(mocks.resolveProxy).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("stops the copies it started, pre-warmed or asked for, when it closes", async () => {
|
|
mocks.scanProjectMediaCodecMap.mockResolvedValue({
|
|
"/clip.mp4": { codecName: "hevc", browserHostile: true, representativeMime: null },
|
|
});
|
|
const projectDir = mk();
|
|
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
|
|
let asked: AbortSignal | undefined;
|
|
mocks.resolveProxy.mockImplementation(
|
|
(_dir, _path, _variant, _box, options) =>
|
|
new Promise((_resolve, reject) => {
|
|
asked = options?.signal;
|
|
asked?.addEventListener("abort", () => reject(asked?.reason));
|
|
}),
|
|
);
|
|
const closing = await serveStaticProjectHtml(projectDir, "<html><head></head></html>");
|
|
const held = fetch(`${closing.url}clip.mp4?hf-proxy=h264`);
|
|
await vi.waitFor(() => expect(asked).toBeDefined());
|
|
const injected = vi.mocked(injectMediaCodecMapIntoHtml).mock.calls.at(-1) as unknown[];
|
|
const prewarms = injected[5] as AbortSignal | undefined;
|
|
|
|
await closing.close();
|
|
|
|
expect(prewarms?.aborted).toBe(true);
|
|
expect(asked?.aborted).toBe(true);
|
|
expect((await held).status).toBe(500);
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml when a sandbox refuses listen()", () => {
|
|
const refuse = (code: string) =>
|
|
vi.spyOn(Server.prototype, "listen").mockImplementation(function (this: Server) {
|
|
process.nextTick(() =>
|
|
this.emit("error", Object.assign(new Error(`listen ${code}`), { code })),
|
|
);
|
|
return this;
|
|
});
|
|
|
|
afterEach(() => vi.restoreAllMocks());
|
|
|
|
it("answers the project in this process, Range included, with nothing listening", async () => {
|
|
const listen = refuse("EPERM");
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-"));
|
|
writeFileSync(join(dir, "tone.wav"), Buffer.from("0123456789", "utf-8"));
|
|
server = await serveStaticProjectHtml(dir, "<html><body>composition</body></html>");
|
|
|
|
expect(listen).toHaveBeenCalledOnce();
|
|
expect(server.port).toBe(0);
|
|
expect(inProcessAnswer(server.url)).toBe(server.answer);
|
|
const page = await server.answer!({ method: "GET", path: "/", headers: {} });
|
|
expect(page.status).toBe(200);
|
|
expect(page.body.toString()).toContain("composition");
|
|
const slice = await server.answer!({
|
|
method: "GET",
|
|
path: "/tone.wav",
|
|
headers: { range: "bytes=2-5" },
|
|
});
|
|
expect(slice.status).toBe(206);
|
|
expect(slice.headers["content-range"]).toBe("bytes 2-5/10");
|
|
expect(slice.body.toString()).toBe("2345");
|
|
expect(
|
|
(await server.answer!({ method: "GET", path: "/missing.png", headers: {} })).status,
|
|
).toBe(404);
|
|
|
|
const url = server.url;
|
|
await server.close();
|
|
server = undefined;
|
|
expect(inProcessAnswer(url)).toBeUndefined();
|
|
});
|
|
|
|
it("still fails on a bind error that is not a refusal", async () => {
|
|
refuse("EADDRINUSE");
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-"));
|
|
await expect(serveStaticProjectHtml(dir, "<html></html>")).rejects.toMatchObject({
|
|
code: "EADDRINUSE",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("serveStaticProjectHtml private project files", () => {
|
|
it.each([".env", ".env.local", ".git/config", "%2egit/config"])(
|
|
"answers %s with 404",
|
|
async (requestPath) => {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-private-"));
|
|
mkdirSync(join(dir, ".git"));
|
|
writeFileSync(join(dir, ".env"), "SECRET=1");
|
|
writeFileSync(join(dir, ".env.local"), "SECRET=1");
|
|
writeFileSync(join(dir, ".git", "config"), "SECRET=1");
|
|
writeFileSync(join(dir, "asset.txt"), "ok");
|
|
server = await serveStaticProjectHtml(dir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}${requestPath}`);
|
|
expect(res.status).toBe(404);
|
|
expect(await res.text()).not.toContain("SECRET");
|
|
expect((await fetch(`${server.url}asset.txt`)).status).toBe(200);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("serveStaticProjectHtml credential files", () => {
|
|
it.each([".npmrc", ".mcp.json", ".claude/x.json", ".aws/credentials", "id_ed25519", "cert.pem"])(
|
|
"answers %s with 404",
|
|
async (requestPath) => {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-credentials-"));
|
|
for (const folder of [".claude", ".aws"]) mkdirSync(join(dir, folder));
|
|
for (const file of [".npmrc", ".mcp.json", ".claude/x.json", ".aws/credentials"]) {
|
|
writeFileSync(join(dir, file), "SECRET=1");
|
|
}
|
|
writeFileSync(join(dir, "id_ed25519"), "SECRET=1");
|
|
writeFileSync(join(dir, "cert.pem"), "SECRET=1");
|
|
writeFileSync(join(dir, "asset.txt"), "ok");
|
|
server = await serveStaticProjectHtml(dir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}${requestPath}`);
|
|
expect(res.status).toBe(404);
|
|
expect(await res.text()).not.toContain("SECRET");
|
|
expect((await fetch(`${server.url}asset.txt`)).status).toBe(200);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("serveStaticProjectHtml page another site loads", () => {
|
|
const MARK = '<meta name="hyperframes-preview-for-another-site">';
|
|
const SANDBOX = "sandbox allow-scripts";
|
|
|
|
async function serveProject(): Promise<string> {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-site-"));
|
|
writeFileSync(join(dir, "scene.html"), "<html><head></head><body>scene</body></html>");
|
|
server = await serveStaticProjectHtml(
|
|
dir,
|
|
"<html><head></head><body>composition</body></html>",
|
|
);
|
|
return server.url;
|
|
}
|
|
|
|
it.each(["", "scene.html"])(
|
|
"marks and sandboxes /%s when another site frames it",
|
|
async (path) => {
|
|
const url = await serveProject();
|
|
const res = await fetch(`${url}${path}`, {
|
|
headers: { "Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "iframe" },
|
|
});
|
|
expect(res.status).toBe(200);
|
|
expect(await res.text()).toContain(MARK);
|
|
expect(res.headers.get("content-security-policy")).toContain(SANDBOX);
|
|
},
|
|
);
|
|
|
|
it.each(["none", "same-origin"])(
|
|
"leaves the capture page unmarked for Sec-Fetch-Site %s",
|
|
async (site) => {
|
|
const url = await serveProject();
|
|
for (const path of ["", "scene.html"]) {
|
|
const res = await fetch(`${url}${path}`, { headers: { "Sec-Fetch-Site": site } });
|
|
expect(await res.text(), path).not.toContain(MARK);
|
|
expect(res.headers.get("content-security-policy"), path).not.toContain(SANDBOX);
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
function writeToolRecords(projectDir: string): void {
|
|
mkdirSync(join(projectDir, ".hyperframes", "prepared-assets"), { recursive: true });
|
|
for (const name of ["app-history.jsonl", "agent-handoff.json", "comments.jsonl"]) {
|
|
writeFileSync(join(projectDir, ".hyperframes", name), "PRIVATE_RECORD");
|
|
}
|
|
writeFileSync(join(projectDir, ".hyperframes", "prepared-assets", "clip.txt"), "prepared");
|
|
symlinkSync(
|
|
join(projectDir, ".hyperframes", "app-history.jsonl"),
|
|
join(projectDir, "linked-history.json"),
|
|
);
|
|
}
|
|
|
|
describe("serveStaticProjectHtml tool records", () => {
|
|
it.each([
|
|
".hyperframes/app-history.jsonl",
|
|
".hyperframes/agent-handoff.json",
|
|
".hyperframes/comments.jsonl",
|
|
"%2ehyperframes/agent-handoff.json",
|
|
".hyperframes%2fcomments.jsonl",
|
|
"linked-history.json",
|
|
])("answers %s with 404 and still serves prepared assets", async (requestPath) => {
|
|
dir = mkdtempSync(join(tmpdir(), "hf-static-records-"));
|
|
writeToolRecords(dir);
|
|
server = await serveStaticProjectHtml(dir, "<html></html>");
|
|
|
|
const res = await fetch(`${server.url}${requestPath}`);
|
|
expect(res.status).toBe(404);
|
|
expect(await res.text()).not.toContain("PRIVATE_RECORD");
|
|
const prepared = await fetch(`${server.url}.hyperframes/prepared-assets/clip.txt`);
|
|
expect(await prepared.text()).toBe("prepared");
|
|
});
|
|
});
|