diff --git a/packages/core/src/gsapCdn.ts b/packages/core/src/gsapCdn.ts index 1091a94734..cd26c30a8e 100644 --- a/packages/core/src/gsapCdn.ts +++ b/packages/core/src/gsapCdn.ts @@ -1,6 +1,10 @@ export const GSAP_CDN_VERSION = "3.15.0"; const GSAP_CDN_BASE_URL = "https://cdn.jsdelivr.net/npm"; export const GSAP_BASE_URL_META = "hyperframes-gsap-base-url"; +export const GSAP_PLUGIN_LOAD_ATTR = "data-hf-gsap-plugin"; +export const NO_PATH_TWEEN_META = "hf-no-path-tween"; + +export const namesMotionPath = (script: string) => /motionPath["']?\s*[:{]/.test(script); function isLoopbackHost(hostname: string): boolean { return hostname === "localhost" || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname); diff --git a/packages/core/src/runtime/editing/softReload.ts b/packages/core/src/runtime/editing/softReload.ts index b297a9504c..f4d7947b1b 100644 --- a/packages/core/src/runtime/editing/softReload.ts +++ b/packages/core/src/runtime/editing/softReload.ts @@ -1,7 +1,13 @@ // A GSAP script edit re-runs the edited composition's script in the live preview, without a reload. // Studio runs it on a frame it can reach; a sealed frame runs it on itself through the editing port, // with the script Studio saved and the authored styles Studio read from that file. -import { GSAP_BASE_URL_META, motionPathPluginUrl } from "../../gsapCdn"; +import { + GSAP_BASE_URL_META, + GSAP_PLUGIN_LOAD_ATTR, + NO_PATH_TWEEN_META, + motionPathPluginUrl, + namesMotionPath, +} from "../../gsapCdn"; import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "../../colorGrading"; import { escapeCssString } from "../editingElement"; import { applyAuthoredTiming } from "../../studioPreviewMark"; @@ -407,6 +413,7 @@ function whenMotionPathLoaded( }; const pluginScript = doc.createElement("script"); pluginScript.src = previewMotionPathUrl(doc, win.gsap?.version); + pluginScript.setAttribute(GSAP_PLUGIN_LOAD_ATTR, ""); pluginScript.onload = () => settle(Boolean(win.MotionPathPlugin)); // Running the script without the plugin would leave a motionPath tween that cannot play. pluginScript.onerror = () => settle(false); @@ -455,12 +462,13 @@ export function swapWaiting(win: SoftReloadWindow = window as SoftReloadWindow): return (win.__hfSwapsWaiting ?? 0) > 0; } -/** Loads and registers MotionPathPlugin ahead of the first re-run that needs it, as Studio does same-origin. */ +/** Loads and registers MotionPathPlugin ahead of a re-run that needs it, unless the page is marked path-free. */ export function preloadMotionPath( win: SoftReloadWindow = window as SoftReloadWindow, doc: Document = document, ): void { if (win.MotionPathPlugin || win.__hfMotionPathWaiters || !win.gsap) return; + if (doc.querySelector(`meta[name="${NO_PATH_TWEEN_META}"]`)) return; const register = () => win.MotionPathPlugin && win.gsap?.registerPlugin?.(win.MotionPathPlugin); whenMotionPathLoaded(win, doc, register, () => {}); } @@ -523,7 +531,7 @@ export function softReloadFrame( return ran && !builtDom; }; - const needsMotionPath = /motionPath\s*[:{]/.test(script); + const needsMotionPath = namesMotionPath(script); if (!needsMotionPath || win.MotionPathPlugin || !win.gsap) { if (!swap(currentTime)) return "cannot-soft-reload"; return verifyTimelinesPopulated(win, targetKeys) ? "applied" : "verify-failed"; diff --git a/packages/core/src/safePath.test.ts b/packages/core/src/safePath.test.ts index 00ec9f7062..db3f2e8e74 100644 --- a/packages/core/src/safePath.test.ts +++ b/packages/core/src/safePath.test.ts @@ -16,6 +16,7 @@ import { isSafePath, isStudioPrivatePath, mkdirWithinProject, + resolveExistingWithinProjectOff, resolveWithinProject, toolTrustedFileKind, } from "./safePath.js"; @@ -189,6 +190,20 @@ describe("resolveWithinProject", () => { if (!tryCreateSymlink(external, join(base, "link"), "dir")) return; expect(resolveWithinProject(base, "link/secret.txt")).toBeNull(); }); + + it("answers the same off the event loop for a file that exists", async () => { + const base = tmpDir("rwp-base-"); + const external = tmpDir("rwp-external-"); + writeFileSync(join(base, "in.js"), "in"); + writeFileSync(join(external, "secret.txt"), "top secret"); + expect(await resolveExistingWithinProjectOff(base, "in.js")).toBe(join(base, "in.js")); + // fails without the fix: a path that does not resolve threw instead of answering null. + expect(await resolveExistingWithinProjectOff(base, "missing.js")).toBeNull(); + const escape = join("..", basename(external), "secret.txt"); + expect(await resolveExistingWithinProjectOff(base, escape)).toBeNull(); + if (!tryCreateSymlink(external, join(base, "link"), "dir")) return; + expect(await resolveExistingWithinProjectOff(base, "link/secret.txt")).toBeNull(); + }); }); describe("mkdirWithinProject", () => { diff --git a/packages/core/src/safePath.ts b/packages/core/src/safePath.ts index 14f1b27664..b30eab7f1b 100644 --- a/packages/core/src/safePath.ts +++ b/packages/core/src/safePath.ts @@ -105,10 +105,27 @@ export function isSafePath(base: string, resolved: string): boolean { const targetReal = trailing.length ? join(ancestorReal, ...[...trailing].reverse()) : ancestorReal; - return targetReal === baseReal || targetReal.startsWith(baseReal + sep); + return realPathWithin(baseReal, targetReal); } } +/** The containment rule once both sides are real paths. */ +export const realPathWithin = (baseReal: string, targetReal: string): boolean => + targetReal === baseReal || targetReal.startsWith(baseReal + sep); + +/** `resolveWithinProject` off the event loop: the absolute path of an existing entry inside `base`, else null. */ +export async function resolveExistingWithinProjectOff( + base: string, + relativePath: string, +): Promise { + const resolved = resolve(base, relativePath); + if (namesAnotherNetworkRoot(resolve(base), resolved)) return null; + const real = await Promise.all([realpathOff(resolve(base)), realpathOff(resolved)]).catch( + () => null, + ); + return real !== null && realPathWithin(real[0], real[1]) ? resolved : null; +} + /** * Resolve `relativePath` against `base` and return the absolute path only if it * stays within `base` (after symlink resolution); otherwise return `null`. diff --git a/packages/studio-server/src/helpers/projectDisk.ts b/packages/studio-server/src/helpers/projectDisk.ts index 45fc068c8c..84b30ba239 100644 --- a/packages/studio-server/src/helpers/projectDisk.ts +++ b/packages/studio-server/src/helpers/projectDisk.ts @@ -1,6 +1,6 @@ import type { Stats } from "node:fs"; import { stat } from "node:fs/promises"; -import { realpathOff } from "@hyperframes/core/safe-path"; +import { realpathOff, resolveExistingWithinProjectOff } from "@hyperframes/core/safe-path"; import { basename, dirname, join, relative, sep } from "node:path"; import { isPrivateProjectPath } from "./safePath.js"; @@ -37,3 +37,11 @@ export async function isPrivateProjectFileOff( ); return real === unresolvable || isPrivateProjectPath(rel(real[0], real[1])); } + +export async function resolveExistingProjectFileOff( + base: string, + relativePath: string, +): Promise { + const file = await resolveExistingWithinProjectOff(base, relativePath); + return file === null || (await isPrivateProjectFileOff(base, file)) ? null : file; +} diff --git a/packages/studio-server/src/routes/preview.noPathTween.test.ts b/packages/studio-server/src/routes/preview.noPathTween.test.ts new file mode 100644 index 0000000000..a5cc851d61 --- /dev/null +++ b/packages/studio-server/src/routes/preview.noPathTween.test.ts @@ -0,0 +1,133 @@ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { NO_PATH_TWEEN_META } from "@hyperframes/core/gsap-cdn"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { + injectStudioPreviewAugmentations, + provesNoPathTween, + withPreviewBase, + withPreviewRuntime, +} from "./preview"; + +const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };"; +const PLAIN_TWEEN = ''; +const LATE_PATH_TWEEN = + 'window.buildPathTween = function () { gsap.to("#card", { motionPath: { path: [{ x: 50, y: 0 }] } }); };'; + +function projectDir(files: Record, links: Record = {}): string { + const dir = mkdtempSync(join(tmpdir(), "hf-no-path-tween-")); + onTestFinished(() => rmSync(dir, { recursive: true, force: true })); + for (const [rel, content] of Object.entries(files)) { + mkdirSync(join(dir, rel, ".."), { recursive: true }); + writeFileSync(join(dir, rel), content, "utf-8"); + } + for (const [rel, target] of Object.entries(links)) symlinkSync(target, join(dir, rel)); + return dir; +} + +/** The main preview page for `scripts` in the head, as the preview route builds it, and the project it reads. */ +function page( + scripts: string, + files: Record = {}, + links: Record = {}, +) { + const index = `${scripts}
${PLAIN_TWEEN}`; + const dir = projectDir({ "index.html": index, ...files }, links); + return { html: withPreviewRuntime(withPreviewBase(index, "film"), "/api/runtime.js"), dir }; +} + +const pathFree = ( + scripts: string, + files?: Record, + links?: Record, +) => { + const { html, dir } = page(scripts, files, links); + return provesNoPathTween(html, dir); +}; + +describe("the preview builder's proof that no script can tween along a path", () => { + // fails without the fix: no preview carried the mark, so every one loaded the plugin. + it("holds for a page whose scripts are read and name no path: its own GSAP file and inline tweens", async () => { + const own = ''; + expect(await pathFree(own, { "gsap.min.js": GSAP_FILE })).toBe(true); + }); + + it("holds for a page that loads GSAP from its CDN", async () => { + const cdn = ''; + expect(await pathFree(cdn)).toBe(true); + }); + + it("fails for a project script that builds a path tween, whatever its name", async () => { + const authored = ''; + expect(await pathFree(authored, { "authored/gsap.js": LATE_PATH_TWEEN })).toBe(false); + }); + + it("fails for a script it cannot read: another host, a missing file, a module, a folder", async () => { + expect(await pathFree('')).toBe(false); + expect(await pathFree('')).toBe(false); + const module = ''; + expect(await pathFree(module, { "gsap.min.js": GSAP_FILE })).toBe(false); + expect(await pathFree('', { "assets/a.txt": "a" })).toBe(false); + }); + + it("fails for a script that links out of the project", async () => { + const outside = projectDir({ "gsap.min.js": GSAP_FILE }); + const own = ''; + expect(await pathFree(own, {}, { "gsap.min.js": join(outside, "gsap.min.js") })).toBe(false); + }); + + // fails without the fix: each project script's path was resolved with a synchronous realpath on the server thread. + it("resolves project scripts without a synchronous realpath", async () => { + const { html, dir } = page('', { "gsap.min.js": GSAP_FILE }); + const fs = createRequire(import.meta.url)("node:fs") as typeof import("node:fs"); + const native = fs.realpathSync.native; + let syncCalls = 0; + fs.realpathSync.native = ((...args: Parameters) => ( + syncCalls++, native(...args) + )) as typeof native; + onTestFinished(() => void (fs.realpathSync.native = native)); + expect(await provesNoPathTween(html, dir)).toBe(true); + expect(syncCalls).toBe(0); + }); + + // fails without the fix: the scan resolved and read the disk on the route's event loop, with no limit on a silent + // drive. + it.each([ + [ + "resolving its path", + { resolve: () => new Promise(() => {}), read: async () => GSAP_FILE }, + ], + [ + "reading it", + { + resolve: async (base: string, rel: string) => join(base, rel), + read: () => new Promise(() => {}), + }, + ], + ])("fails when %s does not answer within the budget", async (_, files) => { + const { html, dir } = page('', { "gsap.min.js": GSAP_FILE }); + expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false); + }); + + it("fails for a page whose own text names a path", async () => { + expect(await pathFree('')).toBe(false); + }); +}); + +describe("the preview's path-free mark", () => { + it("is set only when the builder proved the page path-free", () => { + const { html, dir } = page(""); + const augmented = (proved: boolean) => + injectStudioPreviewAugmentations(html, "/api/runtime.js", "signature", dir, "index.html", { + capture: false, + gsapBaseUrl: "https://cdn.jsdelivr.net/npm", + sandboxedCapture: false, + pathFree: proved, + }); + const mark = ``; + expect(augmented(true)).toContain(mark); + expect(augmented(false)).not.toContain(mark); + }); +}); diff --git a/packages/studio-server/src/routes/preview.scanDeadline.test.ts b/packages/studio-server/src/routes/preview.scanDeadline.test.ts new file mode 100644 index 0000000000..ffe0b36e62 --- /dev/null +++ b/packages/studio-server/src/routes/preview.scanDeadline.test.ts @@ -0,0 +1,56 @@ +// @vitest-environment node +import { afterAll, describe, expect, it, vi } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createStudioApi } from "../createStudioApi"; +import type { StudioApiAdapter } from "../types"; + +vi.mock("../helpers/projectDisk.js", async (real) => { + const disk = await real(); + return { + ...disk, + resolveExistingProjectFileOff: (base: string, rel: string) => + rel.endsWith("held.js") + ? new Promise(() => {}) + : disk.resolveExistingProjectFileOff(base, rel), + }; +}); + +const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-scan-deadline-")); +mkdirSync(join(projectDir, "scenes")); +writeFileSync(join(projectDir, "index.html"), ""); +writeFileSync(join(projectDir, "held.js"), "window.held = true;"); +const scene = (script: string) => + `

Hi

${script}
`; +writeFileSync(join(projectDir, "scenes", "plain.html"), scene("")); +writeFileSync(join(projectDir, "scenes", "held.html"), scene('')); +afterAll(() => rmSync(projectDir, { recursive: true, force: true })); + +const adapter: StudioApiAdapter = { + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir: projectDir }), + bundle: async () => null, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => join(projectDir, "renders"), + startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }), +}; +const DEADLINE_MS = 200; +const api = createStudioApi(adapter, { subCompositionDeadlineMs: DEADLINE_MS }); +// Starts the build worker both share, which a 200 ms request cannot wait for. +const patient = createStudioApi(adapter, { subCompositionDeadlineMs: 60_000 }); +const comp = (file: string, on = api) => + on.request(`http://localhost/projects/demo/preview/comp/scenes/${file}`); + +describe("the preview builder's script scan inside a request's deadline", () => { + // fails without the fix: a held lookup kept the request for the scan's own 1 s, past a 200 ms deadline. + it("gives up within the request's time, and the preview is still served", async () => { + expect((await comp("plain.html", patient)).status).toBe(200); + expect((await comp("plain.html")).status).toBe(200); + const started = performance.now(); + const res = await comp("held.html"); + expect(res.status).toBe(200); + expect(performance.now() - started).toBeLessThan(500); + }, 30_000); +}); diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts index 59aa5baffe..e9732f40d5 100644 --- a/packages/studio-server/src/routes/preview.test.ts +++ b/packages/studio-server/src/routes/preview.test.ts @@ -27,6 +27,7 @@ import { STUDIO_PREVIEW_MARK_META, } from "@hyperframes/core/studio-preview-mark"; import { AFTER_FONTS_SCRIPT_TYPE } from "@hyperframes/core/compiler"; +import { GSAP_PLUGIN_LOAD_ATTR } from "@hyperframes/core/gsap-cdn"; import { PREVIEW_BUNDLE_OPTIONS, PREVIEW_CAPTURE_PARAM, @@ -375,6 +376,38 @@ describe("registerPreviewRoutes", () => { expect(message).toContain(appended[0]?.src); }); + // fails without the fix: a failed MotionPath preload was loaded again from the CDN and reported as the film's GSAP. + it("leaves the preview's own plugin load to its loader: no fallback load, no report", async () => { + const app = new Hono(); + registerPreviewRoutes(app, createAdapter(createProjectDir())); + const html = await (await app.request("http://localhost/projects/demo/preview")).text(); + const fallback = /`): string { const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); const box = (id: string, track: number, style: string) => @@ -65,7 +66,7 @@ function previewHtml(): string { ${box("target", 1, "left: 100px; top: 100px")}${box("b", 2, "left: 600px; top: 100px")}
- + ${main} `; } @@ -300,24 +301,123 @@ describe.each(MODES)("a re-run waiting for the MotionPath plugin, %s", (mode) => }); }); +const PATH_TWEEN = `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0); + window.__timelines["main"] = tl; +})();`; +const PATH_TWEEN_URL = "https://fixture.hyperframes.test/path-tween.js"; + +/** Studio meeting a freshly loaded preview: the same-origin preload (NLEContext), then the editing port. */ +const connect = (page: Page) => + page.evaluate(async () => { + const studio = (window as unknown as { hfStudio: Studio }).hfStudio; + const iframe = document.querySelector("iframe")!; + studio.ensureMotionPathPluginLoaded(iframe); + await studio.previewRequest(iframe, "runtime-snapshot", {}); + }); +const pluginScripts = ({ frame }: Preview) => + frame.evaluate(() => document.querySelectorAll('script[src*="MotionPathPlugin"]').length); + // Parity: a same-origin preview gets the plugin on load (NLEContext), and a sealed one when Studio connects. it.each(MODES)( "the first motion-path re-run after load finds the plugin loaded (%s)", async (mode) => { - const { page, frame, release } = await openPreview(mode); + const { page, frame, release } = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + ); await release(200); - await page.evaluate(async () => { - const studio = (window as unknown as { hfStudio: Studio }).hfStudio; - const iframe = document.querySelector("iframe")!; - studio.ensureMotionPathPluginLoaded(iframe); - await studio.previewRequest(iframe, "runtime-snapshot", {}); - }); + await connect(page); await frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); expect(await rerun(page, timeline("main", "older", 60, true), 1)).toBe("applied"); await page.close(); }, ); +// fails without the fix: the preload read only inline scripts, so this page's plugin was never requested. +it.each(MODES)( + "a path tween from an external script gets the plugin when Studio connects (%s)", + async (mode) => { + const preview = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + { [PATH_TWEEN_URL]: PATH_TWEEN }, + ); + await preview.release(200); + await connect(preview.page); + expect(await pluginScripts(preview)).toBe(1); + await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); + await preview.page.close(); + }, +); + +const LATE_PATH_TWEEN = `(function () { + window.__timelines = window.__timelines || {}; + var tl = gsap.timeline({ paused: true }); + window.__timelines["main"] = tl; + window.buildPathTween = function () { + tl.to("#target", { motionPath: { path: [{ x: 0, y: 0 }, { x: 50, y: 0 }] }, duration: 4, ease: "none" }, 0); + }; +})();`; + +const LATE_TWEEN_CASES = MODES.flatMap((mode) => + [PATH_TWEEN_URL, "https://fixture.hyperframes.test/authored/gsap.js"].map( + (url) => [mode, url] as const, + ), +); + +// fails without the fix: an external script that builds its first path tween after connect, named gsap.js, got no +// plugin and stayed at 0. +it.each(LATE_TWEEN_CASES)( + "a path tween an external script builds after connect plays (%s, %s)", + async (mode, url) => { + const preview = await openSharedPreview( + browser, + studioBundle, + previewHtml(``), + mode, + { [url]: LATE_PATH_TWEEN }, + ); + await preview.release(200); + await connect(preview.page); + await preview.frame.waitForFunction(() => "MotionPathPlugin" in window, { timeout: 5_000 }); + await preview.frame.evaluate(() => + (window as unknown as { buildPathTween(): void }).buildPathTween(), + ); + await preview.seek(4); + const x = await preview.frame.evaluate(() => + Number( + ( + window as unknown as { gsap: { getProperty(t: string, p: string): unknown } } + ).gsap.getProperty("#target", "x"), + ), + ); + expect(x).toBeCloseTo(50, 0); + await preview.page.close(); + }, +); + +// fails without the fix: every preview Studio connected to requested the plugin. +it.each(MODES)( + "a page the preview builder marked as path-free requests no plugin (%s)", + async (mode) => { + const marked = previewHtml().replace( + STUDIO_MARK, + `${STUDIO_MARK}`, + ); + const preview = await openSharedPreview(browser, studioBundle, marked, mode); + await connect(preview.page); + expect(await pluginScripts(preview)).toBe(0); + await preview.page.close(); + }, +); + // fails without the fix: all but "still recovers an older script refusal after an unrelated successful patch", // which guards the coverage rule against dropping a refusal no re-run carries. describe("late answers held in transit, sealed", () => { diff --git a/packages/studio/tests/sealedPreviewHarness.ts b/packages/studio/tests/sealedPreviewHarness.ts index 2f5f1a4fa6..cbb25c42b8 100644 --- a/packages/studio/tests/sealedPreviewHarness.ts +++ b/packages/studio/tests/sealedPreviewHarness.ts @@ -127,12 +127,13 @@ function holdReplies() { }); } -/** Opens the preview in Studio's page; the plugin request waits until `release` is called. */ +/** Opens the preview in Studio's page; the plugin request waits until `release`; a `scripts` URL gets its script. */ export async function openPreview( browser: Browser, studioBundle: string, html: string, mode: string, + scripts: Record = {}, ) { const page: Page = await browser.newPage(); const plugin = readFileSync(require.resolve("gsap/dist/MotionPathPlugin.min.js"), "utf8"); @@ -140,6 +141,9 @@ export async function openPreview( let holding = true; await page.setRequestInterception(true); page.on("request", (request) => { + const script = scripts[request.url()]; + if (script !== undefined) + return void request.respond({ status: 200, contentType: "text/javascript", body: script }); if (!/MotionPathPlugin/.test(request.url())) return void request.continue(); const serve = () => request.respond({ status: 200, contentType: "text/javascript", body: plugin });