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

A data-var-src value the runtime refuses to load is dropped at bind time and
the element's authored fallback src renders instead, so the video ships the
wrong media and the render still exits 0. lint said nothing, because the
scheme allowlist only existed inside the runtime.

Move that predicate into @hyperframes/parsers, where both the runtime and the
linter can reach it, and error at lint time on any declared default it
rejects. The value provably cannot load, so there is no false positive.

While reproducing that, lint turned out to report an unrelated missing file:
`\bsrc\s*=` also matches the tail of `data-var-src="bg"` (hyphen to `s` is a
word boundary), and `[^>]*` is greedy, so the variable id beat the real src
earlier in the same tag. Every binding was reported as a missing asset named
after the variable, and `<audio data-var-src>` was told the render would be
silent. All three copies of that regex now share one helper that requires
whitespace before the attribute.
This commit is contained in:
Miguel Ángel
2026-08-21 19:20:19 -04:00
committed by GitHub
parent 5842dd8df4
commit 41edbfb2ce
9 changed files with 129 additions and 29 deletions
@@ -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)`
+3 -2
View File
@@ -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);
+19
View File
@@ -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(
+4 -3
View File
@@ -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>>();
@@ -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:hi@example.com"}]'><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";
+25 -1
View File
@@ -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;
+14
View File
@@ -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");
}
+1
View File
@@ -14,6 +14,7 @@ export {
parseCompositionVariables,
isCompositionVariable,
isScalarVariableValue,
isSafeMediaUrl,
} from "./compositionVariables.js";
export { scanVariableUsage, type VariableUsageScan } from "./variableUsage.js";
export * from "./compositionContract.js";
@@ -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;
}