From 24508ce2da7182b2c7b5ca368062c18fb85c489b Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Tue, 10 Nov 2026 20:01:29 +0000 Subject: [PATCH] fix: harden docs snippets, SVG sanitizer, lint regexes, GSAP writers and registry pins (#7512) * fix(docs): escape catalog preview values and the install command's --vars argument The catalog preview embeds variable values as JSON that cannot close a script element or attribute, accepts value messages only from the page that embeds it, and reads only declared ids with primitive values from the link. The install command shell-quotes its --vars JSON and keeps only variable-id keys with primitive values. Co-Authored-By: Claude Opus 5.5 * fix(core): fold CSS line endings before decoding escapes in the SVG sanitizer A browser folds CR LF, CR and form feed into one newline before it reads CSS escapes, so the whitespace after a hex escape can be a CR LF pair. The sanitizer now does the same, so an escaped function name split by a line ending is checked under its real name. The media-use bundle is regenerated from the source. Co-Authored-By: Claude Opus 5.5 * fix(lint): match template ids and CSS rules in linear time A getElementById template literal is matched against document ids with an in-order indexOf scan instead of a regex of joined wildcards, so the time no longer grows with the number of placeholders. The CSS rule scanners only start a match at the beginning of a brace-free run, which finds the same rules without rescanning long brace-less text. Lint results on every HTML file in the repository are unchanged. Co-Authored-By: Claude Opus 5.5 * fix(parsers): keep GSAP writer output inside its script element String literals and quoted keys the GSAP writers emit now encode a script closer or comment opener as \u003c, so a value can no longer end the inline script that holds the timeline. Strings without those sequences are written exactly as before. The writers also refuse a tween method outside set, to, from and fromTo, and a motion path whose coordinates or curviness are not numbers, since both are emitted as code. Co-Authored-By: Claude Opus 5.5 * fix(scripts): confine registry asset hosting to files inside the item The asset hosting script now refuses a manifest path that leaves the item directory or reaches its file through a symlink, before anything is read, staged, uploaded or removed. A repository test fails when the registry tracks a symlink or a manifest path that leaves its item. Co-Authored-By: Claude Opus 5.5 * fix(registry): pin the map blocks' d3 and atlas files to exact versions The five map blocks load d3 7.9.2, the build the d3@7 range serves today, with a subresource integrity hash, and fetch us-atlas 3.0.1 and world-atlas 2.0.2, the files their ranges serve today. The bytes are unchanged, so the blocks render the same. A repository test fails when a registry item names an npm CDN package by range, tag or no version. Co-Authored-By: Claude Opus 5.5 * fix(registry): pin map blocks to d3 7.9.0 7.9.0 has been the stable release since 2024; 7.9.1 and 7.9.2 were published days ago. Pin the long-standing version, with its subresource integrity hash. Co-Authored-By: Claude Opus 5.5 * fix(registry): keep the map block PR source-only and formatted Restore the generated catalog pages and payloads, which the catalog publish job regenerates from the item sources. Name the us-atlas URL in us-map-flow so the call fits on one line and formatting is unchanged. Co-Authored-By: Claude Opus 5.5 * refactor(scripts): check registry asset containment with one prefix test Co-Authored-By: Claude Opus 5.5 * fix(lint): scan simple CSS rules in linear time The two CSS-rule scans in the gsap rules took a body that could cross '{', so a closed style of many '{' with no '}' rescanned to its end from every brace. A scanner now returns the same selector and body pairs and remembers the next '}', so each scan is linear. Findings are identical on every tracked HTML file. Co-Authored-By: Claude Opus 5.5 * test(core): label the form-feed sanitizer case as a guard Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- docs/snippets/catalog-detail.jsx | 38 +++++-- docs/snippets/install-command.jsx | 28 ++++-- package.json | 2 +- .../cli/src/media-use/lib/svg-sanitize.mjs | 3 +- packages/core/src/figma/sanitizeSvg.test.ts | 15 +++ packages/core/src/figma/sanitizeSvg.ts | 9 +- packages/lint/src/rules/composition.ts | 8 +- packages/lint/src/rules/gsap.test.ts | 61 ++++++++++++ packages/lint/src/rules/gsap.ts | 51 +++++++++- packages/parsers/src/gsapParser.ts | 48 ++++----- packages/parsers/src/gsapSerialize.ts | 41 +++++++- .../src/gsapWriter.scriptContext.test.ts | 61 ++++++++++++ packages/parsers/src/gsapWriterAcorn.ts | 47 ++++----- registry/blocks/spain-map/spain-map.html | 6 +- .../blocks/us-map-bubble/us-map-bubble.html | 8 +- registry/blocks/us-map-flow/us-map-flow.html | 9 +- registry/blocks/us-map/us-map.html | 8 +- registry/blocks/world-map/world-map.html | 8 +- scripts/catalog-detail.test.ts | 99 ++++++++++++++++++- scripts/host-registry-assets.test.ts | 64 +++++++++++- scripts/host-registry-assets.ts | 20 +++- scripts/registry-cdn-pins.test.ts | 42 ++++++++ 22 files changed, 583 insertions(+), 93 deletions(-) create mode 100644 packages/parsers/src/gsapWriter.scriptContext.test.ts create mode 100644 scripts/registry-cdn-pins.test.ts diff --git a/docs/snippets/catalog-detail.jsx b/docs/snippets/catalog-detail.jsx index 02e476047c..87869d8f5f 100644 --- a/docs/snippets/catalog-detail.jsx +++ b/docs/snippets/catalog-detail.jsx @@ -1710,6 +1710,27 @@ export const CatalogDetail = ({ */ const urlKey = `vars-${compositionId}`; + // >>> preview values + /** JSON that is also inert inside an inline ` +`; + const result = await lintHyperframeHtml(html); + const finding = result.findings.find((f) => f.code === "svg_drawon_css_dasharray_conflict"); + expect(finding).toBeDefined(); + }); + + it("matches a many-placeholder template id against a long near-miss id in linear time", async () => { + const template = Array.from({ length: 40 }, () => "${x}").join("a") + "b"; + const html = ` + +
+ +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(2000); + }); + + it("scans a long style block with no braces in linear time", async () => { + const html = ` +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(3000); + }); + + it("scans a closed style block of many unclosed rules in linear time", async () => { + const html = ` +
+ +`; + const started = performance.now(); + await lintHyperframeHtml(html); + expect(performance.now() - started).toBeLessThan(2000); + }); + // ── gsap_timeline_set_initial_hide ───────────────────────────────────────── it("gsap_timeline_set_initial_hide: warns on tl.set hidden state at position 0", async () => { diff --git a/packages/lint/src/rules/gsap.ts b/packages/lint/src/rules/gsap.ts index 5886ddd4e0..adef478304 100644 --- a/packages/lint/src/rules/gsap.ts +++ b/packages/lint/src/rules/gsap.ts @@ -420,10 +420,35 @@ function styleLooksFullFrameOverlay(style: string): boolean { return coversFrame && styleHasOpaqueBackground(style); } +// The `[selectorList, body]` pairs `/(? { + const out: Array<[string, string]> = []; + let start = 0; + let close = 0; + while (start < css.length) { + let brace = start; + while (brace < css.length && css[brace] !== "{" && css[brace] !== "}") brace++; + if (brace === css.length) break; + if (css[brace] === "{" && brace > start) { + if (close !== -1 && close <= brace) close = css.indexOf("}", brace + 1); + if (close === -1) break; + if (close > brace + 1) { + out.push([css.slice(start, brace), css.slice(brace + 1, close)]); + start = close + 1; + continue; + } + } + start = brace + 1; + } + return out; +} + function collectSimpleStyleRules(styles: LintContext["styles"]): Map { const rules = new Map(); for (const style of styles) { - for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) { + for (const [selectorList, body] of styleRuleBodies(style.content)) { if (!selectorList || !body) continue; for (const selector of selectorList.split(",")) { const token = selector.trim(); @@ -897,6 +922,25 @@ function expressionReachesMeasurement(expression: string, measuring: Set return false; } +const LINE_TERMINATOR = /[\n\r\u2028\u2029]/; + +// Whether `id` is `parts` in order with a gap of non-line-terminators between each pair, the +// language of `^a.*b.*c$`, checked with leftmost indexOf so time stays linear in the id. +function matchesTemplateParts(id: string, parts: string[]): boolean { + const first = parts[0] ?? ""; + const last = parts[parts.length - 1] ?? ""; + if (parts.length === 1) return id === first; + if (!id.startsWith(first)) return false; + let at = first.length; + for (const part of parts.slice(1, -1)) { + const found = id.indexOf(part, at); + if (found === -1 || LINE_TERMINATOR.test(id.slice(at, found))) return false; + at = found + part.length; + } + const end = id.length - last.length; + return end >= at && id.endsWith(last) && !LINE_TERMINATOR.test(id.slice(at, end)); +} + // Resolve script-level element variables to the simple selector tokens they can // denote: literal getElementById/querySelector lookups, template-literal ids // matched against the document's actual ids, and script-assigned class names @@ -923,9 +967,8 @@ function resolveScriptElementTokens(source: string, tags: OpenTag[]): Map part === "")) continue; - const idPattern = new RegExp(`^${staticParts.map(escapeRegExp).join(".*")}$`); for (const id of documentIds) { - if (idPattern.test(id)) add(match[1] ?? "", `#${id}`); + if (matchesTemplateParts(id, staticParts)) add(match[1] ?? "", `#${id}`); } } for (const match of source.matchAll( @@ -2332,7 +2375,7 @@ export const gsapRules: LintRule[] = [ const multiDashTokens = new Set(); for (const style of styles) { - for (const [, selectorList, body] of style.content.matchAll(/([^{}]+)\{([^}]+)\}/g)) { + for (const [selectorList, body] of styleRuleBodies(style.content)) { if (!selectorList || !body) continue; const value = readStyleProperty(body, "stroke-dasharray"); if (!value || !isMultiComponentDasharray(value)) continue; diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.ts index a85689beaf..464bbffb80 100644 --- a/packages/parsers/src/gsapParser.ts +++ b/packages/parsers/src/gsapParser.ts @@ -25,6 +25,9 @@ import { distributeArrayKeyframes, authorsKeyframes, plainPercentKey, + scriptJson, + tweenMethodCode, + assertMotionPathNumbers, } from "./gsapSerialize"; export type { @@ -1479,7 +1482,7 @@ function insertAfterAnchor(parsed: ParsedGsapAst, newStatement: AstNode): void { /** Build the source for a single `tl.method(selector, vars, position)` call. */ function buildTweenStatementCode(timelineVar: string, anim: Omit): string { - const selector = JSON.stringify(anim.targetSelector); + const selector = scriptJson(anim.targetSelector); const props: Record = { ...anim.properties }; if (anim.method !== "set" && anim.duration !== undefined) props.duration = anim.duration; if (anim.ease) props.ease = anim.ease; @@ -1521,7 +1524,7 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit `${k}: ${typeof v === "string" ? JSON.stringify(v) : v}`) + .map(([k, v]) => `${safeKey(k)}: ${typeof v === "string" ? scriptJson(v) : v}`) .join(", "); - const code = `${tlVar}.set(${JSON.stringify(selector)}, { ${props} }, ${position});`; + const code = `${tlVar}.set(${scriptJson(selector)}, { ${props} }, ${position});`; const newStatement = parseScript(code).program.body[0]; const anchor = findTimelineDeclarationPath(parsed.ast, tlVar); if (anchor) { @@ -2071,11 +2074,11 @@ function buildKeyframeObjectCode( ): string { const entries = mergePercentageKeyframes(keyframes).map((kf) => { const props = keyframePropsToCode(kf); - if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`); + if (kf.ease) props.push(`ease: ${scriptJson(kf.ease)}`); if (kf.auto) props.push(`_auto: 1`); - return `${JSON.stringify(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`; + return `${scriptJson(plainPercentKey(kf.percentage))}: { ${props.join(", ")} }`; }); - if (options?.easeEach) entries.push(`easeEach: ${JSON.stringify(options.easeEach)}`); + if (options?.easeEach) entries.push(`easeEach: ${scriptJson(options.easeEach)}`); return `{ ${entries.join(", ")} }`; } @@ -2124,7 +2127,7 @@ function buildKeyframeValueNode( const entries = Object.entries(properties) .filter(([k]) => k !== "ease") .map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); - if (effectiveEase) entries.push(`ease: ${JSON.stringify(effectiveEase)}`); + if (effectiveEase) entries.push(`ease: ${scriptJson(effectiveEase)}`); return parseExpr(`{ ${entries.join(", ")} }`); } @@ -2134,7 +2137,7 @@ function setObjectExpressionEase(node: AstNode, ease: string): boolean { const easeIdx = props.findIndex( (property: AstNode) => isObjectProperty(property) && propKeyName(property) === "ease", ); - const easeNode = parseExpr(`({ ease: ${JSON.stringify(ease)} })`).properties[0]; + const easeNode = parseExpr(`({ ease: ${scriptJson(ease)} })`).properties[0]; if (easeIdx >= 0) props[easeIdx] = easeNode; else props.push(easeNode); return true; @@ -2235,7 +2238,7 @@ function convertArrayKeyframesToObjectNode(varsArg: AstNode, scope: ScopeBinding el.properties = (el.properties ?? []).filter( (property: AstNode) => !isObjectProperty(property) || propKeyName(property) !== "duration", ); - return `${JSON.stringify(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`; + return `${scriptJson(plainPercentKey(timing.percentages[i]!))}: ${recast.print(el).code}`; }); prop.value = parseExpr(`{ ${entries.join(", ")}, easeEach: "none" }`); return prop.value; @@ -2327,7 +2330,7 @@ export function addKeyframeToScript( } } else { // Build the new property node with a quoted percentage key - const newProp = parseExpr(`{ ${JSON.stringify(pctKey)}: {} }`).properties[0]; + const newProp = parseExpr(`{ ${scriptJson(pctKey)}: {} }`).properties[0]; newProp.value = newValueNode; // Insert in sorted order by percentage @@ -2513,7 +2516,7 @@ export function moveKeyframeInScript( const kept = (kfNode.properties ?? []).filter((p: AstNode) => !pctProps.has(p)); kfNode.properties = [ ...entries.map((e) => { - const p = parseExpr(`{ ${JSON.stringify(plainPercentKey(e.pct))}: {} }`).properties[0]; + const p = parseExpr(`{ ${scriptJson(plainPercentKey(e.pct))}: {} }`).properties[0]; p.value = e.value; return p; }), @@ -2555,7 +2558,7 @@ export function resizeKeyframedTweenInScript( seen.add(match.prop); // Replace only the key node; the value node (incl. _auto + per-keyframe ease) // stays verbatim. easeEach is a sibling non-percentage prop, left untouched. - match.prop.key = parseExpr(`{ ${JSON.stringify(plainPercentKey(to))}: 0 }`).properties[0].key; + match.prop.key = parseExpr(`{ ${scriptJson(plainPercentKey(to))}: 0 }`).properties[0].key; } applyUpdatesToCall(loc.target.call, { @@ -2672,7 +2675,7 @@ export function updateKeyframeInScript( else props.push(node); }; for (const [k, v] of Object.entries(properties)) upsert(k, valueToCode(v)); - if (ease !== undefined) upsert("ease", JSON.stringify(ease)); + if (ease !== undefined) upsert("ease", scriptJson(ease)); return recast.print(loc.parsed.ast).code; } match.prop.value = buildKeyframeValueNode(properties, ease); @@ -2701,7 +2704,7 @@ function insertKeyframesProp( ): void { const fromEntries = Object.entries(fromProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); const toEntries = Object.entries(toProps).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`); - const easeEntry = easeEach ? `, easeEach: ${JSON.stringify(easeEach)}` : ""; + const easeEntry = easeEach ? `, easeEach: ${scriptJson(easeEach)}` : ""; const kfCode = `{ "0%": { ${fromEntries.join(", ")} }, "100%": { ${toEntries.join(", ")} }${easeEntry} }`; const kfProp = parseExpr(`{ keyframes: {} }`).properties[0]; kfProp.value = parseExpr(kfCode); @@ -2853,7 +2856,7 @@ export function materializeKeyframesInScript( // Replace dynamic selector with resolved static string if (resolvedSelector && loc.target.call.node.arguments[0]) { - loc.target.call.node.arguments[0] = parseExpr(JSON.stringify(resolvedSelector)); + loc.target.call.node.arguments[0] = parseExpr(scriptJson(resolvedSelector)); } const kfObjCode = buildKeyframeObjectCode(sortedKeyframes(keyframes), { easeEach }); @@ -2898,6 +2901,7 @@ function buildMotionPathObjectCode(config: { segments: ArcPathSegment[]; autoRotate: boolean | number; }): string { + assertMotionPathNumbers(config); const { waypoints, segments, autoRotate } = config; const hasExplicitControlPoints = segments.some((s) => s.cp1 && s.cp2); // The simple `path` array supports only one scalar curviness for the whole @@ -3230,11 +3234,11 @@ export function addMotionPathToScript( segments: [{ curviness: 1 }], autoRotate: false, }); - const selector = JSON.stringify(targetSelector); + const selector = scriptJson(targetSelector); const varEntries = [ `motionPath: ${motionPathCode}`, `duration: ${valueToCode(duration)}`, - `ease: ${JSON.stringify(ease)}`, + `ease: ${scriptJson(ease)}`, ]; const stmtCode = `${parsed.timelineVar}.to(${selector}, { ${varEntries.join(", ")} }, ${valueToCode(position)});`; const newStatement = parseScript(stmtCode).program.body[0]; @@ -3432,7 +3436,7 @@ export function unrollDynamicAnimations( typeof position === "number" ? String(position) : typeof position === "string" - ? JSON.stringify(position) + ? scriptJson(position) : "0"; // Find the enclosing loop (for/forEach) by walking up the AST path @@ -3467,7 +3471,7 @@ export function unrollDynamicAnimations( easeEach: el.easeEach, }); calls.push( - `${loc.parsed.timelineVar}.to(${JSON.stringify(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${JSON.stringify(ease)} }, ${posCode});`, + `${loc.parsed.timelineVar}.to(${scriptJson(el.selector)}, { keyframes: ${kfCode}, duration: ${duration}, ease: ${scriptJson(ease)} }, ${posCode});`, ); } diff --git a/packages/parsers/src/gsapSerialize.ts b/packages/parsers/src/gsapSerialize.ts index 85a3fda390..3cf19a8838 100644 --- a/packages/parsers/src/gsapSerialize.ts +++ b/packages/parsers/src/gsapSerialize.ts @@ -274,7 +274,7 @@ export function serializeGsapAnimations( }); // fallow-ignore-next-line complexity const lines = sorted.map((anim) => { - const selector = JSON.stringify(anim.targetSelector); + const selector = scriptJson(anim.targetSelector); const props: Record = { ...anim.properties }; if (anim.duration !== undefined) props.duration = anim.duration; if (anim.ease) props.ease = anim.ease; @@ -288,7 +288,7 @@ export function serializeGsapAnimations( propsStr = propsStr.slice(0, -2) + `, ${extrasStr} }`; } } - const posStr = JSON.stringify(anim.position); + const posStr = scriptJson(anim.position); switch (anim.method) { case "set": // A global set is a base `gsap.set` — off the timeline, no position arg. @@ -338,11 +338,25 @@ ${lines.join("\n")}${mediaSync}${postamble} `; } +/** `JSON.stringify` whose output cannot end, or open a comment in, the inline script it lands in. */ +export function scriptJson(value: unknown): string { + return String(JSON.stringify(value)).replace(/<(\/script|!--)/gi, "\\u003c$1"); +} + +const TWEEN_METHODS: ReadonlySet = new Set(["set", "to", "from", "fromTo"]); + +/** The method name, checked against the four tween methods because it is emitted as code. */ +export function tweenMethodCode(method: string): GsapMethod { + if (!TWEEN_METHODS.has(method)) + throw new TypeError(`Unsupported tween method: ${scriptJson(method)}`); + return method as GsapMethod; +} + export function serializeValue(value: unknown): string { if (typeof value === "string" && value.startsWith("__raw:")) { return value.slice(6); } - if (typeof value === "string") return JSON.stringify(value); + if (typeof value === "string") return scriptJson(value); return String(value); } @@ -353,7 +367,7 @@ export function plainPercentKey(percentage: number): string { } export function safeJsKey(key: string): string { - return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key); + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : scriptJson(key); } function serializeObject(obj: Record): string { @@ -603,6 +617,24 @@ export function resolveConversionProps( // ── Arc path serialization helpers (shared by recast + acorn writers) ───────── +/** Rejects a motion path whose coordinates or curviness are not numbers, since they are emitted as code. */ +export function assertMotionPathNumbers(config: { + waypoints: Array<{ x: number; y: number }>; + segments: ArcPathSegment[]; +}): void { + const points = [ + ...config.waypoints, + ...config.segments.flatMap((s) => [s.cp1, s.cp2].filter((p) => p !== undefined)), + ]; + const values = [ + ...points.flatMap((p): unknown[] => [p.x, p.y]), + ...config.segments.map((s): unknown => s.curviness ?? 1), + ]; + if (values.some((v) => typeof v !== "number")) { + throw new TypeError("Motion path coordinates and curviness must be numbers"); + } +} + function numericXY(props: Record): { x: number; y: number } | null { const vx = props.x; const vy = props.y; @@ -671,6 +703,7 @@ export function buildMotionPathObjectCode(config: { segments: ArcPathSegment[]; autoRotate: boolean | number; }): string { + assertMotionPathNumbers(config); const { waypoints, segments, autoRotate } = config; const arSuffix = autoRotateSuffix(autoRotate); // GSAP's simple `path` array supports only ONE scalar `curviness` for the whole diff --git a/packages/parsers/src/gsapWriter.scriptContext.test.ts b/packages/parsers/src/gsapWriter.scriptContext.test.ts new file mode 100644 index 0000000000..c2fdb29c67 --- /dev/null +++ b/packages/parsers/src/gsapWriter.scriptContext.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import * as acornWriter from "./gsapWriterAcorn.js"; +import * as recastWriter from "./gsapParser.js"; +import { parseGsapScript } from "./gsapParser.js"; +import type { GsapAnimation } from "./gsapSerialize.js"; + +const SCRIPT = `var tl = gsap.timeline({ paused: true }); +tl.to("#box", { opacity: 1, duration: 1 }, 0);`; +const CLOSER = "