Skip to content

Write HTML. Render video. Built for agents.

fix(lint): surface unloadable media variable defaults, stop reading data-var-src ids as paths (#3406)

Miguel Ángel41edbfb2ce5a
diff --git a/packages/core/src/runtime/applyVariableBindings.ts b/packages/core/src/runtime/applyVariableBindings.ts
index 10e961f54b..41d99e7cc1 100644
--- a/packages/core/src/runtime/applyVariableBindings.ts
+++ b/packages/core/src/runtime/applyVariableBindings.ts
@@ -28,7 +28,10 @@
*/
import { readVariablesForElement } from "./variableScope";
-import { isScalarVariableValue as isScalar } from "@hyperframes/parsers/composition";
+import {
+ isScalarVariableValue as isScalar,
+ isSafeMediaUrl,
+} from "@hyperframes/parsers/composition";
// data-var-src only rebinds media `src` on media elements. A user-controlled
// variable value assigned to a src is an XSS surface on tags whose src executes
@@ -45,28 +48,6 @@ function resolveUrl(value: unknown): string | null {
return null;
}
-/**
- * Protocol allowlist for a resolved media URL. Relative URLs (no scheme) resolve
- * against the page origin and are always safe. Absolute URLs are restricted to
- * http(s)/blob and image data: URIs — defense-in-depth alongside VAR_SRC_TAGS,
- * blocking `javascript:`, `data:text/html`, `file:`, etc. even if a future tag
- * slips past the element guard. Control chars are stripped before the scheme
- * test because browsers ignore them when parsing the URL (`java\tscript:`).
- */
-function isSafeMediaUrl(url: string): boolean {
- // Browsers ignore ASCII control chars/whitespace when parsing a URL, so strip
- // them before reading the scheme (defeats `java\tscript:` style bypasses).
- // oxlint-disable-next-line no-control-regex -- control chars are the target here
- const normalized = url.replace(/[\u0000-\u0020]/g, "");
- const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
- if (!scheme) return true;
- const proto = scheme[1]?.toLowerCase();
- if (!proto) return false;
- if (proto === "https" || proto === "http" || proto === "blob") return true;
- if (proto === "data") return /^data:image\//i.test(normalized);
- return false;
-}
-
/**
* Strip characters that could smuggle additional declarations or markup out of
* a var() substitution site. A scalar value folded into `background: var(--x)`
diff --git a/packages/lint/src/hevcPreviewLint.ts b/packages/lint/src/hevcPreviewLint.ts
index e0cc086c0b..6d9decebd6 100644
--- a/packages/lint/src/hevcPreviewLint.ts
+++ b/packages/lint/src/hevcPreviewLint.ts
@@ -11,6 +11,7 @@ import {
resolveExistingLocalAsset,
} from "@hyperframes/parsers/asset-resolution";
import type { HyperframeLintFinding } from "./types.js";
+import { mediaSrcTagRe } from "./utils";
/** Structurally compatible with `project.ts`'s (unexported) `HtmlSource` —
* duplicated as a shape, not imported, to avoid a circular import between
@@ -82,14 +83,14 @@ export function collectLocalVideoCandidates(
htmlSources: HtmlSourceLike[],
): Map<string, string> {
const candidates = new Map<string, string>();
- const videoSrcRe = /<video\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
+ const videoSrcRe = mediaSrcTagRe("video");
for (const { html, compSrcPath } of htmlSources) {
const scannable = maskNonScannableRanges(html);
const re = new RegExp(videoSrcRe.source, videoSrcRe.flags);
let match: RegExpExecArray | null;
while ((match = re.exec(scannable)) !== null) {
- const rawSrc = match[1] ?? "";
+ const rawSrc = match[2] ?? "";
// Placeholder check runs on the RAW value: cleanAssetUrl() splits on ?/# and would chop inside a ${...} token.
if (isUnresolvedAssetPlaceholder(rawSrc)) continue;
const src = cleanAssetUrl(rawSrc);
diff --git a/packages/lint/src/project.test.ts b/packages/lint/src/project.test.ts
index dbcae844bd..6e0bcd6ca4 100644
--- a/packages/lint/src/project.test.ts
+++ b/packages/lint/src/project.test.ts
@@ -634,6 +634,25 @@ describe("templating tokens are checked on the raw src, before cleanAssetUrl", (
}
});
+ // `\bsrc\s*=` also matched the tail of `data-var-src="bg"`, and `[^>]*` is greedy,
+ // so a real src earlier in the same tag lost to the variable id: bindings were
+ // reported as a missing file named after the variable.
+ it("reports the real src, not the data-var-src variable id", async () => {
+ const { results } = await lintProject(
+ projectWith(`<img src="assets/logo.png" data-var-src="bg" />`),
+ );
+ const finding = results
+ .flatMap((entry) => entry.result.findings)
+ .find((f) => f.code === "missing_local_asset");
+ expect(finding?.message).toContain("assets/logo.png");
+ expect(finding?.message).not.toContain("bg");
+ });
+
+ it("does not invent a missing asset for a binding on an element whose src resolves", async () => {
+ const c = await codes(projectWith(`<img src="${"${imgUrl}"}" data-var-src="bg" />`));
+ expect(c.has("missing_local_asset")).toBe(false);
+ });
+
it("still flags a genuinely missing local video file", async () => {
const c = await codes(
projectWith(
diff --git a/packages/lint/src/project.ts b/packages/lint/src/project.ts
index a9b2999417..1330b467d1 100644
--- a/packages/lint/src/project.ts
+++ b/packages/lint/src/project.ts
@@ -18,6 +18,7 @@ import { collectLocalVideoCandidates, lintHevcPreviewCodec } from "./hevcPreview
import { lintHyperframeHtml } from "./hyperframeLinter.js";
import type { HyperframeLintFinding, HyperframeLintResult } from "./types.js";
import type { ParsableDocumentLike } from "@hyperframes/parsers/sub-composition-validity";
+import { mediaSrcTagRe } from "./utils";
/** Adapts linkedom's `parseHTML` to the `checkSubCompositionUsability` contract. */
function parseSubCompHtml(html: string): ParsableDocumentLike {
@@ -336,13 +337,13 @@ function lintAudioSrcNotFound(
): HyperframeLintFinding[] {
const findings: HyperframeLintFinding[] = [];
- const audioSrcRe = /<audio\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
+ const audioSrcRe = mediaSrcTagRe("audio");
const missingSrcs: string[] = [];
for (const { html, compSrcPath } of htmlSources) {
let match: RegExpExecArray | null;
while ((match = audioSrcRe.exec(html)) !== null) {
- const src = match[1]!;
+ const src = match[2]!;
if (/^(https?:|data:|blob:)/i.test(src)) continue;
if (isUnresolvedAssetPlaceholder(src)) continue;
const rootRelative = compSrcPath
@@ -377,7 +378,7 @@ function lintMissingLocalAsset(
): HyperframeLintFinding[] {
const findings: HyperframeLintFinding[] = [];
- const localAssetSrcRe = /<(video|img|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
+ const localAssetSrcRe = mediaSrcTagRe("video|img|source");
const missingByTag = new Map<string, Map<string, string>>();
diff --git a/packages/lint/src/rules/composition.test.ts b/packages/lint/src/rules/composition.test.ts
index dbf6eecf7c..8f7cc95119 100644
--- a/packages/lint/src/rules/composition.test.ts
+++ b/packages/lint/src/rules/composition.test.ts
@@ -1059,6 +1059,38 @@ describe("composition rules", () => {
});
});
+ describe("unloadable_media_variable_default", () => {
+ const CODE = "unloadable_media_variable_default";
+ const find = (r: { findings: { code: string }[] }) => r.findings.find((f) => f.code === CODE);
+
+ it("errors on an image variable defaulting to a file:// URL", async () => {
+ const html = `<html data-composition-variables='[{"id":"bg","type":"image","label":"BG","default":"file:///abs/assets/blue.png"}]'><body><img data-composition-id="x" src="assets/red.png" data-var-src="bg"></body></html>`;
+ const finding = find(await lintHyperframeHtml(html));
+ expect(finding).toBeDefined();
+ expect(finding?.severity).toBe("error");
+ expect(finding?.message).toMatch(/authored fallback/);
+ });
+
+ it("errors on a non-image variable that a data-var-src binding consumes as a URL", async () => {
+ const html = `<html data-composition-variables='[{"id":"clip","type":"string","label":"Clip","default":"file:///abs/a.mp4"}]'><body><video data-composition-id="x" src="a.mp4" data-var-src="clip"></video></body></html>`;
+ expect(find(await lintHyperframeHtml(html))).toBeDefined();
+ });
+
+ it("stays quiet for relative, http(s) and data:image defaults", async () => {
+ const html = `<html data-composition-variables='[
+ {"id":"a","type":"image","label":"A","default":"assets/blue.png"},
+ {"id":"b","type":"image","label":"B","default":"https://example.com/b.png"},
+ {"id":"c","type":"image","label":"C","default":"data:image/png;base64,iVBORw0KGgo="}
+ ]'><body><img data-composition-id="x" src="r.png" data-var-src="a"></body></html>`;
+ expect(find(await lintHyperframeHtml(html))).toBeUndefined();
+ });
+
+ it("does not treat an unbound scalar variable as a URL", async () => {
+ const html = `<html data-composition-variables='[{"id":"note","type":"string","label":"Note","default":"mailto:[email protected]"}]'><body><div data-composition-id="x"></div></body></html>`;
+ expect(find(await lintHyperframeHtml(html))).toBeUndefined();
+ });
+ });
+
describe("invalid_parent_traversal_in_asset_path", () => {
const RULE_CODE = "invalid_parent_traversal_in_asset_path";
diff --git a/packages/lint/src/rules/composition.ts b/packages/lint/src/rules/composition.ts
index c2902f4c7e..788483d134 100644
--- a/packages/lint/src/rules/composition.ts
+++ b/packages/lint/src/rules/composition.ts
@@ -8,7 +8,7 @@ import {
truncateSnippet,
WINDOW_TIMELINE_ASSIGN_PATTERN,
} from "../utils";
-import { COMPOSITION_VARIABLE_TYPES } from "@hyperframes/parsers/composition";
+import { COMPOSITION_VARIABLE_TYPES, isSafeMediaUrl } from "@hyperframes/parsers/composition";
import { COMPOSITION_ATTRIBUTES, readClipTiming } from "@hyperframes/parsers/composition-contract";
// Agent guidance thresholds: warning-only nudges for files/tracks that become hard
@@ -782,6 +782,14 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
const findings: HyperframeLintFinding[] = [];
const knownTypes = new Set<string>(COMPOSITION_VARIABLE_TYPES);
+ // Ids whose value the runtime pushes through isSafeMediaUrl: every
+ // data-var-src binding, plus image-typed variables (always consumed as a
+ // URL even when the binding lives in a sub-composition this file can't see).
+ const varSrcIds = new Set<string>();
+ for (const tag of tags) {
+ const bound = readAttr(tag.raw, "data-var-src");
+ if (bound) varSrcIds.add(bound);
+ }
for (let i = 0; i < parsed.length; i += 1) {
const entry = parsed[i];
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -806,6 +814,22 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
message: `data-composition-variables entry [${i}] is missing or has invalid: ${missing.join(", ")}. Type must be one of string, number, color, boolean, enum, font, image.`,
snippet: truncateSnippet(htmlTag.raw),
});
+ continue;
+ }
+ const id = String(e.id);
+ if (
+ (e.type === "image" || varSrcIds.has(id)) &&
+ typeof e.default === "string" &&
+ e.default.length > 0 &&
+ !isSafeMediaUrl(e.default)
+ ) {
+ findings.push({
+ code: "unloadable_media_variable_default",
+ severity: "error",
+ message: `Variable "${id}" defaults to a URL the runtime will refuse to load, so any element bound to it renders its authored fallback src instead and the render still exits 0.`,
+ fixHint: `Media URLs must be relative, http(s), blob:, or a data:image/* URI. Copy the file into the project and reference it relatively (e.g. "assets/bg.png") rather than by absolute path.`,
+ snippet: truncateSnippet(htmlTag.raw),
+ });
}
}
return findings;
diff --git a/packages/lint/src/utils.ts b/packages/lint/src/utils.ts
index 4b665dcbe6..9823d90333 100644
--- a/packages/lint/src/utils.ts
+++ b/packages/lint/src/utils.ts
@@ -469,3 +469,17 @@ export function truncateSnippet(value: string, maxLength = 220): string | undefi
if (normalized.length <= maxLength) return normalized;
return `${normalized.slice(0, maxLength - 3)}...`;
}
+
+/**
+ * Matches a media tag carrying a real `src` attribute, capturing the tag name in
+ * group 1 and the src value in group 2.
+ *
+ * The leading whitespace before `src` is load-bearing: `\bsrc\s*=` also matches
+ * the tail of `data-var-src="bg"` (a hyphen/`s` boundary is a word boundary), and
+ * since `[^>]*` is greedy it wins over a real `src` earlier in the same tag. Every
+ * element using a variable binding was therefore reported as referencing a missing
+ * file named after the variable id.
+ */
+export function mediaSrcTagRe(tagAlternation: string): RegExp {
+ return new RegExp(`<(${tagAlternation})\\b[^>]*\\ssrc\\s*=\\s*["']([^"']+)["'][^>]*>`, "gi");
+}
diff --git a/packages/parsers/src/composition.ts b/packages/parsers/src/composition.ts
index ac078646ba..d0c08d9cab 100644
--- a/packages/parsers/src/composition.ts
+++ b/packages/parsers/src/composition.ts
@@ -14,6 +14,7 @@ export {
parseCompositionVariables,
isCompositionVariable,
isScalarVariableValue,
+ isSafeMediaUrl,
} from "./compositionVariables.js";
export { scanVariableUsage, type VariableUsageScan } from "./variableUsage.js";
export * from "./compositionContract.js";
diff --git a/packages/parsers/src/compositionVariables.ts b/packages/parsers/src/compositionVariables.ts
index 2bf9960ada..66fc7ecd8f 100644
--- a/packages/parsers/src/compositionVariables.ts
+++ b/packages/parsers/src/compositionVariables.ts
@@ -77,3 +77,30 @@ export function parseCompositionVariables(htmlEl: Element): CompositionVariable[
return [];
}
}
+
+/**
+ * Protocol allowlist for a resolved media URL. Relative URLs (no scheme) resolve
+ * against the page origin and are always safe. Absolute URLs are restricted to
+ * http(s)/blob and image data: URIs -- defense-in-depth alongside the runtime's
+ * VAR_SRC_TAGS element guard, blocking `javascript:`, `data:text/html`, `file:`,
+ * etc. even if a future tag slips past it. Control chars are stripped before the
+ * scheme test because browsers ignore them when parsing the URL.
+ *
+ * Lives here rather than in the runtime because the linter has to reach the same
+ * verdict on a declared default statically: a value this rejects is dropped at
+ * bind time and the element's authored fallback renders instead, so a second copy
+ * of the scheme list would let lint and the runtime disagree silently.
+ */
+export function isSafeMediaUrl(url: string): boolean {
+ // Browsers ignore ASCII control chars/whitespace when parsing a URL, so strip
+ // them before reading the scheme (defeats `java\tscript:` style bypasses).
+ // oxlint-disable-next-line no-control-regex -- control chars are the target here
+ const normalized = url.replace(/[\u0000-\u0020]/g, "");
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
+ if (!scheme) return true;
+ const proto = scheme[1]?.toLowerCase();
+ if (!proto) return false;
+ if (proto === "https" || proto === "http" || proto === "blob") return true;
+ if (proto === "data") return /^data:image\//i.test(normalized);
+ return false;
+}