Skip to content

Commit 41edbfb

Browse files
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.
1 parent 5842dd8 commit 41edbfb

9 files changed

Lines changed: 129 additions & 29 deletions

File tree

‎packages/core/src/runtime/applyVariableBindings.ts‎

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@
2828
*/
2929

3030
import { readVariablesForElement } from "./variableScope";
31-
import { isScalarVariableValue as isScalar } from "@hyperframes/parsers/composition";
31+
import {
32+
isScalarVariableValue as isScalar,
33+
isSafeMediaUrl,
34+
} from "@hyperframes/parsers/composition";
3235

3336
// data-var-src only rebinds media `src` on media elements. A user-controlled
3437
// 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 {
4548
return null;
4649
}
4750

48-
/**
49-
* Protocol allowlist for a resolved media URL. Relative URLs (no scheme) resolve
50-
* against the page origin and are always safe. Absolute URLs are restricted to
51-
* http(s)/blob and image data: URIs — defense-in-depth alongside VAR_SRC_TAGS,
52-
* blocking `javascript:`, `data:text/html`, `file:`, etc. even if a future tag
53-
* slips past the element guard. Control chars are stripped before the scheme
54-
* test because browsers ignore them when parsing the URL (`java\tscript:`).
55-
*/
56-
function isSafeMediaUrl(url: string): boolean {
57-
// Browsers ignore ASCII control chars/whitespace when parsing a URL, so strip
58-
// them before reading the scheme (defeats `java\tscript:` style bypasses).
59-
// oxlint-disable-next-line no-control-regex -- control chars are the target here
60-
const normalized = url.replace(/[\u0000-\u0020]/g, "");
61-
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
62-
if (!scheme) return true;
63-
const proto = scheme[1]?.toLowerCase();
64-
if (!proto) return false;
65-
if (proto === "https" || proto === "http" || proto === "blob") return true;
66-
if (proto === "data") return /^data:image\//i.test(normalized);
67-
return false;
68-
}
69-
7051
/**
7152
* Strip characters that could smuggle additional declarations or markup out of
7253
* a var() substitution site. A scalar value folded into `background: var(--x)`

‎packages/lint/src/hevcPreviewLint.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
resolveExistingLocalAsset,
1212
} from "@hyperframes/parsers/asset-resolution";
1313
import type { HyperframeLintFinding } from "./types.js";
14+
import { mediaSrcTagRe } from "./utils";
1415

1516
/** Structurally compatible with `project.ts`'s (unexported) `HtmlSource` —
1617
* duplicated as a shape, not imported, to avoid a circular import between
@@ -82,14 +83,14 @@ export function collectLocalVideoCandidates(
8283
htmlSources: HtmlSourceLike[],
8384
): Map<string, string> {
8485
const candidates = new Map<string, string>();
85-
const videoSrcRe = /<video\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
86+
const videoSrcRe = mediaSrcTagRe("video");
8687

8788
for (const { html, compSrcPath } of htmlSources) {
8889
const scannable = maskNonScannableRanges(html);
8990
const re = new RegExp(videoSrcRe.source, videoSrcRe.flags);
9091
let match: RegExpExecArray | null;
9192
while ((match = re.exec(scannable)) !== null) {
92-
const rawSrc = match[1] ?? "";
93+
const rawSrc = match[2] ?? "";
9394
// Placeholder check runs on the RAW value: cleanAssetUrl() splits on ?/# and would chop inside a ${...} token.
9495
if (isUnresolvedAssetPlaceholder(rawSrc)) continue;
9596
const src = cleanAssetUrl(rawSrc);

‎packages/lint/src/project.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,25 @@ describe("templating tokens are checked on the raw src, before cleanAssetUrl", (
634634
}
635635
});
636636

637+
// `\bsrc\s*=` also matched the tail of `data-var-src="bg"`, and `[^>]*` is greedy,
638+
// so a real src earlier in the same tag lost to the variable id: bindings were
639+
// reported as a missing file named after the variable.
640+
it("reports the real src, not the data-var-src variable id", async () => {
641+
const { results } = await lintProject(
642+
projectWith(`<img src="assets/logo.png" data-var-src="bg" />`),
643+
);
644+
const finding = results
645+
.flatMap((entry) => entry.result.findings)
646+
.find((f) => f.code === "missing_local_asset");
647+
expect(finding?.message).toContain("assets/logo.png");
648+
expect(finding?.message).not.toContain("bg");
649+
});
650+
651+
it("does not invent a missing asset for a binding on an element whose src resolves", async () => {
652+
const c = await codes(projectWith(`<img src="${"${imgUrl}"}" data-var-src="bg" />`));
653+
expect(c.has("missing_local_asset")).toBe(false);
654+
});
655+
637656
it("still flags a genuinely missing local video file", async () => {
638657
const c = await codes(
639658
projectWith(

‎packages/lint/src/project.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { collectLocalVideoCandidates, lintHevcPreviewCodec } from "./hevcPreview
1818
import { lintHyperframeHtml } from "./hyperframeLinter.js";
1919
import type { HyperframeLintFinding, HyperframeLintResult } from "./types.js";
2020
import type { ParsableDocumentLike } from "@hyperframes/parsers/sub-composition-validity";
21+
import { mediaSrcTagRe } from "./utils";
2122

2223
/** Adapts linkedom's `parseHTML` to the `checkSubCompositionUsability` contract. */
2324
function parseSubCompHtml(html: string): ParsableDocumentLike {
@@ -336,13 +337,13 @@ function lintAudioSrcNotFound(
336337
): HyperframeLintFinding[] {
337338
const findings: HyperframeLintFinding[] = [];
338339

339-
const audioSrcRe = /<audio\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
340+
const audioSrcRe = mediaSrcTagRe("audio");
340341

341342
const missingSrcs: string[] = [];
342343
for (const { html, compSrcPath } of htmlSources) {
343344
let match: RegExpExecArray | null;
344345
while ((match = audioSrcRe.exec(html)) !== null) {
345-
const src = match[1]!;
346+
const src = match[2]!;
346347
if (/^(https?:|data:|blob:)/i.test(src)) continue;
347348
if (isUnresolvedAssetPlaceholder(src)) continue;
348349
const rootRelative = compSrcPath
@@ -377,7 +378,7 @@ function lintMissingLocalAsset(
377378
): HyperframeLintFinding[] {
378379
const findings: HyperframeLintFinding[] = [];
379380

380-
const localAssetSrcRe = /<(video|img|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi;
381+
const localAssetSrcRe = mediaSrcTagRe("video|img|source");
381382

382383
const missingByTag = new Map<string, Map<string, string>>();
383384

‎packages/lint/src/rules/composition.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,6 +1059,38 @@ describe("composition rules", () => {
10591059
});
10601060
});
10611061

1062+
describe("unloadable_media_variable_default", () => {
1063+
const CODE = "unloadable_media_variable_default";
1064+
const find = (r: { findings: { code: string }[] }) => r.findings.find((f) => f.code === CODE);
1065+
1066+
it("errors on an image variable defaulting to a file:// URL", async () => {
1067+
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>`;
1068+
const finding = find(await lintHyperframeHtml(html));
1069+
expect(finding).toBeDefined();
1070+
expect(finding?.severity).toBe("error");
1071+
expect(finding?.message).toMatch(/authored fallback/);
1072+
});
1073+
1074+
it("errors on a non-image variable that a data-var-src binding consumes as a URL", async () => {
1075+
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>`;
1076+
expect(find(await lintHyperframeHtml(html))).toBeDefined();
1077+
});
1078+
1079+
it("stays quiet for relative, http(s) and data:image defaults", async () => {
1080+
const html = `<html data-composition-variables='[
1081+
{"id":"a","type":"image","label":"A","default":"assets/blue.png"},
1082+
{"id":"b","type":"image","label":"B","default":"https://example.com/b.png"},
1083+
{"id":"c","type":"image","label":"C","default":"data:image/png;base64,iVBORw0KGgo="}
1084+
]'><body><img data-composition-id="x" src="r.png" data-var-src="a"></body></html>`;
1085+
expect(find(await lintHyperframeHtml(html))).toBeUndefined();
1086+
});
1087+
1088+
it("does not treat an unbound scalar variable as a URL", async () => {
1089+
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>`;
1090+
expect(find(await lintHyperframeHtml(html))).toBeUndefined();
1091+
});
1092+
});
1093+
10621094
describe("invalid_parent_traversal_in_asset_path", () => {
10631095
const RULE_CODE = "invalid_parent_traversal_in_asset_path";
10641096

‎packages/lint/src/rules/composition.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
truncateSnippet,
99
WINDOW_TIMELINE_ASSIGN_PATTERN,
1010
} from "../utils";
11-
import { COMPOSITION_VARIABLE_TYPES } from "@hyperframes/parsers/composition";
11+
import { COMPOSITION_VARIABLE_TYPES, isSafeMediaUrl } from "@hyperframes/parsers/composition";
1212
import { COMPOSITION_ATTRIBUTES, readClipTiming } from "@hyperframes/parsers/composition-contract";
1313

1414
// Agent guidance thresholds: warning-only nudges for files/tracks that become hard
@@ -782,6 +782,14 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
782782

783783
const findings: HyperframeLintFinding[] = [];
784784
const knownTypes = new Set<string>(COMPOSITION_VARIABLE_TYPES);
785+
// Ids whose value the runtime pushes through isSafeMediaUrl: every
786+
// data-var-src binding, plus image-typed variables (always consumed as a
787+
// URL even when the binding lives in a sub-composition this file can't see).
788+
const varSrcIds = new Set<string>();
789+
for (const tag of tags) {
790+
const bound = readAttr(tag.raw, "data-var-src");
791+
if (bound) varSrcIds.add(bound);
792+
}
785793
for (let i = 0; i < parsed.length; i += 1) {
786794
const entry = parsed[i];
787795
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
@@ -806,6 +814,22 @@ export const compositionRules: Array<(ctx: LintContext) => HyperframeLintFinding
806814
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.`,
807815
snippet: truncateSnippet(htmlTag.raw),
808816
});
817+
continue;
818+
}
819+
const id = String(e.id);
820+
if (
821+
(e.type === "image" || varSrcIds.has(id)) &&
822+
typeof e.default === "string" &&
823+
e.default.length > 0 &&
824+
!isSafeMediaUrl(e.default)
825+
) {
826+
findings.push({
827+
code: "unloadable_media_variable_default",
828+
severity: "error",
829+
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.`,
830+
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.`,
831+
snippet: truncateSnippet(htmlTag.raw),
832+
});
809833
}
810834
}
811835
return findings;

‎packages/lint/src/utils.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,3 +469,17 @@ export function truncateSnippet(value: string, maxLength = 220): string | undefi
469469
if (normalized.length <= maxLength) return normalized;
470470
return `${normalized.slice(0, maxLength - 3)}...`;
471471
}
472+
473+
/**
474+
* Matches a media tag carrying a real `src` attribute, capturing the tag name in
475+
* group 1 and the src value in group 2.
476+
*
477+
* The leading whitespace before `src` is load-bearing: `\bsrc\s*=` also matches
478+
* the tail of `data-var-src="bg"` (a hyphen/`s` boundary is a word boundary), and
479+
* since `[^>]*` is greedy it wins over a real `src` earlier in the same tag. Every
480+
* element using a variable binding was therefore reported as referencing a missing
481+
* file named after the variable id.
482+
*/
483+
export function mediaSrcTagRe(tagAlternation: string): RegExp {
484+
return new RegExp(`<(${tagAlternation})\\b[^>]*\\ssrc\\s*=\\s*["']([^"']+)["'][^>]*>`, "gi");
485+
}

‎packages/parsers/src/composition.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export {
1414
parseCompositionVariables,
1515
isCompositionVariable,
1616
isScalarVariableValue,
17+
isSafeMediaUrl,
1718
} from "./compositionVariables.js";
1819
export { scanVariableUsage, type VariableUsageScan } from "./variableUsage.js";
1920
export * from "./compositionContract.js";

‎packages/parsers/src/compositionVariables.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,30 @@ export function parseCompositionVariables(htmlEl: Element): CompositionVariable[
7777
return [];
7878
}
7979
}
80+
81+
/**
82+
* Protocol allowlist for a resolved media URL. Relative URLs (no scheme) resolve
83+
* against the page origin and are always safe. Absolute URLs are restricted to
84+
* http(s)/blob and image data: URIs -- defense-in-depth alongside the runtime's
85+
* VAR_SRC_TAGS element guard, blocking `javascript:`, `data:text/html`, `file:`,
86+
* etc. even if a future tag slips past it. Control chars are stripped before the
87+
* scheme test because browsers ignore them when parsing the URL.
88+
*
89+
* Lives here rather than in the runtime because the linter has to reach the same
90+
* verdict on a declared default statically: a value this rejects is dropped at
91+
* bind time and the element's authored fallback renders instead, so a second copy
92+
* of the scheme list would let lint and the runtime disagree silently.
93+
*/
94+
export function isSafeMediaUrl(url: string): boolean {
95+
// Browsers ignore ASCII control chars/whitespace when parsing a URL, so strip
96+
// them before reading the scheme (defeats `java\tscript:` style bypasses).
97+
// oxlint-disable-next-line no-control-regex -- control chars are the target here
98+
const normalized = url.replace(/[\u0000-\u0020]/g, "");
99+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(normalized);
100+
if (!scheme) return true;
101+
const proto = scheme[1]?.toLowerCase();
102+
if (!proto) return false;
103+
if (proto === "https" || proto === "http" || proto === "blob") return true;
104+
if (proto === "data") return /^data:image\//i.test(normalized);
105+
return false;
106+
}

0 commit comments

Comments
 (0)