Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/core/src/gsapCdn.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down
14 changes: 11 additions & 3 deletions packages/core/src/runtime/editing/softReload.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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, () => {});
}
Expand Down Expand Up @@ -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";
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/safePath.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
isSafePath,
isStudioPrivatePath,
mkdirWithinProject,
resolveExistingWithinProjectOff,
resolveWithinProject,
toolTrustedFileKind,
} from "./safePath.js";
Expand Down Expand Up @@ -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", () => {
Expand Down
19 changes: 18 additions & 1 deletion packages/core/src/safePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null> {
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`.
Expand Down
10 changes: 9 additions & 1 deletion packages/studio-server/src/helpers/projectDisk.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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<string | null> {
const file = await resolveExistingWithinProjectOff(base, relativePath);
return file === null || (await isPrivateProjectFileOff(base, file)) ? null : file;
}
133 changes: 133 additions & 0 deletions packages/studio-server/src/routes/preview.noPathTween.test.ts
Original file line number Diff line number Diff line change
@@ -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 = '<script>gsap.timeline({ paused: true }).to("#card", { x: 300 });</script>';
const LATE_PATH_TWEEN =
'window.buildPathTween = function () { gsap.to("#card", { motionPath: { path: [{ x: 50, y: 0 }] } }); };';

function projectDir(files: Record<string, string>, links: Record<string, string> = {}): 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<string, string> = {},
links: Record<string, string> = {},
) {
const index = `<!doctype html><html><head>${scripts}</head><body><div id="card"></div>${PLAIN_TWEEN}</body></html>`;
const dir = projectDir({ "index.html": index, ...files }, links);
return { html: withPreviewRuntime(withPreviewBase(index, "film"), "/api/runtime.js"), dir };
}

const pathFree = (
scripts: string,
files?: Record<string, string>,
links?: Record<string, string>,
) => {
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 = '<script src="gsap.min.js"></script>';
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 = '<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>';
expect(await pathFree(cdn)).toBe(true);
});

it("fails for a project script that builds a path tween, whatever its name", async () => {
const authored = '<script src="authored/gsap.js"></script>';
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('<script src="https://example.com/gsap.min.js"></script>')).toBe(false);
expect(await pathFree('<script src="missing.js"></script>')).toBe(false);
const module = '<script type="module" src="gsap.min.js"></script>';
expect(await pathFree(module, { "gsap.min.js": GSAP_FILE })).toBe(false);
expect(await pathFree('<script src="assets"></script>', { "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 = '<script src="gsap.min.js"></script>';
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('<script src="gsap.min.js"></script>', { "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<typeof native>) => (
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<never>(() => {}), read: async () => GSAP_FILE },
],
[
"reading it",
{
resolve: async (base: string, rel: string) => join(base, rel),
read: () => new Promise<never>(() => {}),
},
],
])("fails when %s does not answer within the budget", async (_, files) => {
const { html, dir } = page('<script src="gsap.min.js"></script>', { "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('<script>gsap.to("#card", { "motionPath": {} });</script>')).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 = `<meta name="${NO_PATH_TWEEN_META}">`;
expect(augmented(true)).toContain(mark);
expect(augmented(false)).not.toContain(mark);
});
});
56 changes: 56 additions & 0 deletions packages/studio-server/src/routes/preview.scanDeadline.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("../helpers/projectDisk.js")>();
return {
...disk,
resolveExistingProjectFileOff: (base: string, rel: string) =>
rel.endsWith("held.js")
? new Promise<never>(() => {})
: disk.resolveExistingProjectFileOff(base, rel),
};
});

const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-scan-deadline-"));
mkdirSync(join(projectDir, "scenes"));
writeFileSync(join(projectDir, "index.html"), "<html><head></head><body></body></html>");
writeFileSync(join(projectDir, "held.js"), "window.held = true;");
const scene = (script: string) =>
`<div data-composition-id="card" data-width="320" data-height="180"><p>Hi</p>${script}</div>`;
writeFileSync(join(projectDir, "scenes", "plain.html"), scene(""));
writeFileSync(join(projectDir, "scenes", "held.html"), scene('<script src="held.js"></script>'));
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);
});
33 changes: 33 additions & 0 deletions packages/studio-server/src/routes/preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 = /<script data-hf-gsap-fallback>([\s\S]*?)<\/script>/.exec(html)?.[1] ?? "";
let onDocumentError: (event: { target: unknown }) => void = () => undefined;
const appended: unknown[] = [];
const reported: unknown[] = [];
new Function("document", "reportError", fallback)(
{
addEventListener: (_type: string, listener: typeof onDocumentError) => {
onDocumentError = listener;
},
createElement: () => ({ tagName: "SCRIPT", src: "" }),
head: { appendChild: (script: unknown) => appended.push(script) },
},
(error: unknown) => reported.push(error),
);

onDocumentError({
target: {
tagName: "SCRIPT",
src: "https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/MotionPathPlugin.min.js",
hasAttribute: (name: string) => name === GSAP_PLUGIN_LOAD_ATTR,
},
});
await new Promise((settle) => setTimeout(settle, 0));
expect(appended).toHaveLength(0);
expect(reported).toHaveLength(0);
});

it("keeps every error a Studio preview raises from its first script, and leaves captures without it", async () => {
const projectDir = createProjectDir();
writeFileSync(
Expand Down
Loading
Loading