Skip to content

Commit 4cf26b5

Browse files
fix(producer): render reads a composition src like the preview, refuses paths outside (heygen-com#7317)
* fix(producer): render reads a composition src like the preview, refuses paths outside * fix(producer): a src with an encoded folder re-points its sibling assets; format
1 parent de2d21a commit 4cf26b5

3 files changed

Lines changed: 104 additions & 8 deletions

File tree

‎packages/producer/src/services/htmlCompiler.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,72 @@ describe("detectRenderModeHints", () => {
10271027
).rejects.toThrow(/compositions\/does-not-exist\.html/);
10281028
});
10291029

1030+
it.each([
1031+
["a %20-encoded name", "compositions/my%20scene.html"],
1032+
["a leading slash for the project root", "/compositions/my scene.html"],
1033+
])("compileForRender reads a data-composition-src written with %s", async (_label, src) => {
1034+
const projectDir = makeSubCompProject("hf-spelled-subcomp-", [{ id: "intro", src }], {
1035+
"my scene.html": validSubCompHtml("intro", "Spelled"),
1036+
});
1037+
try {
1038+
const compiled = await compileForRender(
1039+
projectDir,
1040+
join(projectDir, "index.html"),
1041+
projectDir,
1042+
);
1043+
expect(compiled.html).toContain("Spelled");
1044+
} finally {
1045+
rmSync(projectDir, { recursive: true, force: true });
1046+
}
1047+
});
1048+
1049+
it("compileForRender re-points a sibling asset of a sub-composition whose folder is %20-encoded", async () => {
1050+
const projectDir = makeSubCompProject(
1051+
"hf-encoded-dir-subcomp-",
1052+
[{ id: "intro", src: "my%20dir/scene.html" }],
1053+
{},
1054+
);
1055+
try {
1056+
mkdirSync(join(projectDir, "my dir"), { recursive: true });
1057+
writeFileSync(join(projectDir, "my dir", "img.png"), "png");
1058+
writeFileSync(
1059+
join(projectDir, "my dir", "scene.html"),
1060+
`<!doctype html><html><body><div data-composition-id="intro" data-width="100" data-height="100"><img id="pic" src="img.png"></div></body></html>`,
1061+
);
1062+
const compiled = await compileForRender(
1063+
projectDir,
1064+
join(projectDir, "index.html"),
1065+
projectDir,
1066+
);
1067+
const src = parseHTML(compiled.html).document.getElementById("pic")?.getAttribute("src");
1068+
expect(decodeURIComponent(src ?? "")).toContain("my dir/img.png");
1069+
} finally {
1070+
rmSync(projectDir, { recursive: true, force: true });
1071+
}
1072+
});
1073+
1074+
it.each([
1075+
["dot-dot segments", "../outside-scene.html"],
1076+
["an encoded ../", "%2e%2e%2foutside-scene.html"],
1077+
["a leading slash and dot-dot", "/../outside-scene.html"],
1078+
["an encoded leading slash and dot-dot", "%2f%2e%2e%2foutside-scene.html"],
1079+
])(
1080+
"compileForRender refuses a data-composition-src that leaves the project through %s",
1081+
async (_label, src) => {
1082+
const projectDir = makeSubCompProject("hf-outside-subcomp-", [{ id: "intro", src }], {});
1083+
const outside = join(dirname(projectDir), "outside-scene.html");
1084+
writeFileSync(outside, validSubCompHtml("intro", "Outside"));
1085+
try {
1086+
await expect(
1087+
compileForRender(projectDir, join(projectDir, "index.html"), projectDir),
1088+
).rejects.toThrow(/outside the project folder/);
1089+
} finally {
1090+
rmSync(outside, { force: true });
1091+
rmSync(projectDir, { recursive: true, force: true });
1092+
}
1093+
},
1094+
);
1095+
10301096
it("compileForRender preserves a bare fragment's markup, sibling styles, and script", async () => {
10311097
const projectDir = makeSubCompProject(
10321098
"hf-fragment-subcomp-",

‎packages/producer/src/services/htmlCompiler.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
1313

1414
import { createHash } from "node:crypto";
1515
import { createReadStream, existsSync, mkdirSync, readFileSync } from "fs";
16-
import { join, dirname, resolve, basename, relative } from "path";
16+
import { join, dirname, resolve, basename, relative, sep } from "path";
1717
import { parseHTML } from "linkedom";
1818
import {
1919
COMPOSITION_SOURCE_URL,
@@ -74,7 +74,7 @@ import {
7474
readTextFile,
7575
} from "@hyperframes/parsers/asset-resolution";
7676
import { extractMediaMetadata, extractAudioMetadata } from "../utils/ffprobe.js";
77-
import { isPathInside, toExternalAssetKey } from "../utils/paths.js";
77+
import { isPathInside, resolveCompositionSrc, toExternalAssetKey } from "../utils/paths.js";
7878
import { collectHiddenVideoIds, collectRenderMedia } from "./renderMediaCollector.js";
7979
import {
8080
type VideoElement,
@@ -213,6 +213,16 @@ class EmptyCompositionError extends Error {
213213
}
214214
}
215215

216+
/** The html with each data-composition-src as the project-relative path it names (%xx decoded, no leading /). */
217+
function normalizeCompositionSrcs(html: string, projectDir: string): string {
218+
return html.replace(/(\bdata-composition-src=)(["'])([^"']*)\2/g, (whole, name, quote, value) => {
219+
if (!value.includes("%") && !value.startsWith("/")) return whole;
220+
const file = resolveCompositionSrc(projectDir, value);
221+
if (file === null) return whole;
222+
return `${name}${quote}${relative(projectDir, file).split(sep).join("/")}${quote}`;
223+
});
224+
}
225+
216226
/**
217227
* Recursively walk every `data-composition-src` reference reachable from
218228
* `html` (including nested sub-compositions) and verify each resolves to a
@@ -242,7 +252,11 @@ function assertSubCompositionsUsable(
242252
if (!srcPath) continue;
243253
if (isUnresolvedAssetPlaceholder(srcPath)) continue; // __UPPER__ placeholder or unresolved templating token — not a real reference (shared with lint via @hyperframes/parsers)
244254

245-
const filePath = resolve(projectDir, srcPath);
255+
const filePath = resolveCompositionSrc(projectDir, srcPath);
256+
if (filePath === null) {
257+
problems.push({ srcPath, detail: "it is outside the project folder" });
258+
continue;
259+
}
246260
// Circular reference guard. parseSubCompositions (below) silently
247261
// `continue`s on a repeat visit with no reporting at all — mirror that
248262
// silence here rather than pretend it surfaces an error somewhere else.
@@ -779,7 +793,8 @@ async function parseSubCompositions(
779793
const srcPath = el.getAttribute("data-composition-src");
780794
if (!srcPath) continue;
781795

782-
const filePath = resolve(projectDir, srcPath);
796+
const filePath = resolveCompositionSrc(projectDir, srcPath);
797+
if (filePath === null) continue;
783798

784799
// Circular reference guard
785800
if (visited.has(filePath)) {
@@ -791,7 +806,7 @@ async function parseSubCompositions(
791806
continue;
792807
}
793808

794-
const rawSubHtml = read.text;
809+
const rawSubHtml = normalizeCompositionSrcs(read.text, projectDir);
795810
const nestedVisited = new Set(visited);
796811
nestedVisited.add(filePath);
797812

@@ -1072,8 +1087,9 @@ function inlineSubCompositions(
10721087
resolveHtml: (srcPath: string) => {
10731088
let compHtml = subCompositions.get(srcPath) || null;
10741089
if (!compHtml) {
1075-
const read = readProjectFile(resolve(projectDir, srcPath));
1076-
if (read.kind === "file") {
1090+
const filePath = resolveCompositionSrc(projectDir, srcPath);
1091+
const read = filePath ? readProjectFile(filePath) : null;
1092+
if (read?.kind === "file") {
10771093
compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
10781094
}
10791095
}
@@ -2067,7 +2083,10 @@ export async function compileForRender(
20672083
options: CompileForRenderOptions = {},
20682084
): Promise<CompiledComposition> {
20692085
const entryHtml = rebaseDirectEntryAssetPaths(readTextFile(htmlPath), projectDir, htmlPath);
2070-
const rawHtml = rewriteUnresolvableGsapToCdn(entryHtml, projectDir);
2086+
const rawHtml = normalizeCompositionSrcs(
2087+
rewriteUnresolvableGsapToCdn(entryHtml, projectDir),
2088+
projectDir,
2089+
);
20712090

20722091
// Pre-flight: every data-composition-src reference must resolve to a
20732092
// usable file before we spend any time compiling, launching a browser, or

‎packages/producer/src/utils/paths.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import {
99
relative as nodeRelative,
1010
isAbsolute as nodeIsAbsolute,
1111
} from "node:path";
12+
import { existsSync } from "node:fs";
1213
import { fileURLToPath } from "node:url";
14+
import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
1315

1416
export interface RenderPaths {
1517
absoluteProjectDir: string;
@@ -134,3 +136,12 @@ export function resolveRenderPaths(
134136

135137
return { absoluteProjectDir, absoluteOutputPath };
136138
}
139+
140+
/** The project file a data-composition-src names, as the preview reads it; null when it leaves the project. */
141+
export function resolveCompositionSrc(projectDir: string, src: string): string | null {
142+
const rooted = (value: string) => nodeResolve(projectDir, value.replace(/^(?:\.?[\\/])+/, ""));
143+
const decoded = rooted(decodedUrlPath(src));
144+
if (!isPathInside(decoded, projectDir)) return null;
145+
const raw = rooted(src);
146+
return !existsSync(decoded) && isPathInside(raw, projectDir) && existsSync(raw) ? raw : decoded;
147+
}

0 commit comments

Comments
 (0)