fix: preview image prep reads no HEIC or GIF outside the project unless render would (#8001)

* fix: preview image prep reads no HEIC or GIF outside the project unless render would

Image prep now keeps sources inside the project unless the caller
opts in with allowOutsideFiles. Studio preview opts in only when a
local render of the project would bring in outside files, so a
received project's preview converts nothing from outside it.

* fix: keep comment share flat; Windows share test takes the trusted path

The Windows path test checks that image prep never looks at a share.
It now passes allowOutsideFiles, so a local path is still looked up on
the widest path even though the fake project folder does not exist.

* test(cli): the Windows share preview test takes the trusted outside-file path

The fake C:\project folder does not exist on the test host, so the
received-project check fails closed and preview would contain every
source. The test mocks that check to allow outside files, so a local
path is still looked up on the widest path.
This commit is contained in:
Michael Wang
2026-11-17 03:15:26 +00:00
committed by GitHub
parent 38aaad1b20
commit f880693cf1
9 changed files with 123 additions and 7 deletions
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { createStudioServer, type StudioServer } from "./studioServer.js";
import { cleanupStudioServerRoot, makeStudioServerRoot } from "./studioServerTestFixture.js";
@@ -141,3 +142,50 @@ describe("bundled GSAP", () => {
}
});
});
describe("preview image prep and files outside the project", () => {
const heic = fileURLToPath(
new URL("../../../producer/tests/fixtures/heic/rotated-grid.heic", import.meta.url),
);
const outsidePhoto = () => path.join(root, "Pictures", "IMG_0001.HEIC");
const preparedHeif = () => path.join(projectDir, ".hyperframes", "prepared-assets", "heif");
beforeEach(() => {
fs.mkdirSync(path.dirname(outsidePhoto()));
fs.copyFileSync(heic, outsidePhoto());
fs.writeFileSync(
path.join(projectDir, "index.html"),
`<!doctype html><html><body><div data-composition-id="main" data-width="320" data-height="180">
<img id="photo" src="../Pictures/IMG_0001.HEIC" data-start="0" data-duration="1">
</div></body></html>`,
);
});
async function previewPhotoSrc(): Promise<string | undefined> {
const html = await (await server.app.request("/api/projects/film/preview")).text();
return html.match(/<img [^>]*id="photo"[^>]*src="([^"]+)"/)?.[1];
}
it("converts no outside photo for a received project, as its render would not", async () => {
fs.mkdirSync(path.join(projectDir, ".hyperframes"), { recursive: true });
fs.writeFileSync(
path.join(projectDir, ".hyperframes", "received-files.json"),
JSON.stringify({ files: ["index.html"] }),
);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
expect(await previewPhotoSrc()).not.toContain("prepared-assets");
expect(await previewPhotoSrc()).not.toContain("prepared-assets");
expect(fs.existsSync(preparedHeif())).toBe(false);
const refusals = warn.mock.calls.filter(([line]) => String(line).includes("someone else"));
expect(refusals).toHaveLength(1);
} finally {
warn.mockRestore();
}
});
it("still converts an outside photo for the developer's own project, as its render does", async () => {
expect(await previewPhotoSrc()).toMatch(/^\.hyperframes\/prepared-assets\/heif\//);
expect(fs.readdirSync(preparedHeif())).toHaveLength(1);
});
});
@@ -35,6 +35,8 @@ vi.mock("node:fs", async () => {
return { ...fs, ...overrides, default: { ...fs, ...overrides } };
});
vi.mock("../utils/receivedRender.js", () => ({ outsideAssetsAllowed: () => true }));
const { createStudioServer } = await import("./studioServer.js");
const { cleanupStudioServerRoot, makeStudioServerRoot } =
await import("./studioServerTestFixture.js");
+10
View File
@@ -540,6 +540,13 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
// launching a browser shutdown() has no way to know about and close.
let shuttingDown = false;
const previewWarnings = new Set<string>();
const warnPreviewOnce = (line: string) => {
if (previewWarnings.has(line)) return;
previewWarnings.add(line);
console.warn(`[studio] ${line}`);
};
const adapter: PreviewApiAdapter = {
history: () => (hostAppOwnsHistory ? null : projectHistory()),
loadSharp: () => loadSharpInBackground("image thumbnails"),
@@ -594,11 +601,13 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
const preparedDirs = [gifOutputDir, gifDownloadDir, heifOutputDir];
if (!preparedDirs.every((dir) => isLinkFreeWithinProject(project.dir, dir)))
return injectDeterministicFontFaces(html);
const allowOutsideFiles = outsideAssetsAllowed(project.dir, undefined, warnPreviewOnce);
const { html: htmlWithJpegs } = await prepareHeifImageInputs(html, {
projectDir: project.dir,
downloadDir: gifDownloadDir,
outputDir: heifOutputDir,
outputSrcPrefix: ".hyperframes/prepared-assets/heif",
allowOutsideFiles,
onFailure: (error) => console.warn(`[studio] ${error.message}`),
});
const prepared = await prepareAnimatedGifInputs(htmlWithJpegs, {
@@ -606,6 +615,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
downloadDir: gifDownloadDir,
outputDir: gifOutputDir,
outputSrcPrefix: ".hyperframes/prepared-assets/gif",
allowOutsideFiles,
cacheDir: gifOutputDir,
sourceAssets: await downloadRemoteGifImageSources(html, gifDownloadDir, (url, destDir) =>
downloadToTemp(url, destDir, undefined, undefined, undefined, {
@@ -256,6 +256,36 @@ describe("prepareAnimatedGifInputs", () => {
expect(calls[0]?.args).toContain("2");
});
it("reads no GIF outside the project unless the caller allows outside files", async () => {
const root = makeProject();
const projectDir = join(root, "project");
const outside = join(root, "Downloads", "reaction.gif");
mkdirSync(projectDir);
mkdirSync(dirname(outside));
writeFileSync(outside, gif([...frame(10), ...frame(10)], 0));
const html = `<img data-start="0" data-duration="1" src="../Downloads/reaction.gif"><img data-start="0" data-duration="1" src="${outside}">`;
const calls: AnimatedGifTranscodeRequest[] = [];
const options = {
projectDir,
downloadDir: join(projectDir, "downloads"),
transcode: async (request: AnimatedGifTranscodeRequest) => {
calls.push(request);
writeFileSync(request.outputPath, "webm");
},
};
for (const src of ["../Downloads/reaction.gif", outside]) {
expect(resolveLocalImageSourcePath(src, options)).toBeNull();
}
const contained = await prepareAnimatedGifInputs(html, options);
expect(contained.html).toBe(html);
expect(calls).toHaveLength(0);
const trusted = await prepareAnimatedGifInputs(html, { ...options, allowOutsideFiles: true });
expect(trusted.preparedGifs).toHaveLength(2);
expect(calls).toHaveLength(1);
});
it("uses source asset mappings for remote GIF URLs", async () => {
const projectDir = makeProject();
const sourceUrl = "https://cdn.example.com/reaction.gif";
@@ -39,7 +39,7 @@ export interface PrepareAnimatedGifInputsOptions {
sourceAssets?: Map<string, string>;
timeoutMs?: number;
transcode?: (input: AnimatedGifTranscodeRequest) => Promise<void>;
assetRoot?: string;
allowOutsideFiles?: boolean;
}
export interface AnimatedGifTranscodeRequest {
@@ -89,7 +89,7 @@ export function resolveLocalImageSourcePath(
src: string,
options: Pick<
PrepareAnimatedGifInputsOptions,
"projectDir" | "downloadDir" | "sourceAssets" | "assetRoot"
"projectDir" | "downloadDir" | "sourceAssets" | "allowOutsideFiles"
>,
): string | null {
const trimmed = src.trim();
@@ -110,10 +110,11 @@ export function resolveLocalImageSourcePath(
resolve(options.downloadDir, normalizedBase),
];
const assetRoot = options.allowOutsideFiles ? undefined : options.projectDir;
const allowed = (candidate: string) =>
!namesAnotherNetworkRoot(options.projectDir, candidate) &&
!isPrivateUnderAssetRoots(candidate, [options.projectDir, options.downloadDir]) &&
((!escapesAssetRoot(candidate, options.assetRoot) &&
((!escapesAssetRoot(candidate, assetRoot) &&
outsideAssetRefusal(options.projectDir, candidate) !== "blocklisted") ||
!escapesAssetRoot(candidate, options.downloadDir));
return candidates.find((candidate) => allowed(candidate) && existsSync(candidate)) ?? null;
@@ -241,6 +241,29 @@ describe("prepareHeifImageInputs", () => {
expect(primaryGrid({ stream_groups: [grid(5)] })?.width).toBe(5);
});
it("reads no HEIC outside the project unless the caller allows outside files", async () => {
const d = project({});
const outside = join(d.base, "Pictures", "IMG_0001.HEIC");
spawnSync("mkdir", ["-p", join(outside, "..")]);
writeFileSync(outside, readFileSync(FIXTURE));
const html = `<img src="../Pictures/IMG_0001.HEIC"><img src="${outside}">`;
const { calls, transcode } = countingTranscode();
const contained = await prepareHeifImageInputs(html, { ...d, transcode });
expect(contained.html).toBe(html);
expect(contained.preparedImages).toEqual([]);
expect(calls).toHaveLength(0);
expect(existsSync(d.outputDir)).toBe(false);
const trusted = await prepareHeifImageInputs(html, {
...d,
transcode,
allowOutsideFiles: true,
});
expect(trusted.preparedImages).toHaveLength(2);
expect(trusted.html).not.toContain("IMG_0001.HEIC");
});
it("spawns nothing and writes nothing without a HEIC image", async () => {
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==",
@@ -81,7 +81,7 @@ export interface PrepareHeifImageInputsOptions {
sourceAssets?: Map<string, string>;
timeoutMs?: number;
transcode?: (input: HeifTranscodeRequest) => Promise<void>;
assetRoot?: string;
allowOutsideFiles?: boolean;
/** Leaves an image whose conversion failed as authored and reports it, instead of throwing. */
onFailure?: (error: HeifImageConversionError | HeifToolUnavailableError) => void;
}
@@ -2375,7 +2375,7 @@ export async function compileForRender(
cacheDir: options.animatedGifCacheDir,
sourceAssets: remoteImageAssets,
timeoutMs: options.ffmpegProcessTimeout,
assetRoot,
allowOutsideFiles: assetRoot === undefined,
});
if (preparedHeifImages.length > 0) {
defaultLogger.debug(`[Compiler] Converted ${preparedHeifImages.length} HEIC image(s) to JPEG`);
@@ -2392,7 +2392,7 @@ export async function compileForRender(
cacheDir: options.animatedGifCacheDir,
sourceAssets: gifSourceAssets,
timeoutMs: options.ffmpegProcessTimeout,
assetRoot,
allowOutsideFiles: assetRoot === undefined,
});
if (preparedGifs.length > 0) {
defaultLogger.debug(`[Compiler] Prepared ${preparedGifs.length} animated GIF input(s) as WebM`);
@@ -70,6 +70,7 @@ describe("image prep under Windows path rules", () => {
await prepareHeifImageInputs(page([...SHARES, "local.gif"]), {
projectDir: PROJECT,
downloadDir: DOWNLOADS,
allowOutsideFiles: true,
});
expect(touched.filter(onAShare)).toEqual([]);
expect(touched).toContain("C:\\project\\local.gif");
@@ -79,6 +80,7 @@ describe("image prep under Windows path rules", () => {
await prepareAnimatedGifInputs(page([...SHARES, "local.gif"]), {
projectDir: PROJECT,
downloadDir: DOWNLOADS,
allowOutsideFiles: true,
});
expect(touched.filter(onAShare)).toEqual([]);
expect(touched).toContain("C:\\project\\local.gif");