mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
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.
This commit is contained in:
@@ -215,7 +215,7 @@ export async function initThreeDProjectionInPage(): Promise<ThreeDProjectionResu
|
||||
if (!src) continue;
|
||||
try {
|
||||
const data = await toDataUrl(new URL(src, document.baseURI).href);
|
||||
text = text.replace(m[0], `url(${data})`);
|
||||
text = text.replace(m[0], () => `url(${data})`);
|
||||
} catch {
|
||||
// unfetchable font src — leave as-is; SVG will skip it
|
||||
}
|
||||
@@ -257,7 +257,8 @@ export async function initThreeDProjectionInPage(): Promise<ThreeDProjectionResu
|
||||
const src = m[2];
|
||||
if (!src) continue;
|
||||
try {
|
||||
inlined = inlined.replace(m[0], `url(${await toDataUrl(src)})`);
|
||||
const data = await toDataUrl(src);
|
||||
inlined = inlined.replace(m[0], () => `url(${data})`);
|
||||
} catch {
|
||||
/* leave */
|
||||
}
|
||||
|
||||
@@ -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<string> {
|
||||
_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$/);
|
||||
});
|
||||
});
|
||||
@@ -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}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<typeof import("../utils/urlDownloader.js")>()),
|
||||
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 = `<video id="v" src="https://m.example/a.mp4" data-start="0"></video>`;
|
||||
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 = `<img id="i" src='https://m.example/a.png' alt="">`;
|
||||
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 = `<div id="b" style='background-image: ${url}'></div>`;
|
||||
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 = `<style>@font-face { font-family: "B"; src: url(https://f.example/a.woff2); }</style>`;
|
||||
const { html } = await localizeRemoteFontFaces(page, dir);
|
||||
expect(parseHTML(html).document.querySelector("style")!.textContent).toBe(
|
||||
`@font-face { font-family: "B"; src: url("${rel}"); }`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
"</style>".length,
|
||||
css.replaceAll(`url(${url})`, `url("${relPath}")`),
|
||||
css.replaceAll(`url(${url})`, () => `url("${relPath}")`),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user