From f2087431b3c78df7f733a1d7cf245b7744cfdf07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 17:51:22 +0000 Subject: [PATCH] fix(producer): a downloaded asset's local path is written into the page exactly as named (#8739) The compiler rewrote each remote media, image, background and font URL with replaceAll, passing the local path as a replacement string, so a $ sequence in it was read as a pattern. Each rewrite now passes a function, so the path is inserted literally; the 3D projection's inlined data URLs get the same. A downloaded file's name keeps only the hash and a short alphanumeric extension from the URL. --- .../engine/src/services/threeDProjection.ts | 5 +- .../src/utils/urlDownloader.names.test.ts | 47 +++++++++++ packages/engine/src/utils/urlDownloader.ts | 2 +- .../htmlCompiler.remoteAssetLiteral.test.ts | 83 +++++++++++++++++++ .../producer/src/services/htmlCompiler.ts | 8 +- 5 files changed, 139 insertions(+), 6 deletions(-) create mode 100644 packages/engine/src/utils/urlDownloader.names.test.ts create mode 100644 packages/producer/src/services/htmlCompiler.remoteAssetLiteral.test.ts diff --git a/packages/engine/src/services/threeDProjection.ts b/packages/engine/src/services/threeDProjection.ts index 9e2b4717f4..8fbfe578f2 100644 --- a/packages/engine/src/services/threeDProjection.ts +++ b/packages/engine/src/services/threeDProjection.ts @@ -215,7 +215,7 @@ export async function initThreeDProjectionInPage(): Promise `url(${data})`); } catch { // unfetchable font src — leave as-is; SVG will skip it } @@ -257,7 +257,8 @@ export async function initThreeDProjectionInPage(): Promise `url(${data})`); } catch { /* leave */ } diff --git a/packages/engine/src/utils/urlDownloader.names.test.ts b/packages/engine/src/utils/urlDownloader.names.test.ts new file mode 100644 index 0000000000..790ba6b572 --- /dev/null +++ b/packages/engine/src/utils/urlDownloader.names.test.ts @@ -0,0 +1,47 @@ +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { _setDownloadFetchForTests, downloadToTemp } from "./urlDownloader.js"; + +const dirs: string[] = []; + +afterEach(() => { + _setDownloadFetchForTests(); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +async function download(url: string): Promise { + _setDownloadFetchForTests( + vi.fn(async () => new Response("media", { headers: { "content-length": "5" } })) as never, + ); + const dir = mkdtempSync(join(tmpdir(), "hf-url-names-")); + dirs.push(dir); + const path = await downloadToTemp(url, dir, 1_000); + expect(readFileSync(path, "utf8")).toBe("media"); + return basename(path); +} + +const SAFE_NAME = /^download_[0-9a-f]{12}\.[A-Za-z0-9]{1,10}$/; + +// fails without the fix: the URL path's extension was copied into the file name as is +describe("a downloaded file's name", () => { + it.each([ + ["https://cdn.example/a.mp4$&x", ".mp4"], + ["https://cdn.example/a.png$'x", ".png"], + ["https://cdn.example/a.webm$`x", ".webm"], + ["https://cdn.example/a.mp3$$x", ".mp3"], + ["https://cdn.example/a.mp4'onerror=x", ".mp4"], + ["https://cdn.example/a.jpg=(x)&y", ".jpg"], + [`https://cdn.example/a.${"m".repeat(300)}`, `.${"m".repeat(10)}`], + ["https://cdn.example/a.$&", ".mp4"], + ])("keeps only a short alphanumeric extension for %s", async (url, ext) => { + const name = await download(url); + expect(name).toMatch(SAFE_NAME); + expect(name.endsWith(ext)).toBe(true); + }); + + it("keeps a plain extension", async () => { + expect(await download("https://cdn.example/clip.MOV")).toMatch(/^download_[0-9a-f]{12}\.MOV$/); + }); +}); diff --git a/packages/engine/src/utils/urlDownloader.ts b/packages/engine/src/utils/urlDownloader.ts index d0c17aa604..866125de5a 100644 --- a/packages/engine/src/utils/urlDownloader.ts +++ b/packages/engine/src/utils/urlDownloader.ts @@ -271,7 +271,7 @@ function getFilenameFromUrl(url: string, validationScope: string): string { const physicalIdentity = validationScope === "" ? url : `${url}\0${validationScope}`; const hash = createHash("md5").update(physicalIdentity).digest("hex").slice(0, 12); const urlObj = new URL(url); - const ext = extname(urlObj.pathname) || ".mp4"; + const ext = /^\.[a-z0-9]{1,10}/i.exec(extname(urlObj.pathname))?.[0] ?? ".mp4"; return `download_${hash}${ext}`; } diff --git a/packages/producer/src/services/htmlCompiler.remoteAssetLiteral.test.ts b/packages/producer/src/services/htmlCompiler.remoteAssetLiteral.test.ts new file mode 100644 index 0000000000..a422fd40bf --- /dev/null +++ b/packages/producer/src/services/htmlCompiler.remoteAssetLiteral.test.ts @@ -0,0 +1,83 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseHTML } from "linkedom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + localizeRemoteBackgroundImages, + localizeRemoteFontFaces, + localizeRemoteImageSources, + localizeRemoteMediaSources, + REMOTE_MEDIA_SUBDIR, +} from "./htmlCompiler.js"; + +const downloaded = vi.hoisted(() => ({ name: "" })); + +vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({ + ...(await importOriginal()), + downloadToTemp: async (_url: string, destDir: string) => { + mkdirSync(destDir, { recursive: true }); + const local = join(destDir, downloaded.name); + writeFileSync(local, "bytes"); + return local; + }, +})); + +let dir = ""; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "hf-remote-literal-")); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +const element = (html: string, id: string) => parseHTML(html).document.getElementById(id)!; + +// fails without the fix: the local file name was a replaceAll pattern, so "$&" put the quoted remote URL back +// into the page outside its attribute, and "$$" and "$`" rewrote the text around the match +describe.each(["$&", "$$", "$`"])("a downloaded file whose name holds %s", (sequence) => { + const local = (ext: string) => { + downloaded.name = `download_1${sequence}x${ext}`; + return `${REMOTE_MEDIA_SUBDIR}/${downloaded.name}`; + }; + + it("becomes exactly the media src, with only the authored attributes", async () => { + const rel = local(".mp4"); + const page = ``; + const { html } = await localizeRemoteMediaSources(page, dir); + const video = element(html, "v"); + expect(video.getAttributeNames()).toEqual(["id", "src", "data-start"]); + expect(video.getAttribute("src")).toBe(rel); + }); + + it("becomes exactly the image src, with only the authored attributes", async () => { + const rel = local(".png"); + const page = ``; + const { html } = await localizeRemoteImageSources(page, dir); + const image = element(html, "i"); + expect(image.getAttributeNames()).toEqual(["id", "src", "alt"]); + expect(image.getAttribute("src")).toBe(rel); + }); + + it.each([ + ["unquoted", "url(https://m.example/b.png)"], + ["quoted", 'url("https://m.example/b.png")'], + ])("becomes exactly an %s background url", async (_form, url) => { + const rel = local(".png"); + const page = `
`; + const { html } = await localizeRemoteBackgroundImages(page, dir); + const div = element(html, "b"); + expect(div.getAttributeNames()).toEqual(["id", "style"]); + expect(div.getAttribute("style")).toBe( + `background-image: ${url.split("https://m.example/b.png").join(rel)}`, + ); + }); + + it("becomes exactly the font url", async () => { + const rel = local(".woff2"); + const page = ``; + const { html } = await localizeRemoteFontFaces(page, dir); + expect(parseHTML(html).document.querySelector("style")!.textContent).toBe( + `@font-face { font-family: "B"; src: url("${rel}"); }`, + ); + }); +}); diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 80ee34ded5..7472f84e11 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -1999,7 +1999,9 @@ async function downloadAndRewriteUrls( let result = html; for (const [url, relPath] of urlToRelPath) { - result = result.replaceAll(`"${url}"`, `"${relPath}"`).replaceAll(`'${url}'`, `'${relPath}'`); + result = result + .replaceAll(`"${url}"`, () => `"${relPath}"`) + .replaceAll(`'${url}'`, () => `'${relPath}'`); if (extraRewrite) result = extraRewrite(result, url, relPath); } @@ -2130,7 +2132,7 @@ export async function localizeRemoteBackgroundImages( assets, // Quoted url('..')/url("..") are rewritten by downloadAndRewriteUrls' default // replaceAll; this handles the unquoted url(https://..) form. - (h, url, rel) => h.replaceAll(`url(${url})`, `url(${rel})`), + (h, url, rel) => h.replaceAll(`url(${url})`, () => `url(${rel})`), ); } @@ -2376,7 +2378,7 @@ function localizeFontFaceUrls( style, css, "".length, - css.replaceAll(`url(${url})`, `url("${relPath}")`), + css.replaceAll(`url(${url})`, () => `url("${relPath}")`), ), ), );