From f0964019b082f94a3f0400390c1f3a06464012c6 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 14:33:47 -0800 Subject: [PATCH 01/29] fix(cli): a subfolder of an imported project keeps its received-files record Publish, cloud render and feedback now read the received-files record at the nearest folder at or above the one they stage, so staging a subfolder of an imported project still leaves out the outside files its received files reference. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/utils/privateProjectFile.ts | 51 ++++++++++++++----- .../utils/publishProject.absolutePath.test.ts | 19 +++++++ 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 0059aa4ac71..eb30be708c1 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -1,5 +1,5 @@ -import { readFileSync } from "node:fs"; -import { join, relative } from "node:path"; +import { readFileSync, realpathSync } from "node:fs"; +import { dirname, join, relative, resolve, sep } from "node:path"; import { isEnvOrGitPath, isPrivateOutsideFile, @@ -13,18 +13,45 @@ export function linksToPrivateOutsideFile(projectDir: string, filePath: string): return linksOutside(projectDir, filePath) && isPrivateOutsideFile(projectDir, filePath); } -export function receivedFiles(projectDir: string): (path: string) => boolean { - let listed: unknown; +const RECEIVED_RECORD = join(".hyperframes", "received-files.json"); + +interface ReceivedRecord { + root: string; + projectDirFromRoot: string; + listed: unknown; +} + +function nearestReceivedRecordAtOrAbove(projectDir: string): ReceivedRecord | null { + let start: string; try { - listed = JSON.parse( - readFileSync(join(projectDir, ".hyperframes", "received-files.json"), "utf-8"), - ).files; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return () => false; + start = realpathSync(projectDir); + } catch { + start = resolve(projectDir); } - if (!Array.isArray(listed)) return () => true; - const files = new Set(listed.map((path) => String(path).normalize("NFC"))); - return (path) => files.has(path.normalize("NFC")); + for (let dir = start; ; ) { + const projectDirFromRoot = relative(dir, start).split(sep).join("/"); + try { + const listed: unknown = JSON.parse(readFileSync(join(dir, RECEIVED_RECORD), "utf-8")).files; + return { root: dir, projectDirFromRoot, listed }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "ENOENT" && code !== "ENOTDIR") + return { root: dir, projectDirFromRoot, listed: undefined }; + } + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } +} + +export function receivedFiles(projectDir: string): (path: string) => boolean { + const record = nearestReceivedRecordAtOrAbove(projectDir); + if (!record) return () => false; + if (!Array.isArray(record.listed)) return () => true; + const files = new Set(record.listed.map((path) => String(path).normalize("NFC"))); + const keyOf = (path: string) => + (record.projectDirFromRoot ? `${record.projectDirFromRoot}/${path}` : path).normalize("NFC"); + return (path) => files.has(keyOf(path)); } /** Project files no composition loads, so none is served or uploaded for one: env files, Git data, tool records. */ diff --git a/packages/cli/src/utils/publishProject.absolutePath.test.ts b/packages/cli/src/utils/publishProject.absolutePath.test.ts index a1439ae5637..4b288676dc1 100644 --- a/packages/cli/src/utils/publishProject.absolutePath.test.ts +++ b/packages/cli/src/utils/publishProject.absolutePath.test.ts @@ -417,6 +417,25 @@ describe("outside references in files that came in with an imported project", () expect(staged.get("index.html")!.toString()).toContain("file://"); }); + it("leaves out a received file's outside reference when only its subfolder is staged", () => { + const { root } = stageReceived( + { + "index.html": "", + "sub/index.html": ``, + "sub/mine.html": ``, + }, + { files: ["index.html", "sub/index.html"] }, + ); + const warnings: string[] = []; + const staged = stagePublishFiles(join(root, "p", "sub"), Infinity, (w) => warnings.push(w)); + expect([...staged.keys()].filter((key) => key.startsWith("_ext/"))).toEqual([ + "_ext/shared/logo.png", + ]); + expect(warnings).toEqual([ + "index.html references ../../shared/logo.png, which leads outside the project and came in with an imported project; it was left out of the upload.", + ]); + }); + it("treats every file as received when the record cannot be read", () => { const { ext, warnings } = stageReceived( { "index.html": `` }, From 4f0af2b3d46ef6d7cd7b8ce5ce6638e62090c106 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 14:34:25 -0800 Subject: [PATCH 02/29] fix(cli): a received file counts under any spelling of the same file on disk The received-files lookup now also matches a project file that is the same file on disk as a listed path, so a name respelled in letter case on a case-insensitive disk keeps its received status. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/utils/privateProjectFile.ts | 24 ++++++++++++++++--- .../utils/publishProject.absolutePath.test.ts | 12 +++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index eb30be708c1..239e85243fa 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -1,4 +1,4 @@ -import { readFileSync, realpathSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync } from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; import { isEnvOrGitPath, @@ -44,14 +44,32 @@ function nearestReceivedRecordAtOrAbove(projectDir: string): ReceivedRecord | nu } } +function fileIdentity(path: string): string | null { + try { + const stat = lstatSync(path, { bigint: true }); + return `${stat.dev}:${stat.ino}`; + } catch { + return null; + } +} + export function receivedFiles(projectDir: string): (path: string) => boolean { const record = nearestReceivedRecordAtOrAbove(projectDir); if (!record) return () => false; if (!Array.isArray(record.listed)) return () => true; - const files = new Set(record.listed.map((path) => String(path).normalize("NFC"))); + const listed = record.listed.map((path) => String(path).normalize("NFC")); + const files = new Set(listed); const keyOf = (path: string) => (record.projectDirFromRoot ? `${record.projectDirFromRoot}/${path}` : path).normalize("NFC"); - return (path) => files.has(keyOf(path)); + let listedOnDisk: Set | undefined; + const sameFileAsListed = (path: string) => { + listedOnDisk ??= new Set( + listed.flatMap((entry) => fileIdentity(join(record.root, entry)) ?? []), + ); + const identity = fileIdentity(join(projectDir, path)); + return identity !== null && listedOnDisk.has(identity); + }; + return (path) => files.has(keyOf(path)) || sameFileAsListed(path); } /** Project files no composition loads, so none is served or uploaded for one: env files, Git data, tool records. */ diff --git a/packages/cli/src/utils/publishProject.absolutePath.test.ts b/packages/cli/src/utils/publishProject.absolutePath.test.ts index 4b288676dc1..27783a6da7e 100644 --- a/packages/cli/src/utils/publishProject.absolutePath.test.ts +++ b/packages/cli/src/utils/publishProject.absolutePath.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, dirname, join, relative } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -436,6 +436,16 @@ describe("outside references in files that came in with an imported project", () ]); }); + it("matches a listed file under another spelling of the same file on disk", () => { + const { root, ext, warnings } = stageReceived( + { "index.html": "", "assets/a.html": `` }, + { files: ["index.html", "Assets/a.html"] }, + ); + const caseInsensitive = existsSync(join(root, "p", "ASSETS", "a.html")); + expect(ext).toEqual(caseInsensitive ? [] : ["_ext/shared/logo.png"]); + expect(warnings).toHaveLength(caseInsensitive ? 1 : 0); + }); + it("treats every file as received when the record cannot be read", () => { const { ext, warnings } = stageReceived( { "index.html": `` }, From 740be08134cfe4e27c431d608b25a66a816d3025 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 14:36:51 -0800 Subject: [PATCH 03/29] fix(cli): cloud render prepares only the GIFs staging kept The entry GIF prep before a cloud render upload now reads only the staged copies it is handed. An image whose source staging left out keeps its reference as written and is never read from disk. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/cloud/offload.test.ts | 57 ++++++++++++++++++++++++++ packages/cli/src/cloud/offload.ts | 2 + 2 files changed, 59 insertions(+) diff --git a/packages/cli/src/cloud/offload.test.ts b/packages/cli/src/cloud/offload.test.ts index f515e222f77..b3963052035 100644 --- a/packages/cli/src/cloud/offload.test.ts +++ b/packages/cli/src/cloud/offload.test.ts @@ -503,6 +503,63 @@ describe("offloadHeavyMedia", () => { expect(fileMap.get("index.html")!.toString()).toContain(``); }); + it("prepares only staged GIFs, never one staging left out", async () => { + const root = mkdtempSync(join(tmpdir(), "hf-offload-test-")); + dirs.push(root); + const frame = [0x21, 0xf9, 4, 0, 5, 0, 0, 0, 0x2c, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x4c, 1, 0]; + const animated = Buffer.from([ + ...Buffer.from("GIF89a"), + 1, + 0, + 1, + 0, + 0, + 0, + 0, + ...frame, + ...frame, + 0x3b, + ]); + mkdirSync(join(root, "outside")); + writeFileSync(join(root, "outside", "clip.gif"), animated); + const dir = join(root, "p"); + mkdirSync(join(dir, "media"), { recursive: true }); + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(join(dir, "media", "loop.gif"), Buffer.concat([animated, HEAVY])); + writeFileSync( + join(dir, "index.html"), + html(``), + ); + writeFileSync( + join(dir, ".hyperframes", "received-files.json"), + JSON.stringify({ files: ["index.html"] }), + ); + const { prepareAnimatedGifInputs } = await import("@hyperframes/producer"); + const transcoded: string[] = []; + const gifPrep: GifPrep = (input, options) => + prepareAnimatedGifInputs(input, { + ...options, + cacheDir: options.outputDir, + transcode: async (request) => { + transcoded.push( + readFileSync(request.inputPath).length === animated.length ? "outside" : "staged", + ); + writeFileSync(request.outputPath, honest(".webm")); + }, + }); + const fileMap = stagePublishFiles(dir, Infinity); + + await offloadHeavyMedia(dir, fileMap, { + apiBaseUrl: "https://api.example", + gifPrep, + reencoder: { choose: async () => null, run: vi.fn() }, + cachePath: cachePath(), + }); + + expect(transcoded).toEqual(["staged"]); + expect(fileMap.get("index.html")!.toString()).toContain(`src="../outside/clip.gif"`); + }); + it("offloads the video the renderer's GIF prep makes from an entry GIF, and drops the GIF", async () => { const dir = project({ "index.html": html(``), diff --git a/packages/cli/src/cloud/offload.ts b/packages/cli/src/cloud/offload.ts index cb9952135d2..5ebe370042d 100644 --- a/packages/cli/src/cloud/offload.ts +++ b/packages/cli/src/cloud/offload.ts @@ -172,6 +172,7 @@ export type GifPrep = ( outputSrcPrefix: string; cacheDir: string; sourceAssets: Map; + assetRoot: string; }, ) => Promise<{ html: string; preparedGifs: Array<{ sourceSrc: string; outputPath: string }> }>; @@ -740,6 +741,7 @@ async function prepareEntryGifs( outputSrcPrefix: posix.relative(posix.dirname(entryPath), GIF_PREFIX), cacheDir: hyperframesCacheDir("animated-gif"), sourceAssets, + assetRoot: outputDir, }); if (result.preparedGifs.length === 0) return; fileMap.set(entryPath, Buffer.from(result.html, "utf-8")); From 31fb585faf8e68d7c7c05ef876870d9fc15f75e5 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 14:41:48 -0800 Subject: [PATCH 04/29] fix(cli,studio-server): never hand a playlist named as media to ffmpeg A media file whose first bytes are an HLS playlist, an XML manifest or a concat script now stays out of ffprobe and ffmpeg: cloud render leaves it in the zip as authored, the media probe reports it as not media, and the proxy copy refuses it. Real media never starts with these bytes, so it probes and transcodes as before. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/cloud/offload.test.ts | 26 +++++++++++++++++++ packages/cli/src/cloud/offload.ts | 10 +++++-- .../src/helpers/mediaExtensions.ts | 9 +++++++ .../src/helpers/mediaMetadata.test.ts | 21 +++++++++++++++ .../src/helpers/mediaMetadata.ts | 18 +++++++++++++ .../studio-server/src/helpers/outsideFile.ts | 9 +++++-- .../src/helpers/proxyTranscoder.ts | 2 ++ 7 files changed, 91 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/cloud/offload.test.ts b/packages/cli/src/cloud/offload.test.ts index b3963052035..9dabe115eb3 100644 --- a/packages/cli/src/cloud/offload.test.ts +++ b/packages/cli/src/cloud/offload.test.ts @@ -372,6 +372,32 @@ describe("offloadHeavyMedia", () => { }); }); + it.each([ + ["an HLS playlist", "#EXTM3U\n#EXT-X-TARGETDURATION:10\n"], + ["a DASH manifest", ''], + ["a concat script", "ffconcat version 1.0\nfile clip.mp4\n"], + ])("leaves %s named as media in the zip without probing it", async (_name, text) => { + const playlist = Buffer.concat([Buffer.from(text), Buffer.alloc(OFFLOAD_MIN_BYTES, 0x20)]); + const dir = project({ + "index.html": html(``), + "clip.mp4": playlist, + }); + const reencoder: Reencoder = { hasVideo: vi.fn(), choose: vi.fn(), run: vi.fn() }; + const fileMap = buildPublishFileMap(dir); + + const report = await offloadHeavyMedia(dir, fileMap, { + apiBaseUrl: "https://api.example", + upload: fakeUpload(), + reencoder, + cachePath: cachePath(), + }); + + expect(report).toEqual([]); + expect(reencoder.hasVideo).not.toHaveBeenCalled(); + expect(reencoder.choose).not.toHaveBeenCalled(); + expect(fileMap.has("clip.mp4")).toBe(true); + }); + it("treats an audio-only MP4 named .mp4 as audio, whatever brand its ftyp box has", async () => { const audioOnly = Buffer.concat([ HEADERS[".mp4"]!, diff --git a/packages/cli/src/cloud/offload.ts b/packages/cli/src/cloud/offload.ts index 5ebe370042d..7073b85c132 100644 --- a/packages/cli/src/cloud/offload.ts +++ b/packages/cli/src/cloud/offload.ts @@ -36,6 +36,7 @@ import { bytesMatchExtension } from "./offloadSniff.js"; import { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, + startsAsMediaPlaylist, VIDEO_EXTS, } from "@hyperframes/studio-server/outside-file"; import { type PlayedSegment, planTrim } from "./offloadTrim.js"; @@ -603,14 +604,19 @@ function readHead(file: StagedFile): Buffer { } } +function mediaFileKind(path: string, file: StagedFile): MediaKind | null { + const kind = mediaKind(path); + return kind && !startsAsMediaPlaylist(readHead(file)) ? kind : null; +} + async function planFile( ctx: OffloadContext, path: string, file: StagedFile, ): Promise { - let kind = mediaKind(path); const size = stagedSize(file); - if (!kind || size < OFFLOAD_MIN_BYTES) return null; + let kind = size < OFFLOAD_MIN_BYTES ? null : mediaFileKind(path, file); + if (!kind) return null; const ext = extname(path).toLowerCase(); const accepted = ACCEPTED[ext]; // The API reads the stored bytes, not the name: a file whose bytes differ from its extension is re-encoded. diff --git a/packages/studio-server/src/helpers/mediaExtensions.ts b/packages/studio-server/src/helpers/mediaExtensions.ts index 643fce00643..cbba19d9891 100644 --- a/packages/studio-server/src/helpers/mediaExtensions.ts +++ b/packages/studio-server/src/helpers/mediaExtensions.ts @@ -30,3 +30,12 @@ export const AUDIO_EXTS = new Set([ ]); // Still images the API refuses; converted to PNG unless animated. export const CONVERTIBLE_IMAGE_EXTS = new Set([".gif", ".avif", ".bmp", ".tif", ".tiff"]); + +export const NOT_MEDIA = "not a media file"; + +const PLAYLIST_START = /^(?:\xEF\xBB\xBF)?\s*(?:#EXTM3U|ffconcat|<)/; +const isControlByte = (byte: number) => byte < 0x09 || (byte > 0x0d && byte < 0x20); + +export function startsAsMediaPlaylist(head: Buffer): boolean { + return PLAYLIST_START.test(head.toString("latin1")) && !head.some(isControlByte); +} diff --git a/packages/studio-server/src/helpers/mediaMetadata.test.ts b/packages/studio-server/src/helpers/mediaMetadata.test.ts index 11ef87356e0..d51714742bc 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.test.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.test.ts @@ -1,4 +1,8 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { NOT_MEDIA } from "./mediaExtensions.js"; import { classifyMediaColor, probeMediaMetadata } from "./mediaMetadata.js"; afterEach(() => vi.unstubAllEnvs()); @@ -247,6 +251,23 @@ describe("probeMediaMetadata", () => { }); }); + it.each([ + ["an HLS playlist", "#EXTM3U\n#EXT-X-TARGETDURATION:10\n/elsewhere/clip.mp4\n"], + ["a DASH manifest", '\uFEFF\n'], + ["a concat script", "ffconcat version 1.0\nfile clip.mp4\n"], + ])("never hands %s named as a video to ffprobe", async (_name, text) => { + const dir = mkdtempSync(join(tmpdir(), "hf-media-metadata-")); + try { + writeFileSync(join(dir, "clip.mp4"), text); + const runner = vi.fn(); + const metadata = await probeMediaMetadata(join(dir, "clip.mp4"), runner); + expect(metadata).toMatchObject({ kind: "video", probeError: NOT_MEDIA }); + expect(runner).not.toHaveBeenCalled(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it("supports an injected async runner without requiring local ffprobe", async () => { vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", "/definitely/missing/ffprobe"); const metadata = await probeMediaMetadata("/tmp/clip.mp4", async () => ({ diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 2e05dc93402..51c01e3a091 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -1,4 +1,5 @@ import { execFile } from "node:child_process"; +import { closeSync, openSync, readSync } from "node:fs"; import { extname } from "node:path"; import { firstFrameColourArgs, @@ -10,6 +11,7 @@ import { type ToneMapFrameColour, } from "@hyperframes/core"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; +import { NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; import { videoStreamHasAlpha } from "@hyperframes/parsers/media-alpha"; import { decodableAudioStream, type FfprobeStreamCodec } from "@hyperframes/parsers/media-streams"; @@ -313,6 +315,19 @@ export async function probeAudioTrack( return stream === null ? null : { stream, channels: streams[stream]?.channels ?? 0 }; } +function readsAsMediaPlaylist(filePath: string): boolean { + let fd: number | undefined; + try { + fd = openSync(filePath, "r"); + const head = Buffer.alloc(64); + return startsAsMediaPlaylist(head.subarray(0, readSync(fd, head, 0, head.length, 0))); + } catch { + return false; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + export async function probeMediaMetadata( filePath: string, runner: FfprobeRunner = execFileRunner, @@ -321,6 +336,9 @@ export async function probeMediaMetadata( if (kind === "audio" || kind === "unknown") { return { kind, color: classifyMediaColor(null) }; } + if (readsAsMediaPlaylist(filePath)) { + return { kind, color: classifyMediaColor(null), probeError: NOT_MEDIA }; + } // The default runner degrades a missing ffprobe to "unavailable" without // spawning; injected runners own execution and receive the normal command. diff --git a/packages/studio-server/src/helpers/outsideFile.ts b/packages/studio-server/src/helpers/outsideFile.ts index 1c0729bb43e..10dfaef96ff 100644 --- a/packages/studio-server/src/helpers/outsideFile.ts +++ b/packages/studio-server/src/helpers/outsideFile.ts @@ -1,10 +1,15 @@ import { homedir } from "node:os"; import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"; import { MIME_TYPES } from "./mime.js"; -import { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, VIDEO_EXTS } from "./mediaExtensions.js"; +import { + AUDIO_EXTS, + CONVERTIBLE_IMAGE_EXTS, + startsAsMediaPlaylist, + VIDEO_EXTS, +} from "./mediaExtensions.js"; import { realFilePath } from "./safePath.js"; -export { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, VIDEO_EXTS }; +export { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, startsAsMediaPlaylist, VIDEO_EXTS }; const COPIED_TYPE = /^(?:image|video|audio|font)\/|^text\/(?:css|javascript);/; diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index 559bcc2219e..0e64a8bba4a 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -15,6 +15,7 @@ import { hdrToSdrToneMapFilter, type PreviewProxyBox } from "@hyperframes/core"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { alphaDecoderFor } from "@hyperframes/parsers/media-alpha"; import { ffmpegHasHdrFilters } from "./hdrFilters.js"; +import { NOT_MEDIA } from "./mediaExtensions.js"; import { probeFirstFrameColour, probeMediaMetadata } from "./mediaMetadata.js"; import { cleanupProxyCache } from "./proxyCache.js"; import { @@ -731,6 +732,7 @@ async function runFfmpeg( isBackground: () => boolean = () => false, ): Promise { const metadata = await probeMediaMetadata(sourcePath); + if (metadata.probeError === NOT_MEDIA) throw new ProxyTranscodeError(NOT_MEDIA, null, ""); const ffmpegPath = findFfBinary("ffmpeg", { configuredMustExist: true }); if (!ffmpegPath) { throw new FfmpegUnavailableError(); From a2abe2256f32405c181913f86009e7c68ac22c39 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:08:10 -0800 Subject: [PATCH 05/29] fix(studio-server): catch playlists with control bytes, and keep them from stills and audio probes A text playlist or concat script is detected whatever bytes follow its first line; only markup must be all text. A still frame and the audio probe behind waveforms, peaks and loudness now refuse a file the probe reads as not media, as the proxy copy already does. Co-Authored-By: Claude Opus 5.5 --- .../src/helpers/mediaExtensions.ts | 6 ++-- .../src/helpers/mediaMetadata.test.ts | 34 +++++++++++++++++-- .../src/helpers/mediaMetadata.ts | 27 ++++++++------- .../src/helpers/proxyTranscoder.test.ts | 15 ++++++++ .../src/helpers/proxyTranscoder.ts | 10 ++---- 5 files changed, 68 insertions(+), 24 deletions(-) diff --git a/packages/studio-server/src/helpers/mediaExtensions.ts b/packages/studio-server/src/helpers/mediaExtensions.ts index cbba19d9891..16847fadfb5 100644 --- a/packages/studio-server/src/helpers/mediaExtensions.ts +++ b/packages/studio-server/src/helpers/mediaExtensions.ts @@ -33,9 +33,11 @@ export const CONVERTIBLE_IMAGE_EXTS = new Set([".gif", ".avif", ".bmp", ".tif", export const NOT_MEDIA = "not a media file"; -const PLAYLIST_START = /^(?:\xEF\xBB\xBF)?\s*(?:#EXTM3U|ffconcat|<)/; +const PLAYLIST_START = /^(?:\xEF\xBB\xBF)?\s*(?:#EXTM3U|ffconcat)/; +const MARKUP_START = /^(?:\xEF\xBB\xBF)?\s* byte < 0x09 || (byte > 0x0d && byte < 0x20); export function startsAsMediaPlaylist(head: Buffer): boolean { - return PLAYLIST_START.test(head.toString("latin1")) && !head.some(isControlByte); + const text = head.toString("latin1"); + return PLAYLIST_START.test(text) || (MARKUP_START.test(text) && !head.some(isControlByte)); } diff --git a/packages/studio-server/src/helpers/mediaMetadata.test.ts b/packages/studio-server/src/helpers/mediaMetadata.test.ts index d51714742bc..09f65bf9fdd 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.test.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { NOT_MEDIA } from "./mediaExtensions.js"; -import { classifyMediaColor, probeMediaMetadata } from "./mediaMetadata.js"; +import { NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; +import { classifyMediaColor, probeAudioTrack, probeMediaMetadata } from "./mediaMetadata.js"; afterEach(() => vi.unstubAllEnvs()); @@ -280,3 +280,33 @@ describe("probeMediaMetadata", () => { expect(metadata).toMatchObject({ kind: "video", color: { codecName: "h264" } }); }); }); + +describe("startsAsMediaPlaylist", () => { + it.each([ + [ + "a concat script with a control byte in a comment", + "ffconcat version 1.0\n#\u0001\nfile seg.ts", + true, + ], + ["an HLS playlist with a control byte", "#EXTM3U\n\u0002", true], + ["markup", '', true], + ["binary that starts with <", "<\u0000\u0001\u0002binary", false], + ["an MP4 header", "\u0000\u0000\u0000\u0018ftypisom", false], + ])("reads %s as %s", (_name, text, playlist) => { + expect(startsAsMediaPlaylist(Buffer.from(text, "latin1"))).toBe(playlist); + }); +}); + +describe("probeAudioTrack", () => { + it("never hands a playlist named as audio to ffprobe", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-media-metadata-")); + try { + writeFileSync(join(dir, "song.mp3"), "#EXTM3U\n#EXT-X-TARGETDURATION:10\n/elsewhere.mp3\n"); + const runner = vi.fn(); + expect(await probeAudioTrack(join(dir, "song.mp3"), runner)).toBeNull(); + expect(runner).not.toHaveBeenCalled(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 51c01e3a091..d3b58ab5c78 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -292,10 +292,24 @@ function metadataFromProbe(kind: MediaMetadata["kind"], parsed: ProbeOutput): Me } /** The audio track ffmpeg can decode in a file, with its channel count; null when it has none. */ +function readsAsMediaPlaylist(filePath: string): boolean { + let fd: number | undefined; + try { + fd = openSync(filePath, "r"); + const head = Buffer.alloc(64); + return startsAsMediaPlaylist(head.subarray(0, readSync(fd, head, 0, head.length, 0))); + } catch { + return false; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + export async function probeAudioTrack( filePath: string, runner: FfprobeRunner = execFileRunner, ): Promise<{ stream: number; channels: number } | null> { + if (readsAsMediaPlaylist(filePath)) return null; const ffprobePath = findFfBinary("ffprobe", { configuredMustExist: true }) ?? (runner === execFileRunner ? undefined : "ffprobe"); @@ -315,19 +329,6 @@ export async function probeAudioTrack( return stream === null ? null : { stream, channels: streams[stream]?.channels ?? 0 }; } -function readsAsMediaPlaylist(filePath: string): boolean { - let fd: number | undefined; - try { - fd = openSync(filePath, "r"); - const head = Buffer.alloc(64); - return startsAsMediaPlaylist(head.subarray(0, readSync(fd, head, 0, head.length, 0))); - } catch { - return false; - } finally { - if (fd !== undefined) closeSync(fd); - } -} - export async function probeMediaMetadata( filePath: string, runner: FfprobeRunner = execFileRunner, diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.ts index 6cf66981659..47b6c5865af 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts @@ -1994,6 +1994,21 @@ describe("resolveProxy", () => { describe("resolveStill", () => { const canStill = Boolean(realFfmpeg) && Boolean(findFfBinary("ffprobe")); + it("refuses a playlist named as a video without running ffmpeg", async () => { + const { spawn, calls } = createSpawnSpy(); + vi.resetModules(); + vi.doMock("node:child_process", () => ({ spawn, default: { spawn } })); + vi.doMock("@hyperframes/parsers/ff-binaries", () => ({ findFfBinary: () => FFMPEG_PATH })); + vi.doUnmock("./mediaMetadata.js"); + const { resolveStill } = await import("./proxyTranscoder.js"); + const projectDir = tmpProject(); + const clip = join(projectDir, "clip.mp4"); + writeFileSync(clip, "ffconcat version 1.0\n#\u0001\nfile seg.ts\n"); + + await expect(resolveStill(projectDir, clip, 1)).rejects.toThrow("not a media file"); + expect(calls).toHaveLength(0); + }); + it.skipIf(!canStill)( "cuts one JPEG at the asked time and reuses it for the same tenth of a second", async () => { diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index 0e64a8bba4a..c4e0bf63783 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -1175,13 +1175,9 @@ async function makeStill( ): Promise { const ffmpegPath = findFfBinary("ffmpeg", { configuredMustExist: true }); if (!ffmpegPath) throw new FfmpegUnavailableError(); - const filter = await buildVideoFilter( - ffmpegPath, - source.sourcePath, - await probeMediaMetadata(source.sourcePath), - false, - box, - ); + const metadata = await probeMediaMetadata(source.sourcePath); + if (metadata.probeError === NOT_MEDIA) throw new ProxyTranscodeError(NOT_MEDIA, null, ""); + const filter = await buildVideoFilter(ffmpegPath, source.sourcePath, metadata, false, box); mkdirWithinProject(source.projectDir, dirname(cachePath)); const tempPath = join(dirname(cachePath), `.tmp-${randomUUID()}-${basename(cachePath)}`); try { From cc513441c4f448eff5bc49808ddeab4681d7820b Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:08:49 -0800 Subject: [PATCH 06/29] fix(cli): a parent folder's state the CLI cannot read never marks a project received The walk up for a received-files record now skips a parent whose record cannot be reached. Only a record file that is there but cannot be read or parsed counts every file as received. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/utils/privateProjectFile.ts | 36 +++++++++++----- .../utils/publishProject.absolutePath.test.ts | 43 ++++++++++++++++++- 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 239e85243fa..dffba67a0e7 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -1,4 +1,4 @@ -import { lstatSync, readFileSync, realpathSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs"; import { dirname, join, relative, resolve, sep } from "node:path"; import { isEnvOrGitPath, @@ -21,6 +21,24 @@ interface ReceivedRecord { listed: unknown; } +function recordFileAt(dir: string): boolean { + try { + return statSync(join(dir, RECEIVED_RECORD)).isFile(); + } catch { + return false; + } +} + +function readRecord(dir: string, ownFolder: boolean): { listed: unknown } | null { + if (!ownFolder && !recordFileAt(dir)) return null; + try { + return { listed: JSON.parse(readFileSync(join(dir, RECEIVED_RECORD), "utf-8")).files }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + return ownFolder && (code === "ENOENT" || code === "ENOTDIR") ? null : { listed: undefined }; + } +} + function nearestReceivedRecordAtOrAbove(projectDir: string): ReceivedRecord | null { let start: string; try { @@ -29,15 +47,13 @@ function nearestReceivedRecordAtOrAbove(projectDir: string): ReceivedRecord | nu start = resolve(projectDir); } for (let dir = start; ; ) { - const projectDirFromRoot = relative(dir, start).split(sep).join("/"); - try { - const listed: unknown = JSON.parse(readFileSync(join(dir, RECEIVED_RECORD), "utf-8")).files; - return { root: dir, projectDirFromRoot, listed }; - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code !== "ENOENT" && code !== "ENOTDIR") - return { root: dir, projectDirFromRoot, listed: undefined }; - } + const record = readRecord(dir, dir === start); + if (record) + return { + root: dir, + projectDirFromRoot: relative(dir, start).split(sep).join("/"), + ...record, + }; const parent = dirname(dir); if (parent === dir) return null; dir = parent; diff --git a/packages/cli/src/utils/publishProject.absolutePath.test.ts b/packages/cli/src/utils/publishProject.absolutePath.test.ts index 27783a6da7e..c5a23eeb049 100644 --- a/packages/cli/src/utils/publishProject.absolutePath.test.ts +++ b/packages/cli/src/utils/publishProject.absolutePath.test.ts @@ -1,4 +1,12 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { basename, dirname, join, relative } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -436,6 +444,39 @@ describe("outside references in files that came in with an imported project", () ]); }); + it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( + "skips a parent folder whose state it cannot read, and still copies the person's reference", + () => { + const root = temp(); + mkdirSync(join(root, "shared")); + writeFileSync(join(root, "shared", "logo.png"), "png"); + mkdirSync(join(root, ".hyperframes")); + mkdirSync(join(root, "p")); + writeFileSync(join(root, "p", "index.html"), ``); + chmodSync(join(root, ".hyperframes"), 0o000); + try { + const staged = stagePublishFiles(join(root, "p"), Infinity); + expect([...staged.keys()].filter((key) => key.startsWith("_ext/"))).toEqual([ + "_ext/shared/logo.png", + ]); + } finally { + chmodSync(join(root, ".hyperframes"), 0o755); + } + }, + ); + + it("counts every file received below a parent whose record cannot be parsed", () => { + const root = temp(); + mkdirSync(join(root, "shared")); + writeFileSync(join(root, "shared", "logo.png"), "png"); + mkdirSync(join(root, ".hyperframes")); + writeFileSync(join(root, ".hyperframes", "received-files.json"), "{oops"); + mkdirSync(join(root, "p")); + writeFileSync(join(root, "p", "index.html"), ``); + const staged = stagePublishFiles(join(root, "p"), Infinity); + expect([...staged.keys()].filter((key) => key.startsWith("_ext/"))).toEqual([]); + }); + it("matches a listed file under another spelling of the same file on disk", () => { const { root, ext, warnings } = stageReceived( { "index.html": "", "assets/a.html": `` }, From 23376662aa0572b1c52f5631ac3e271436c514db Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:09:40 -0800 Subject: [PATCH 07/29] fix(cli): a drive that reports no file ids matches no received file by identity Some network and virtual drives report a file id of 0 for every file, so the same-file match now gives such a file no identity instead of matching it to every listed file. Co-Authored-By: Claude Opus 5.5 --- .../cli/src/utils/privateProjectFile.test.ts | 33 +++++++++++++++++-- packages/cli/src/utils/privateProjectFile.ts | 2 +- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.test.ts b/packages/cli/src/utils/privateProjectFile.test.ts index 4e19cb1f362..8b084813fb4 100644 --- a/packages/cli/src/utils/privateProjectFile.test.ts +++ b/packages/cli/src/utils/privateProjectFile.test.ts @@ -1,12 +1,24 @@ -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { isEnvOrGitPath, isPrivateCompositionFile } from "./privateProjectFile.js"; +import { isEnvOrGitPath, isPrivateCompositionFile, receivedFiles } from "./privateProjectFile.js"; + +const zeroFileIds = vi.hoisted(() => ({ on: false })); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + const lstatSync = ((path: string, options?: { bigint?: boolean }) => { + const stat = actual.lstatSync(path, options as never); + return zeroFileIds.on ? Object.assign(stat, { dev: 0n, ino: 0n }) : stat; + }) as typeof actual.lstatSync; + return { ...actual, default: { ...actual, lstatSync }, lstatSync }; +}); let dir: string | undefined; afterEach(() => { + zeroFileIds.on = false; if (dir) rmSync(dir, { recursive: true, force: true }); dir = undefined; }); @@ -53,3 +65,20 @@ describe("isPrivateCompositionFile", () => { }, ); }); + +describe("receivedFiles", () => { + it("matches no file by identity on a drive that reports no file ids", () => { + dir = mkdtempSync(join(tmpdir(), "hf-received-")); + mkdirSync(join(dir, ".hyperframes")); + writeFileSync(join(dir, "theirs.html"), ""); + writeFileSync(join(dir, "mine.html"), ""); + writeFileSync( + join(dir, ".hyperframes", "received-files.json"), + JSON.stringify({ files: ["theirs.html"] }), + ); + zeroFileIds.on = true; + const received = receivedFiles(dir); + expect(received("theirs.html")).toBe(true); + expect(received("mine.html")).toBe(false); + }); +}); diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index dffba67a0e7..3431f1a0800 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -63,7 +63,7 @@ function nearestReceivedRecordAtOrAbove(projectDir: string): ReceivedRecord | nu function fileIdentity(path: string): string | null { try { const stat = lstatSync(path, { bigint: true }); - return `${stat.dev}:${stat.ino}`; + return stat.ino === 0n ? null : `${stat.dev}:${stat.ino}`; } catch { return null; } From 0e6a871edec0c68b79f12f0359c0c21f4ffd199f Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:38:12 -0800 Subject: [PATCH 08/29] refactor(studio-server): read a media file's first bytes with a read stream The playlist check reads the first 64 bytes through a bounded read stream instead of a raw file descriptor, and the audio-track probe's doc comment sits on its function again. Co-Authored-By: Claude Opus 5.5 --- .../src/helpers/mediaMetadata.ts | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index d3b58ab5c78..79c09e822ee 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -1,5 +1,5 @@ import { execFile } from "node:child_process"; -import { closeSync, openSync, readSync } from "node:fs"; +import { createReadStream } from "node:fs"; import { extname } from "node:path"; import { firstFrameColourArgs, @@ -291,25 +291,24 @@ function metadataFromProbe(kind: MediaMetadata["kind"], parsed: ProbeOutput): Me return metadata; } -/** The audio track ffmpeg can decode in a file, with its channel count; null when it has none. */ -function readsAsMediaPlaylist(filePath: string): boolean { - let fd: number | undefined; +async function readsAsMediaPlaylist(filePath: string): Promise { try { - fd = openSync(filePath, "r"); - const head = Buffer.alloc(64); - return startsAsMediaPlaylist(head.subarray(0, readSync(fd, head, 0, head.length, 0))); + const chunks: Buffer[] = []; + for await (const chunk of createReadStream(filePath, { start: 0, end: 63 })) { + chunks.push(chunk as Buffer); + } + return startsAsMediaPlaylist(Buffer.concat(chunks)); } catch { return false; - } finally { - if (fd !== undefined) closeSync(fd); } } +/** The audio track ffmpeg can decode in a file, with its channel count; null when it has none. */ export async function probeAudioTrack( filePath: string, runner: FfprobeRunner = execFileRunner, ): Promise<{ stream: number; channels: number } | null> { - if (readsAsMediaPlaylist(filePath)) return null; + if (await readsAsMediaPlaylist(filePath)) return null; const ffprobePath = findFfBinary("ffprobe", { configuredMustExist: true }) ?? (runner === execFileRunner ? undefined : "ffprobe"); @@ -337,7 +336,7 @@ export async function probeMediaMetadata( if (kind === "audio" || kind === "unknown") { return { kind, color: classifyMediaColor(null) }; } - if (readsAsMediaPlaylist(filePath)) { + if (await readsAsMediaPlaylist(filePath)) { return { kind, color: classifyMediaColor(null), probeError: NOT_MEDIA }; } From ce688c4803cdc20d557f8f3498b50ae7d8133427 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:38:28 -0800 Subject: [PATCH 09/29] chore(studio-server): raise the packed size budget for the media playlist check Main packs @hyperframes/studio-server close to the 1% tolerance on the 168500 budget, and the playlist check adds about 320 bytes, which put the Build over. Set the budget to 172000. Co-Authored-By: Claude Opus 5.5 --- scripts/package-size-budgets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index a106d8c667f..dea9bec5dda 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -56,7 +56,7 @@ "unpacked": 26703858 }, "@hyperframes/studio-server": { - "packed": 168500, + "packed": 172000, "unpacked": 654000 } } From 6ba3835bbced548e9060607c650f309550c456e9 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 15:56:36 -0800 Subject: [PATCH 10/29] fix(cli,studio-server): open media only through self-contained media demuxers Every ffprobe and ffmpeg input that cloud render offload, the publish proxy bake and Studio's media helpers open now carries a demuxer whitelist built from the supported media extensions: MP4/MOV/M4A/AVIF, Matroska/WebM, MXF, AVI, MPEG-PS/TS, FLV, ASF, Ogg, WAV, MP3, AAC, FLAC, AIFF and the still-image formats. Playlist, manifest and concat demuxers can no longer open, whatever a file's bytes say. The proxy's own concat step is left as it is. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/audio/analysis/decode.ts | 6 +- packages/cli/src/cloud/offload.test.ts | 40 +++++++++++ packages/cli/src/cloud/offload.ts | 29 ++++++-- .../src/helpers/freezeFrame.test.ts | 2 + .../studio-server/src/helpers/freezeFrame.ts | 2 + .../src/helpers/loudness.test.ts | 9 ++- .../studio-server/src/helpers/loudness.ts | 2 + .../src/helpers/mediaExtensions.test.ts | 68 +++++++++++++++++++ .../src/helpers/mediaExtensions.ts | 5 ++ .../src/helpers/mediaMetadata.test.ts | 20 +++++- .../src/helpers/mediaMetadata.ts | 37 +++++++--- .../src/helpers/mediaValidation.ts | 13 +++- .../studio-server/src/helpers/outsideFile.ts | 3 +- packages/studio-server/src/helpers/peakMap.ts | 2 + .../src/helpers/proxyTranscoder.test.ts | 4 +- .../src/helpers/proxyTranscoder.ts | 14 +++- .../studio-server/src/helpers/waveform.ts | 2 + .../src/routes/freezeFrame.test.ts | 10 ++- 18 files changed, 245 insertions(+), 23 deletions(-) create mode 100644 packages/studio-server/src/helpers/mediaExtensions.test.ts diff --git a/packages/cli/src/audio/analysis/decode.ts b/packages/cli/src/audio/analysis/decode.ts index f8ecf0f7079..319bcad1e68 100644 --- a/packages/cli/src/audio/analysis/decode.ts +++ b/packages/cli/src/audio/analysis/decode.ts @@ -25,7 +25,10 @@ function requiredBinary(name: "ffmpeg" | "ffprobe"): string { } /** The format of the audio track ffmpeg can decode, or `null` when the file has none. */ -export async function probeAudio(file: string): Promise { +export async function probeAudio( + file: string, + inputArgs: readonly string[] = [], +): Promise { const { stdout } = await run( requiredBinary("ffprobe"), [ @@ -37,6 +40,7 @@ export async function probeAudio(file: string): Promise "-show_format", "-of", "json", + ...inputArgs, "--", file, ], diff --git a/packages/cli/src/cloud/offload.test.ts b/packages/cli/src/cloud/offload.test.ts index 9dabe115eb3..749f083372d 100644 --- a/packages/cli/src/cloud/offload.test.ts +++ b/packages/cli/src/cloud/offload.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + chmodSync, createReadStream, existsSync, mkdirSync, @@ -21,6 +22,7 @@ import { type UploadableFile, } from "./offload.js"; import { bytesMatchExtension } from "./offloadSniff.js"; +import { MEDIA_INPUT_ARGS } from "@hyperframes/studio-server/outside-file"; vi.mock("node:fs", async (importOriginal) => { const actual = await importOriginal(); @@ -398,6 +400,44 @@ describe("offloadHeavyMedia", () => { expect(fileMap.has("clip.mp4")).toBe(true); }); + it.skipIf(process.platform === "win32")( + "opens media in ffprobe and ffmpeg only through the self-contained media demuxers", + async () => { + const bin = mkdtempSync(join(tmpdir(), "hf-offload-bin-")); + dirs.push(bin); + const log = join(bin, "calls.log"); + const fake = join(bin, "ff"); + writeFileSync( + fake, + [ + "#!/bin/sh", + `printf '%s\\n' "$*" >> '${log}'`, + "for last; do :; done", + 'case " $* " in *" -y "*) printf data > "$last" ;; *) printf "{}" ;; esac', + ].join("\n"), + ); + chmodSync(fake, 0o755); + vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", fake); + vi.stubEnv("HYPERFRAMES_FFMPEG_PATH", fake); + try { + const dir = project({ + "index.html": html(``), + "clip.mkv": HEAVY, + }); + await offloadHeavyMedia(dir, buildPublishFileMap(dir), { + apiBaseUrl: "https://api.example", + upload: fakeUpload(), + cachePath: cachePath(), + }).catch(() => undefined); + } finally { + vi.unstubAllEnvs(); + } + const calls = readFileSync(log, "utf8").trim().split("\n"); + expect(calls.some((call) => call.includes(" -y "))).toBe(true); + for (const call of calls) expect(call).toContain(MEDIA_INPUT_ARGS.join(" ")); + }, + ); + it("treats an audio-only MP4 named .mp4 as audio, whatever brand its ftyp box has", async () => { const audioOnly = Buffer.concat([ HEADERS[".mp4"]!, diff --git a/packages/cli/src/cloud/offload.ts b/packages/cli/src/cloud/offload.ts index 7073b85c132..163a20dfaa8 100644 --- a/packages/cli/src/cloud/offload.ts +++ b/packages/cli/src/cloud/offload.ts @@ -36,6 +36,7 @@ import { bytesMatchExtension } from "./offloadSniff.js"; import { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, + MEDIA_INPUT_ARGS, startsAsMediaPlaylist, VIDEO_EXTS, } from "@hyperframes/studio-server/outside-file"; @@ -240,6 +241,7 @@ async function probeVideo(path: string): Promise { "stream=codec_name,pix_fmt,color_primaries,color_transfer,color_space:stream_tags", "-of", "json", + ...MEDIA_INPUT_ARGS, "--", path, ]); @@ -288,10 +290,16 @@ async function segmentArgs( segments: PlayedSegment[] | undefined, media: "audio" | "image" | "video", ): Promise { - if (media === "image") return [...decoder, "-i", sourcePath]; + if (media === "image") return [...decoder, ...MEDIA_INPUT_ARGS, "-i", sourcePath]; const audio = await keptAudio(sourcePath, media); const cuts = segments?.length ? segments : [undefined]; - const inputs = cuts.flatMap((s) => [...decoder, ...seekArgs(s), "-i", sourcePath]); + const inputs = cuts.flatMap((s) => [ + ...decoder, + ...seekArgs(s), + ...MEDIA_INPUT_ARGS, + "-i", + sourcePath, + ]); const video = media === "video"; return [ ...inputs, @@ -300,7 +308,7 @@ async function segmentArgs( } async function keptAudio(sourcePath: string, media: "audio" | "video"): Promise { - const audio = (await probeAudio(sourcePath))?.audioStream ?? null; + const audio = (await probeAudio(sourcePath, MEDIA_INPUT_ARGS))?.audioStream ?? null; if (media === "audio" && audio === null) { throw new Error("the file has no audio track ffmpeg can decode"); } @@ -355,7 +363,17 @@ async function durationSeconds(sourcePath: string): Promise { const ffprobe = findFFprobe(); if (!ffprobe) return null; const { stdout } = await execFileAsync(ffprobe, [ - ...["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", "--", sourcePath], + ...[ + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + ...MEDIA_INPUT_ARGS, + "--", + sourcePath, + ], ]); const value = Number(stdout.trim()); return Number.isFinite(value) && value > 0 ? value : null; @@ -445,6 +463,7 @@ async function isAnimatedImage(path: string): Promise { "stream=nb_frames", "-of", "csv=p=0", + ...MEDIA_INPUT_ARGS, "--", path, ]); @@ -469,6 +488,7 @@ async function trimGrid(sourcePath: string, kind: MediaKind): Promise { "stream=codec_type", "-of", "csv=p=0", + ...MEDIA_INPUT_ARGS, "--", sourcePath, ]); diff --git a/packages/studio-server/src/helpers/freezeFrame.test.ts b/packages/studio-server/src/helpers/freezeFrame.test.ts index aaae1b77b55..3bf039497b6 100644 --- a/packages/studio-server/src/helpers/freezeFrame.test.ts +++ b/packages/studio-server/src/helpers/freezeFrame.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; import { parseHTML } from "linkedom"; import { applyFreezeFrameToHtml, @@ -68,6 +69,7 @@ describe("freezeExtractArgs", () => { "-y", "-ss", "7.2", + ...MEDIA_INPUT_ARGS, "-i", "/p/a.mp4", "-frames:v", diff --git a/packages/studio-server/src/helpers/freezeFrame.ts b/packages/studio-server/src/helpers/freezeFrame.ts index a7045a25b01..2f32cb20e5f 100644 --- a/packages/studio-server/src/helpers/freezeFrame.ts +++ b/packages/studio-server/src/helpers/freezeFrame.ts @@ -3,6 +3,7 @@ import { ensureHfIds } from "@hyperframes/parsers/hf-ids"; import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration"; import { resolveRateSpec, sourceTimeAt } from "@hyperframes/core/speed-ramp"; import { MEDIA_LINK_ATTR as LINK_ATTR, relinkSplitHalves } from "@hyperframes/core/media-link"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; import { findTargetElement, isHTMLElement, @@ -45,6 +46,7 @@ export function freezeExtractArgs(src: string, mediaTime: number, output: string "-y", "-ss", String(round3(mediaTime)), + ...MEDIA_INPUT_ARGS, "-i", src, "-frames:v", diff --git a/packages/studio-server/src/helpers/loudness.test.ts b/packages/studio-server/src/helpers/loudness.test.ts index fc5c6c5522f..bfaf583f247 100644 --- a/packages/studio-server/src/helpers/loudness.test.ts +++ b/packages/studio-server/src/helpers/loudness.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; import { absoluteLoudnessPlan, absoluteOutcome, @@ -36,7 +37,13 @@ describe("audioTags playback offsets", () => { expect(tag).toBeDefined(); if (!tag) throw new Error("missing video"); const args = loudnessMeasureArgs("talk.mp4", tag, 0); - expect(args.slice(args.indexOf("-ss"), args.indexOf("-i"))).toEqual(["-ss", "4", "-t", "4"]); + expect(args.slice(args.indexOf("-ss"), args.indexOf("-i"))).toEqual([ + "-ss", + "4", + "-t", + "4", + ...MEDIA_INPUT_ARGS, + ]); }); it("preserves the selected in-point when writing the matched gain", () => { diff --git a/packages/studio-server/src/helpers/loudness.ts b/packages/studio-server/src/helpers/loudness.ts index 65c8ab325ec..aeff7886231 100644 --- a/packages/studio-server/src/helpers/loudness.ts +++ b/packages/studio-server/src/helpers/loudness.ts @@ -8,6 +8,7 @@ import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { readMediaOffsetSeconds } from "@hyperframes/parsers/media-duration"; import { requestedProjectPath } from "./requestSubPath.js"; import { probeAudioTrack } from "./mediaMetadata.js"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; const execFileAsync = promisify(execFile); @@ -454,6 +455,7 @@ export function loudnessMeasureArgs(file: string, tag: MeasuredWindow, stream: n const sourceSpan = tag.duration === null ? null : tag.duration * (tag.playbackRate ?? 1); if (sourceSpan !== null && sourceSpan > 0) args.push("-t", String(sourceSpan)); args.push( + ...MEDIA_INPUT_ARGS, "-i", file, "-map", diff --git a/packages/studio-server/src/helpers/mediaExtensions.test.ts b/packages/studio-server/src/helpers/mediaExtensions.test.ts new file mode 100644 index 00000000000..04fffd3bb36 --- /dev/null +++ b/packages/studio-server/src/helpers/mediaExtensions.test.ts @@ -0,0 +1,68 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; + +const ffmpeg = findFfBinary("ffmpeg"); +const ffprobe = findFfBinary("ffprobe"); +const dir = mkdtempSync(join(tmpdir(), "hf-media-input-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +const probe = (file: string) => + spawnSync( + ffprobe!, + [ + "-v", + "error", + "-show_entries", + "format=format_name", + "-of", + "csv=p=0", + ...MEDIA_INPUT_ARGS, + "--", + file, + ], + { encoding: "utf8" }, + ); + +describe.skipIf(!ffmpeg || !ffprobe)("MEDIA_INPUT_ARGS with a real ffprobe", () => { + const video = ["-f", "lavfi", "-i", "testsrc2=s=64x36:r=10:d=1"]; + const audio = ["-f", "lavfi", "-i", "sine=d=1"]; + const make = (name: string, args: string[]) => { + execFileSync(ffmpeg!, ["-v", "error", "-y", ...args, join(dir, name)]); + return join(dir, name); + }; + + it.each([ + ["clip.mp4", [...video, "-pix_fmt", "yuv420p"]], + ["frag.mp4", [...video, "-pix_fmt", "yuv420p", "-movflags", "frag_keyframe+empty_moov"]], + ["clip.mov", [...video, "-c:v", "prores_ks"]], + ["clip.webm", [...video, "-c:v", "libvpx"]], + ["clip.ts", [...video, "-pix_fmt", "yuv420p", "-f", "mpegts"]], + ["song.wav", audio], + ["song.mp3", audio], + ["still.png", [...video, "-frames:v", "1"]], + ["still.jpg", [...video, "-frames:v", "1"]], + ["loop.gif", [...video, "-frames:v", "3"]], + ])("still reads %s", (name, args) => { + const result = probe(make(name, args as string[])); + expect(result.status, result.stderr).toBe(0); + }); + + it.each([ + ["a concat script", "list.mp4", "ffconcat version 1.0\nfile clip.mp4\n"], + [ + "an HLS playlist", + "list.m3u8", + "#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nclip.ts\n#EXT-X-ENDLIST\n", + ], + ])("never opens %s, which names other files", (_kind, name, text) => { + writeFileSync(join(dir, name), text); + const result = probe(join(dir, name)); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/not on whitelist/); + }); +}); diff --git a/packages/studio-server/src/helpers/mediaExtensions.ts b/packages/studio-server/src/helpers/mediaExtensions.ts index 16847fadfb5..5d48977f003 100644 --- a/packages/studio-server/src/helpers/mediaExtensions.ts +++ b/packages/studio-server/src/helpers/mediaExtensions.ts @@ -33,6 +33,11 @@ export const CONVERTIBLE_IMAGE_EXTS = new Set([".gif", ".avif", ".bmp", ".tif", export const NOT_MEDIA = "not a media file"; +export const MEDIA_INPUT_ARGS: readonly string[] = [ + "-format_whitelist", + "mov,matroska,mxf,avi,mpeg,mpegts,mpegvideo,flv,asf,ogg,wav,mp3,aac,flac,aiff,gif,image2,png_pipe,jpeg_pipe,webp_pipe,bmp_pipe,tiff_pipe", +]; + const PLAYLIST_START = /^(?:\xEF\xBB\xBF)?\s*(?:#EXTM3U|ffconcat)/; const MARKUP_START = /^(?:\xEF\xBB\xBF)?\s* byte < 0x09 || (byte > 0x0d && byte < 0x20); diff --git a/packages/studio-server/src/helpers/mediaMetadata.test.ts b/packages/studio-server/src/helpers/mediaMetadata.test.ts index 09f65bf9fdd..bc651131e6a 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.test.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; +import { MEDIA_INPUT_ARGS, NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; import { classifyMediaColor, probeAudioTrack, probeMediaMetadata } from "./mediaMetadata.js"; afterEach(() => vi.unstubAllEnvs()); @@ -310,3 +310,21 @@ describe("probeAudioTrack", () => { } }); }); + +describe("the media probes", () => { + it("hand ffprobe only the self-contained media demuxers", async () => { + vi.stubEnv("HYPERFRAMES_FFPROBE_PATH", "/definitely/missing/ffprobe"); + const seen: string[][] = []; + const runner = async (_command: string, args: string[]) => { + seen.push(args); + return { status: 0, stdout: "{}", stderr: "" }; + }; + await probeMediaMetadata("/tmp/missing-clip.mp4", runner); + await probeAudioTrack("/tmp/missing-song.mp3", runner); + expect(seen).toHaveLength(2); + for (const args of seen) { + const at = args.indexOf("--"); + expect(args.slice(at - MEDIA_INPUT_ARGS.length, at)).toEqual(MEDIA_INPUT_ARGS); + } + }); +}); diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 79c09e822ee..455af43f284 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -11,7 +11,7 @@ import { type ToneMapFrameColour, } from "@hyperframes/core"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; -import { NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; +import { MEDIA_INPUT_ARGS, NOT_MEDIA, startsAsMediaPlaylist } from "./mediaExtensions.js"; import { videoStreamHasAlpha } from "@hyperframes/parsers/media-alpha"; import { decodableAudioStream, type FfprobeStreamCodec } from "@hyperframes/parsers/media-streams"; @@ -202,16 +202,24 @@ export async function probeFirstFrameColour( findFfBinary("ffmpeg", { configuredMustExist: true }) ?? (runner === execFileRunner ? undefined : "ffmpeg"); if (!ffmpegPath) return {}; - const result = await runner(ffmpegPath, firstFrameColourArgs(filePath), { - timeout: 15_000, - maxBuffer: 1024 * 1024, - }); + const result = await runner( + ffmpegPath, + [...MEDIA_INPUT_ARGS, ...firstFrameColourArgs(filePath)], + { + timeout: 15_000, + maxBuffer: 1024 * 1024, + }, + ); const first = result.status === 0 ? parseFirstFrameColour(String(result.stderr)) : {}; if (result.status !== 0 || !readsKeyframeTransfers(first)) return first; - const keyframes = await runner(ffmpegPath, keyframeTransferArgs(filePath, codec), { - timeout: 30_000, - maxBuffer: 8 * 1024 * 1024, - }); + const keyframes = await runner( + ffmpegPath, + [...MEDIA_INPUT_ARGS, ...keyframeTransferArgs(filePath, codec)], + { + timeout: 30_000, + maxBuffer: 8 * 1024 * 1024, + }, + ); const keyframeTransfers = keyframes.status === 0 ? parseKeyframeTransfers(String(keyframes.stderr)) : []; return { ...first, keyframeTransfers }; @@ -317,7 +325,15 @@ export async function probeAudioTrack( ffprobePath, [ ...["-v", "error", "-select_streams", "a"], - ...["-show_entries", "stream=codec_type,codec_name,channels", "-of", "json", "--", filePath], + ...[ + "-show_entries", + "stream=codec_type,codec_name,channels", + "-of", + "json", + ...MEDIA_INPUT_ARGS, + "--", + filePath, + ], ], { timeout: 30_000 }, ); @@ -358,6 +374,7 @@ export async function probeMediaMetadata( "stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate:stream_disposition:stream_tags=alpha_mode:format=duration,bit_rate", "-of", "json", + ...MEDIA_INPUT_ARGS, "--", filePath, ], diff --git a/packages/studio-server/src/helpers/mediaValidation.ts b/packages/studio-server/src/helpers/mediaValidation.ts index 5c5562b9d21..ce8fa90b64e 100644 --- a/packages/studio-server/src/helpers/mediaValidation.ts +++ b/packages/studio-server/src/helpers/mediaValidation.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import { FFPROBE_PATH_ENV, findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { decodableAudioStream, type FfprobeStreamCodec } from "@hyperframes/parsers/media-streams"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; const VIDEO_EXT = /\.(mp4|webm|mov|mkv|avi|m4v|mxf|mts|m2ts|ts)$/i; const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac|flac)$/i; @@ -39,7 +40,17 @@ export function validateUploadedMedia( if (!ffprobe) return { ok: true, unchecked: FFPROBE_MISSING }; const result = runner( ffprobe, - ["-v", "error", "-show_entries", "stream=codec_type,codec_name", "-of", "json", "--", filePath], + [ + "-v", + "error", + "-show_entries", + "stream=codec_type,codec_name", + "-of", + "json", + ...MEDIA_INPUT_ARGS, + "--", + filePath, + ], { windowsHide: true }, ); diff --git a/packages/studio-server/src/helpers/outsideFile.ts b/packages/studio-server/src/helpers/outsideFile.ts index 10dfaef96ff..9f262f5ebbf 100644 --- a/packages/studio-server/src/helpers/outsideFile.ts +++ b/packages/studio-server/src/helpers/outsideFile.ts @@ -4,12 +4,13 @@ import { MIME_TYPES } from "./mime.js"; import { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, + MEDIA_INPUT_ARGS, startsAsMediaPlaylist, VIDEO_EXTS, } from "./mediaExtensions.js"; import { realFilePath } from "./safePath.js"; -export { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, startsAsMediaPlaylist, VIDEO_EXTS }; +export { AUDIO_EXTS, CONVERTIBLE_IMAGE_EXTS, MEDIA_INPUT_ARGS, startsAsMediaPlaylist, VIDEO_EXTS }; const COPIED_TYPE = /^(?:image|video|audio|font)\/|^text\/(?:css|javascript);/; diff --git a/packages/studio-server/src/helpers/peakMap.ts b/packages/studio-server/src/helpers/peakMap.ts index cc9018846ab..0bdb61bc706 100644 --- a/packages/studio-server/src/helpers/peakMap.ts +++ b/packages/studio-server/src/helpers/peakMap.ts @@ -1,6 +1,7 @@ import { spawn } from "node:child_process"; import { requireFfBinary } from "@hyperframes/parsers/ff-binaries"; import { probeAudioTrack } from "./mediaMetadata.js"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; export const PEAK_BIN_SECONDS = 0.05; const PEAK_SAMPLE_RATE = 48_000; @@ -71,6 +72,7 @@ export async function decodePeakMap(mediaPath: string): Promise { [ "-v", "error", + ...MEDIA_INPUT_ARGS, "-i", mediaPath, "-map", diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.ts index 47b6c5865af..a3ebc1e0d90 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts @@ -1,4 +1,5 @@ import { execFileSync, spawn as realSpawn, spawnSync, type ChildProcess } from "node:child_process"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; import os from "node:os"; import { EventEmitter, once } from "node:events"; import { @@ -537,9 +538,10 @@ describe("resolveProxy", () => { const vp8 = resolveProxy(projectDir, sourcePath, "vp8"); await flush(); const vp8Args = calls[0]!.args; - expect(vp8Args.slice(vp8Args.indexOf("-i") - 2, vp8Args.indexOf("-i"))).toEqual([ + expect(vp8Args.slice(vp8Args.indexOf("-i") - 4, vp8Args.indexOf("-i"))).toEqual([ "-c:v", "libvpx-vp9", + ...MEDIA_INPUT_ARGS, ]); succeed(calls[0]!, "fake-vp8-bytes"); await vp8; diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index c4e0bf63783..0b4d47a0411 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -15,7 +15,7 @@ import { hdrToSdrToneMapFilter, type PreviewProxyBox } from "@hyperframes/core"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import { alphaDecoderFor } from "@hyperframes/parsers/media-alpha"; import { ffmpegHasHdrFilters } from "./hdrFilters.js"; -import { NOT_MEDIA } from "./mediaExtensions.js"; +import { MEDIA_INPUT_ARGS, NOT_MEDIA } from "./mediaExtensions.js"; import { probeFirstFrameColour, probeMediaMetadata } from "./mediaMetadata.js"; import { cleanupProxyCache } from "./proxyCache.js"; import { @@ -762,6 +762,7 @@ async function runFfmpeg( "-nostats", ...(range ? ["-ss", String(range.startSeconds)] : []), ...decoderArgs, + ...MEDIA_INPUT_ARGS, "-i", sourcePath, ...streamArgs, @@ -1181,7 +1182,16 @@ async function makeStill( mkdirWithinProject(source.projectDir, dirname(cachePath)); const tempPath = join(dirname(cachePath), `.tmp-${randomUUID()}-${basename(cachePath)}`); try { - const args = ["-y", "-ss", String(at), "-i", source.sourcePath, "-map", "0:V:0"]; + const args = [ + "-y", + "-ss", + String(at), + ...MEDIA_INPUT_ARGS, + "-i", + source.sourcePath, + "-map", + "0:V:0", + ]; args.push("-frames:v", "1", "-vf", filter, "-pix_fmt", "yuvj420p", "-q:v", "3", tempPath); await spawnFfmpeg(ffmpegPath, args, TRANSCODE_STALL_MS, new AbortController().signal); renameSync(tempPath, cachePath); diff --git a/packages/studio-server/src/helpers/waveform.ts b/packages/studio-server/src/helpers/waveform.ts index 3752e4841ba..354f9a465b7 100644 --- a/packages/studio-server/src/helpers/waveform.ts +++ b/packages/studio-server/src/helpers/waveform.ts @@ -12,6 +12,7 @@ import { dirname, join } from "node:path"; import { requireFfBinary } from "@hyperframes/parsers/ff-binaries"; import { probeAudioTrack } from "./mediaMetadata.js"; import { createStagingDir } from "@hyperframes/core/atomic-file"; +import { MEDIA_INPUT_ARGS } from "./mediaExtensions.js"; const SAMPLE_RATE = 4000; const PEAK_COUNT = 4000; @@ -67,6 +68,7 @@ export async function decodeAudioPeaks(audioPath: string): Promise { const proc = spawn( ffmpeg, [ + ...MEDIA_INPUT_ARGS, "-i", audioPath, "-map", diff --git a/packages/studio-server/src/routes/freezeFrame.test.ts b/packages/studio-server/src/routes/freezeFrame.test.ts index c2ca0a25338..c46dcb97024 100644 --- a/packages/studio-server/src/routes/freezeFrame.test.ts +++ b/packages/studio-server/src/routes/freezeFrame.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it } from "vitest"; +import { MEDIA_INPUT_ARGS } from "../helpers/mediaExtensions.js"; import { Hono } from "hono"; import { chmodSync, @@ -74,7 +75,14 @@ describe("freeze-frame route", () => { await res.json(); expect(res.status).toBe(200); const output = calls[0]?.at(-1) ?? ""; - expect(calls[0]?.slice(0, 5)).toEqual(["-y", "-ss", "2.5", "-i", join(dir, "media/talk.mp4")]); + expect(calls[0]?.slice(0, 7)).toEqual([ + "-y", + "-ss", + "2.5", + ...MEDIA_INPUT_ARGS, + "-i", + join(dir, "media/talk.mp4"), + ]); expect(isAtomicTempPath(output)).toBe(true); const still = stillOf(output); expect(dirname(still)).toBe(join(dir, "assets/freeze")); From dc3c26582ddc5fcafc5cd0a4c0c266cb77a29116 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 16:14:45 -0800 Subject: [PATCH 11/29] fix(cli,studio-server): keep media probe argv flat, and expect the demuxer list in loudness args Two probe argv literals built from nested spreads are flat again, so "--" stays the visible second-to-last entry the argv contract checks. The normalize-audio test expects the demuxer list before the input. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/cloud/offload.ts | 20 ++++++++---------- .../cli/src/commands/normalize-audio.test.ts | 9 +++++++- .../src/helpers/mediaMetadata.ts | 21 ++++++++++--------- 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/packages/cli/src/cloud/offload.ts b/packages/cli/src/cloud/offload.ts index 163a20dfaa8..d3fa06055e8 100644 --- a/packages/cli/src/cloud/offload.ts +++ b/packages/cli/src/cloud/offload.ts @@ -363,17 +363,15 @@ async function durationSeconds(sourcePath: string): Promise { const ffprobe = findFFprobe(); if (!ffprobe) return null; const { stdout } = await execFileAsync(ffprobe, [ - ...[ - "-v", - "error", - "-show_entries", - "format=duration", - "-of", - "csv=p=0", - ...MEDIA_INPUT_ARGS, - "--", - sourcePath, - ], + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + ...MEDIA_INPUT_ARGS, + "--", + sourcePath, ]); const value = Number(stdout.trim()); return Number.isFinite(value) && value > 0 ? value : null; diff --git a/packages/cli/src/commands/normalize-audio.test.ts b/packages/cli/src/commands/normalize-audio.test.ts index 2e1d6b76a43..4f6b78c0dc2 100644 --- a/packages/cli/src/commands/normalize-audio.test.ts +++ b/packages/cli/src/commands/normalize-audio.test.ts @@ -1,5 +1,6 @@ import { resolve } from "node:path"; import { describe, expect, it } from "vitest"; +import { MEDIA_INPUT_ARGS } from "@hyperframes/studio-server/outside-file"; import { audioNormalizationPlan, audioTags, @@ -76,7 +77,13 @@ describe("loudnessMeasureArgs", () => { const args = loudnessMeasureArgs("clip.wav", { mediaStart: 2, duration: 4 }, 0); expect(args.indexOf("-ss")).toBeLessThan(args.indexOf("-i")); expect(args.indexOf("-t")).toBeLessThan(args.indexOf("-i")); - expect(args.slice(args.indexOf("-ss"), args.indexOf("-i"))).toEqual(["-ss", "2", "-t", "4"]); + expect(args.slice(args.indexOf("-ss"), args.indexOf("-i"))).toEqual([ + "-ss", + "2", + "-t", + "4", + ...MEDIA_INPUT_ARGS, + ]); }); it("leaves an untrimmed clip unbounded", () => { diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 455af43f284..6451c4ef850 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -324,16 +324,17 @@ export async function probeAudioTrack( const result = await runner( ffprobePath, [ - ...["-v", "error", "-select_streams", "a"], - ...[ - "-show_entries", - "stream=codec_type,codec_name,channels", - "-of", - "json", - ...MEDIA_INPUT_ARGS, - "--", - filePath, - ], + "-v", + "error", + "-select_streams", + "a", + "-show_entries", + "stream=codec_type,codec_name,channels", + "-of", + "json", + ...MEDIA_INPUT_ARGS, + "--", + filePath, ], { timeout: 30_000 }, ); From cbd61220131049a32f1f080f1a4e27729dac04ba Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 16:59:26 -0800 Subject: [PATCH 12/29] fix(cli): play and present answer only local host names and allowed hosts play and present listen on every interface. Each request now passes the same Host check preview uses: localhost, loopback addresses and this machine's own addresses and names are answered, and any other host name gets a 403 naming HYPERFRAMES_PREVIEW_ALLOWED_HOSTS until it is listed there. Phones and other machines on the network still open them by LAN address or .local name. --- docs/packages/cli.mdx | 20 ++++++ packages/cli/src/commands/play.ts | 2 + packages/cli/src/commands/present.ts | 2 + .../cli/src/utils/compositionServer.test.ts | 63 ++++++++++++++++++- packages/cli/src/utils/compositionServer.ts | 29 +++++++++ .../src/createStudioApi.originGuard.test.ts | 33 +++++++++- .../src/helpers/requestIdentity.ts | 17 ++++- 7 files changed, 160 insertions(+), 6 deletions(-) diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 9e2a87ad345..7273c887191 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1072,6 +1072,15 @@ the CLI itself, or when you set `HYPERFRAMES_LOCAL_STUDIO=1`; a Studio in the project's own `node_modules` is not used otherwise. `--background` works with the embedded server only. +The preview server answers only the host names it serves. To open it through +a tunnel, Codespaces or a reverse proxy, name that host in +`HYPERFRAMES_PREVIEW_ALLOWED_HOSTS` (comma separated). A refused request +answers 403 with the host named and this variable as the fix: + +```bash +HYPERFRAMES_PREVIEW_ALLOWED_HOSTS=demo.tunnels.example hyperframes preview +``` + The CLI ships GSAP, CustomEase, and MotionPathPlugin, so the GSAP scripts Studio adds to previews load from the preview server itself, not from jsDelivr. To use your own mirror instead, set `HYPERFRAMES_GSAP_BASE_URL` before starting @@ -1105,6 +1114,17 @@ npx hyperframes present [dir] --port 3004 editor, just playback. Same flags, `--port` defaults to 3003, plus `--proxy` / `--no-proxy`. +Both listen on every network interface, so a phone or another computer on your +network can open them at this machine's LAN address or `.local` name. They +answer `localhost`, loopback addresses, and this machine's own addresses and +names. Any other host name, such as a tunnel, Codespaces or a reverse proxy, +gets a 403 until you name it in `HYPERFRAMES_PREVIEW_ALLOWED_HOSTS`, the same +setting `preview` uses: + +```bash +HYPERFRAMES_PREVIEW_ALLOWED_HOSTS=demo.tunnels.example hyperframes present +``` + ### `publish` For new video reviews, use [`share`](#share). Legacy source publishing stays diff --git a/packages/cli/src/commands/play.ts b/packages/cli/src/commands/play.ts index 37115d6204d..ebaf1c09aa8 100644 --- a/packages/cli/src/commands/play.ts +++ b/packages/cli/src/commands/play.ts @@ -36,6 +36,7 @@ import { resolveRuntimePath, resolvePlayerPath, listenOnFreePort, + refuseUnknownHosts, injectRuntime, injectMediaCodecMap, buildRangeResponse, @@ -145,6 +146,7 @@ export default defineCommand({ const { createAdaptorServer } = await import("@hono/node-server"); const app = new Hono(); + refuseUnknownHosts(app); // Serve the player JS app.get("/player.js", (ctx) => diff --git a/packages/cli/src/commands/present.ts b/packages/cli/src/commands/present.ts index 684ad4b921f..2e672143bd9 100644 --- a/packages/cli/src/commands/present.ts +++ b/packages/cli/src/commands/present.ts @@ -27,6 +27,7 @@ import { resolvePlayerPath, resolveSlideshowPath, listenOnFreePort, + refuseUnknownHosts, assetContentType, } from "../utils/compositionServer.js"; import { isPrivateCompositionFile } from "../utils/privateProjectFile.js"; @@ -123,6 +124,7 @@ export default defineCommand({ const { createAdaptorServer } = await import("@hono/node-server"); const app = new Hono(); + refuseUnknownHosts(app); app.get("/player.js", (ctx) => ctx.body(readFileSync(playerPath, "utf-8"), 200, { diff --git a/packages/cli/src/utils/compositionServer.test.ts b/packages/cli/src/utils/compositionServer.test.ts index e4474be0075..dc7b3db95fa 100644 --- a/packages/cli/src/utils/compositionServer.test.ts +++ b/packages/cli/src/utils/compositionServer.test.ts @@ -1,8 +1,9 @@ import { afterEach, describe, expect, it } from "vitest"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { hostname, networkInterfaces, tmpdir } from "node:os"; import { join } from "node:path"; -import { buildRangeResponse } from "./compositionServer.js"; +import { Hono } from "hono"; +import { buildRangeResponse, refuseUnknownHosts } from "./compositionServer.js"; const TAGGED_PNG = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGNJQ1ABAQABlXPCVgAAAAxJREFUeJxj0NfXBwABHgCOTp25kgAAAABJRU5ErkJggg==", @@ -30,3 +31,61 @@ describe("buildRangeResponse colour-tagged PNGs", () => { expect(res.headers.get("content-length")).toBe(String(body.length)); }); }); + +describe("refuseUnknownHosts", () => { + const ENV = "HYPERFRAMES_PREVIEW_ALLOWED_HOSTS"; + + afterEach(() => { + delete process.env[ENV]; + }); + + function guardedApp(): Hono { + const app = new Hono(); + refuseUnknownHosts(app); + app.get("/composition/*", (c) => c.text("project file")); + return app; + } + + function get(app: Hono, host: string): Promise { + return Promise.resolve(app.request("/composition/package.json", { headers: { host } })); + } + + function lanAddress(): string | undefined { + for (const entries of Object.values(networkInterfaces())) { + for (const entry of entries ?? []) { + if (entry.family === "IPv4" && !entry.internal) return entry.address; + } + } + return undefined; + } + + it("answers localhost and loopback addresses", async () => { + const app = guardedApp(); + for (const host of ["localhost:3003", "127.0.0.1:3003", "[::1]:3003"]) { + expect((await get(app, host)).status, host).toBe(200); + } + }); + + it("answers this machine's LAN address and .local name, so another device can open it", async () => { + const app = guardedApp(); + const lan = lanAddress(); + if (lan) expect((await get(app, `${lan}:3003`)).status).toBe(200); + const short = hostname().toLowerCase().split(".")[0]; + if (short) expect((await get(app, `${short}.local:3003`)).status).toBe(200); + }); + + it("refuses any other host name and names the setting that allows it", async () => { + const res = await get(guardedApp(), "rebound.example:3003"); + expect(res.status).toBe(403); + const text = await res.text(); + expect(text).not.toContain("project file"); + expect(text).toContain(`${ENV}=rebound.example:3003`); + }); + + it("answers a host named in HYPERFRAMES_PREVIEW_ALLOWED_HOSTS", async () => { + process.env[ENV] = "other.example, demo.tunnels.example"; + const res = await get(guardedApp(), "demo.tunnels.example"); + expect(res.status).toBe(200); + expect(await res.text()).toBe("project file"); + }); +}); diff --git a/packages/cli/src/utils/compositionServer.ts b/packages/cli/src/utils/compositionServer.ts index c64ae46f060..1be0b61fccd 100644 --- a/packages/cli/src/utils/compositionServer.ts +++ b/packages/cli/src/utils/compositionServer.ts @@ -9,6 +9,12 @@ import { fileURLToPath } from "node:url"; import { getMimeType, openRangeEnd } from "@hyperframes/studio-server"; import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags"; import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document"; +import { + PREVIEW_ALLOWED_HOSTS_ENV, + previewAllowedHostsFromEnv, + wildcardBindHostAllowed, +} from "@hyperframes/studio-server/request-identity"; +import type { Hono } from "hono"; /** * `window.__HF_MEDIA_CODEC_MAP__` injection + proxy pre-warm for HTML served @@ -175,6 +181,29 @@ export function buildRangeResponse( }); } +/** + * The server listens on every interface, so every route answers only loopback, + * this machine's own addresses and names, or a host named in + * HYPERFRAMES_PREVIEW_ALLOWED_HOSTS. A browser cannot forge Host, which keeps a + * rebound page name from reading project files. + */ +export function refuseUnknownHosts(app: Hono): void { + const allowedHosts = previewAllowedHostsFromEnv(); + app.use(async function refuseUnknownHost(c, next) { + const host = c.req.header("host") ?? new URL(c.req.url).host; + if (wildcardBindHostAllowed(host, allowedHosts)) return next(); + return c.json( + { + error: + `forbidden: host "${host}" is not allowed. ` + + `Set ${PREVIEW_ALLOWED_HOSTS_ENV}=${host} to allow it ` + + `(comma separated for several hosts).`, + }, + 403, + ); + }); +} + /** * Bind `server` to the first free port at or after `startPort` (scanning up to * 10 ports). Returns the bound port. Rejects if all candidates are in use or on diff --git a/packages/studio-server/src/createStudioApi.originGuard.test.ts b/packages/studio-server/src/createStudioApi.originGuard.test.ts index 3658369addf..e8c0c401976 100644 --- a/packages/studio-server/src/createStudioApi.originGuard.test.ts +++ b/packages/studio-server/src/createStudioApi.originGuard.test.ts @@ -6,10 +6,10 @@ // so it needs Node's fetch classes, which keep them. import { afterEach, describe, expect, it } from "vitest"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { networkInterfaces, tmpdir } from "node:os"; import { join } from "node:path"; import { createStudioApi } from "./createStudioApi"; -import { previewAllowedHostsFromEnv } from "./helpers/requestIdentity"; +import { previewAllowedHostsFromEnv, wildcardBindHostAllowed } from "./helpers/requestIdentity"; import { stubAdapter } from "./routes/stubAdapter.test-helpers"; const tempDirs: string[] = []; @@ -294,3 +294,32 @@ describe("previewAllowedHostsFromEnv", () => { expect(previewAllowedHostsFromEnv({ HYPERFRAMES_PREVIEW_ALLOWED_HOSTS: " " })).toEqual([]); }); }); + +describe("wildcardBindHostAllowed", () => { + it("allows loopback names and this machine's interface addresses", () => { + expect(wildcardBindHostAllowed("localhost:3003")).toBe(true); + expect(wildcardBindHostAllowed("127.0.0.1")).toBe(true); + const address = Object.values(networkInterfaces()) + .flatMap((entries) => entries ?? []) + .find((entry) => entry.family === "IPv4")?.address; + if (address) expect(wildcardBindHostAllowed(`${address}:3003`)).toBe(true); + }); + + it("refuses other names unless they are listed", () => { + expect(wildcardBindHostAllowed("rebound.example:3003")).toBe(false); + expect(wildcardBindHostAllowed("")).toBe(false); + expect(wildcardBindHostAllowed(undefined)).toBe(false); + expect(wildcardBindHostAllowed("demo.tunnels.example", ["demo.tunnels.example"])).toBe(true); + }); + + it("ignores the preview bind setting", () => { + const saved = process.env["HYPERFRAMES_PREVIEW_HOST"]; + process.env["HYPERFRAMES_PREVIEW_HOST"] = "rebound.example"; + try { + expect(wildcardBindHostAllowed("rebound.example")).toBe(false); + } finally { + if (saved === undefined) delete process.env["HYPERFRAMES_PREVIEW_HOST"]; + else process.env["HYPERFRAMES_PREVIEW_HOST"] = saved; + } + }); +}); diff --git a/packages/studio-server/src/helpers/requestIdentity.ts b/packages/studio-server/src/helpers/requestIdentity.ts index 7de237146f1..4853879383f 100644 --- a/packages/studio-server/src/helpers/requestIdentity.ts +++ b/packages/studio-server/src/helpers/requestIdentity.ts @@ -76,13 +76,16 @@ export function identityAllowed(host: string | undefined): boolean { return hostMatchesBind(host, bind); } -function hostAllowed(host: string, allowedHosts: readonly string[] | undefined): boolean { - if (identityAllowed(host)) return true; +function inAllowedHosts(host: string, allowedHosts: readonly string[] | undefined): boolean { if (!allowedHosts) return false; const name = hostnameOf(host); return name !== "" && allowedHosts.some((allowed) => hostnameOf(allowed) === name); } +function hostAllowed(host: string, allowedHosts: readonly string[] | undefined): boolean { + return identityAllowed(host) || inAllowedHosts(host, allowedHosts); +} + // Reads included. Only Host counts: a page can set X-Forwarded-Host, and a read has no Origin to check. export function hostHeaderAllowed( host: string | undefined, @@ -91,6 +94,16 @@ export function hostHeaderAllowed( return host !== undefined && host !== "" && hostAllowed(host, allowedHosts); } +export function wildcardBindHostAllowed( + host: string | undefined, + allowedHosts?: readonly string[], +): boolean { + if (host === undefined || host === "") return false; + return ( + isLoopbackHost(host) || hostMatchesBind(host, "0.0.0.0") || inAllowedHosts(host, allowedHosts) + ); +} + function firstForwarded(value: string | undefined): string | undefined { const first = value?.split(",")[0]?.trim(); return first === "" ? undefined : first; From d08156d304b8a1b4c53140a52d51ea7d9058b5fc Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 17:05:33 -0800 Subject: [PATCH 13/29] fix(cli): a local render of a received composition leaves out files outside the project When the composition a local render opens is listed in the project's received-files record, hyperframes render (full and range) no longer brings in files outside the project. It prints one line naming the references it leaves out and why. An unreadable record counts as received. A project whose entry is the person's own, or that has no record, renders exactly as before. --- packages/cli/src/commands/render.test.ts | 43 ++++++- packages/cli/src/commands/render.ts | 10 +- packages/cli/src/utils/receivedRender.test.ts | 85 ++++++++++++++ packages/cli/src/utils/receivedRender.ts | 105 ++++++++++++++++++ 4 files changed, 239 insertions(+), 4 deletions(-) create mode 100644 packages/cli/src/utils/receivedRender.test.ts create mode 100644 packages/cli/src/utils/receivedRender.ts diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 4b79561f331..824d28e5d74 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -124,9 +124,17 @@ vi.mock("../utils/producer.js", () => ({ }), ), renderConfigFromRequest: vi.fn( - (request: { options: Record }, runtime: { logger?: unknown }) => { + ( + request: { options: Record }, + runtime: { logger?: unknown; allowOutsideProjectAssets?: boolean }, + ) => { const { engineConfig, ...options } = request.options; - return { ...options, producerConfig: engineConfig, logger: runtime.logger }; + return { + ...options, + producerConfig: engineConfig, + logger: runtime.logger, + allowOutsideProjectAssets: runtime.allowOutsideProjectAssets, + }; }, ), createRenderJob: vi.fn((config: Record) => { @@ -580,6 +588,37 @@ describe("renderLocal browser GPU config", () => { warn.mockRestore(); }); + it.each([ + { name: "a received entry", files: ["index.html"], allowed: false }, + { name: "the person's own entry", files: ["assets/in.png"], allowed: true }, + { name: "no received-files record", files: undefined, allowed: true }, + ])("brings in outside files for $name: $allowed", async ({ files, allowed }) => { + const projectDir = mkdtempSync(join(tmpdir(), "hf-render-received-")); + writeFileSync(join(projectDir, "index.html"), "
"); + if (files) { + mkdirSync(join(projectDir, ".hyperframes")); + writeFileSync( + join(projectDir, ".hyperframes", "received-files.json"), + JSON.stringify({ files }), + ); + } + try { + await renderLocal(projectDir, join(projectDir, "out.mp4"), { + fps: { num: 30, den: 1 }, + quality: "standard", + format: "mp4", + gpu: false, + browserGpuMode: "software", + hdrMode: "auto", + quiet: true, + throwOnError: true, + }); + expect(producerState.createdJobs.at(-1)?.allowOutsideProjectAssets).toBe(allowed); + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }); + it("cleans orphaned browser trees before starting a local render", async () => { orphanCleanupState.killed = 1; diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index 9e4380998f6..a19e0f0084e 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -72,6 +72,7 @@ import { freemem, tmpdir } from "node:os"; import { resolve, dirname, join, basename } from "node:path"; import { execFileSync, spawn } from "node:child_process"; import { loadProducer } from "../utils/producer.js"; +import { outsideAssetsAllowed } from "../utils/receivedRender.js"; import { c } from "../ui/colors.js"; import { desktopHint } from "../utils/desktopApp.js"; import { @@ -1148,6 +1149,9 @@ async function executeLocalRender( process.env.HYPERFRAMES_GSAP_VENDOR_DIR = gsapVendorDir; } const producer = await loadProducer(); + const allowOutsideProjectAssets = outsideAssetsAllowed(projectDir, options.entryFile, (line) => + console.warn(c.warn(` ${line}`)), + ); const deParallelRouterActive = options.manageDeParallelRouterBreaker === true ? applyDeParallelRouterCircuitBreaker(options.quiet) @@ -1227,10 +1231,11 @@ async function executeLocalRender( startTime, cpu, signal: cancellation.signal, + allowOutsideProjectAssets, }); } const job = producer.createRenderJob( - producer.renderConfigFromRequest(request, { logger, allowOutsideProjectAssets: true }), + producer.renderConfigFromRequest(request, { logger, allowOutsideProjectAssets }), ); const onProgress = options.quiet @@ -1348,6 +1353,7 @@ async function renderRange(input: { startTime: number; cpu: RenderCpuSampler; signal: AbortSignal; + allowOutsideProjectAssets: boolean; }): Promise { const { producer, options } = input; let framesEncoded = 0; @@ -1362,7 +1368,7 @@ async function renderRange(input: { config, input.range, input.outputPath, - { allowOutsideProjectAssets: true }, + { allowOutsideProjectAssets: input.allowOutsideProjectAssets }, ); framesEncoded = spanResult.framesEncoded; reference = producer.referenceBackgroundResult(spanResult[producer.REFERENCE_BACKGROUND_FIELD]); diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts new file mode 100644 index 00000000000..a1d0ad63169 --- /dev/null +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -0,0 +1,85 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { outsideAssetsAllowed } from "./receivedRender.js"; + +let root: string | undefined; + +afterEach(() => { + if (root) rmSync(root, { recursive: true, force: true }); + root = undefined; +}); + +function write(path: string, text: string): void { + mkdirSync(join(path, ".."), { recursive: true }); + writeFileSync(path, text); +} + +function project(record?: string): string { + root = mkdtempSync(join(tmpdir(), "hf-received-render-")); + for (const name of ["secret.js", "pic.png", "clip.mp4", "bg.png"]) { + write(join(root, "outside", name), "x"); + } + const dir = join(root, "project"); + write( + join(dir, "index.html"), + ` + + + +
`, + ); + write(join(dir, "compositions", "scene.html"), ``); + write(join(dir, "style.css"), `body { background: url(../outside/bg.png); }`); + write(join(dir, "assets", "in.png"), "x"); + if (record !== undefined) write(join(dir, ".hyperframes", "received-files.json"), record); + return dir; +} + +const received = (...files: string[]) => JSON.stringify({ files }); + +describe("outsideAssetsAllowed", () => { + it("refuses outside files for a received entry and names every reference it leaves out", () => { + const warn = vi.fn(); + expect(outsideAssetsAllowed(project(received("index.html")), undefined, warn)).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + const line = String(warn.mock.calls[0]?.[0]); + expect(line).toContain("index.html came from someone else"); + for (const ref of [ + "../outside/secret.js", + "../outside/pic.png", + "../../outside/clip.mp4", + "../outside/bg.png", + ]) { + expect(line).toContain(ref); + } + expect(line).not.toContain("assets/in.png"); + expect(line).not.toContain("cdn.example"); + }); + + it("checks the composition being rendered, not index.html", () => { + const dir = project(received("compositions/scene.html")); + const warn = vi.fn(); + expect(outsideAssetsAllowed(dir, "compositions/scene.html", warn)).toBe(false); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("../../outside/clip.mp4")); + expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(true); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it("keeps outside files for the person's own entry", () => { + const warn = vi.fn(); + expect(outsideAssetsAllowed(project(received("assets/in.png")), undefined, warn)).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + it("keeps outside files for a project with no received-files record", () => { + const warn = vi.fn(); + expect(outsideAssetsAllowed(project(), undefined, warn)).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + it("treats an unreadable record as received", () => { + expect(outsideAssetsAllowed(project("{not json"), undefined, vi.fn())).toBe(false); + }); +}); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts new file mode 100644 index 00000000000..0b1385d1343 --- /dev/null +++ b/packages/cli/src/utils/receivedRender.ts @@ -0,0 +1,105 @@ +import { readFileSync, statSync } from "node:fs"; +import { dirname, isAbsolute, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseHTML } from "linkedom"; +import { CSS_URL_RE, isNonRelativeUrl, isPathInside } from "@hyperframes/core"; +import { linksOutside, receivedFiles } from "./privateProjectFile.js"; + +const REFERENCE_ATTRS = ["src", "href", "poster"]; + +interface Reference { + raw: string; + fromRoot: boolean; +} + +function cssReferences(css: string): Reference[] { + return [...css.matchAll(CSS_URL_RE)].map((match) => ({ + raw: (match[2] ?? "").trim(), + fromRoot: false, + })); +} + +function htmlReferences(html: string): Reference[] { + const { document } = parseHTML(html); + const refs: Reference[] = []; + for (const el of document.querySelectorAll("[src], [href], [poster], [data-composition-src]")) { + for (const attr of REFERENCE_ATTRS) { + const raw = el.getAttribute(attr)?.trim(); + if (raw) refs.push({ raw, fromRoot: false }); + } + const composition = el.getAttribute("data-composition-src")?.trim(); + if (composition) refs.push({ raw: composition, fromRoot: true }); + } + for (const style of document.querySelectorAll("style")) { + refs.push(...cssReferences(style.textContent ?? "")); + } + for (const el of document.querySelectorAll("[style]")) { + refs.push(...cssReferences(el.getAttribute("style") ?? "")); + } + return refs; +} + +function localPath(raw: string, fromDir: string): string | null { + if (raw.startsWith("file:")) { + try { + return fileURLToPath(raw); + } catch { + return null; + } + } + const path = raw.replace(/[?#].*$/, ""); + if (isAbsolute(path) && !path.startsWith("//")) return path; + if (path === "" || isNonRelativeUrl(path)) return null; + try { + return resolve(fromDir, decodeURIComponent(path)); + } catch { + return resolve(fromDir, path); + } +} + +const isFile = (path: string) => statSync(path, { throwIfNoEntry: false })?.isFile() === true; + +function referencedFiles(file: string, projectDir: string): Array<{ raw: string; path: string }> { + const text = readFileSync(file, "utf-8"); + const refs = /\.css$/i.test(file) ? cssReferences(text) : htmlReferences(text); + return refs.flatMap(({ raw, fromRoot }) => { + const path = localPath(raw, fromRoot ? projectDir : dirname(file)); + return path !== null && isFile(path) ? [{ raw, path }] : []; + }); +} + +const isPageOrStylesheet = (path: string) => /\.(?:html?|css)$/i.test(path); + +// References from the entry, and the compositions and stylesheets it pulls in, that reach existing files outside the project. +function outsideReferences(projectDir: string, entryFile: string): string[] { + const found = new Set(); + const visited = new Set(); + const pending = [resolve(projectDir, entryFile)]; + for (let file = pending.pop(); file !== undefined; file = pending.pop()) { + if (visited.has(file) || !isPathInside(file, projectDir) || !isFile(file)) continue; + visited.add(file); + for (const { raw, path } of referencedFiles(file, projectDir)) { + if (linksOutside(projectDir, path)) found.add(raw); + else if (isPageOrStylesheet(path)) pending.push(path); + } + } + return [...found]; +} + +/** False when the composition a local render opens came from someone else; `warn` then names the references outside the project it leaves out. */ +export function outsideAssetsAllowed( + projectDir: string, + entryFile: string | undefined, + warn: (line: string) => void, +): boolean { + const absProjectDir = resolve(projectDir); + const entry = entryFile ?? "index.html"; + if (!receivedFiles(absProjectDir)(entry)) return true; + const refs = outsideReferences(absProjectDir, entry); + if (refs.length > 0) { + warn( + `${entry} came from someone else, so the render leaves out what it references outside the project: ${refs.join(", ")}`, + ); + } + return false; +} From 6c9ae0bbcbd94dc9d06bb7a9da0e5c2b250b8363 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 17:12:16 -0800 Subject: [PATCH 14/29] fix(cli): received-render scan reads safely and treats an unreadable record as unknown The scan behind the received-composition notice skips a file it cannot read, finds url() references with a linear forward scan, and reads at most 2 MB of each file. An unreadable received-files record no longer counts as everything received for local render: the render keeps outside files and names the record it could not read. Publish and cloud upload still treat it as received. The notice now says the render stops on a sub-composition outside the project rather than leaving it out. --- packages/cli/src/utils/privateProjectFile.ts | 6 ++ packages/cli/src/utils/receivedRender.test.ts | 50 ++++++++- packages/cli/src/utils/receivedRender.ts | 100 +++++++++++++----- 3 files changed, 126 insertions(+), 30 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 3431f1a0800..9c4c461e654 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -88,6 +88,12 @@ export function receivedFiles(projectDir: string): (path: string) => boolean { return (path) => files.has(keyOf(path)) || sameFileAsListed(path); } +/** The nearest received-files record when it exists but lists no files a reader can trust, else null. */ +export function unreadableReceivedRecord(projectDir: string): string | null { + const record = nearestReceivedRecordAtOrAbove(projectDir); + return record && !Array.isArray(record.listed) ? join(record.root, RECEIVED_RECORD) : null; +} + /** Project files no composition loads, so none is served or uploaded for one: env files, Git data, tool records. */ export function isPrivateCompositionFile(projectDir: string, filePath: string): boolean { return ( diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index a1d0ad63169..99cd2ebc295 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { outsideAssetsAllowed } from "./receivedRender.js"; @@ -46,6 +46,8 @@ describe("outsideAssetsAllowed", () => { expect(warn).toHaveBeenCalledTimes(1); const line = String(warn.mock.calls[0]?.[0]); expect(line).toContain("index.html came from someone else"); + expect(line).toContain("It leaves out"); + expect(line).not.toContain("compositions"); for (const ref of [ "../outside/secret.js", "../outside/pic.png", @@ -79,7 +81,49 @@ describe("outsideAssetsAllowed", () => { expect(warn).not.toHaveBeenCalled(); }); - it("treats an unreadable record as received", () => { - expect(outsideAssetsAllowed(project("{not json"), undefined, vi.fn())).toBe(false); + it.each(["{not json", "", "{}"])( + "keeps outside files and names the record when it cannot be read: %j", + (record) => { + const dir = project(record); + const warn = vi.fn(); + expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(true); + expect(warn).toHaveBeenCalledTimes(1); + const line = String(warn.mock.calls[0]?.[0]); + expect(line).toContain(join(dir, ".hyperframes", "received-files.json")); + expect(line).not.toContain("someone else"); + }, + ); + + it("says the render stops on a composition outside the project", () => { + const dir = project(received("index.html")); + write(join(dir, "..", "outside", "shared.html"), "
"); + write(join(dir, "index.html"), `
`); + const warn = vi.fn(); + expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(false); + const line = String(warn.mock.calls[0]?.[0]); + expect(line).toContain("stops on the compositions ../outside/shared.html"); + expect(line).not.toContain("leaves out"); + }); + + it("skips a stylesheet it cannot read instead of failing", () => { + const dir = project(received("index.html")); + rmSync(join(dir, "style.css")); + mkdirSync(join(dir, "style.css")); + if (process.platform !== "win32") { + write(join(dir, "locked.css"), "body { background: url(../outside/bg.png); }"); + chmodSync(join(dir, "locked.css"), 0o000); + write(join(dir, "index.html"), ``); + } + const warn = vi.fn(); + expect(() => outsideAssetsAllowed(dir, undefined, warn)).not.toThrow(); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("../outside/pic.png")); + }); + + it("scans a long unclosed url( run in linear time", () => { + const dir = project(received("index.html")); + write(join(dir, "style.css"), "url(".repeat(1_000_000)); + const started = performance.now(); + outsideAssetsAllowed(dir, undefined, vi.fn()); + expect(performance.now() - started).toBeLessThan(2_000); }); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 0b1385d1343..a0b38aa8112 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,22 +1,35 @@ -import { readFileSync, statSync } from "node:fs"; +import { closeSync, openSync, readSync, statSync } from "node:fs"; import { dirname, isAbsolute, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; -import { CSS_URL_RE, isNonRelativeUrl, isPathInside } from "@hyperframes/core"; -import { linksOutside, receivedFiles } from "./privateProjectFile.js"; +import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; +import { linksOutside, receivedFiles, unreadableReceivedRecord } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; +const MAX_SCANNED_BYTES = 2 * 1024 * 1024; interface Reference { raw: string; - fromRoot: boolean; + composition: boolean; +} + +function unquote(value: string): string { + const first = value[0]; + return value.length >= 2 && (first === '"' || first === "'") && value.at(-1) === first + ? value.slice(1, -1).trim() + : value; } function cssReferences(css: string): Reference[] { - return [...css.matchAll(CSS_URL_RE)].map((match) => ({ - raw: (match[2] ?? "").trim(), - fromRoot: false, - })); + const refs: Reference[] = []; + for (let at = css.indexOf("url("); at !== -1; ) { + const close = css.indexOf(")", at + 4); + if (close === -1) break; + const raw = unquote(css.slice(at + 4, close).trim()); + if (raw) refs.push({ raw, composition: false }); + at = css.indexOf("url(", close + 1); + } + return refs; } function htmlReferences(html: string): Reference[] { @@ -25,10 +38,10 @@ function htmlReferences(html: string): Reference[] { for (const el of document.querySelectorAll("[src], [href], [poster], [data-composition-src]")) { for (const attr of REFERENCE_ATTRS) { const raw = el.getAttribute(attr)?.trim(); - if (raw) refs.push({ raw, fromRoot: false }); + if (raw) refs.push({ raw, composition: false }); } const composition = el.getAttribute("data-composition-src")?.trim(); - if (composition) refs.push({ raw: composition, fromRoot: true }); + if (composition) refs.push({ raw: composition, composition: true }); } for (const style of document.querySelectorAll("style")) { refs.push(...cssReferences(style.textContent ?? "")); @@ -59,34 +72,66 @@ function localPath(raw: string, fromDir: string): string | null { const isFile = (path: string) => statSync(path, { throwIfNoEntry: false })?.isFile() === true; -function referencedFiles(file: string, projectDir: string): Array<{ raw: string; path: string }> { - const text = readFileSync(file, "utf-8"); +function readHead(file: string): string | null { + let fd: number | undefined; + try { + fd = openSync(file, "r"); + const buffer = Buffer.alloc(Math.min(statSync(file).size, MAX_SCANNED_BYTES)); + return buffer.toString("utf-8", 0, readSync(fd, buffer, 0, buffer.length, 0)); + } catch { + return null; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + +function referencedFiles(file: string, projectDir: string) { + const text = readHead(file); + if (text === null) return []; const refs = /\.css$/i.test(file) ? cssReferences(text) : htmlReferences(text); - return refs.flatMap(({ raw, fromRoot }) => { - const path = localPath(raw, fromRoot ? projectDir : dirname(file)); - return path !== null && isFile(path) ? [{ raw, path }] : []; + return refs.flatMap(({ raw, composition }) => { + const path = localPath(raw, composition ? projectDir : dirname(file)); + return path !== null && isFile(path) ? [{ raw, path, composition }] : []; }); } const isPageOrStylesheet = (path: string) => /\.(?:html?|css)$/i.test(path); +interface OutsideReferences { + assets: Set; + compositions: Set; +} + // References from the entry, and the compositions and stylesheets it pulls in, that reach existing files outside the project. -function outsideReferences(projectDir: string, entryFile: string): string[] { - const found = new Set(); +function outsideReferences(projectDir: string, entryFile: string): OutsideReferences { + const found: OutsideReferences = { assets: new Set(), compositions: new Set() }; const visited = new Set(); const pending = [resolve(projectDir, entryFile)]; for (let file = pending.pop(); file !== undefined; file = pending.pop()) { if (visited.has(file) || !isPathInside(file, projectDir) || !isFile(file)) continue; visited.add(file); - for (const { raw, path } of referencedFiles(file, projectDir)) { - if (linksOutside(projectDir, path)) found.add(raw); + for (const { raw, path, composition } of referencedFiles(file, projectDir)) { + if (linksOutside(projectDir, path)) + (composition ? found.compositions : found.assets).add(raw); else if (isPageOrStylesheet(path)) pending.push(path); } } - return [...found]; + return found; } -/** False when the composition a local render opens came from someone else; `warn` then names the references outside the project it leaves out. */ +function receivedEntryNotice(entry: string, refs: OutsideReferences): string | null { + const parts: string[] = []; + if (refs.assets.size > 0) parts.push(`It leaves out ${[...refs.assets].join(", ")}.`); + if (refs.compositions.size > 0) { + parts.push( + `It stops on the compositions ${[...refs.compositions].join(", ")}; move them into the project to render them.`, + ); + } + if (parts.length === 0) return null; + return `${entry} came from someone else, so the render reads nothing outside the project. ${parts.join(" ")}`; +} + +/** False when the composition a local render opens came from someone else; `warn` then names the references outside the project it refuses. */ export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, @@ -94,12 +139,13 @@ export function outsideAssetsAllowed( ): boolean { const absProjectDir = resolve(projectDir); const entry = entryFile ?? "index.html"; - if (!receivedFiles(absProjectDir)(entry)) return true; - const refs = outsideReferences(absProjectDir, entry); - if (refs.length > 0) { - warn( - `${entry} came from someone else, so the render leaves out what it references outside the project: ${refs.join(", ")}`, - ); + const unreadable = unreadableReceivedRecord(absProjectDir); + if (unreadable !== null) { + warn(`Could not read ${unreadable}; the render brings in files outside the project as usual.`); + return true; } + if (!receivedFiles(absProjectDir)(entry)) return true; + const notice = receivedEntryNotice(entry, outsideReferences(absProjectDir, entry)); + if (notice !== null) warn(notice); return false; } From 73cb36a171431c56d706a8a3c7c65d1b982d0149 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 17:12:49 -0800 Subject: [PATCH 15/29] fix(cli): the studio render of a received composition leaves out files outside the project The Studio render route applies the same rule as hyperframes render: when the composition it renders is listed in the received-files record, the job does not bring in files outside the project, and the server log names the references it refuses. --- .../server/studioServer.renderBrowser.test.ts | 39 ++++++++++++++++++- packages/cli/src/server/studioServer.ts | 8 +++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/server/studioServer.renderBrowser.test.ts b/packages/cli/src/server/studioServer.renderBrowser.test.ts index 5377205ede5..9717df58c85 100644 --- a/packages/cli/src/server/studioServer.renderBrowser.test.ts +++ b/packages/cli/src/server/studioServer.renderBrowser.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createStudioServer, type StudioServer } from "./studioServer.js"; @@ -43,9 +43,16 @@ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); -function startStudioRender(extra: Record = {}) { +function startStudioRender(extra: Record = {}, receivedFiles?: string[]) { const dir = mkdtempSync(join(tmpdir(), "hf-studio-render-browser-")); dirs.push(dir); + if (receivedFiles) { + mkdirSync(join(dir, ".hyperframes")); + writeFileSync( + join(dir, ".hyperframes", "received-files.json"), + JSON.stringify({ files: receivedFiles }), + ); + } server = createStudioServer({ projectDir: dir }); return server.adapter.startRender({ project: { dir, id: "p", title: "p" }, @@ -137,3 +144,31 @@ describe("Studio render motion blur", () => { ); }); }); + +describe("Studio render of a received composition", () => { + it.each([ + { name: "a received entry", extra: {}, files: ["index.html"], allowed: false }, + { + name: "a received composition picked to render", + extra: { composition: "scene.html" }, + files: ["scene.html"], + allowed: false, + }, + { name: "the person's own entry", extra: {}, files: ["other.html"], allowed: true }, + { name: "no received-files record", extra: {}, files: undefined, allowed: true }, + ])("brings in outside files for $name: $allowed", async ({ extra, files, allowed }) => { + mocks.resolveRenderBrowser.mockResolvedValue({ + executablePath: "/opt/chrome", + source: "cache", + }); + + startStudioRender(extra, files); + await vi.waitFor(() => expect(mocks.createRenderJob).toHaveBeenCalledTimes(1), { + timeout: 10_000, + }); + + expect(mocks.createRenderJob).toHaveBeenCalledWith( + expect.objectContaining({ allowOutsideProjectAssets: allowed }), + ); + }); +}); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index aa10d8b6cd3..4be70c217e0 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -43,6 +43,7 @@ import { } from "@hyperframes/studio-server/request-identity"; import { mountShareRoutes } from "./shareRoutes.js"; import { isDevMode } from "../utils/env.js"; +import { outsideAssetsAllowed } from "../utils/receivedRender.js"; import { insideHostApp } from "../utils/desktopApp.js"; import { runRenderSetupWorker } from "../utils/cancellableProcess.js"; import { acquireRenderLock, describeRenderLockHolder } from "../utils/renderLock.js"; @@ -667,6 +668,11 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { process.env.PRODUCER_HEADLESS_SHELL_PATH = browser.executablePath; } + const allowOutsideProjectAssets = outsideAssetsAllowed( + opts.project.dir, + opts.composition, + (line) => console.warn(`[studio] ${line}`), + ); const manifestContent = readStudioManualEditManifestContent(opts.project.dir); const manualEditsRenderScript = createStudioManualEditsRenderBodyScript(manifestContent); const job = createRenderJob({ @@ -683,7 +689,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { ...encoderJobOptions(opts), ...(opts.useGpu ? { useGpu: true } : {}), ...(opts.pageMotionBlur ? { pageMotionBlur: opts.pageMotionBlur } : {}), - allowOutsideProjectAssets: true, + allowOutsideProjectAssets, }); renderJob = job; const onProgress = (j: { progress: number; currentStage?: string }) => { From d15a5b21fd5d0677c2b135c7fdaff5e088683209 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 17:39:10 -0800 Subject: [PATCH 16/29] chore(cli): name the unreadable received-files record helper without a comment --- packages/cli/src/utils/privateProjectFile.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 9c4c461e654..94123e66975 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -88,7 +88,6 @@ export function receivedFiles(projectDir: string): (path: string) => boolean { return (path) => files.has(keyOf(path)) || sameFileAsListed(path); } -/** The nearest received-files record when it exists but lists no files a reader can trust, else null. */ export function unreadableReceivedRecord(projectDir: string): string | null { const record = nearestReceivedRecordAtOrAbove(projectDir); return record && !Array.isArray(record.listed) ? join(record.root, RECEIVED_RECORD) : null; From f454138d2285c89a31a4a8ee20945c80a54e58d4 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 18:42:38 -0800 Subject: [PATCH 17/29] fix(cli): local render refuses outside files when any composition it plays was received The received-file rule for local render (CLI and Studio) now checks every page and stylesheet the render pulls in, not only the entry, so an own index.html that plays a received scene also reads nothing outside the project, and the notice names the received file. An unreadable, truncated or empty received-files record refuses outside files too, as publish and cloud upload do, and the notice names the record it could not read. --- .../server/studioServer.renderBrowser.test.ts | 9 +++ packages/cli/src/utils/receivedRender.test.ts | 36 ++++++--- packages/cli/src/utils/receivedRender.ts | 77 +++++++++++++------ 3 files changed, 89 insertions(+), 33 deletions(-) diff --git a/packages/cli/src/server/studioServer.renderBrowser.test.ts b/packages/cli/src/server/studioServer.renderBrowser.test.ts index 9717df58c85..c86b24df196 100644 --- a/packages/cli/src/server/studioServer.renderBrowser.test.ts +++ b/packages/cli/src/server/studioServer.renderBrowser.test.ts @@ -46,6 +46,9 @@ afterEach(() => { function startStudioRender(extra: Record = {}, receivedFiles?: string[]) { const dir = mkdtempSync(join(tmpdir(), "hf-studio-render-browser-")); dirs.push(dir); + writeFileSync(join(dir, "index.html"), `
`); + writeFileSync(join(dir, "scene.html"), "
"); + writeFileSync(join(dir, "other.html"), "
"); if (receivedFiles) { mkdirSync(join(dir, ".hyperframes")); writeFileSync( @@ -154,6 +157,12 @@ describe("Studio render of a received composition", () => { files: ["scene.html"], allowed: false, }, + { + name: "the person's own entry playing a received composition", + extra: {}, + files: ["scene.html"], + allowed: false, + }, { name: "the person's own entry", extra: {}, files: ["other.html"], allowed: true }, { name: "no received-files record", extra: {}, files: undefined, allowed: true }, ])("brings in outside files for $name: $allowed", async ({ extra, files, allowed }) => { diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 99cd2ebc295..f0de9dfbc6a 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { outsideAssetsAllowed } from "./receivedRender.js"; @@ -60,13 +60,29 @@ describe("outsideAssetsAllowed", () => { expect(line).not.toContain("cdn.example"); }); - it("checks the composition being rendered, not index.html", () => { + it("refuses outside files when the own entry plays a received composition, and names it", () => { const dir = project(received("compositions/scene.html")); + for (const entry of ["compositions/scene.html", undefined]) { + const warn = vi.fn(); + expect(outsideAssetsAllowed(dir, entry, warn)).toBe(false); + const line = String(warn.mock.calls[0]?.[0]); + expect(line).toContain("compositions/scene.html came from someone else"); + expect(line).toContain("../../outside/clip.mp4"); + } + }); + + it("refuses outside files when a received stylesheet is pulled in", () => { + const warn = vi.fn(); + expect(outsideAssetsAllowed(project(received("style.css")), undefined, warn)).toBe(false); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("style.css came from someone else")); + }); + + it("keeps outside files when the received file is one the render never opens", () => { + const dir = project(received("unused.html")); + write(join(dir, "unused.html"), ``); const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, "compositions/scene.html", warn)).toBe(false); - expect(warn).toHaveBeenCalledWith(expect.stringContaining("../../outside/clip.mp4")); expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(true); - expect(warn).toHaveBeenCalledTimes(1); + expect(warn).not.toHaveBeenCalled(); }); it("keeps outside files for the person's own entry", () => { @@ -82,15 +98,17 @@ describe("outsideAssetsAllowed", () => { }); it.each(["{not json", "", "{}"])( - "keeps outside files and names the record when it cannot be read: %j", + "refuses outside files and names the record when it cannot be read: %j", (record) => { const dir = project(record); const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(true); + expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(false); expect(warn).toHaveBeenCalledTimes(1); const line = String(warn.mock.calls[0]?.[0]); - expect(line).toContain(join(dir, ".hyperframes", "received-files.json")); - expect(line).not.toContain("someone else"); + expect(line).toContain( + `Could not read ${join(realpathSync(dir), ".hyperframes", "received-files.json")}`, + ); + expect(line).toContain("../outside/secret.js"); }, ); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index a0b38aa8112..0727c60c3dc 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,5 +1,5 @@ import { closeSync, openSync, readSync, statSync } from "node:fs"; -import { dirname, isAbsolute, resolve } from "node:path"; +import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; @@ -97,55 +97,84 @@ function referencedFiles(file: string, projectDir: string) { const isPageOrStylesheet = (path: string) => /\.(?:html?|css)$/i.test(path); -interface OutsideReferences { +interface RenderGraph { assets: Set; compositions: Set; + received: string[]; } -// References from the entry, and the compositions and stylesheets it pulls in, that reach existing files outside the project. -function outsideReferences(projectDir: string, entryFile: string): OutsideReferences { - const found: OutsideReferences = { assets: new Set(), compositions: new Set() }; +function recordReferences(graph: RenderGraph, file: string, projectDir: string): string[] { + const next: string[] = []; + for (const ref of referencedFiles(file, projectDir)) { + if (!linksOutside(projectDir, ref.path)) { + if (isPageOrStylesheet(ref.path)) next.push(ref.path); + } else if (ref.composition) graph.compositions.add(ref.raw); + else graph.assets.add(ref.raw); + } + return next; +} + +// Walks the entry and the compositions and stylesheets it pulls in: which of them came from someone else, and which references reach existing files outside the project. +function walkRenderGraph( + projectDir: string, + entryFile: string, + isReceived: (path: string) => boolean, +): RenderGraph { + const graph: RenderGraph = { assets: new Set(), compositions: new Set(), received: [] }; const visited = new Set(); + const unvisited = (file: string) => + !visited.has(file) && isPathInside(file, projectDir) && isFile(file); const pending = [resolve(projectDir, entryFile)]; for (let file = pending.pop(); file !== undefined; file = pending.pop()) { - if (visited.has(file) || !isPathInside(file, projectDir) || !isFile(file)) continue; + if (!unvisited(file)) continue; visited.add(file); - for (const { raw, path, composition } of referencedFiles(file, projectDir)) { - if (linksOutside(projectDir, path)) - (composition ? found.compositions : found.assets).add(raw); - else if (isPageOrStylesheet(path)) pending.push(path); - } + const path = relative(projectDir, file).split(sep).join("/"); + if (isReceived(path)) graph.received.push(path); + pending.push(...recordReferences(graph, file, projectDir)); } - return found; + return graph; } -function receivedEntryNotice(entry: string, refs: OutsideReferences): string | null { +function refusedReferences(graph: RenderGraph): string { const parts: string[] = []; - if (refs.assets.size > 0) parts.push(`It leaves out ${[...refs.assets].join(", ")}.`); - if (refs.compositions.size > 0) { + if (graph.assets.size > 0) parts.push(` It leaves out ${[...graph.assets].join(", ")}.`); + if (graph.compositions.size > 0) { parts.push( - `It stops on the compositions ${[...refs.compositions].join(", ")}; move them into the project to render them.`, + ` It stops on the compositions ${[...graph.compositions].join(", ")}; move them into the project to render them.`, ); } - if (parts.length === 0) return null; - return `${entry} came from someone else, so the render reads nothing outside the project. ${parts.join(" ")}`; + return parts.join(""); +} + +function receivedNotice(graph: RenderGraph): string | null { + const refused = refusedReferences(graph); + if (refused === "") return null; + const [first, ...others] = graph.received; + const who = others.length === 0 ? first : `${first} and ${others.length} more file(s)`; + return `${who} came from someone else, so the render reads nothing outside the project.${refused}`; } -/** False when the composition a local render opens came from someone else; `warn` then names the references outside the project it refuses. */ +/** False when the composition a local render opens, or any composition or stylesheet it pulls in, came from someone else, or when the received-files record cannot be read; `warn` then says why and names the references outside the project it refuses. */ export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, warn: (line: string) => void, ): boolean { const absProjectDir = resolve(projectDir); - const entry = entryFile ?? "index.html"; + const graph = walkRenderGraph( + absProjectDir, + entryFile ?? "index.html", + receivedFiles(absProjectDir), + ); const unreadable = unreadableReceivedRecord(absProjectDir); if (unreadable !== null) { - warn(`Could not read ${unreadable}; the render brings in files outside the project as usual.`); - return true; + warn( + `Could not read ${unreadable}, so the render treats the project as received and reads nothing outside it.${refusedReferences(graph)}`, + ); + return false; } - if (!receivedFiles(absProjectDir)(entry)) return true; - const notice = receivedEntryNotice(entry, outsideReferences(absProjectDir, entry)); + if (graph.received.length === 0) return true; + const notice = receivedNotice(graph); if (notice !== null) warn(notice); return false; } From 12b6542d55ab14fc885a1a5cc1e54ce17eb394e5 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 19:17:58 -0800 Subject: [PATCH 18/29] fix(cli): decide a received render from the files the compiler reads Local render (CLI and Studio) now leaves outside-file handling as it is for a project with no received-files record or an empty one, without scanning anything. When the record lists files, the compiler's own read list for the composition decides: the bundler runs out of process with a deadline and reports every project file it reads, so stylesheet imports and files past any scan limit count. A received file in that list, a build that fails or runs past its deadline, or an unreadable record refuses outside files. The scan that names refused references in the notice is advisory only: it guards every file system call, tracks visited files by real path, and caps the files and bytes it reads. --- packages/cli/src/commands/render.ts | 6 +- packages/cli/src/renderSetupWorker.ts | 2 + packages/cli/src/server/studioServer.ts | 2 +- packages/cli/src/utils/cancellableProcess.ts | 2 +- packages/cli/src/utils/privateProjectFile.ts | 8 +- packages/cli/src/utils/receivedRender.test.ts | 142 +++++++---- packages/cli/src/utils/receivedRender.ts | 220 ++++++++++++------ 7 files changed, 260 insertions(+), 122 deletions(-) diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index a19e0f0084e..efc870ba37b 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -1149,8 +1149,10 @@ async function executeLocalRender( process.env.HYPERFRAMES_GSAP_VENDOR_DIR = gsapVendorDir; } const producer = await loadProducer(); - const allowOutsideProjectAssets = outsideAssetsAllowed(projectDir, options.entryFile, (line) => - console.warn(c.warn(` ${line}`)), + const allowOutsideProjectAssets = await outsideAssetsAllowed( + projectDir, + options.entryFile, + (line) => console.warn(c.warn(` ${line}`)), ); const deParallelRouterActive = options.manageDeParallelRouterBreaker === true diff --git a/packages/cli/src/renderSetupWorker.ts b/packages/cli/src/renderSetupWorker.ts index 7e5b1ac44bc..67ff6cf2653 100644 --- a/packages/cli/src/renderSetupWorker.ts +++ b/packages/cli/src/renderSetupWorker.ts @@ -5,6 +5,7 @@ import { runBrowserInstall } from "./browser/installRun.js"; import { ensureBrowser, releaseOwnedBrowserInstallLock } from "./browser/manager.js"; import { lintProject } from "./utils/lintProject.js"; import { killOrphanedProcesses } from "./utils/orphanCleanup.js"; +import { compilerReadsInProcess } from "./utils/receivedRender.js"; import { installRenderSetupSignalHandlers, renderSetupErrorLine, @@ -48,6 +49,7 @@ async function runMode(): Promise { input.host ? { host: input.host } : undefined, ); } + if (mode === "render-reads") return compilerReadsInProcess(input.projectDir, input.entryFile); if (mode === "orphan-cleanup") { const killed = killOrphanedProcesses(); if (killed > 0) await new Promise((resolve) => setTimeout(resolve, 600)); diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 4be70c217e0..769b4f09920 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -668,7 +668,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { process.env.PRODUCER_HEADLESS_SHELL_PATH = browser.executablePath; } - const allowOutsideProjectAssets = outsideAssetsAllowed( + const allowOutsideProjectAssets = await outsideAssetsAllowed( opts.project.dir, opts.composition, (line) => console.warn(`[studio] ${line}`), diff --git a/packages/cli/src/utils/cancellableProcess.ts b/packages/cli/src/utils/cancellableProcess.ts index 05a783ae24c..66e30f53cb5 100644 --- a/packages/cli/src/utils/cancellableProcess.ts +++ b/packages/cli/src/utils/cancellableProcess.ts @@ -210,7 +210,7 @@ function tsxLoaderFromCliInstall(): string { } export async function runRenderSetupWorker( - mode: "browser" | "browser-install" | "lint" | "orphan-cleanup", + mode: "browser" | "browser-install" | "lint" | "orphan-cleanup" | "render-reads", input: unknown, options: CancellableProcessOptions, ): Promise { diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 94123e66975..d6b7ce59708 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -88,9 +88,13 @@ export function receivedFiles(projectDir: string): (path: string) => boolean { return (path) => files.has(keyOf(path)) || sameFileAsListed(path); } -export function unreadableReceivedRecord(projectDir: string): string | null { +export function receivedRecordStatus( + projectDir: string, +): { path: string; listedCount: number | null } | null { const record = nearestReceivedRecordAtOrAbove(projectDir); - return record && !Array.isArray(record.listed) ? join(record.root, RECEIVED_RECORD) : null; + if (!record) return null; + const listedCount = Array.isArray(record.listed) ? record.listed.length : null; + return { path: join(record.root, RECEIVED_RECORD), listedCount }; } /** Project files no composition loads, so none is served or uploaded for one: env files, Git data, tool records. */ diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index f0de9dfbc6a..882f0d6a88a 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -1,5 +1,13 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { outsideAssetsAllowed } from "./receivedRender.js"; @@ -33,21 +41,25 @@ function project(record?: string): string { write(join(dir, "compositions", "scene.html"), ``); write(join(dir, "style.css"), `body { background: url(../outside/bg.png); }`); write(join(dir, "assets", "in.png"), "x"); + write(join(dir, "unused.html"), ``); if (record !== undefined) write(join(dir, ".hyperframes", "received-files.json"), record); return dir; } const received = (...files: string[]) => JSON.stringify({ files }); +async function decide(dir: string, entry?: string) { + const warn = vi.fn(); + const allowed = await outsideAssetsAllowed(dir, entry, warn); + return { allowed, warn, line: String(warn.mock.calls[0]?.[0] ?? "") }; +} + describe("outsideAssetsAllowed", () => { - it("refuses outside files for a received entry and names every reference it leaves out", () => { - const warn = vi.fn(); - expect(outsideAssetsAllowed(project(received("index.html")), undefined, warn)).toBe(false); + it("refuses outside files for a received entry and names every reference it leaves out", async () => { + const { allowed, warn, line } = await decide(project(received("index.html"))); + expect(allowed).toBe(false); expect(warn).toHaveBeenCalledTimes(1); - const line = String(warn.mock.calls[0]?.[0]); expect(line).toContain("index.html came from someone else"); - expect(line).toContain("It leaves out"); - expect(line).not.toContain("compositions"); for (const ref of [ "../outside/secret.js", "../outside/pic.png", @@ -60,51 +72,78 @@ describe("outsideAssetsAllowed", () => { expect(line).not.toContain("cdn.example"); }); - it("refuses outside files when the own entry plays a received composition, and names it", () => { + it("refuses outside files when the own entry plays a received composition, and names it", async () => { const dir = project(received("compositions/scene.html")); for (const entry of ["compositions/scene.html", undefined]) { - const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, entry, warn)).toBe(false); - const line = String(warn.mock.calls[0]?.[0]); + const { allowed, line } = await decide(dir, entry); + expect(allowed).toBe(false); expect(line).toContain("compositions/scene.html came from someone else"); - expect(line).toContain("../../outside/clip.mp4"); } }); - it("refuses outside files when a received stylesheet is pulled in", () => { - const warn = vi.fn(); - expect(outsideAssetsAllowed(project(received("style.css")), undefined, warn)).toBe(false); - expect(warn).toHaveBeenCalledWith(expect.stringContaining("style.css came from someone else")); + it("refuses outside files when a linked stylesheet was received", async () => { + const { allowed, line } = await decide(project(received("style.css"))); + expect(allowed).toBe(false); + expect(line).toContain("style.css came from someone else"); }); - it("keeps outside files when the received file is one the render never opens", () => { - const dir = project(received("unused.html")); - write(join(dir, "unused.html"), ``); - const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(true); - expect(warn).not.toHaveBeenCalled(); + it("refuses outside files when a stylesheet @imports a received stylesheet", async () => { + const dir = project(received("theme.css")); + write(join(dir, "style.css"), `@import "theme.css";\nbody { color: red; }`); + write(join(dir, "theme.css"), `body { background: url(../outside/bg.png); }`); + const { allowed } = await decide(dir); + expect(allowed).toBe(false); }); - it("keeps outside files for the person's own entry", () => { - const warn = vi.fn(); - expect(outsideAssetsAllowed(project(received("assets/in.png")), undefined, warn)).toBe(true); + it("refuses outside files when a received composition sits past the scan limit", async () => { + const dir = project(received("compositions/scene.html")); + write( + join(dir, "index.html"), + `

${"a".repeat(2_200_000)}

`, + ); + const { allowed, line } = await decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("compositions/scene.html came from someone else"); + }); + + it("keeps outside files when the received file is one the render never opens", async () => { + const { allowed, warn } = await decide(project(received("unused.html"))); + expect(allowed).toBe(true); expect(warn).not.toHaveBeenCalled(); }); - it("keeps outside files for a project with no received-files record", () => { - const warn = vi.fn(); - expect(outsideAssetsAllowed(project(), undefined, warn)).toBe(true); + it("keeps outside files when the record lists no files", async () => { + expect((await decide(project(received()))).allowed).toBe(true); + }); + + it("keeps outside files for a project with no received-files record", async () => { + const { allowed, warn } = await decide(project()); + expect(allowed).toBe(true); expect(warn).not.toHaveBeenCalled(); }); + it.runIf(process.platform !== "win32")( + "renders an owned project with a symlink loop normally", + async () => { + const dir = project(); + symlinkSync("loop", join(dir, "loop")); + write( + join(dir, "index.html"), + `x`, + ); + expect((await decide(dir)).allowed).toBe(true); + write(join(dir, ".hyperframes", "received-files.json"), received("unused.html")); + await expect(decide(dir)).resolves.toMatchObject({ allowed: true }); + }, + ); + it.each(["{not json", "", "{}"])( "refuses outside files and names the record when it cannot be read: %j", - (record) => { + async (record) => { const dir = project(record); - const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(false); + const { allowed, warn, line } = await decide(dir); + expect(allowed).toBe(false); expect(warn).toHaveBeenCalledTimes(1); - const line = String(warn.mock.calls[0]?.[0]); expect(line).toContain( `Could not read ${join(realpathSync(dir), ".hyperframes", "received-files.json")}`, ); @@ -112,36 +151,39 @@ describe("outsideAssetsAllowed", () => { }, ); - it("says the render stops on a composition outside the project", () => { + it("says the render stops on a composition outside the project", async () => { const dir = project(received("index.html")); write(join(dir, "..", "outside", "shared.html"), "
"); write(join(dir, "index.html"), `
`); - const warn = vi.fn(); - expect(outsideAssetsAllowed(dir, undefined, warn)).toBe(false); - const line = String(warn.mock.calls[0]?.[0]); + const { allowed, line } = await decide(dir); + expect(allowed).toBe(false); expect(line).toContain("stops on the compositions ../outside/shared.html"); - expect(line).not.toContain("leaves out"); }); - it("skips a stylesheet it cannot read instead of failing", () => { - const dir = project(received("index.html")); - rmSync(join(dir, "style.css")); - mkdirSync(join(dir, "style.css")); - if (process.platform !== "win32") { + it.runIf(process.platform !== "win32")( + "skips a stylesheet it cannot read instead of failing", + async () => { + const dir = project(received("index.html")); write(join(dir, "locked.css"), "body { background: url(../outside/bg.png); }"); chmodSync(join(dir, "locked.css"), 0o000); write(join(dir, "index.html"), ``); - } - const warn = vi.fn(); - expect(() => outsideAssetsAllowed(dir, undefined, warn)).not.toThrow(); - expect(warn).toHaveBeenCalledWith(expect.stringContaining("../outside/pic.png")); + const { allowed, line } = await decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("../outside/pic.png"); + }, + ); + + it("refuses outside files when the compiler cannot say what it reads", async () => { + const { allowed, line } = await decide(project(received("index.html")), "missing.html"); + expect(allowed).toBe(false); + expect(line).toContain("Could not tell which files missing.html reads"); }); - it("scans a long unclosed url( run in linear time", () => { - const dir = project(received("index.html")); + it("scans a long unclosed url( run in linear time", async () => { + const dir = project("{not json"); write(join(dir, "style.css"), "url(".repeat(1_000_000)); const started = performance.now(); - outsideAssetsAllowed(dir, undefined, vi.fn()); - expect(performance.now() - started).toBeLessThan(2_000); + await decide(dir); + expect(performance.now() - started).toBeLessThan(5_000); }); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 0727c60c3dc..99f712cf758 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,16 +1,20 @@ -import { closeSync, openSync, readSync, statSync } from "node:fs"; +import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs"; import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; -import { linksOutside, receivedFiles, unreadableReceivedRecord } from "./privateProjectFile.js"; +import { runRenderSetupWorker } from "./cancellableProcess.js"; +import { linksOutside, receivedFiles, receivedRecordStatus } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; const MAX_SCANNED_BYTES = 2 * 1024 * 1024; +const MAX_SCANNED_FILES = 500; +const COMPILER_READS_TIMEOUT_MS = 60_000; interface Reference { raw: string; composition: boolean; + follow: boolean; } function unquote(value: string): string { @@ -26,7 +30,7 @@ function cssReferences(css: string): Reference[] { const close = css.indexOf(")", at + 4); if (close === -1) break; const raw = unquote(css.slice(at + 4, close).trim()); - if (raw) refs.push({ raw, composition: false }); + if (raw) refs.push({ raw, composition: false, follow: true }); at = css.indexOf("url(", close + 1); } return refs; @@ -36,12 +40,13 @@ function htmlReferences(html: string): Reference[] { const { document } = parseHTML(html); const refs: Reference[] = []; for (const el of document.querySelectorAll("[src], [href], [poster], [data-composition-src]")) { + const follow = el.localName === "link"; for (const attr of REFERENCE_ATTRS) { const raw = el.getAttribute(attr)?.trim(); - if (raw) refs.push({ raw, composition: false }); + if (raw) refs.push({ raw, composition: false, follow }); } const composition = el.getAttribute("data-composition-src")?.trim(); - if (composition) refs.push({ raw: composition, composition: true }); + if (composition) refs.push({ raw: composition, composition: true, follow: true }); } for (const style of document.querySelectorAll("style")) { refs.push(...cssReferences(style.textContent ?? "")); @@ -70,14 +75,30 @@ function localPath(raw: string, fromDir: string): string | null { } } -const isFile = (path: string) => statSync(path, { throwIfNoEntry: false })?.isFile() === true; +function isFile(path: string): boolean { + try { + return statSync(path, { throwIfNoEntry: false })?.isFile() === true; + } catch { + return false; + } +} -function readHead(file: string): string | null { +function realOrNull(path: string): string | null { + try { + return realpathSync(path); + } catch { + return null; + } +} + +function readHead(file: string): { text: string; whole: boolean } | null { let fd: number | undefined; try { fd = openSync(file, "r"); - const buffer = Buffer.alloc(Math.min(statSync(file).size, MAX_SCANNED_BYTES)); - return buffer.toString("utf-8", 0, readSync(fd, buffer, 0, buffer.length, 0)); + const size = statSync(file).size; + const buffer = Buffer.alloc(Math.min(size, MAX_SCANNED_BYTES)); + const read = readSync(fd, buffer, 0, buffer.length, 0); + return { text: buffer.toString("utf-8", 0, read), whole: size <= MAX_SCANNED_BYTES }; } catch { return null; } finally { @@ -85,96 +106,163 @@ function readHead(file: string): string | null { } } -function referencedFiles(file: string, projectDir: string) { - const text = readHead(file); - if (text === null) return []; - const refs = /\.css$/i.test(file) ? cssReferences(text) : htmlReferences(text); - return refs.flatMap(({ raw, composition }) => { - const path = localPath(raw, composition ? projectDir : dirname(file)); - return path !== null && isFile(path) ? [{ raw, path, composition }] : []; - }); -} - const isPageOrStylesheet = (path: string) => /\.(?:html?|css)$/i.test(path); -interface RenderGraph { +interface OutsideReferences { assets: Set; compositions: Set; - received: string[]; + complete: boolean; +} + +function referencesIn(found: OutsideReferences, file: string): Reference[] { + const read = readHead(file); + if (read === null || !read.whole) found.complete = false; + if (read === null) return []; + return /\.css$/i.test(file) ? cssReferences(read.text) : htmlReferences(read.text); } -function recordReferences(graph: RenderGraph, file: string, projectDir: string): string[] { +function noteReference( + found: OutsideReferences, + ref: Reference, + path: string, + projectDir: string, +): string | null { + try { + if (linksOutside(projectDir, path)) { + (ref.composition ? found.compositions : found.assets).add(ref.raw); + return null; + } + } catch { + found.complete = false; + return null; + } + return ref.follow && isPageOrStylesheet(path) ? path : null; +} + +function scanFile(found: OutsideReferences, file: string, projectDir: string): string[] { const next: string[] = []; - for (const ref of referencedFiles(file, projectDir)) { - if (!linksOutside(projectDir, ref.path)) { - if (isPageOrStylesheet(ref.path)) next.push(ref.path); - } else if (ref.composition) graph.compositions.add(ref.raw); - else graph.assets.add(ref.raw); + for (const ref of referencesIn(found, file)) { + const path = localPath(ref.raw, ref.composition ? projectDir : dirname(file)); + if (path === null || !isFile(path)) continue; + const follow = noteReference(found, ref, path, projectDir); + if (follow !== null) next.push(follow); } return next; } -// Walks the entry and the compositions and stylesheets it pulls in: which of them came from someone else, and which references reach existing files outside the project. -function walkRenderGraph( - projectDir: string, - entryFile: string, - isReceived: (path: string) => boolean, -): RenderGraph { - const graph: RenderGraph = { assets: new Set(), compositions: new Set(), received: [] }; +// Names the references outside the project in the entry and the compositions and stylesheets it pulls in; only the notice reads it. +function outsideReferences(projectDir: string, entryFile: string): OutsideReferences { + const found: OutsideReferences = { assets: new Set(), compositions: new Set(), complete: true }; const visited = new Set(); - const unvisited = (file: string) => - !visited.has(file) && isPathInside(file, projectDir) && isFile(file); const pending = [resolve(projectDir, entryFile)]; for (let file = pending.pop(); file !== undefined; file = pending.pop()) { - if (!unvisited(file)) continue; - visited.add(file); - const path = relative(projectDir, file).split(sep).join("/"); - if (isReceived(path)) graph.received.push(path); - pending.push(...recordReferences(graph, file, projectDir)); + const real = realOrNull(file); + if (real === null || visited.has(real) || !isPathInside(file, projectDir)) continue; + if (visited.size >= MAX_SCANNED_FILES) { + found.complete = false; + break; + } + visited.add(real); + pending.push(...scanFile(found, file, projectDir)); } - return graph; + return found; } -function refusedReferences(graph: RenderGraph): string { +function refusedReferences(found: OutsideReferences): string { const parts: string[] = []; - if (graph.assets.size > 0) parts.push(` It leaves out ${[...graph.assets].join(", ")}.`); - if (graph.compositions.size > 0) { + if (found.assets.size > 0) parts.push(` It leaves out ${[...found.assets].join(", ")}.`); + if (found.compositions.size > 0) { parts.push( - ` It stops on the compositions ${[...graph.compositions].join(", ")}; move them into the project to render them.`, + ` It stops on the compositions ${[...found.compositions].join(", ")}; move them into the project to render them.`, ); } + if (!found.complete) parts.push(" Some files could not be checked for references."); return parts.join(""); } -function receivedNotice(graph: RenderGraph): string | null { - const refused = refusedReferences(graph); - if (refused === "") return null; - const [first, ...others] = graph.received; - const who = others.length === 0 ? first : `${first} and ${others.length} more file(s)`; - return `${who} came from someone else, so the render reads nothing outside the project.${refused}`; +function projectRelative(projectDir: string, realProjectDir: string | null, path: string): string { + const rel = relative(projectDir, path); + const inside = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); + return (inside || realProjectDir === null ? rel : relative(realProjectDir, path)) + .split(sep) + .join("/"); } -/** False when the composition a local render opens, or any composition or stylesheet it pulls in, came from someone else, or when the received-files record cannot be read; `warn` then says why and names the references outside the project it refuses. */ -export function outsideAssetsAllowed( +/** The project files the compiler reads, or looks for, to build this composition. */ +export async function compilerReadsInProcess( + projectDir: string, + entryFile: string, +): Promise { + const { bundleToSingleHtml } = await import("@hyperframes/core/compiler"); + const reads: string[] = []; + await bundleToSingleHtml(projectDir, { + entryFile, + runtime: "placeholder", + inlineAssets: false, + staticGuard: false, + onRead: (path) => reads.push(path), + }); + const realProjectDir = realOrNull(projectDir); + return reads.map((path) => projectRelative(projectDir, realProjectDir, path)); +} + +// Out of process with a deadline: a build that fails or runs long cannot say what it reads. +async function compilerReads(projectDir: string, entryFile: string): Promise { + try { + const reads = await runRenderSetupWorker( + "render-reads", + { projectDir, entryFile }, + { timeoutMs: COMPILER_READS_TIMEOUT_MS, maxBufferBytes: 16 * 1024 * 1024 }, + ); + return Array.isArray(reads) ? reads.map(String) : null; + } catch { + return null; + } +} + +function receivedAmong(projectDir: string, paths: string[]): string[] { + const isReceived = receivedFiles(projectDir); + return [...new Set(paths)].filter((path) => { + try { + return isReceived(path); + } catch { + return true; + } + }); +} + +/** False when the received-files record cannot be read, or the compiler reads a received file, or cannot say what it reads, to build this composition; `warn` then says why and names the references outside the project it refuses. */ +export async function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, warn: (line: string) => void, -): boolean { +): Promise { const absProjectDir = resolve(projectDir); - const graph = walkRenderGraph( - absProjectDir, - entryFile ?? "index.html", - receivedFiles(absProjectDir), - ); - const unreadable = unreadableReceivedRecord(absProjectDir); - if (unreadable !== null) { + const record = receivedRecordStatus(absProjectDir); + if (record === null || record.listedCount === 0) return true; + const entry = entryFile ?? "index.html"; + if (record.listedCount === null) { + const refused = refusedReferences(outsideReferences(absProjectDir, entry)); warn( - `Could not read ${unreadable}, so the render treats the project as received and reads nothing outside it.${refusedReferences(graph)}`, + `Could not read ${record.path}, so the render treats the project as received and reads nothing outside it.${refused}`, ); return false; } - if (graph.received.length === 0) return true; - const notice = receivedNotice(graph); - if (notice !== null) warn(notice); + const reads = await compilerReads(absProjectDir, entry); + const received = reads === null ? null : receivedAmong(absProjectDir, reads); + if (received !== null && received.length === 0) return true; + const found = outsideReferences(absProjectDir, entry); + const refused = refusedReferences(found); + if (received === null) { + warn( + `Could not tell which files ${entry} reads, so the render reads nothing outside the project.${refused}`, + ); + } else if (refused !== "") { + const [first, ...others] = received; + const who = others.length === 0 ? first : `${first} and ${others.length} more file(s)`; + warn( + `${who} came from someone else, so the render reads nothing outside the project.${refused}`, + ); + } return false; } From fda9855af79309c03e5e2f0cc7797f3561976278 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 21:07:49 -0800 Subject: [PATCH 19/29] fix(cli,producer): decide a received render with the render compiler's own composition traversal The producer exports renderCompositionFiles, which walks data-composition-src with the same resolution, normalization and private file rules the render's sub-composition pass uses; that pass now calls the same helper. The received-render decision adds those files to the bundler's read list, so leading-slash and percent-encoded references the render reads count. The advisory scan resolves compositions the same way and reads template contents. --- packages/cli/src/utils/receivedRender.test.ts | 52 ++++++++++++++ packages/cli/src/utils/receivedRender.ts | 45 +++++++++---- packages/producer/src/index.ts | 1 + .../producer/src/services/htmlCompiler.ts | 67 +++++++++++++------ 4 files changed, 133 insertions(+), 32 deletions(-) diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 882f0d6a88a..cc8c4adefdc 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -10,6 +10,7 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { compileForRender } from "../../../producer/src/services/htmlCompiler.js"; import { outsideAssetsAllowed } from "./receivedRender.js"; let root: string | undefined; @@ -186,4 +187,55 @@ describe("outsideAssetsAllowed", () => { await decide(dir); expect(performance.now() - started).toBeLessThan(5_000); }); + + describe("parity with the render compiler", () => { + const scene = (id: string) => + ``; + + it.each([ + { + name: "a root-relative reference with a leading slash", + files: { "compositions/scene.html": scene("received-scene") }, + src: "/compositions/scene.html", + receivedFile: "compositions/scene.html", + }, + { + name: "a percent-encoded reference", + files: { "compositions/my scene.html": scene("received-scene") }, + src: "compositions/my%20scene.html", + receivedFile: "compositions/my scene.html", + }, + { + name: "a nested reference resolved from the project root", + files: { + "compositions/outer.html": + ``, + "compositions/inner.html": scene("received-scene"), + }, + src: "compositions/outer.html", + receivedFile: "compositions/inner.html", + }, + ])("refuses outside files for $name the render compiler reads", async (probe) => { + const dir = project(received(probe.receivedFile)); + for (const [file, text] of Object.entries(probe.files)) write(join(dir, file), text); + write( + join(dir, "index.html"), + `
` + + `
`, + ); + + const compiled = await compileForRender(dir, join(dir, "index.html"), join(dir, ".dl"), { + allowOutsideProjectAssets: true, + }); + const rendered = [compiled.html, ...compiled.subCompositions.values()].join("\n"); + expect(rendered).toContain("received-scene-marker"); + + const { allowed, line } = await decide(dir); + expect(allowed).toBe(false); + expect(line).toContain(`${probe.receivedFile} came from someone else`); + expect(line).toContain("../../outside/pic.png"); + }); + }); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 99f712cf758..3d957ef3878 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -3,7 +3,9 @@ import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; +import { resolveCompositionSrc } from "@hyperframes/parsers/asset-resolution"; import { runRenderSetupWorker } from "./cancellableProcess.js"; +import { loadProducer } from "./producer.js"; import { linksOutside, receivedFiles, receivedRecordStatus } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; @@ -36,24 +38,30 @@ function cssReferences(css: string): Reference[] { return refs; } +function elementReferences(el: Element): Reference[] { + const follow = el.localName === "link"; + const refs: Reference[] = REFERENCE_ATTRS.flatMap((attr) => { + const raw = el.getAttribute(attr)?.trim(); + return raw ? [{ raw, composition: false, follow }] : []; + }); + const composition = el.getAttribute("data-composition-src")?.trim(); + if (composition) refs.push({ raw: composition, composition: true, follow: true }); + return refs; +} + function htmlReferences(html: string): Reference[] { const { document } = parseHTML(html); - const refs: Reference[] = []; - for (const el of document.querySelectorAll("[src], [href], [poster], [data-composition-src]")) { - const follow = el.localName === "link"; - for (const attr of REFERENCE_ATTRS) { - const raw = el.getAttribute(attr)?.trim(); - if (raw) refs.push({ raw, composition: false, follow }); - } - const composition = el.getAttribute("data-composition-src")?.trim(); - if (composition) refs.push({ raw: composition, composition: true, follow: true }); - } + const hosts = document.querySelectorAll("[src], [href], [poster], [data-composition-src]"); + const refs = [...hosts].flatMap(elementReferences); for (const style of document.querySelectorAll("style")) { refs.push(...cssReferences(style.textContent ?? "")); } for (const el of document.querySelectorAll("[style]")) { refs.push(...cssReferences(el.getAttribute("style") ?? "")); } + for (const template of document.querySelectorAll("template")) { + refs.push(...htmlReferences(template.innerHTML)); + } return refs; } @@ -114,6 +122,16 @@ interface OutsideReferences { complete: boolean; } +// A composition resolves as the render compiler resolves it; one that leaves the project resolves as written. +function referencePath(ref: Reference, file: string, projectDir: string): string | null { + if (!ref.composition) return localPath(ref.raw, dirname(file)); + try { + return resolveCompositionSrc(projectDir, ref.raw) ?? localPath(ref.raw, projectDir); + } catch { + return null; + } +} + function referencesIn(found: OutsideReferences, file: string): Reference[] { const read = readHead(file); if (read === null || !read.whole) found.complete = false; @@ -142,7 +160,7 @@ function noteReference( function scanFile(found: OutsideReferences, file: string, projectDir: string): string[] { const next: string[] = []; for (const ref of referencesIn(found, file)) { - const path = localPath(ref.raw, ref.composition ? projectDir : dirname(file)); + const path = referencePath(ref, file, projectDir); if (path === null || !isFile(path)) continue; const follow = noteReference(found, ref, path, projectDir); if (follow !== null) next.push(follow); @@ -188,13 +206,14 @@ function projectRelative(projectDir: string, realProjectDir: string | null, path .join("/"); } -/** The project files the compiler reads, or looks for, to build this composition. */ +/** The project files a render of this composition reads: the render compiler's own composition traversal, plus every file the bundler reads or looks for. */ export async function compilerReadsInProcess( projectDir: string, entryFile: string, ): Promise { + const { renderCompositionFiles } = await loadProducer(); + const reads = renderCompositionFiles(projectDir, resolve(projectDir, entryFile)); const { bundleToSingleHtml } = await import("@hyperframes/core/compiler"); - const reads: string[] = []; await bundleToSingleHtml(projectDir, { entryFile, runtime: "placeholder", diff --git a/packages/producer/src/index.ts b/packages/producer/src/index.ts index a339817859e..a3fd0b17486 100644 --- a/packages/producer/src/index.ts +++ b/packages/producer/src/index.ts @@ -74,6 +74,7 @@ export { localizeRemoteMediaSources, localizeRemoteImageSources, localizeRemoteFontFaces, + renderCompositionFiles, } from "./services/htmlCompiler.js"; // ── Frame capture (lower-level) ───────────────────────────────────────────── diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 9c05aea5842..6bbcfd9268a 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -802,6 +802,48 @@ async function compileHtmlFile( return { html: compiledHtml, unresolvedCompositions }; } +/** The sub-composition files a render reads for `hosts`, resolved and normalized as the render resolves them. */ +function subCompositionReads( + hosts: Iterable, + projectDir: string, + visited: ReadonlySet, + assetRoot: string | undefined, +): Array<{ srcPath: string; filePath: string; rawSubHtml: string }> { + const reads: Array<{ srcPath: string; filePath: string; rawSubHtml: string }> = []; + for (const el of hosts) { + const srcPath = el.getAttribute("data-composition-src"); + if (!srcPath) continue; + const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); + if (filePath === null || isPrivateCompositionFile(projectDir, filePath)) continue; + if (visited.has(filePath)) continue; + const read = readProjectFile(filePath); + if (read.kind !== "file") continue; + reads.push({ srcPath, filePath, rawSubHtml: normalizeCompositionSrcs(read.text, projectDir) }); + } + return reads; +} + +/** The entry and every sub-composition file a render of it reads, found by the render's own traversal. */ +export function renderCompositionFiles( + projectDir: string, + htmlPath: string, + assetRoot?: string, +): string[] { + const files = [htmlPath]; + const seen = new Set([htmlPath]); + const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath); + const pending = [normalizeCompositionSrcs(entryHtml, projectDir)]; + for (let html = pending.pop(); html !== undefined; html = pending.pop()) { + const hosts = parseHTML(html).document.querySelectorAll("[data-composition-src]"); + for (const read of subCompositionReads(hosts, projectDir, seen, assetRoot)) { + seen.add(read.filePath); + files.push(read.filePath); + pending.push(read.rawSubHtml); + } + } + return files; +} + /** * Compile every sub-composition referenced via data-composition-src, keyed by * its source path for the inliner to hoist into the render document. @@ -834,27 +876,14 @@ async function parseSubCompositions( nestedVisited: Set; }> = []; - for (const el of compEls) { - const srcPath = el.getAttribute("data-composition-src"); - if (!srcPath) continue; - - const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); - if (filePath === null || isPrivateCompositionFile(projectDir, filePath)) continue; - - // Circular reference guard - if (visited.has(filePath)) { - continue; - } - - const read = readProjectFile(filePath); - if (read.kind !== "file") { - continue; - } - - const rawSubHtml = normalizeCompositionSrcs(read.text, projectDir); + for (const { srcPath, filePath, rawSubHtml } of subCompositionReads( + compEls, + projectDir, + visited, + assetRoot, + )) { const nestedVisited = new Set(visited); nestedVisited.add(filePath); - workItems.push({ srcPath, filePath, rawSubHtml, nestedVisited }); } From 2f949329c080bf445347557ca87690ede075b9e7 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 21:37:46 -0800 Subject: [PATCH 20/29] fix(cli): refuse outside files in a local render whenever the project has received files A local render (CLI and Studio) reads nothing outside the project when the project's received-files record lists any file, or cannot be read. No static list matches what a render consumes: the page loads its stylesheets and scripts through the browser at capture time, and scripts can load more, so the decision no longer depends on one. The reference scan stays only to name what the notice says is left out. This drops the out-of-process bundler read list and the producer composition walk added for that decision. --- packages/cli/src/commands/render.test.ts | 7 +- packages/cli/src/commands/render.ts | 6 +- packages/cli/src/renderSetupWorker.ts | 2 - .../server/studioServer.renderBrowser.test.ts | 8 +- packages/cli/src/server/studioServer.ts | 2 +- packages/cli/src/utils/cancellableProcess.ts | 2 +- packages/cli/src/utils/receivedRender.test.ts | 142 ++++++++++++------ packages/cli/src/utils/receivedRender.ts | 94 ++---------- packages/producer/src/index.ts | 1 - .../producer/src/services/htmlCompiler.ts | 67 +++------ 10 files changed, 150 insertions(+), 181 deletions(-) diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 824d28e5d74..0ab56df17ea 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -590,7 +590,12 @@ describe("renderLocal browser GPU config", () => { it.each([ { name: "a received entry", files: ["index.html"], allowed: false }, - { name: "the person's own entry", files: ["assets/in.png"], allowed: true }, + { + name: "a record listing a file the render never opens", + files: ["assets/in.png"], + allowed: false, + }, + { name: "a record listing no files", files: [], allowed: true }, { name: "no received-files record", files: undefined, allowed: true }, ])("brings in outside files for $name: $allowed", async ({ files, allowed }) => { const projectDir = mkdtempSync(join(tmpdir(), "hf-render-received-")); diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index efc870ba37b..a19e0f0084e 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -1149,10 +1149,8 @@ async function executeLocalRender( process.env.HYPERFRAMES_GSAP_VENDOR_DIR = gsapVendorDir; } const producer = await loadProducer(); - const allowOutsideProjectAssets = await outsideAssetsAllowed( - projectDir, - options.entryFile, - (line) => console.warn(c.warn(` ${line}`)), + const allowOutsideProjectAssets = outsideAssetsAllowed(projectDir, options.entryFile, (line) => + console.warn(c.warn(` ${line}`)), ); const deParallelRouterActive = options.manageDeParallelRouterBreaker === true diff --git a/packages/cli/src/renderSetupWorker.ts b/packages/cli/src/renderSetupWorker.ts index 67ff6cf2653..7e5b1ac44bc 100644 --- a/packages/cli/src/renderSetupWorker.ts +++ b/packages/cli/src/renderSetupWorker.ts @@ -5,7 +5,6 @@ import { runBrowserInstall } from "./browser/installRun.js"; import { ensureBrowser, releaseOwnedBrowserInstallLock } from "./browser/manager.js"; import { lintProject } from "./utils/lintProject.js"; import { killOrphanedProcesses } from "./utils/orphanCleanup.js"; -import { compilerReadsInProcess } from "./utils/receivedRender.js"; import { installRenderSetupSignalHandlers, renderSetupErrorLine, @@ -49,7 +48,6 @@ async function runMode(): Promise { input.host ? { host: input.host } : undefined, ); } - if (mode === "render-reads") return compilerReadsInProcess(input.projectDir, input.entryFile); if (mode === "orphan-cleanup") { const killed = killOrphanedProcesses(); if (killed > 0) await new Promise((resolve) => setTimeout(resolve, 600)); diff --git a/packages/cli/src/server/studioServer.renderBrowser.test.ts b/packages/cli/src/server/studioServer.renderBrowser.test.ts index c86b24df196..73f58ba00b4 100644 --- a/packages/cli/src/server/studioServer.renderBrowser.test.ts +++ b/packages/cli/src/server/studioServer.renderBrowser.test.ts @@ -163,7 +163,13 @@ describe("Studio render of a received composition", () => { files: ["scene.html"], allowed: false, }, - { name: "the person's own entry", extra: {}, files: ["other.html"], allowed: true }, + { + name: "a record listing a file the render never opens", + extra: {}, + files: ["other.html"], + allowed: false, + }, + { name: "a record listing no files", extra: {}, files: [], allowed: true }, { name: "no received-files record", extra: {}, files: undefined, allowed: true }, ])("brings in outside files for $name: $allowed", async ({ extra, files, allowed }) => { mocks.resolveRenderBrowser.mockResolvedValue({ diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts index 769b4f09920..4be70c217e0 100644 --- a/packages/cli/src/server/studioServer.ts +++ b/packages/cli/src/server/studioServer.ts @@ -668,7 +668,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer { process.env.PRODUCER_HEADLESS_SHELL_PATH = browser.executablePath; } - const allowOutsideProjectAssets = await outsideAssetsAllowed( + const allowOutsideProjectAssets = outsideAssetsAllowed( opts.project.dir, opts.composition, (line) => console.warn(`[studio] ${line}`), diff --git a/packages/cli/src/utils/cancellableProcess.ts b/packages/cli/src/utils/cancellableProcess.ts index 66e30f53cb5..05a783ae24c 100644 --- a/packages/cli/src/utils/cancellableProcess.ts +++ b/packages/cli/src/utils/cancellableProcess.ts @@ -210,7 +210,7 @@ function tsxLoaderFromCliInstall(): string { } export async function runRenderSetupWorker( - mode: "browser" | "browser-install" | "lint" | "orphan-cleanup" | "render-reads", + mode: "browser" | "browser-install" | "lint" | "orphan-cleanup", input: unknown, options: CancellableProcessOptions, ): Promise { diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index cc8c4adefdc..ac2774dc578 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -49,18 +49,20 @@ function project(record?: string): string { const received = (...files: string[]) => JSON.stringify({ files }); -async function decide(dir: string, entry?: string) { +const SOMEONE_ELSE = "This project has files that came from someone else"; + +function decide(dir: string, entry?: string) { const warn = vi.fn(); - const allowed = await outsideAssetsAllowed(dir, entry, warn); + const allowed = outsideAssetsAllowed(dir, entry, warn); return { allowed, warn, line: String(warn.mock.calls[0]?.[0] ?? "") }; } describe("outsideAssetsAllowed", () => { - it("refuses outside files for a received entry and names every reference it leaves out", async () => { - const { allowed, warn, line } = await decide(project(received("index.html"))); + it("refuses outside files for a received entry and names every reference it leaves out", () => { + const { allowed, warn, line } = decide(project(received("index.html"))); expect(allowed).toBe(false); expect(warn).toHaveBeenCalledTimes(1); - expect(line).toContain("index.html came from someone else"); + expect(line).toContain(SOMEONE_ELSE); for (const ref of [ "../outside/secret.js", "../outside/pic.png", @@ -73,76 +75,77 @@ describe("outsideAssetsAllowed", () => { expect(line).not.toContain("cdn.example"); }); - it("refuses outside files when the own entry plays a received composition, and names it", async () => { + it("refuses outside files when the own entry plays a received composition, and names it", () => { const dir = project(received("compositions/scene.html")); for (const entry of ["compositions/scene.html", undefined]) { - const { allowed, line } = await decide(dir, entry); + const { allowed, line } = decide(dir, entry); expect(allowed).toBe(false); - expect(line).toContain("compositions/scene.html came from someone else"); + expect(line).toContain(SOMEONE_ELSE); } }); - it("refuses outside files when a linked stylesheet was received", async () => { - const { allowed, line } = await decide(project(received("style.css"))); + it("refuses outside files when a linked stylesheet was received", () => { + const { allowed, line } = decide(project(received("style.css"))); expect(allowed).toBe(false); - expect(line).toContain("style.css came from someone else"); + expect(line).toContain(SOMEONE_ELSE); }); - it("refuses outside files when a stylesheet @imports a received stylesheet", async () => { + it("refuses outside files when a stylesheet @imports a received stylesheet", () => { const dir = project(received("theme.css")); write(join(dir, "style.css"), `@import "theme.css";\nbody { color: red; }`); write(join(dir, "theme.css"), `body { background: url(../outside/bg.png); }`); - const { allowed } = await decide(dir); + const { allowed } = decide(dir); expect(allowed).toBe(false); }); - it("refuses outside files when a received composition sits past the scan limit", async () => { + it("refuses outside files when a received composition sits past the scan limit", () => { const dir = project(received("compositions/scene.html")); write( join(dir, "index.html"), `

${"a".repeat(2_200_000)}

`, ); - const { allowed, line } = await decide(dir); + const { allowed, line } = decide(dir); expect(allowed).toBe(false); - expect(line).toContain("compositions/scene.html came from someone else"); + expect(line).toContain(SOMEONE_ELSE); }); - it("keeps outside files when the received file is one the render never opens", async () => { - const { allowed, warn } = await decide(project(received("unused.html"))); - expect(allowed).toBe(true); - expect(warn).not.toHaveBeenCalled(); + it("refuses outside files whenever the record lists a file, even one the render never opens", () => { + const { allowed, line } = decide(project(received("unused.html"))); + expect(allowed).toBe(false); + expect(line).toContain(SOMEONE_ELSE); + expect(line).toContain("../outside/secret.js"); }); - it("keeps outside files when the record lists no files", async () => { - expect((await decide(project(received()))).allowed).toBe(true); + it("keeps outside files when the record lists no files", () => { + expect(decide(project(received())).allowed).toBe(true); }); - it("keeps outside files for a project with no received-files record", async () => { - const { allowed, warn } = await decide(project()); + it("keeps outside files for a project with no received-files record", () => { + const { allowed, warn } = decide(project()); expect(allowed).toBe(true); expect(warn).not.toHaveBeenCalled(); }); it.runIf(process.platform !== "win32")( "renders an owned project with a symlink loop normally", - async () => { + () => { const dir = project(); symlinkSync("loop", join(dir, "loop")); write( join(dir, "index.html"), `x`, ); - expect((await decide(dir)).allowed).toBe(true); + expect(decide(dir).allowed).toBe(true); write(join(dir, ".hyperframes", "received-files.json"), received("unused.html")); - await expect(decide(dir)).resolves.toMatchObject({ allowed: true }); + expect(() => decide(dir)).not.toThrow(); }, ); it.each(["{not json", "", "{}"])( "refuses outside files and names the record when it cannot be read: %j", - async (record) => { + (record) => { const dir = project(record); - const { allowed, warn, line } = await decide(dir); + const { allowed, warn, line } = decide(dir); expect(allowed).toBe(false); expect(warn).toHaveBeenCalledTimes(1); expect(line).toContain( @@ -152,39 +155,33 @@ describe("outsideAssetsAllowed", () => { }, ); - it("says the render stops on a composition outside the project", async () => { + it("says the render stops on a composition outside the project", () => { const dir = project(received("index.html")); write(join(dir, "..", "outside", "shared.html"), "
"); write(join(dir, "index.html"), `
`); - const { allowed, line } = await decide(dir); + const { allowed, line } = decide(dir); expect(allowed).toBe(false); expect(line).toContain("stops on the compositions ../outside/shared.html"); }); it.runIf(process.platform !== "win32")( "skips a stylesheet it cannot read instead of failing", - async () => { + () => { const dir = project(received("index.html")); write(join(dir, "locked.css"), "body { background: url(../outside/bg.png); }"); chmodSync(join(dir, "locked.css"), 0o000); write(join(dir, "index.html"), ``); - const { allowed, line } = await decide(dir); + const { allowed, line } = decide(dir); expect(allowed).toBe(false); expect(line).toContain("../outside/pic.png"); }, ); - it("refuses outside files when the compiler cannot say what it reads", async () => { - const { allowed, line } = await decide(project(received("index.html")), "missing.html"); - expect(allowed).toBe(false); - expect(line).toContain("Could not tell which files missing.html reads"); - }); - - it("scans a long unclosed url( run in linear time", async () => { + it("scans a long unclosed url( run in linear time", () => { const dir = project("{not json"); write(join(dir, "style.css"), "url(".repeat(1_000_000)); const started = performance.now(); - await decide(dir); + decide(dir); expect(performance.now() - started).toBeLessThan(5_000); }); @@ -199,12 +196,14 @@ describe("outsideAssetsAllowed", () => { files: { "compositions/scene.html": scene("received-scene") }, src: "/compositions/scene.html", receivedFile: "compositions/scene.html", + consumed: "received-scene-marker", }, { name: "a percent-encoded reference", files: { "compositions/my scene.html": scene("received-scene") }, src: "compositions/my%20scene.html", receivedFile: "compositions/my scene.html", + consumed: "received-scene-marker", }, { name: "a nested reference resolved from the project root", @@ -216,6 +215,61 @@ describe("outsideAssetsAllowed", () => { }, src: "compositions/outer.html", receivedFile: "compositions/inner.html", + consumed: "received-scene-marker", + }, + { + name: "an owned scene's received stylesheet", + files: { + "compositions/scene.html": + ``, + "compositions/scene.css": "body { color: red; }", + }, + src: "compositions/scene.html", + receivedFile: "compositions/scene.css", + consumed: "scene.css", + }, + { + name: "a received stylesheet of an owned scene nested in an owned scene", + files: { + "compositions/outer.html": + ``, + "compositions/scene.html": + ``, + "compositions/scene.css": "body { color: red; }", + }, + src: "compositions/outer.html", + receivedFile: "compositions/scene.css", + consumed: "scene.css", + }, + { + name: "an owned scene's received script", + files: { + "compositions/scene.html": + ``, + "compositions/scene.js": "window.sceneLoaded = true;", + }, + src: "compositions/scene.html", + receivedFile: "compositions/scene.js", + consumed: "scene.js", + }, + { + name: "a received script of an owned scene nested in an owned scene", + files: { + "compositions/outer.html": + ``, + "compositions/scene.html": + ``, + "compositions/scene.js": "window.sceneLoaded = true;", + }, + src: "compositions/outer.html", + receivedFile: "compositions/scene.js", + consumed: "scene.js", }, ])("refuses outside files for $name the render compiler reads", async (probe) => { const dir = project(received(probe.receivedFile)); @@ -230,11 +284,11 @@ describe("outsideAssetsAllowed", () => { allowOutsideProjectAssets: true, }); const rendered = [compiled.html, ...compiled.subCompositions.values()].join("\n"); - expect(rendered).toContain("received-scene-marker"); + expect(rendered).toContain(probe.consumed); - const { allowed, line } = await decide(dir); + const { allowed, line } = decide(dir); expect(allowed).toBe(false); - expect(line).toContain(`${probe.receivedFile} came from someone else`); + expect(line).toContain(SOMEONE_ELSE); expect(line).toContain("../../outside/pic.png"); }); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 3d957ef3878..cc8019e49f6 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,17 +1,14 @@ import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs"; -import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; +import { dirname, isAbsolute, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; import { resolveCompositionSrc } from "@hyperframes/parsers/asset-resolution"; -import { runRenderSetupWorker } from "./cancellableProcess.js"; -import { loadProducer } from "./producer.js"; -import { linksOutside, receivedFiles, receivedRecordStatus } from "./privateProjectFile.js"; +import { linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; const MAX_SCANNED_BYTES = 2 * 1024 * 1024; const MAX_SCANNED_FILES = 500; -const COMPILER_READS_TIMEOUT_MS = 60_000; interface Reference { raw: string; @@ -106,7 +103,10 @@ function readHead(file: string): { text: string; whole: boolean } | null { const size = statSync(file).size; const buffer = Buffer.alloc(Math.min(size, MAX_SCANNED_BYTES)); const read = readSync(fd, buffer, 0, buffer.length, 0); - return { text: buffer.toString("utf-8", 0, read), whole: size <= MAX_SCANNED_BYTES }; + return { + text: buffer.toString("utf-8", 0, read), + whole: size <= MAX_SCANNED_BYTES, + }; } catch { return null; } finally { @@ -170,7 +170,11 @@ function scanFile(found: OutsideReferences, file: string, projectDir: string): s // Names the references outside the project in the entry and the compositions and stylesheets it pulls in; only the notice reads it. function outsideReferences(projectDir: string, entryFile: string): OutsideReferences { - const found: OutsideReferences = { assets: new Set(), compositions: new Set(), complete: true }; + const found: OutsideReferences = { + assets: new Set(), + compositions: new Set(), + complete: true, + }; const visited = new Set(); const pending = [resolve(projectDir, entryFile)]; for (let file = pending.pop(); file !== undefined; file = pending.pop()) { @@ -198,89 +202,23 @@ function refusedReferences(found: OutsideReferences): string { return parts.join(""); } -function projectRelative(projectDir: string, realProjectDir: string | null, path: string): string { - const rel = relative(projectDir, path); - const inside = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); - return (inside || realProjectDir === null ? rel : relative(realProjectDir, path)) - .split(sep) - .join("/"); -} - -/** The project files a render of this composition reads: the render compiler's own composition traversal, plus every file the bundler reads or looks for. */ -export async function compilerReadsInProcess( - projectDir: string, - entryFile: string, -): Promise { - const { renderCompositionFiles } = await loadProducer(); - const reads = renderCompositionFiles(projectDir, resolve(projectDir, entryFile)); - const { bundleToSingleHtml } = await import("@hyperframes/core/compiler"); - await bundleToSingleHtml(projectDir, { - entryFile, - runtime: "placeholder", - inlineAssets: false, - staticGuard: false, - onRead: (path) => reads.push(path), - }); - const realProjectDir = realOrNull(projectDir); - return reads.map((path) => projectRelative(projectDir, realProjectDir, path)); -} - -// Out of process with a deadline: a build that fails or runs long cannot say what it reads. -async function compilerReads(projectDir: string, entryFile: string): Promise { - try { - const reads = await runRenderSetupWorker( - "render-reads", - { projectDir, entryFile }, - { timeoutMs: COMPILER_READS_TIMEOUT_MS, maxBufferBytes: 16 * 1024 * 1024 }, - ); - return Array.isArray(reads) ? reads.map(String) : null; - } catch { - return null; - } -} - -function receivedAmong(projectDir: string, paths: string[]): string[] { - const isReceived = receivedFiles(projectDir); - return [...new Set(paths)].filter((path) => { - try { - return isReceived(path); - } catch { - return true; - } - }); -} - -/** False when the received-files record cannot be read, or the compiler reads a received file, or cannot say what it reads, to build this composition; `warn` then says why and names the references outside the project it refuses. */ -export async function outsideAssetsAllowed( +/** False when the project's received-files record lists any file, or cannot be read: the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ +export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, warn: (line: string) => void, -): Promise { +): boolean { const absProjectDir = resolve(projectDir); const record = receivedRecordStatus(absProjectDir); if (record === null || record.listedCount === 0) return true; - const entry = entryFile ?? "index.html"; + const refused = refusedReferences(outsideReferences(absProjectDir, entryFile ?? "index.html")); if (record.listedCount === null) { - const refused = refusedReferences(outsideReferences(absProjectDir, entry)); warn( `Could not read ${record.path}, so the render treats the project as received and reads nothing outside it.${refused}`, ); - return false; - } - const reads = await compilerReads(absProjectDir, entry); - const received = reads === null ? null : receivedAmong(absProjectDir, reads); - if (received !== null && received.length === 0) return true; - const found = outsideReferences(absProjectDir, entry); - const refused = refusedReferences(found); - if (received === null) { - warn( - `Could not tell which files ${entry} reads, so the render reads nothing outside the project.${refused}`, - ); } else if (refused !== "") { - const [first, ...others] = received; - const who = others.length === 0 ? first : `${first} and ${others.length} more file(s)`; warn( - `${who} came from someone else, so the render reads nothing outside the project.${refused}`, + `This project has files that came from someone else (listed in ${record.path}), so the render reads nothing outside it.${refused}`, ); } return false; diff --git a/packages/producer/src/index.ts b/packages/producer/src/index.ts index a3fd0b17486..a339817859e 100644 --- a/packages/producer/src/index.ts +++ b/packages/producer/src/index.ts @@ -74,7 +74,6 @@ export { localizeRemoteMediaSources, localizeRemoteImageSources, localizeRemoteFontFaces, - renderCompositionFiles, } from "./services/htmlCompiler.js"; // ── Frame capture (lower-level) ───────────────────────────────────────────── diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 6bbcfd9268a..9c05aea5842 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -802,48 +802,6 @@ async function compileHtmlFile( return { html: compiledHtml, unresolvedCompositions }; } -/** The sub-composition files a render reads for `hosts`, resolved and normalized as the render resolves them. */ -function subCompositionReads( - hosts: Iterable, - projectDir: string, - visited: ReadonlySet, - assetRoot: string | undefined, -): Array<{ srcPath: string; filePath: string; rawSubHtml: string }> { - const reads: Array<{ srcPath: string; filePath: string; rawSubHtml: string }> = []; - for (const el of hosts) { - const srcPath = el.getAttribute("data-composition-src"); - if (!srcPath) continue; - const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); - if (filePath === null || isPrivateCompositionFile(projectDir, filePath)) continue; - if (visited.has(filePath)) continue; - const read = readProjectFile(filePath); - if (read.kind !== "file") continue; - reads.push({ srcPath, filePath, rawSubHtml: normalizeCompositionSrcs(read.text, projectDir) }); - } - return reads; -} - -/** The entry and every sub-composition file a render of it reads, found by the render's own traversal. */ -export function renderCompositionFiles( - projectDir: string, - htmlPath: string, - assetRoot?: string, -): string[] { - const files = [htmlPath]; - const seen = new Set([htmlPath]); - const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath); - const pending = [normalizeCompositionSrcs(entryHtml, projectDir)]; - for (let html = pending.pop(); html !== undefined; html = pending.pop()) { - const hosts = parseHTML(html).document.querySelectorAll("[data-composition-src]"); - for (const read of subCompositionReads(hosts, projectDir, seen, assetRoot)) { - seen.add(read.filePath); - files.push(read.filePath); - pending.push(read.rawSubHtml); - } - } - return files; -} - /** * Compile every sub-composition referenced via data-composition-src, keyed by * its source path for the inliner to hoist into the render document. @@ -876,14 +834,27 @@ async function parseSubCompositions( nestedVisited: Set; }> = []; - for (const { srcPath, filePath, rawSubHtml } of subCompositionReads( - compEls, - projectDir, - visited, - assetRoot, - )) { + for (const el of compEls) { + const srcPath = el.getAttribute("data-composition-src"); + if (!srcPath) continue; + + const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); + if (filePath === null || isPrivateCompositionFile(projectDir, filePath)) continue; + + // Circular reference guard + if (visited.has(filePath)) { + continue; + } + + const read = readProjectFile(filePath); + if (read.kind !== "file") { + continue; + } + + const rawSubHtml = normalizeCompositionSrcs(read.text, projectDir); const nestedVisited = new Set(visited); nestedVisited.add(filePath); + workItems.push({ srcPath, filePath, rawSubHtml, nestedVisited }); } From 705ec5b8d98df42c997ec90cbb71accf3ba18d4b Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 21:40:15 -0800 Subject: [PATCH 21/29] fix(cli): refuse outside files only when a received file can load other files A local render (CLI and Studio) reads nothing outside the project when the received-files record cannot be read, or lists a received file that can reference others: an .html, .htm, .css, .js, .mjs, .cjs or .svg name, or content that reads as HTML, SVG or CSS. A project that only received images, video, audio or fonts keeps bringing in outside files as before. --- packages/cli/src/commands/render.test.ts | 7 +-- packages/cli/src/utils/privateProjectFile.ts | 12 +++-- packages/cli/src/utils/receivedRender.test.ts | 26 +++++++++- packages/cli/src/utils/receivedRender.ts | 47 +++++++++++++++++-- 4 files changed, 78 insertions(+), 14 deletions(-) diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 0ab56df17ea..c19dc4f4476 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -590,11 +590,8 @@ describe("renderLocal browser GPU config", () => { it.each([ { name: "a received entry", files: ["index.html"], allowed: false }, - { - name: "a record listing a file the render never opens", - files: ["assets/in.png"], - allowed: false, - }, + { name: "a record listing only an image", files: ["assets/in.png"], allowed: true }, + { name: "a record listing a received stylesheet", files: ["style.css"], allowed: false }, { name: "a record listing no files", files: [], allowed: true }, { name: "no received-files record", files: undefined, allowed: true }, ])("brings in outside files for $name: $allowed", async ({ files, allowed }) => { diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index d6b7ce59708..c6f3bdb2051 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -90,11 +90,17 @@ export function receivedFiles(projectDir: string): (path: string) => boolean { export function receivedRecordStatus( projectDir: string, -): { path: string; listedCount: number | null } | null { +): { path: string; listed: string[] | null } | null { const record = nearestReceivedRecordAtOrAbove(projectDir); if (!record) return null; - const listedCount = Array.isArray(record.listed) ? record.listed.length : null; - return { path: join(record.root, RECEIVED_RECORD), listedCount }; + const path = join(record.root, RECEIVED_RECORD); + if (!Array.isArray(record.listed)) return { path, listed: null }; + const prefix = record.projectDirFromRoot ? `${record.projectDirFromRoot}/` : ""; + const listed = record.listed + .map((entry) => String(entry).normalize("NFC")) + .filter((entry) => entry.startsWith(prefix)) + .map((entry) => join(record.root, entry)); + return { path, listed }; } /** Project files no composition loads, so none is served or uploaded for one: env files, Git data, tool records. */ diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index ac2774dc578..82995ae4ca6 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -49,7 +49,7 @@ function project(record?: string): string { const received = (...files: string[]) => JSON.stringify({ files }); -const SOMEONE_ELSE = "This project has files that came from someone else"; +const SOMEONE_ELSE = "came from someone else and can load other files"; function decide(dir: string, entry?: string) { const warn = vi.fn(); @@ -116,6 +116,30 @@ describe("outsideAssetsAllowed", () => { expect(line).toContain("../outside/secret.js"); }); + it.each([ + ["an image", "assets/in.png"], + ["a video", "media/clip.mp4"], + ["a font", "fonts/brand.woff2"], + ])("keeps outside files when only %s was received", (_kind, file) => { + const dir = project(received(file)); + if (file !== "assets/in.png") write(join(dir, file), "\u0000binary\u0000"); + const { allowed, warn } = decide(dir); + expect(allowed).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + it.each([ + ["HTML", "notes.txt", "
"], + ["CSS", "theme.dat", "body { background: url(../outside/bg.png); }"], + ["SVG", "logo.img", ""], + ])("refuses outside files when a received file sniffs as %s", (_kind, file, text) => { + const dir = project(received(file)); + write(join(dir, file), text); + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain(`${file} ${SOMEONE_ELSE}`); + }); + it("keeps outside files when the record lists no files", () => { expect(decide(project(received())).allowed).toBe(true); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index cc8019e49f6..6470b7e4fbc 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,5 +1,5 @@ import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs"; -import { dirname, isAbsolute, resolve } from "node:path"; +import { dirname, isAbsolute, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; @@ -202,7 +202,42 @@ function refusedReferences(found: OutsideReferences): string { return parts.join(""); } -/** False when the project's received-files record lists any file, or cannot be read: the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ +const REFERENCING_EXTENSION = /\.(?:html?|css|[cm]?js|svg)$/i; +const SNIFFED_BYTES = 4096; + +function firstBytes(path: string): Buffer | null { + let fd: number | undefined; + try { + fd = openSync(path, "r"); + const head = Buffer.alloc(SNIFFED_BYTES); + return head.subarray(0, readSync(fd, head, 0, SNIFFED_BYTES, 0)); + } catch { + return null; + } finally { + if (fd !== undefined) closeSync(fd); + } +} + +function readsAsPageOrStylesheet(text: string): boolean { + if (text.startsWith("<") || text.includes("@import") || text.includes("url(")) return true; + return text.includes("{") && text.includes(":") && text.includes("}"); +} + +function sniffsAsPageOrStylesheet(path: string): boolean { + const bytes = isFile(path) ? firstBytes(path) : null; + if (bytes === null || bytes.includes(0)) return false; + return readsAsPageOrStylesheet( + bytes + .toString("utf-8") + .replace(/^\uFEFF/, "") + .trimStart(), + ); +} + +const canReferenceFiles = (path: string) => + REFERENCING_EXTENSION.test(path) || sniffsAsPageOrStylesheet(path); + +/** False when the received-files record cannot be read, or lists a received page, stylesheet, script or SVG; the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, @@ -210,15 +245,17 @@ export function outsideAssetsAllowed( ): boolean { const absProjectDir = resolve(projectDir); const record = receivedRecordStatus(absProjectDir); - if (record === null || record.listedCount === 0) return true; + if (record === null) return true; + const referencing = record.listed?.find(canReferenceFiles); + if (record.listed !== null && referencing === undefined) return true; const refused = refusedReferences(outsideReferences(absProjectDir, entryFile ?? "index.html")); - if (record.listedCount === null) { + if (referencing === undefined) { warn( `Could not read ${record.path}, so the render treats the project as received and reads nothing outside it.${refused}`, ); } else if (refused !== "") { warn( - `This project has files that came from someone else (listed in ${record.path}), so the render reads nothing outside it.${refused}`, + `${relative(realOrNull(absProjectDir) ?? absProjectDir, referencing)} came from someone else and can load other files, so the render reads nothing outside the project.${refused}`, ); } return false; From c130e33edca4b443805465285cde8aed52f1d3ab Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 22:07:24 -0800 Subject: [PATCH 22/29] fix(cli): keep outside files only when every received file is positively media, a font or an image A local render keeps bringing in outside files only when each file the received-files record lists has a known media, font or image extension and starts with that type's signature bytes. Any other received file, a listed file that is missing or unreadable, or a mismatch between name and content refuses outside files. An ancestor record's entries now match a subfolder whose name is spelled in another Unicode form; the entry keeps its own spelling on disk. --- packages/cli/src/commands/render.test.ts | 5 ++ packages/cli/src/utils/privateProjectFile.ts | 6 +- packages/cli/src/utils/receivedRender.test.ts | 58 ++++++++++++-- packages/cli/src/utils/receivedRender.ts | 76 +++++++++++++------ 4 files changed, 109 insertions(+), 36 deletions(-) diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index c19dc4f4476..348fed694b8 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -597,6 +597,11 @@ describe("renderLocal browser GPU config", () => { ])("brings in outside files for $name: $allowed", async ({ files, allowed }) => { const projectDir = mkdtempSync(join(tmpdir(), "hf-render-received-")); writeFileSync(join(projectDir, "index.html"), "
"); + mkdirSync(join(projectDir, "assets")); + writeFileSync( + join(projectDir, "assets", "in.png"), + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + ); if (files) { mkdirSync(join(projectDir, ".hyperframes")); writeFileSync( diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index c6f3bdb2051..df35b2b737c 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -95,10 +95,10 @@ export function receivedRecordStatus( if (!record) return null; const path = join(record.root, RECEIVED_RECORD); if (!Array.isArray(record.listed)) return { path, listed: null }; - const prefix = record.projectDirFromRoot ? `${record.projectDirFromRoot}/` : ""; + const prefix = record.projectDirFromRoot ? `${record.projectDirFromRoot}/`.normalize("NFC") : ""; const listed = record.listed - .map((entry) => String(entry).normalize("NFC")) - .filter((entry) => entry.startsWith(prefix)) + .map(String) + .filter((entry) => entry.normalize("NFC").startsWith(prefix)) .map((entry) => join(record.root, entry)); return { path, listed }; } diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 82995ae4ca6..28b99818748 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -13,6 +13,14 @@ import { join } from "node:path"; import { compileForRender } from "../../../producer/src/services/htmlCompiler.js"; import { outsideAssetsAllowed } from "./receivedRender.js"; +const SIGNATURES = { + png: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0x0d]), + mp4: Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from("ftypisom\0\0\0\0")]), + mp3: Buffer.from("ID3\u0004\0\0\0\0\0\0"), + woff2: Buffer.from("wOF2\0\u0001\0\0\0\0\0\0"), + jpg: Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10]), +}; + let root: string | undefined; afterEach(() => { @@ -20,7 +28,7 @@ afterEach(() => { root = undefined; }); -function write(path: string, text: string): void { +function write(path: string, text: string | Buffer): void { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, text); } @@ -41,7 +49,7 @@ function project(record?: string): string { ); write(join(dir, "compositions", "scene.html"), ``); write(join(dir, "style.css"), `body { background: url(../outside/bg.png); }`); - write(join(dir, "assets", "in.png"), "x"); + write(join(dir, "assets", "in.png"), SIGNATURES.png); write(join(dir, "unused.html"), ``); if (record !== undefined) write(join(dir, ".hyperframes", "received-files.json"), record); return dir; @@ -49,7 +57,7 @@ function project(record?: string): string { const received = (...files: string[]) => JSON.stringify({ files }); -const SOMEONE_ELSE = "came from someone else and can load other files"; +const SOMEONE_ELSE = "came from someone else and is not a media, font or image file"; function decide(dir: string, entry?: string) { const warn = vi.fn(); @@ -117,17 +125,51 @@ describe("outsideAssetsAllowed", () => { }); it.each([ - ["an image", "assets/in.png"], - ["a video", "media/clip.mp4"], - ["a font", "fonts/brand.woff2"], - ])("keeps outside files when only %s was received", (_kind, file) => { + ["an image", "assets/in.png", SIGNATURES.png], + ["a JPEG", "media/photo.jpg", SIGNATURES.jpg], + ["a video", "media/clip.mp4", SIGNATURES.mp4], + ["audio", "media/voice.mp3", SIGNATURES.mp3], + ["a font", "fonts/brand.woff2", SIGNATURES.woff2], + ])("keeps outside files when only %s was received", (_kind, file, bytes) => { const dir = project(received(file)); - if (file !== "assets/in.png") write(join(dir, file), "\u0000binary\u0000"); + write(join(dir, file), bytes); const { allowed, warn } = decide(dir); expect(allowed).toBe(true); expect(warn).not.toHaveBeenCalled(); }); + it.each([ + ["a media name over HTML", "media/clip.mp4", "
"], + ["an image name over a script", "assets/in.png", "window.x = 1;"], + ["UTF-16 HTML under an unknown name", "scene.dat", Buffer.from("\uFEFF
", "utf16le")], + ["an empty media file", "media/empty.mp4", ""], + ])("refuses outside files for %s", (_kind, file, content) => { + const dir = project(received(file)); + write(join(dir, file), content); + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain(SOMEONE_ELSE); + }); + + it("refuses outside files when a listed media file is missing", () => { + expect(decide(project(received("media/gone.mp4"))).allowed).toBe(false); + }); + + it("keeps a received entry listed by an ancestor record for a decomposed-Unicode subfolder", () => { + root = mkdtempSync(join(tmpdir(), "hf-received-render-")); + write(join(root, "outside", "pic.png"), SIGNATURES.png); + const nfd = "Su\u0308bfolder"; + const dir = join(root, nfd); + write(join(dir, "index.html"), ``); + write( + join(root, ".hyperframes", "received-files.json"), + received(`${nfd.normalize("NFC")}/index.html`), + ); + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("../outside/pic.png"); + }); + it.each([ ["HTML", "notes.txt", "
"], ["CSS", "theme.dat", "body { background: url(../outside/bg.png); }"], diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 6470b7e4fbc..12a39257d2e 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,5 +1,5 @@ import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs"; -import { dirname, isAbsolute, relative, resolve } from "node:path"; +import { dirname, extname, isAbsolute, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; @@ -202,15 +202,54 @@ function refusedReferences(found: OutsideReferences): string { return parts.join(""); } -const REFERENCING_EXTENSION = /\.(?:html?|css|[cm]?js|svg)$/i; -const SNIFFED_BYTES = 4096; +const SIGNATURE_BYTES = 16; + +const ascii = (bytes: Buffer, at: number, text: string) => + bytes.toString("latin1", at, at + text.length) === text; +const startsWith = (bytes: Buffer, ...values: number[]) => + values.every((value, index) => bytes[index] === value); +const isoMedia = (bytes: Buffer) => + ["ftyp", "moov", "mdat", "wide", "free", "skip"].some((box) => ascii(bytes, 4, box)); +const riff = (form: string) => (bytes: Buffer) => ascii(bytes, 0, "RIFF") && ascii(bytes, 8, form); +const ebml = (bytes: Buffer) => startsWith(bytes, 0x1a, 0x45, 0xdf, 0xa3); +const mpegAudio = (bytes: Buffer) => + ascii(bytes, 0, "ID3") || (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0); +const adts = (bytes: Buffer) => + ascii(bytes, 0, "ADIF") || (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xf6) === 0xf0); +const avif = (bytes: Buffer) => + ascii(bytes, 4, "ftyp") && ["avif", "avis", "mif1"].some((brand) => ascii(bytes, 8, brand)); + +// Each media, font or image extension and the leading bytes a file of that type starts with. +const MEDIA_SIGNATURES: Record boolean> = { + ".mp4": isoMedia, + ".m4v": isoMedia, + ".m4a": isoMedia, + ".mov": isoMedia, + ".webm": ebml, + ".mkv": ebml, + ".mp3": mpegAudio, + ".wav": riff("WAVE"), + ".ogg": (bytes) => ascii(bytes, 0, "OggS"), + ".flac": (bytes) => ascii(bytes, 0, "fLaC"), + ".aac": adts, + ".png": (bytes) => startsWith(bytes, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a), + ".jpg": (bytes) => startsWith(bytes, 0xff, 0xd8, 0xff), + ".jpeg": (bytes) => startsWith(bytes, 0xff, 0xd8, 0xff), + ".gif": (bytes) => ascii(bytes, 0, "GIF87a") || ascii(bytes, 0, "GIF89a"), + ".webp": riff("WEBP"), + ".avif": avif, + ".woff": (bytes) => ascii(bytes, 0, "wOFF"), + ".woff2": (bytes) => ascii(bytes, 0, "wOF2"), + ".ttf": (bytes) => startsWith(bytes, 0x00, 0x01, 0x00, 0x00) || ascii(bytes, 0, "true"), + ".otf": (bytes) => ascii(bytes, 0, "OTTO"), +}; function firstBytes(path: string): Buffer | null { let fd: number | undefined; try { fd = openSync(path, "r"); - const head = Buffer.alloc(SNIFFED_BYTES); - return head.subarray(0, readSync(fd, head, 0, SNIFFED_BYTES, 0)); + const head = Buffer.alloc(SIGNATURE_BYTES); + return head.subarray(0, readSync(fd, head, 0, SIGNATURE_BYTES, 0)); } catch { return null; } finally { @@ -218,26 +257,13 @@ function firstBytes(path: string): Buffer | null { } } -function readsAsPageOrStylesheet(text: string): boolean { - if (text.startsWith("<") || text.includes("@import") || text.includes("url(")) return true; - return text.includes("{") && text.includes(":") && text.includes("}"); +function isMediaFontOrImage(path: string): boolean { + const matches = MEDIA_SIGNATURES[extname(path).toLowerCase()]; + const bytes = matches && isFile(path) ? firstBytes(path) : null; + return bytes !== null && matches !== undefined && matches(bytes); } -function sniffsAsPageOrStylesheet(path: string): boolean { - const bytes = isFile(path) ? firstBytes(path) : null; - if (bytes === null || bytes.includes(0)) return false; - return readsAsPageOrStylesheet( - bytes - .toString("utf-8") - .replace(/^\uFEFF/, "") - .trimStart(), - ); -} - -const canReferenceFiles = (path: string) => - REFERENCING_EXTENSION.test(path) || sniffsAsPageOrStylesheet(path); - -/** False when the received-files record cannot be read, or lists a received page, stylesheet, script or SVG; the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ +/** False when the received-files record cannot be read, or lists a received file that is not positively media, a font or an image by extension and leading bytes; the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, @@ -246,7 +272,7 @@ export function outsideAssetsAllowed( const absProjectDir = resolve(projectDir); const record = receivedRecordStatus(absProjectDir); if (record === null) return true; - const referencing = record.listed?.find(canReferenceFiles); + const referencing = record.listed?.find((path) => !isMediaFontOrImage(path)); if (record.listed !== null && referencing === undefined) return true; const refused = refusedReferences(outsideReferences(absProjectDir, entryFile ?? "index.html")); if (referencing === undefined) { @@ -255,7 +281,7 @@ export function outsideAssetsAllowed( ); } else if (refused !== "") { warn( - `${relative(realOrNull(absProjectDir) ?? absProjectDir, referencing)} came from someone else and can load other files, so the render reads nothing outside the project.${refused}`, + `${relative(realOrNull(absProjectDir) ?? absProjectDir, referencing)} came from someone else and is not a media, font or image file, so the render reads nothing outside the project.${refused}`, ); } return false; From 33ec87beef016613a3339678438097f87be63711 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 22:40:43 -0800 Subject: [PATCH 23/29] fix(producer,core): a sub-composition must be an .html file The render compiler and the runtime load a data-composition-src only when it names an .html or .htm file. Any other file, such as an image or video, is refused as a page: render stops naming it, and the runtime reports the load failure without fetching it. --- .../src/runtime/compositionLoader.test.ts | 19 +++++++++++++++++++ .../core/src/runtime/compositionLoader.ts | 3 +++ .../src/services/htmlCompiler.test.ts | 17 +++++++++++++++++ .../producer/src/services/htmlCompiler.ts | 16 +++++++++++++++- 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/core/src/runtime/compositionLoader.test.ts b/packages/core/src/runtime/compositionLoader.test.ts index 00977798b2a..5de13420bd1 100644 --- a/packages/core/src/runtime/compositionLoader.test.ts +++ b/packages/core/src/runtime/compositionLoader.test.ts @@ -437,6 +437,25 @@ describe("loadCompositions external hosts", () => { ); }); + it.each(["https://example.com/scene.png", "https://example.com/scene.mp4?x=.html", "scene"])( + "never fetches a data-composition-src that is not an .html file: %s", + async (src) => { + const host = document.createElement("div"); + host.setAttribute("data-composition-src", src); + document.body.appendChild(host); + const fetchSpy = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(new Response("

media as page

")); + const onDiagnostic = vi.fn(); + await loadCompositions({ ...createLoaderParams(), onDiagnostic }); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(host.innerHTML).not.toContain("media as page"); + expect(onDiagnostic).toHaveBeenCalledWith( + expect.objectContaining({ code: "external_composition_load_failed" }), + ); + }, + ); + it("calls onDiagnostic when HTTP response is not ok", async () => { const host = document.createElement("div"); host.setAttribute("data-composition-src", "https://example.com/404.html"); diff --git a/packages/core/src/runtime/compositionLoader.ts b/packages/core/src/runtime/compositionLoader.ts index cc1ee698a31..9fc327ec6ba 100644 --- a/packages/core/src/runtime/compositionLoader.ts +++ b/packages/core/src/runtime/compositionLoader.ts @@ -793,6 +793,9 @@ async function mountExternalCompositions( onDiagnostic: params.onDiagnostic, }); } + if (!compositionUrl || !/\.html?$/i.test(compositionUrl.pathname)) { + throw new Error("data-composition-src must name an .html file"); + } const response = await fetch(src); if (!response.ok) { throw new Error(`HTTP ${response.status}`); diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts index d9a784a9909..3ffd5ace1cc 100644 --- a/packages/producer/src/services/htmlCompiler.test.ts +++ b/packages/producer/src/services/htmlCompiler.test.ts @@ -1171,6 +1171,23 @@ describe("detectRenderModeHints", () => { } }); + it.each(["compositions/scene.png", "/compositions/scene.png", "compositions/scene.mp4"])( + "compileForRender refuses a data-composition-src that is not an .html file: %s", + async (src) => { + const name = src.split("/").pop() ?? ""; + const projectDir = makeSubCompProject("hf-media-subcomp-", [{ id: "intro", src }], { + [name]: validSubCompHtml("intro", "Media named"), + }); + try { + await expect( + compileForRender(projectDir, join(projectDir, "index.html"), projectDir), + ).rejects.toThrow(/not an \.html file/); + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }, + ); + it.each([ ["dot-dot segments", "../outside-scene.html"], ["an encoded ../", "%2e%2e%2foutside-scene.html"], diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 9c05aea5842..7c19b3d9834 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -237,13 +237,22 @@ function normalizeCompositionSrcs(html: string, projectDir: string): string { }); } +const COMPOSITION_FILE = /\.html?$/i; + +const NOT_A_COMPOSITION_FILE: Record["kind"], string> = { + missing: "the file does not exist", + folder: "it is a folder, not an HTML file", + file: "it is not an .html file", +}; + function resolveCompositionFile( projectDir: string, src: string, assetRoot: string | undefined, ): string | null { const file = resolveCompositionSrc(projectDir, src); - return file === null || escapesAssetRoot(file, assetRoot) ? null : file; + if (file === null || !COMPOSITION_FILE.test(file)) return null; + return escapesAssetRoot(file, assetRoot) ? null : file; } // Git metadata and env files are never inlined into a render, as the preview bundler refuses them. @@ -280,6 +289,11 @@ function assertSubCompositionsUsable( if (!srcPath) continue; if (isUnresolvedAssetPlaceholder(srcPath)) continue; // __UPPER__ placeholder or unresolved templating token — not a real reference (shared with lint via @hyperframes/parsers) + const named = resolveCompositionSrc(projectDir, srcPath); + if (named !== null && !COMPOSITION_FILE.test(named)) { + problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE[readProjectFile(named).kind] }); + continue; + } const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); if (filePath === null) { problems.push({ srcPath, detail: "it is outside the project folder" }); From e1d49a234bca486b35020c7fad9aa2455bb676c0 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 22:41:07 -0800 Subject: [PATCH 24/29] fix(producer,cli): the render and static file servers forbid type sniffing Both servers send X-Content-Type-Options: nosniff with every response, so the browser loads a file only as the type its extension names: an image or video cannot run as a script or apply as a stylesheet. .cjs is served as JavaScript. --- .../cli/src/utils/staticProjectServer.test.ts | 11 ++++++++ packages/cli/src/utils/staticProjectServer.ts | 1 + .../producer/src/services/fileServer.test.ts | 27 +++++++++++++++++++ packages/producer/src/services/fileServer.ts | 6 +++++ packages/studio-server/src/helpers/mime.ts | 1 + 5 files changed, 46 insertions(+) diff --git a/packages/cli/src/utils/staticProjectServer.test.ts b/packages/cli/src/utils/staticProjectServer.test.ts index e4e92eaad5f..f63e8b36b0c 100644 --- a/packages/cli/src/utils/staticProjectServer.test.ts +++ b/packages/cli/src/utils/staticProjectServer.test.ts @@ -159,6 +159,17 @@ describe("serveStaticProjectHtml colour-tagged PNGs", () => { }); }); +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, diff --git a/packages/cli/src/utils/staticProjectServer.ts b/packages/cli/src/utils/staticProjectServer.ts index 177c09ca4a4..298ef78c2a9 100644 --- a/packages/cli/src/utils/staticProjectServer.ts +++ b/packages/cli/src/utils/staticProjectServer.ts @@ -305,6 +305,7 @@ export async function serveStaticProjectHtml( // fallow-ignore-next-line complexity const server = createServer((req, res) => { + res.setHeader("X-Content-Type-Options", "nosniff"); const url = req.url ?? "/"; if (url === "/" || url === "/index.html") { res.writeHead(200, { "Content-Type": getMimeType("index.html") }); diff --git a/packages/producer/src/services/fileServer.test.ts b/packages/producer/src/services/fileServer.test.ts index af9d3a9fc04..dfa1340a03e 100644 --- a/packages/producer/src/services/fileServer.test.ts +++ b/packages/producer/src/services/fileServer.test.ts @@ -405,6 +405,33 @@ describe("createFileServer", () => { } }); + it("tells the browser not to sniff a type, so an image cannot load as a script or stylesheet", async () => { + const projectDir = mkdtempSync(join(tmpdir(), "hf-file-server-nosniff-")); + try { + writeEmptyIndex(projectDir); + writeFileSync(join(projectDir, "scene.png"), "window.ran = true;"); + writeFileSync(join(projectDir, "scene.js"), "window.ran = true;"); + const server = await createFileServer({ projectDir, preHeadScripts: [], headScripts: [] }); + try { + for (const [name, type] of [ + ["scene.png", "image/png"], + ["scene.js", "application/javascript; charset=utf-8"], + ["index.html", "text/html; charset=utf-8"], + ]) { + const response = await fetch(`${server.url}/${name}`); + expect(response.headers.get("content-type")).toBe(type); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); + } + const missing = await fetch(`${server.url}/missing.js`); + expect(missing.headers.get("x-content-type-options")).toBe("nosniff"); + } finally { + server.close(); + } + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }); + it("serves ES modules with a JavaScript MIME type", async () => { const projectDir = mkdtempSync(join(tmpdir(), "hf-file-server-mjs-")); try { diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.ts index 443a3439d31..ac993bea268 100644 --- a/packages/producer/src/services/fileServer.ts +++ b/packages/producer/src/services/fileServer.ts @@ -99,6 +99,7 @@ const MIME_TYPES: Record = { ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".mjs": "application/javascript; charset=utf-8", + ".cjs": "application/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".cube": "text/plain; charset=utf-8", ".png": "image/png", @@ -817,6 +818,11 @@ export function createFileServer(options: FileServerOptions): Promise console.warn(`[FileServer] ${line}`); + app.use(async function loadEachFileOnlyAsItsNamedType(c, next) { + await next(); + c.res.headers.set("X-Content-Type-Options", "nosniff"); + }); + app.get("/*", async (c) => { let requestPath = c.req.path; if (requestPath === "/") requestPath = "/index.html"; diff --git a/packages/studio-server/src/helpers/mime.ts b/packages/studio-server/src/helpers/mime.ts index 2ef35faf3ae..8003cd9f5d3 100644 --- a/packages/studio-server/src/helpers/mime.ts +++ b/packages/studio-server/src/helpers/mime.ts @@ -3,6 +3,7 @@ export const MIME_TYPES: Record = { ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", + ".cjs": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", From eb47e27f1828e426cce3a71d7d834087d92437f7 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 22:41:14 -0800 Subject: [PATCH 25/29] test(cli): a received media file in a composition slot is refused as a page --- packages/cli/src/utils/receivedRender.test.ts | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 28b99818748..d22f89f19b4 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -358,4 +358,35 @@ describe("outsideAssetsAllowed", () => { expect(line).toContain("../../outside/pic.png"); }); }); + + describe("a received media file in a composition slot", () => { + it.each(["assets/scene.png", "/assets/scene.png"])( + "the render compiler refuses %s as a page, so the media exemption holds", + async (src) => { + const dir = project(received("assets/scene.png")); + write( + join(dir, "assets", "scene.png"), + Buffer.concat([ + SIGNATURES.png, + Buffer.from( + ``, + ), + ]), + ); + write( + join(dir, "index.html"), + `
` + + `
`, + ); + + await expect( + compileForRender(dir, join(dir, "index.html"), join(dir, ".dl"), { + allowOutsideProjectAssets: true, + }), + ).rejects.toThrow(/assets\/scene\.png: it is not an \.html file/); + expect(decide(dir).allowed).toBe(true); + }, + ); + }); }); From 7e8f156c159bba92505f2dcdb065534083d29526 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 23:07:08 -0800 Subject: [PATCH 26/29] test(cli): an empty nested received-files record cannot hide an outer record's received page --- packages/cli/src/utils/receivedRender.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index d22f89f19b4..96f67b9fa2f 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -182,6 +182,18 @@ describe("outsideAssetsAllowed", () => { expect(line).toContain(`${file} ${SOMEONE_ELSE}`); }); + it("refuses outside files when an outer record lists received HTML under an empty nested record", () => { + root = mkdtempSync(join(tmpdir(), "hf-received-render-")); + write(join(root, "outside", "pic.png"), SIGNATURES.png); + const dir = join(root, "sub"); + write(join(dir, "index.html"), ``); + write(join(dir, ".hyperframes", "received-files.json"), received()); + write(join(root, ".hyperframes", "received-files.json"), received("sub/index.html")); + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain(`index.html ${SOMEONE_ELSE}`); + }); + it("keeps outside files when the record lists no files", () => { expect(decide(project(received())).allowed).toBe(true); }); From 0638f94b4aacd09732a51647f9aaa0db5c356cd3 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sat, 14 Nov 2026 23:38:42 -0800 Subject: [PATCH 27/29] fix(cli): a received media file reached under another name refuses outside files The received-render decision now compares file identities, not names. It walks the project once, bounded by entry count and time, and refuses outside files when a hardlink or a symlink with a name that is not media reaches a received file, or when the walk cannot finish. A received file with no identity matches nothing, as in the received files check. --- packages/cli/src/utils/compositionEntry.ts | 9 +- packages/cli/src/utils/privateProjectFile.ts | 2 +- packages/cli/src/utils/receivedRender.test.ts | 62 ++++++++++ packages/cli/src/utils/receivedRender.ts | 112 +++++++++++++++--- packages/cli/src/utils/renderArgs.test.ts | 10 ++ .../src/services/htmlCompiler.test.ts | 49 ++++++-- .../producer/src/services/htmlCompiler.ts | 33 +++--- 7 files changed, 237 insertions(+), 40 deletions(-) diff --git a/packages/cli/src/utils/compositionEntry.ts b/packages/cli/src/utils/compositionEntry.ts index e5980149ac9..c0eb40e06bb 100644 --- a/packages/cli/src/utils/compositionEntry.ts +++ b/packages/cli/src/utils/compositionEntry.ts @@ -4,7 +4,7 @@ import { errorBox } from "../ui/format.js"; import { failUsage } from "./commandResult.js"; export type CompositionEntryParseError = { - kind: "outside-project" | "not-found" | "not-a-file"; + kind: "outside-project" | "not-found" | "not-a-file" | "not-html"; entryFile: string; entryPath: string; projectDir: string; @@ -56,6 +56,7 @@ export function parseCompositionEntryArg( // A directory would pass existsSync downstream and fail with EISDIR in the producer. return fail("not-a-file"); } + if (!/\.html?$/i.test(entryPath)) return fail("not-html"); return { ok: true, value: relativeEntry.split(sep).join("/") }; } @@ -92,6 +93,12 @@ export function compositionEntryErrorMessage(error: CompositionEntryParseError): message: `${resolved}, a directory, not an .html file (project directory ${error.projectDir}).`, hint: "Pass a path to a .html file (e.g. compositions/intro.html), or omit --composition to render index.html.", }; + case "not-html": + return { + title: "Invalid composition path", + message: `${resolved}, which is not an .html file, so it is refused.`, + hint: "Pass a path to a .html or .htm file (e.g. compositions/intro.html).", + }; } } diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 2b815f6bc85..6ce9d702247 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -61,7 +61,7 @@ function receivedRecordsAtOrAbove(projectDir: string): ReceivedRecord[] { } } -function fileIdentity(path: string): string | null { +export function fileIdentity(path: string): string | null { try { const stat = lstatSync(path, { bigint: true }); return stat.ino === 0n ? null : `${stat.dev}:${stat.ino}`; diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index 96f67b9fa2f..ada37280704 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { chmodSync, + linkSync, mkdirSync, mkdtempSync, realpathSync, @@ -401,4 +402,65 @@ describe("outsideAssetsAllowed", () => { }, ); }); + + describe("another name for a received media file", () => { + const MEDIA_PAGE = Buffer.concat([ + SIGNATURES.png, + Buffer.from( + ``, + ), + ]); + + function aliasProject(makeAlias: (target: string, alias: string) => void, alias: string) { + const dir = project(received("assets/scene.png")); + write(join(dir, "assets", "scene.png"), MEDIA_PAGE); + makeAlias(join(dir, "assets", "scene.png"), join(dir, alias)); + write( + join(dir, "index.html"), + `
` + + `
`, + ); + return dir; + } + + it.each([ + ["hardlink", (target: string, alias: string) => linkSync(target, alias)], + ["symlink", (target: string, alias: string) => symlinkSync(target, alias)], + ])("refuses outside files when a %s with an HTML name reaches it", async (_kind, makeAlias) => { + const dir = aliasProject(makeAlias, "scene.html"); + const compiled = await compileForRender(dir, join(dir, "index.html"), join(dir, ".dl"), { + allowOutsideProjectAssets: true, + }); + const rendered = [compiled.html, ...compiled.subCompositions.values()].join("\n"); + expect(rendered).toContain("received-scene-marker"); + + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("scene.html is another name for a file that came from someone else"); + }); + + it("keeps outside files when the other name is also a media name", () => { + const dir = project(received("assets/scene.png")); + write(join(dir, "assets", "scene.png"), SIGNATURES.png); + linkSync(join(dir, "assets", "scene.png"), join(dir, "assets", "copy.png")); + expect(decide(dir).allowed).toBe(true); + }); + + it.runIf(process.platform !== "win32")( + "refuses outside files when it cannot check every project file", + () => { + const dir = project(received("assets/in.png")); + mkdirSync(join(dir, "locked")); + chmodSync(join(dir, "locked"), 0o000); + try { + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("Could not check every project file"); + } finally { + chmodSync(join(dir, "locked"), 0o755); + } + }, + ); + }); }); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 12a39257d2e..746106e1268 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -1,10 +1,18 @@ -import { closeSync, openSync, readSync, realpathSync, statSync } from "node:fs"; -import { dirname, extname, isAbsolute, relative, resolve } from "node:path"; +import { + closeSync, + openSync, + readdirSync, + readSync, + realpathSync, + statSync, + type Dirent, +} from "node:fs"; +import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; import { resolveCompositionSrc } from "@hyperframes/parsers/asset-resolution"; -import { linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; +import { fileIdentity, linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; const MAX_SCANNED_BYTES = 2 * 1024 * 1024; @@ -263,7 +271,88 @@ function isMediaFontOrImage(path: string): boolean { return bytes !== null && matches !== undefined && matches(bytes); } -/** False when the received-files record cannot be read, or lists a received file that is not positively media, a font or an image by extension and leading bytes; the render then reads nothing outside the project, and `warn` says why and names the references it refuses. */ +const ALIAS_WALK_MAX_ENTRIES = 20_000; +const ALIAS_WALK_MAX_MS = 2_000; + +function aliasIdentity(path: string, isLink: boolean): string | null { + const target = isLink ? realOrNull(path) : path; + return target === null ? null : fileIdentity(target); +} + +function listDir(dir: string): Dirent[] | null { + try { + return readdirSync(dir, { withFileTypes: true }); + } catch { + return null; + } +} + +function receivedAlias(dir: string, entry: Dirent, received: ReadonlySet): string | null { + const path = join(dir, entry.name); + if (MEDIA_SIGNATURES[extname(path).toLowerCase()] !== undefined) return null; + const identity = aliasIdentity(path, entry.isSymbolicLink()); + return identity !== null && received.has(identity) ? path : null; +} + +function walkBudget(): (entries: number) => boolean { + const deadline = Date.now() + ALIAS_WALK_MAX_MS; + let seen = 0; + return (entries) => { + seen += entries; + return seen <= ALIAS_WALK_MAX_ENTRIES && Date.now() <= deadline; + }; +} + +// Project files whose own identity, or whose link target's, is a received file's, under a name that is not media; null when the walk could not finish. +function nonMediaAliases(projectDir: string, received: ReadonlySet): string[] | null { + const withinBudget = walkBudget(); + const aliases: string[] = []; + const pending = [projectDir]; + for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) { + const listing = listDir(dir); + if (listing === null || !withinBudget(listing.length)) return null; + for (const entry of listing) { + const alias = entry.isDirectory() ? null : receivedAlias(dir, entry, received); + if (entry.isDirectory()) pending.push(join(dir, entry.name)); + if (alias !== null) aliases.push(alias); + } + } + return aliases; +} + +interface Refusal { + reason: string; + alwaysWarn: boolean; +} + +const READS_NOTHING_OUTSIDE = "so the render reads nothing outside the project."; + +function receivedRefusal( + projectDir: string, + record: { path: string; listed: string[] | null }, +): Refusal | null { + const shown = (path: string) => relative(realOrNull(projectDir) ?? projectDir, path); + if (record.listed === null) { + return { reason: `Could not read ${record.path}, ${READS_NOTHING_OUTSIDE}`, alwaysWarn: true }; + } + const nonMedia = record.listed.find((path) => !isMediaFontOrImage(path)); + if (nonMedia !== undefined) { + const reason = `${shown(nonMedia)} came from someone else and is not a media, font or image file, ${READS_NOTHING_OUTSIDE}`; + return { reason, alwaysWarn: false }; + } + const received = new Set(record.listed.flatMap((path) => fileIdentity(path) ?? [])); + const aliases = nonMediaAliases(projectDir, received); + if (aliases === null) { + const reason = `Could not check every project file for another name of a received file, ${READS_NOTHING_OUTSIDE}`; + return { reason, alwaysWarn: true }; + } + const [alias] = aliases; + if (alias === undefined) return null; + const reason = `${shown(alias)} is another name for a file that came from someone else, ${READS_NOTHING_OUTSIDE}`; + return { reason, alwaysWarn: false }; +} + +/** False when the received-files record cannot be read, lists a received file that is not positively media, a font or an image by extension and leading bytes, or a project file reaches a received file under another kind of name; `warn` then says why and names the references outside the project it refuses. */ export function outsideAssetsAllowed( projectDir: string, entryFile: string | undefined, @@ -271,18 +360,9 @@ export function outsideAssetsAllowed( ): boolean { const absProjectDir = resolve(projectDir); const record = receivedRecordStatus(absProjectDir); - if (record === null) return true; - const referencing = record.listed?.find((path) => !isMediaFontOrImage(path)); - if (record.listed !== null && referencing === undefined) return true; + const refusal = record === null ? null : receivedRefusal(absProjectDir, record); + if (refusal === null) return true; const refused = refusedReferences(outsideReferences(absProjectDir, entryFile ?? "index.html")); - if (referencing === undefined) { - warn( - `Could not read ${record.path}, so the render treats the project as received and reads nothing outside it.${refused}`, - ); - } else if (refused !== "") { - warn( - `${relative(realOrNull(absProjectDir) ?? absProjectDir, referencing)} came from someone else and is not a media, font or image file, so the render reads nothing outside the project.${refused}`, - ); - } + if (refusal.alwaysWarn || refused !== "") warn(`${refusal.reason}${refused}`); return false; } diff --git a/packages/cli/src/utils/renderArgs.test.ts b/packages/cli/src/utils/renderArgs.test.ts index acad6444f27..768ae3253da 100644 --- a/packages/cli/src/utils/renderArgs.test.ts +++ b/packages/cli/src/utils/renderArgs.test.ts @@ -173,6 +173,8 @@ describe("parseCompositionEntryArg", () => { [resolve(PROJECT, "index.html")]: "file", [resolve(PROJECT, "compositions/intro.html")]: "file", [resolve(PROJECT, "compositions")]: "directory", + [resolve(PROJECT, "assets/scene.png")]: "file", + [resolve(PROJECT, "compositions/old.htm")]: "file", [PROJECT]: "directory", }); @@ -239,6 +241,13 @@ describe("parseCompositionEntryArg", () => { }); }); + it("accepts an .htm entry", () => { + expect(parseCompositionEntryArg("compositions/old.htm", PROJECT, stat)).toEqual({ + ok: true, + value: "compositions/old.htm", + }); + }); + it("rejects an absolute path outside the project", () => { const outsideStat = makeStat({ "/elsewhere/x.html": "file", [PROJECT]: "directory" }); const err = expectCompositionErr( @@ -251,6 +260,7 @@ describe("parseCompositionEntryArg", () => { ["../escape.html", "outside-project", "/escape.html"], ["missing.html", "not-found", "/proj/missing.html"], ["compositions", "not-a-file", "/proj/compositions"], + ["assets/scene.png", "not-html", "/proj/assets/scene.png"], ])("names the resolved entry path and project directory for %s", (raw, kind, entryPath) => { const err = expectCompositionErr(parseCompositionEntryArg(raw, PROJECT, stat)); expect(err).toEqual({ diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts index 3ffd5ace1cc..342f6edc9cf 100644 --- a/packages/producer/src/services/htmlCompiler.test.ts +++ b/packages/producer/src/services/htmlCompiler.test.ts @@ -1082,19 +1082,14 @@ describe("detectRenderModeHints", () => { it("compileForRender aborts naming a data-composition-src that points at a folder", async () => { const projectDir = makeSubCompProject( "hf-folder-subcomp-", - [{ id: "intro", src: "compositions/intro" }], + [{ id: "intro", src: "compositions/intro.html" }], {}, ); try { - mkdirSync(join(projectDir, "compositions", "intro")); - writeFileSync( - join(projectDir, "compositions", "intro", "index.html"), - validSubCompHtml("intro", "Intro"), - ); - + mkdirSync(join(projectDir, "compositions", "intro.html")); await expect( compileForRender(projectDir, join(projectDir, "index.html"), projectDir), - ).rejects.toThrow(/compositions\/intro[\s\S]*a folder, not an HTML file/); + ).rejects.toThrow(/compositions\/intro\.html[\s\S]*a folder, not an HTML file/); } finally { rmSync(projectDir, { recursive: true, force: true }); } @@ -1171,6 +1166,44 @@ describe("detectRenderModeHints", () => { } }); + it("compileForRender refuses an entry that is not an .html file, and renders the same page named .html", async () => { + const projectDir = makeSubCompProject("hf-media-entry-", [], {}); + try { + const page = readFileSync(join(projectDir, "index.html"), "utf-8"); + writeFileSync(join(projectDir, "scene.png"), page); + writeFileSync(join(projectDir, "scene.html"), page); + await expect( + compileForRender(projectDir, join(projectDir, "scene.png"), projectDir), + ).rejects.toThrow(/scene\.png is not an \.html file, so it is refused/); + const compiled = await compileForRender( + projectDir, + join(projectDir, "scene.html"), + projectDir, + ); + expect(compiled.html).toContain('data-composition-id="main"'); + } finally { + rmSync(projectDir, { recursive: true, force: true }); + } + }); + + it("compileForRender checks containment before the file type of a data-composition-src", async () => { + const projectDir = makeSubCompProject( + "hf-outside-media-subcomp-", + [{ id: "intro", src: "../outside-scene.png" }], + {}, + ); + const outside = join(dirname(projectDir), "outside-scene.png"); + writeFileSync(outside, validSubCompHtml("intro", "Outside")); + try { + await expect( + compileForRender(projectDir, join(projectDir, "index.html"), projectDir), + ).rejects.toThrow(/outside-scene\.png: it is outside the project folder/); + } finally { + rmSync(outside, { force: true }); + rmSync(projectDir, { recursive: true, force: true }); + } + }); + it.each(["compositions/scene.png", "/compositions/scene.png", "compositions/scene.mp4"])( "compileForRender refuses a data-composition-src that is not an .html file: %s", async (src) => { diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 7c19b3d9834..928f6dcebd2 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -238,21 +238,24 @@ function normalizeCompositionSrcs(html: string, projectDir: string): string { } const COMPOSITION_FILE = /\.html?$/i; +const NOT_A_COMPOSITION_FILE = "it is not an .html file, so it is refused"; -const NOT_A_COMPOSITION_FILE: Record["kind"], string> = { - missing: "the file does not exist", - folder: "it is a folder, not an HTML file", - file: "it is not an .html file", -}; +function resolveCompositionPath( + projectDir: string, + src: string, + assetRoot: string | undefined, +): string | null { + const file = resolveCompositionSrc(projectDir, src); + return file === null || escapesAssetRoot(file, assetRoot) ? null : file; +} function resolveCompositionFile( projectDir: string, src: string, assetRoot: string | undefined, ): string | null { - const file = resolveCompositionSrc(projectDir, src); - if (file === null || !COMPOSITION_FILE.test(file)) return null; - return escapesAssetRoot(file, assetRoot) ? null : file; + const file = resolveCompositionPath(projectDir, src, assetRoot); + return file !== null && COMPOSITION_FILE.test(file) ? file : null; } // Git metadata and env files are never inlined into a render, as the preview bundler refuses them. @@ -289,12 +292,7 @@ function assertSubCompositionsUsable( if (!srcPath) continue; if (isUnresolvedAssetPlaceholder(srcPath)) continue; // __UPPER__ placeholder or unresolved templating token — not a real reference (shared with lint via @hyperframes/parsers) - const named = resolveCompositionSrc(projectDir, srcPath); - if (named !== null && !COMPOSITION_FILE.test(named)) { - problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE[readProjectFile(named).kind] }); - continue; - } - const filePath = resolveCompositionFile(projectDir, srcPath, assetRoot); + const filePath = resolveCompositionPath(projectDir, srcPath, assetRoot); if (filePath === null) { problems.push({ srcPath, detail: "it is outside the project folder" }); continue; @@ -307,6 +305,10 @@ function assertSubCompositionsUsable( problems.push({ srcPath, detail: "it is git metadata or an env file" }); continue; } + if (!COMPOSITION_FILE.test(filePath)) { + problems.push({ srcPath, detail: NOT_A_COMPOSITION_FILE }); + continue; + } // Circular reference guard. parseSubCompositions (below) silently // `continue`s on a repeat visit with no reporting at all — mirror that // silence here rather than pretend it surfaces an error somewhere else. @@ -2248,6 +2250,9 @@ export async function compileForRender( if (isPathInside(htmlPath, projectDir) && escapesAssetRoot(htmlPath, assetRoot)) { throw new Error(`Entry file ${htmlPath} leads outside the project folder`); } + if (!COMPOSITION_FILE.test(htmlPath)) { + throw new Error(`Entry file ${htmlPath} is not an .html file, so it is refused`); + } const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath); const rawHtml = bindVariableMediaSources( normalizeCompositionSrcs(rewriteUnresolvableGsapToCdn(entryHtml, projectDir), projectDir), From df1949028a6cc3e9bf923ca2246465d8f9a0f1c6 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sun, 15 Nov 2026 00:05:34 -0800 Subject: [PATCH 28/29] fix(cli): compare received files by link target and keep outside files for an empty record A received media file and every other project name are now compared by the identity of the file they reach with links followed. A linked folder that leads outside the project, or a file whose identity cannot be read, counts as unchecked and refuses outside files. An empty received-files record keeps outside files without walking the project. --- packages/cli/src/utils/privateProjectFile.ts | 2 +- packages/cli/src/utils/receivedRender.test.ts | 88 +++++++++++++++-- packages/cli/src/utils/receivedRender.ts | 98 +++++++++++++++---- 3 files changed, 160 insertions(+), 28 deletions(-) diff --git a/packages/cli/src/utils/privateProjectFile.ts b/packages/cli/src/utils/privateProjectFile.ts index 6ce9d702247..2b815f6bc85 100644 --- a/packages/cli/src/utils/privateProjectFile.ts +++ b/packages/cli/src/utils/privateProjectFile.ts @@ -61,7 +61,7 @@ function receivedRecordsAtOrAbove(projectDir: string): ReceivedRecord[] { } } -export function fileIdentity(path: string): string | null { +function fileIdentity(path: string): string | null { try { const stat = lstatSync(path, { bigint: true }); return stat.ino === 0n ? null : `${stat.dev}:${stat.ino}`; diff --git a/packages/cli/src/utils/receivedRender.test.ts b/packages/cli/src/utils/receivedRender.test.ts index ada37280704..dd07c4b8683 100644 --- a/packages/cli/src/utils/receivedRender.test.ts +++ b/packages/cli/src/utils/receivedRender.test.ts @@ -199,6 +199,16 @@ describe("outsideAssetsAllowed", () => { expect(decide(project(received())).allowed).toBe(true); }); + it("keeps outside files for an empty record in a project with very many files", () => { + const dir = project(received()); + const many = join(dir, "node_modules"); + mkdirSync(many); + for (let i = 0; i <= 20_000; i++) writeFileSync(join(many, `f${i}`), ""); + const { allowed, warn } = decide(dir); + expect(allowed).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + it("keeps outside files for a project with no received-files record", () => { const { allowed, warn } = decide(project()); expect(allowed).toBe(true); @@ -404,13 +414,15 @@ describe("outsideAssetsAllowed", () => { }); describe("another name for a received media file", () => { - const MEDIA_PAGE = Buffer.concat([ - SIGNATURES.png, - Buffer.from( - ``, - ), - ]); + const mediaPage = (outsideRef: string) => + Buffer.concat([ + SIGNATURES.png, + Buffer.from( + ``, + ), + ]); + const MEDIA_PAGE = mediaPage("../outside/pic.png"); function aliasProject(makeAlias: (target: string, alias: string) => void, alias: string) { const dir = project(received("assets/scene.png")); @@ -440,6 +452,68 @@ describe("outsideAssetsAllowed", () => { expect(line).toContain("scene.html is another name for a file that came from someone else"); }); + async function compiledPage(dir: string) { + const compiled = await compileForRender(dir, join(dir, "index.html"), join(dir, ".dl"), { + allowOutsideProjectAssets: true, + }); + const rendered = [compiled.html, ...compiled.subCompositions.values()].join("\n"); + return { rendered, outside: [...compiled.externalAssets.values()] }; + } + + function playScene(dir: string, src: string): void { + write( + join(dir, "index.html"), + `
` + + `
`, + ); + } + + it.runIf(process.platform !== "win32")( + "refuses outside files when the received name is a link and an HTML link reaches the same file", + async () => { + const dir = project(received("assets/scene.png")); + write(join(dir, "media", "real.png"), MEDIA_PAGE); + symlinkSync(join(dir, "media", "real.png"), join(dir, "assets", "scene.png")); + symlinkSync(join(dir, "media", "real.png"), join(dir, "scene.html")); + playScene(dir, "scene.html"); + const { rendered, outside } = await compiledPage(dir); + expect(rendered).toContain("received-scene-marker"); + expect(outside).toContainEqual(expect.stringMatching(/[\\/]outside[\\/]pic\.png$/)); + + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("scene.html is another name for a file that came from someone else"); + }, + ); + + it.runIf(process.platform !== "win32")( + "refuses outside files when a linked folder leading outside the project holds the received file", + async () => { + const dir = project(received("pages/scene.png")); + const shared = join(dir, "..", "shared"); + write(join(shared, "scene.png"), mediaPage("assets/../../outside/pic.png")); + symlinkSync("scene.png", join(shared, "scene.html")); + symlinkSync(shared, join(dir, "pages")); + playScene(dir, "pages/scene.html"); + const { rendered, outside } = await compiledPage(dir); + expect(rendered).toContain("received-scene-marker"); + expect(outside).toContainEqual(expect.stringMatching(/[\\/]outside[\\/]pic\.png$/)); + + const { allowed, line } = decide(dir); + expect(allowed).toBe(false); + expect(line).toContain("Could not check every project file"); + }, + ); + + it.runIf(process.platform !== "win32")( + "keeps outside files when a linked folder stays inside the project", + () => { + const dir = project(received("assets/in.png")); + symlinkSync(join(dir, "assets"), join(dir, "pictures")); + expect(decide(dir).allowed).toBe(true); + }, + ); + it("keeps outside files when the other name is also a media name", () => { const dir = project(received("assets/scene.png")); write(join(dir, "assets", "scene.png"), SIGNATURES.png); diff --git a/packages/cli/src/utils/receivedRender.ts b/packages/cli/src/utils/receivedRender.ts index 746106e1268..58fe07824f4 100644 --- a/packages/cli/src/utils/receivedRender.ts +++ b/packages/cli/src/utils/receivedRender.ts @@ -12,7 +12,7 @@ import { fileURLToPath } from "node:url"; import { parseHTML } from "linkedom"; import { isNonRelativeUrl, isPathInside } from "@hyperframes/core"; import { resolveCompositionSrc } from "@hyperframes/parsers/asset-resolution"; -import { fileIdentity, linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; +import { linksOutside, receivedRecordStatus } from "./privateProjectFile.js"; const REFERENCE_ATTRS = ["src", "href", "poster"]; const MAX_SCANNED_BYTES = 2 * 1024 * 1024; @@ -274,9 +274,32 @@ function isMediaFontOrImage(path: string): boolean { const ALIAS_WALK_MAX_ENTRIES = 20_000; const ALIAS_WALK_MAX_MS = 2_000; -function aliasIdentity(path: string, isLink: boolean): string | null { - const target = isLink ? realOrNull(path) : path; - return target === null ? null : fileIdentity(target); +interface Target { + identity: string; + isDirectory: boolean; +} + +const NOTHING_THERE = new Set(["ENOENT", "ENOTDIR", "ELOOP"]); + +// What a path reaches with links followed; "missing" when nothing can be read through it, null when its identity is unknown. +function targetOf(path: string): Target | "missing" | null { + try { + const stat = statSync(path, { bigint: true }); + if (stat.ino === 0n) return null; + return { identity: `${stat.dev}:${stat.ino}`, isDirectory: stat.isDirectory() }; + } catch (error) { + return NOTHING_THERE.has((error as NodeJS.ErrnoException).code ?? "") ? "missing" : null; + } +} + +function receivedIdentities(listed: string[]): Set | null { + const identities = new Set(); + for (const path of listed) { + const target = targetOf(path); + if (target === null || target === "missing" || target.isDirectory) return null; + identities.add(target.identity); + } + return identities; } function listDir(dir: string): Dirent[] | null { @@ -287,11 +310,28 @@ function listDir(dir: string): Dirent[] | null { } } -function receivedAlias(dir: string, entry: Dirent, received: ReadonlySet): string | null { +const isMediaName = (path: string) => MEDIA_SIGNATURES[extname(path).toLowerCase()] !== undefined; + +// A linked folder is checked when it leads to a folder inside the project, which the walk lists under its own name. +function linkedFolderChecked(path: string, realProjectDir: string): boolean { + const real = realOrNull(path); + return real !== null && isPathInside(real, realProjectDir); +} + +// The entry's path when it reaches a received file under a name that is not media; undefined when that cannot be told. +function receivedAlias( + dir: string, + entry: Dirent, + received: ReadonlySet, + realProjectDir: string, +): string | null | undefined { const path = join(dir, entry.name); - if (MEDIA_SIGNATURES[extname(path).toLowerCase()] !== undefined) return null; - const identity = aliasIdentity(path, entry.isSymbolicLink()); - return identity !== null && received.has(identity) ? path : null; + if (isMediaName(path) && !entry.isSymbolicLink()) return null; + const target = targetOf(path); + if (target === "missing") return null; + if (target === null) return undefined; + if (target.isDirectory) return linkedFolderChecked(path, realProjectDir) ? null : undefined; + return !isMediaName(path) && received.has(target.identity) ? path : null; } function walkBudget(): (entries: number) => boolean { @@ -303,21 +343,38 @@ function walkBudget(): (entries: number) => boolean { }; } -// Project files whose own identity, or whose link target's, is a received file's, under a name that is not media; null when the walk could not finish. +interface AliasWalk { + received: ReadonlySet; + realProjectDir: string; + pending: string[]; + aliases: string[]; +} + +// Queues the folder's subfolders and records its aliases; false when an entry cannot be checked. +function walkListing(walk: AliasWalk, dir: string, listing: Dirent[]): boolean { + for (const entry of listing) { + if (entry.isDirectory()) { + walk.pending.push(join(dir, entry.name)); + continue; + } + const alias = receivedAlias(dir, entry, walk.received, walk.realProjectDir); + if (alias === undefined) return false; + if (alias !== null) walk.aliases.push(alias); + } + return true; +} + +// Project files that reach a received file, links followed, under a name that is not media; null when the walk could not check every file, including one through a linked folder that leads outside the project. function nonMediaAliases(projectDir: string, received: ReadonlySet): string[] | null { const withinBudget = walkBudget(); - const aliases: string[] = []; - const pending = [projectDir]; - for (let dir = pending.pop(); dir !== undefined; dir = pending.pop()) { + const realProjectDir = realOrNull(projectDir) ?? projectDir; + const walk: AliasWalk = { received, realProjectDir, pending: [projectDir], aliases: [] }; + for (let dir = walk.pending.pop(); dir !== undefined; dir = walk.pending.pop()) { const listing = listDir(dir); if (listing === null || !withinBudget(listing.length)) return null; - for (const entry of listing) { - const alias = entry.isDirectory() ? null : receivedAlias(dir, entry, received); - if (entry.isDirectory()) pending.push(join(dir, entry.name)); - if (alias !== null) aliases.push(alias); - } + if (!walkListing(walk, dir, listing)) return null; } - return aliases; + return walk.aliases; } interface Refusal { @@ -335,13 +392,14 @@ function receivedRefusal( if (record.listed === null) { return { reason: `Could not read ${record.path}, ${READS_NOTHING_OUTSIDE}`, alwaysWarn: true }; } + if (record.listed.length === 0) return null; const nonMedia = record.listed.find((path) => !isMediaFontOrImage(path)); if (nonMedia !== undefined) { const reason = `${shown(nonMedia)} came from someone else and is not a media, font or image file, ${READS_NOTHING_OUTSIDE}`; return { reason, alwaysWarn: false }; } - const received = new Set(record.listed.flatMap((path) => fileIdentity(path) ?? [])); - const aliases = nonMediaAliases(projectDir, received); + const received = receivedIdentities(record.listed); + const aliases = received === null ? null : nonMediaAliases(projectDir, received); if (aliases === null) { const reason = `Could not check every project file for another name of a received file, ${READS_NOTHING_OUTSIDE}`; return { reason, alwaysWarn: true }; From c5118694b4bbdf4e790c815a2aa5d91fee6da3f6 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sun, 15 Nov 2026 00:58:44 -0800 Subject: [PATCH 29/29] chore: raise the producer unpacked size budget for the composition file checks --- scripts/package-size-budgets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 9649cb8889b..43843ca8067 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -37,7 +37,7 @@ }, "@hyperframes/producer": { "packed": 901000, - "unpacked": 3245000 + "unpacked": 3290000 }, "@hyperframes/sdk": { "packed": 90662,