mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 07:50:13 +00:00
fix: keep private project files out of preview bundles and local sharing (#7563)
* fix(core): keep git metadata and env files out of bundled HTML The bundler now checks every file it reads against the project's private paths (git metadata and env files, spelled directly or through a link) and leaves a refused reference as authored instead of inlining it. Bundle options gain a canRead predicate; Studio's preview passes its own private-file rule so the preview document matches what the file routes serve. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): check capture read grants against the decoded path A capture page's read grant now looks at the path the way the static preview route decodes it, including encoded separators, so a URL that resolves to a dotfile or into a dot-folder gets no CORS grant. Ordinary project files keep loading in thumbnails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): accept local share requests only from loopback connections The local share routes already require loopback Host and same-origin headers. They now also require the connection itself to come from this machine, so a Studio bound to a network address still keeps sharing local to the person running it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): ask the bundler for Studio's private-file rule as plain data The preview route passed a fresh `canRead` callback on every build. A host that builds on a worker thread cannot send a function across, so it built on its own thread, and it could no longer share one build between two same-content requests. The bundler now takes `privateFiles: "studio"`, a plain string, and applies Studio's private-file rule itself. That rule (git metadata, env files, and the app's records under `.hyperframes/`) now lives in `@hyperframes/core/safe-path`, and studio-server reuses it. The `canRead` option is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(studio-server): do not serve a preview main file linked to a private file When index.html (or <id>.html) is a link to an env file or into git metadata, the bundler refuses it and the route falls back to reading the main file from disk. That fallback now skips a candidate that is a private project file, by the same rule the file routes use. A main file linked from outside the project is still served. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(producer): never inline git or env files as render sub-compositions The render compiler resolved data-composition-src and inlined the file it named, so `data-composition-src=".env"` put the env file's text into the render page. It now refuses git metadata and env files with the same shared rule the bundler uses. The pre-render check names the refused reference and stops the render. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore: raise the inspector unpacked size budget to 3,722,000 bytes The inspector already sat about 36.8 KB over its 3,684,092 budget, just inside the 1% tolerance. Moving Studio's private-file rule into core added a few hundred bytes to the bundles it ships, which pushed it to 3,721,419 bytes and over the tolerance. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9a048ac019
commit
a243169f8a
@@ -1,6 +1,15 @@
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
export function localShareRequestAllowed(request: Request): boolean {
|
||||
const isLoopbackSocketPeer = (address: string | undefined): boolean => {
|
||||
const ip = address?.replace(/^::ffff:/i, "") ?? "";
|
||||
return ip === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip);
|
||||
};
|
||||
|
||||
export function localShareRequestAllowed(
|
||||
request: Request,
|
||||
socketPeer: string | undefined,
|
||||
): boolean {
|
||||
if (!isLoopbackSocketPeer(socketPeer)) return false;
|
||||
const host = request.headers.get("host");
|
||||
if (!host || request.headers.get("sec-fetch-site") !== "same-origin") return false;
|
||||
try {
|
||||
|
||||
@@ -41,13 +41,14 @@ function fixture() {
|
||||
mountShareRoutes(app, "/fixed/project", create, login, track);
|
||||
return { app, service, create, login, track };
|
||||
}
|
||||
const LOCAL_PEER = { incoming: { socket: { remoteAddress: "127.0.0.1" } } };
|
||||
const headers = {
|
||||
host: "localhost:3000",
|
||||
origin: "http://localhost:3000",
|
||||
"sec-fetch-site": "same-origin",
|
||||
};
|
||||
async function token(app: Hono) {
|
||||
const response = await app.request("/api/share/bootstrap", { headers });
|
||||
const response = await app.request("/api/share/bootstrap", { headers }, LOCAL_PEER);
|
||||
expect(response.status).toBe(200);
|
||||
const body: unknown = await response.json();
|
||||
if (!body || typeof body !== "object" || !("csrf" in body) || typeof body.csrf !== "string")
|
||||
@@ -55,11 +56,15 @@ async function token(app: Hono) {
|
||||
return body.csrf;
|
||||
}
|
||||
function request(app: Hono, path: string, csrf: string, body?: unknown) {
|
||||
return app.request(`/api/share/${path}`, {
|
||||
method: body ? "POST" : "GET",
|
||||
headers: { ...headers, "x-hyperframes-share-csrf": csrf, "content-type": "application/json" },
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return app.request(
|
||||
`/api/share/${path}`,
|
||||
{
|
||||
method: body ? "POST" : "GET",
|
||||
headers: { ...headers, "x-hyperframes-share-csrf": csrf, "content-type": "application/json" },
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
},
|
||||
LOCAL_PEER,
|
||||
);
|
||||
}
|
||||
describe("local share boundary", () => {
|
||||
it.each([
|
||||
@@ -72,7 +77,19 @@ describe("local share boundary", () => {
|
||||
{ ...headers, host: "localhost:3000@evil.example" },
|
||||
])("denies foreign, LAN and missing-origin requests before authentication %j", async (input) => {
|
||||
const { app, create } = fixture();
|
||||
expect((await app.request("/api/share/bootstrap", { headers: input })).status).toBe(403);
|
||||
expect((await app.request("/api/share/bootstrap", { headers: input }, LOCAL_PEER)).status).toBe(
|
||||
403,
|
||||
);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([
|
||||
["a LAN peer", { incoming: { socket: { remoteAddress: "192.168.1.20" } } }],
|
||||
["a mapped LAN peer", { incoming: { socket: { remoteAddress: "::ffff:10.0.0.5" } } }],
|
||||
["an unknown peer", {}],
|
||||
["no server bindings", undefined],
|
||||
])("denies %s even with local headers", async (_, peer) => {
|
||||
const { app, create } = fixture();
|
||||
expect((await app.request("/api/share/bootstrap", { headers }, peer)).status).toBe(403);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
it("allows same-origin browser GET Referer and IPv6 loopback", () => {
|
||||
@@ -85,6 +102,7 @@ describe("local share boundary", () => {
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
"127.0.0.1",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
@@ -96,6 +114,7 @@ describe("local share boundary", () => {
|
||||
"sec-fetch-site": "same-origin",
|
||||
},
|
||||
}),
|
||||
"::1",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Hono } from "hono";
|
||||
import type { HttpBindings } from "@hono/node-server";
|
||||
import { bodyLimit } from "hono/body-limit";
|
||||
import type {
|
||||
LocalShareAction,
|
||||
@@ -93,7 +94,7 @@ export function mountShareRoutes(
|
||||
login: () => Promise<void> = defaultLogin,
|
||||
track: typeof trackShareInteraction = trackShareInteraction,
|
||||
): void {
|
||||
const routes = new Hono();
|
||||
const routes = new Hono<{ Bindings: Partial<HttpBindings> }>();
|
||||
let job: LocalShareJob | null = null;
|
||||
const hasRunningJob = () => job?.state === "running";
|
||||
let jobOwner: string | null = null;
|
||||
@@ -112,7 +113,7 @@ export function mountShareRoutes(
|
||||
};
|
||||
routes.use("*", async (c, next) => {
|
||||
c.header("Cache-Control", "no-store");
|
||||
if (!localShareRequestAllowed(c.req.raw))
|
||||
if (!localShareRequestAllowed(c.req.raw, c.env?.incoming?.socket.remoteAddress))
|
||||
return c.json({ code: "forbidden", message: "Open sharing from this local Studio." }, 403);
|
||||
if (
|
||||
c.req.path !== "/api/share/bootstrap" &&
|
||||
|
||||
@@ -201,6 +201,61 @@ describe("bundleToSingleHtml", () => {
|
||||
expect(reads).not.toContain(join(dir, "notes.md"));
|
||||
});
|
||||
|
||||
it("never inlines git metadata or env files, spelled directly or through a link", async () => {
|
||||
const secret = "SECRET_TOKEN_VALUE";
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html><html><head>
|
||||
<link rel="stylesheet" href=".env"><link rel="stylesheet" href="style.css">
|
||||
</head><body>
|
||||
<div data-composition-id="root" data-width="320" data-height="180" data-start="0" data-duration="2">
|
||||
<img src=".git/config">
|
||||
<div data-composition-id="intro" data-composition-src="scenes/intro.html" data-start="0" data-duration="1"></div>
|
||||
<div data-composition-id="env" data-composition-src=".env.html" data-start="0" data-duration="1"></div>
|
||||
</div>
|
||||
<script src=".git/config"></script>
|
||||
<script src="linked.js"></script>
|
||||
</body></html>`,
|
||||
"style.css": '@import ".env.local"; .a { color: red; }',
|
||||
"scenes/intro.html": `<template><div data-composition-id="intro" data-width="320" data-height="180">
|
||||
<p>intro</p><script src="../.env"></script></div></template>`,
|
||||
".env": `TOKEN=${secret}`,
|
||||
".env.local": `TOKEN=${secret}`,
|
||||
".env.html": `<template><div data-composition-id="env">${secret}</div></template>`,
|
||||
".git/config": `[remote "origin"] url = https://${secret}@example.com/repo.git`,
|
||||
});
|
||||
symlinkSync(join(dir, ".env"), join(dir, "linked.js"));
|
||||
try {
|
||||
const bundled = await bundleToSingleHtml(dir, { inlineAssets: true });
|
||||
expect(bundled).not.toContain(secret);
|
||||
expect(bundled).not.toContain(Buffer.from(`TOKEN=${secret}`).toString("base64"));
|
||||
expect(bundled).toContain(".a { color: red; }");
|
||||
expect(bundled).toContain("<p>intro</p>");
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses the app's records only under the studio private-file policy", async () => {
|
||||
const dir = makeTempProject({
|
||||
"index.html": `<!doctype html><html><head>
|
||||
<link rel="stylesheet" href=".hyperframes/handoff.css">
|
||||
<link rel="stylesheet" href=".hyperframes/prepared-assets/fonts.css">
|
||||
</head><body><div data-composition-id="root" data-width="320" data-height="180"></div></body></html>`,
|
||||
".hyperframes/handoff.css": ".app-record { color: red; }",
|
||||
".hyperframes/prepared-assets/fonts.css": ".prepared { color: blue; }",
|
||||
});
|
||||
try {
|
||||
const studio = await bundleToSingleHtml(dir, { privateFiles: "studio" });
|
||||
expect(studio).not.toContain(".app-record");
|
||||
expect(studio).toContain('href=".hyperframes/handoff.css"');
|
||||
expect(studio).toContain(".prepared { color: blue; }");
|
||||
const plain = await bundleToSingleHtml(dir);
|
||||
expect(plain).toContain(".app-record { color: red; }");
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"UTF-16LE",
|
||||
|
||||
@@ -70,7 +70,13 @@ import {
|
||||
isLibraryCopy,
|
||||
refuseSwapsReachedByRootScripts,
|
||||
} from "./inlineSubCompositions";
|
||||
import { isSafePath, resolveWithinProject } from "../safePath.js";
|
||||
import {
|
||||
isPrivateFileUnder,
|
||||
isSafePath,
|
||||
isStudioPrivatePath,
|
||||
isVcsOrSecretPath,
|
||||
resolveWithinProject,
|
||||
} from "../safePath.js";
|
||||
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
|
||||
import { readTextFile } from "@hyperframes/parsers/asset-resolution";
|
||||
import { HF_COLOR_GRADING_ATTR } from "../colorGrading";
|
||||
@@ -111,15 +117,28 @@ function isRelativeUrl(url: string): boolean {
|
||||
return !isNonRelativeUrl(url) && !isAbsolute(url);
|
||||
}
|
||||
|
||||
const bundleReads = new AsyncLocalStorage<(filePath: string) => void>();
|
||||
interface BundleReadScope {
|
||||
projectDir: string;
|
||||
privateFiles: BundlePrivateFiles;
|
||||
noteRead: (filePath: string) => void;
|
||||
}
|
||||
|
||||
const bundleReads = new AsyncLocalStorage<BundleReadScope>();
|
||||
|
||||
function noteRead(filePath: string): void {
|
||||
bundleReads.getStore()?.(filePath);
|
||||
bundleReads.getStore()?.noteRead(filePath);
|
||||
}
|
||||
|
||||
function readAllowed(filePath: string): boolean {
|
||||
const scope = bundleReads.getStore();
|
||||
if (!scope) return true;
|
||||
const isPrivate = scope.privateFiles === "studio" ? isStudioPrivatePath : isVcsOrSecretPath;
|
||||
return !isPrivateFileUnder(scope.projectDir, filePath, isPrivate);
|
||||
}
|
||||
|
||||
function safeReadFile(filePath: string): string | null {
|
||||
noteRead(filePath);
|
||||
if (!existsSync(filePath)) return null;
|
||||
if (!readAllowed(filePath) || !existsSync(filePath)) return null;
|
||||
try {
|
||||
return readTextFile(filePath);
|
||||
} catch {
|
||||
@@ -290,7 +309,7 @@ function inlineCssFile(
|
||||
|
||||
function safeReadFileBuffer(filePath: string): Buffer | null {
|
||||
noteRead(filePath);
|
||||
if (!existsSync(filePath)) return null;
|
||||
if (!readAllowed(filePath) || !existsSync(filePath)) return null;
|
||||
try {
|
||||
return readFileSync(filePath);
|
||||
} catch {
|
||||
@@ -912,8 +931,16 @@ export interface BundleOptions {
|
||||
staticGuard?: boolean;
|
||||
/** Called once per build for each project file the build reads or looks for. */
|
||||
onRead?: (filePath: string) => void;
|
||||
/**
|
||||
* Project files the build never reads; a refused file keeps its authored reference. Git metadata and env files
|
||||
* always; `"studio"` also refuses the app's records under `.hyperframes/`, as Studio's file routes do.
|
||||
*/
|
||||
privateFiles?: BundlePrivateFiles;
|
||||
}
|
||||
|
||||
/** Plain data, so the option crosses to a build thread and keys a shared build. */
|
||||
export type BundlePrivateFiles = "vcs-and-secrets" | "studio";
|
||||
|
||||
/**
|
||||
* Bundle a project's index.html into a single self-contained HTML file.
|
||||
*
|
||||
@@ -1038,16 +1065,19 @@ function hoistCompositionScripts(
|
||||
}
|
||||
|
||||
export function bundleToSingleHtml(projectDir: string, options?: BundleOptions): Promise<string> {
|
||||
const bundle = () => bundleProject(projectDir, options);
|
||||
const onRead = options?.onRead;
|
||||
if (!onRead) return bundle();
|
||||
const noted = new Set<string>();
|
||||
const noteOnce = (filePath: string) => {
|
||||
const noteRead = (filePath: string) => {
|
||||
if (noted.has(filePath)) return;
|
||||
noted.add(filePath);
|
||||
onRead(filePath);
|
||||
onRead?.(filePath);
|
||||
};
|
||||
return bundleReads.run(noteOnce, bundle);
|
||||
const scope: BundleReadScope = {
|
||||
projectDir,
|
||||
privateFiles: options?.privateFiles ?? "vcs-and-secrets",
|
||||
noteRead,
|
||||
};
|
||||
return bundleReads.run(scope, () => bundleProject(projectDir, options));
|
||||
}
|
||||
|
||||
// A <template> scene has no root or GSAP of its own: bundle it inside the index that mounts it, as render does.
|
||||
@@ -1066,7 +1096,7 @@ function readMountedSceneShell(
|
||||
async function bundleProject(projectDir: string, options?: BundleOptions): Promise<string> {
|
||||
const entryFile = options?.entryFile ?? "index.html";
|
||||
const indexPath = resolveWithinProject(projectDir, entryFile);
|
||||
if (!indexPath || !existsSync(indexPath)) {
|
||||
if (!indexPath || !readAllowed(indexPath) || !existsSync(indexPath)) {
|
||||
throw new Error(`${entryFile} not found in project directory`);
|
||||
}
|
||||
noteRead(indexPath);
|
||||
|
||||
@@ -33,6 +33,7 @@ export {
|
||||
type BundledHostCompositionIdentity,
|
||||
bundleToSingleHtml,
|
||||
type BundleOptions,
|
||||
type BundlePrivateFiles,
|
||||
type BundleScriptProvenance,
|
||||
prepareFlattenedInnerRoot,
|
||||
FLATTENED_INNER_ROOT_STRIP_ATTRS,
|
||||
|
||||
@@ -105,6 +105,61 @@ export function resolveWithinProject(base: string, relativePath: string): string
|
||||
return isSafePath(base, resolved) ? resolved : null;
|
||||
}
|
||||
|
||||
/** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
|
||||
export function projectPathSegments(relPath: string): string[] {
|
||||
return relPath
|
||||
.toLowerCase()
|
||||
.split(/[\\/]/)
|
||||
.map((segment) => withoutTrailingDotsOrSpaces(segment.split(":", 1)[0] ?? ""));
|
||||
}
|
||||
|
||||
function withoutTrailingDotsOrSpaces(segment: string): string {
|
||||
let end = segment.length;
|
||||
while (end > 0 && (segment[end - 1] === "." || segment[end - 1] === " ")) end--;
|
||||
return segment.slice(0, end);
|
||||
}
|
||||
|
||||
// Git metadata and env files hold commands other tools run and secrets: nothing serves or inlines them.
|
||||
export function isVcsOrSecretPath(relPath: string): boolean {
|
||||
return projectPathSegments(relPath).some(
|
||||
(segment) => segment === ".git" || segment.startsWith(".env"),
|
||||
);
|
||||
}
|
||||
|
||||
// `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): Studio
|
||||
// reaches none of it, the folder itself included, but its own files and the app's request pictures.
|
||||
const STUDIO_FILES = new Set([
|
||||
".hyperframes/studio-motion.json",
|
||||
".hyperframes/studio-manual-edits.json",
|
||||
]);
|
||||
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
|
||||
|
||||
/** Studio's private files, for a project-relative path with `/` separators: git, env, and the app's records. */
|
||||
export function isStudioPrivatePath(relPath: string): boolean {
|
||||
const path = relPath.toLowerCase();
|
||||
if (isVcsOrSecretPath(path)) return true;
|
||||
return (
|
||||
(path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
|
||||
!STUDIO_FILES.has(path) &&
|
||||
!STUDIO_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`))
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `isPrivate` holds for a file under `projectDir`, spelled as given or with its links resolved. */
|
||||
export function isPrivateFileUnder(
|
||||
projectDir: string,
|
||||
filePath: string,
|
||||
isPrivate: (relPath: string) => boolean,
|
||||
): boolean {
|
||||
const rel = (from: string, to: string) => relative(from, to).split(sep).join("/");
|
||||
if (isPrivate(rel(resolve(projectDir), resolve(filePath)))) return true;
|
||||
try {
|
||||
return isPrivate(rel(realpath(resolve(projectDir)), realpath(filePath)));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The project folder is gone, renamed or deleted while open; a write must not bring it back. */
|
||||
export class ProjectRootMissingError extends Error {
|
||||
constructor(readonly root: string) {
|
||||
|
||||
@@ -1015,6 +1015,21 @@ describe("detectRenderModeHints", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("compileForRender refuses to inline an env file named as a data-composition-src", async () => {
|
||||
const projectDir = makeSubCompProject(
|
||||
"hf-env-subcomp-",
|
||||
[{ id: "intro", src: "compositions/.env.html" }],
|
||||
{ ".env.html": validSubCompHtml("intro", "ENV_SECRET_VALUE") },
|
||||
);
|
||||
try {
|
||||
await expect(
|
||||
compileForRender(projectDir, join(projectDir, "index.html"), projectDir),
|
||||
).rejects.toThrow(/compositions\/\.env\.html[\s\S]*git metadata or an env file/);
|
||||
} finally {
|
||||
rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("compileForRender aborts when a data-composition-src reference points at a missing file", async () => {
|
||||
const projectDir = makeSubCompProject(
|
||||
"hf-missing-subcomp-",
|
||||
|
||||
@@ -77,6 +77,7 @@ import {
|
||||
readTextFile,
|
||||
resolveCompositionSrc,
|
||||
} from "@hyperframes/parsers/asset-resolution";
|
||||
import { isPrivateFileUnder, isVcsOrSecretPath } from "@hyperframes/core/safe-path";
|
||||
import { extractMediaMetadata, extractAudioMetadata } from "../utils/ffprobe.js";
|
||||
import { isPathInside, toExternalAssetKey } from "../utils/paths.js";
|
||||
import { collectHiddenVideoIds, collectRenderMedia } from "./renderMediaCollector.js";
|
||||
@@ -227,6 +228,10 @@ function normalizeCompositionSrcs(html: string, projectDir: string): string {
|
||||
});
|
||||
}
|
||||
|
||||
// Git metadata and env files are never inlined into a render, as the preview bundler refuses them.
|
||||
const isPrivateCompositionFile = (projectDir: string, filePath: string): boolean =>
|
||||
isPrivateFileUnder(projectDir, filePath, isVcsOrSecretPath);
|
||||
|
||||
/**
|
||||
* Recursively walk every `data-composition-src` reference reachable from
|
||||
* `html` (including nested sub-compositions) and verify each resolves to a
|
||||
@@ -261,6 +266,10 @@ function assertSubCompositionsUsable(
|
||||
problems.push({ srcPath, detail: "it is outside the project folder" });
|
||||
continue;
|
||||
}
|
||||
if (isPrivateCompositionFile(projectDir, filePath)) {
|
||||
problems.push({ srcPath, detail: "it is git metadata or an env file" });
|
||||
continue;
|
||||
}
|
||||
// Circular reference guard. parseSubCompositions (below) silently
|
||||
// `continue`s on a repeat visit with no reporting at all — mirror that
|
||||
// silence here rather than pretend it surfaces an error somewhere else.
|
||||
@@ -801,7 +810,7 @@ async function parseSubCompositions(
|
||||
if (!srcPath) continue;
|
||||
|
||||
const filePath = resolveCompositionSrc(projectDir, srcPath);
|
||||
if (filePath === null) continue;
|
||||
if (filePath === null || isPrivateCompositionFile(projectDir, filePath)) continue;
|
||||
|
||||
// Circular reference guard
|
||||
if (visited.has(filePath)) {
|
||||
@@ -1095,7 +1104,10 @@ function inlineSubCompositions(
|
||||
let compHtml = subCompositions.get(srcPath) || null;
|
||||
if (!compHtml) {
|
||||
const filePath = resolveCompositionSrc(projectDir, srcPath);
|
||||
const read = filePath ? readProjectFile(filePath) : null;
|
||||
const read =
|
||||
filePath && !isPrivateCompositionFile(projectDir, filePath)
|
||||
? readProjectFile(filePath)
|
||||
: null;
|
||||
if (read?.kind === "file") {
|
||||
compHtml = rewriteUnresolvableGsapToCdn(read.text, projectDir, srcPath);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ describe("captureLoadGrant", () => {
|
||||
["XHR", `${PREVIEW}/assets/fonts/Geist-Bold.ttf`],
|
||||
["XHR", `${PREVIEW}/notes.txt`],
|
||||
["XHR", `${PREVIEW}/assets/clip.mov?hf-proxy=h264&hf-proxy-box=1448x724`],
|
||||
["Image", `${PREVIEW}/assets%2Flogo%20v2.png`],
|
||||
])("lets the frame read a %s load of %s", (resourceType, url) => {
|
||||
expect(captureLoadGrant({ url, method: "GET", resourceType }, CAPTURE)).toBe("read");
|
||||
});
|
||||
@@ -34,6 +35,10 @@ describe("captureLoadGrant", () => {
|
||||
["XHR", `${PREVIEW}/.git/config`, "GET"],
|
||||
["XHR", `${PREVIEW}/assets/.npmrc`, "GET"],
|
||||
["XHR", `${PREVIEW}/%2Eenv`, "GET"],
|
||||
["XHR", `${PREVIEW}/assets%2F.npmrc`, "GET"],
|
||||
["Fetch", `${PREVIEW}/assets%2F.config%2Fsettings.json`, "GET"],
|
||||
["XHR", `${PREVIEW}/x%2F..%2F.npmrc`, "GET"],
|
||||
["XHR", `${PREVIEW}/assets%5C.npmrc`, "GET"],
|
||||
["XHR", `${PREVIEW}/%E0%A4%A.html`, "GET"],
|
||||
["Script", `${PREVIEW}/.env`, "GET"],
|
||||
["Image", `${PREVIEW}/.git/logo.png`, "GET"],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { PREVIEW_PROXY_PRIORITY_HEADER, PREVIEW_PROXY_PROGRESS_HEADER } from "@hyperframes/core";
|
||||
import { decodeWellFormedEscapes } from "./requestSubPath.js";
|
||||
|
||||
/**
|
||||
* A sandboxed capture document's CORS-mode loads fail, so the trusted renderer adds CORS headers for
|
||||
@@ -45,11 +46,13 @@ const decodedSegment = (segment: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const isDotPath = (url: URL, prefix: string) =>
|
||||
url.pathname
|
||||
.slice(new URL(prefix).pathname.length)
|
||||
.split("/")
|
||||
.some((segment) => decodedSegment(segment).startsWith("."));
|
||||
const isDotPath = (url: URL, prefix: string) => {
|
||||
const rest = url.pathname.slice(new URL(prefix).pathname.length);
|
||||
return [
|
||||
...rest.split("/").map(decodedSegment),
|
||||
...decodeWellFormedEscapes(rest).split(/[\\/]/),
|
||||
].some((segment) => segment.startsWith("."));
|
||||
};
|
||||
|
||||
export function captureLoadGrant(
|
||||
load: CaptureLoad,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { lstatSync, readdirSync, type Dirent } from "node:fs";
|
||||
import {
|
||||
isStudioPrivatePath,
|
||||
mkdirWithinProject,
|
||||
projectPathSegments,
|
||||
realpath,
|
||||
resolveWithinProject as resolveInProject,
|
||||
} from "@hyperframes/core/safe-path";
|
||||
import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
|
||||
import { STUDIO_MANUAL_EDITS_PATH } from "./manualEditsRenderScript.js";
|
||||
import { STUDIO_MOTION_PATH } from "./studioMotionRenderScript.js";
|
||||
|
||||
// `isSafePath` lives at the package root so non-studio-api layers (compiler,
|
||||
// CLI, engine) can share it without a backwards dependency on studio-api.
|
||||
@@ -42,39 +42,8 @@ export function realFilePath(filePath: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
// `.hyperframes/` holds the desktop app's and the CLI's own records (a hand-off, chat history, read marks): no route
|
||||
// reaches any of it, the folder itself included, but Studio's own files and the app's request pictures.
|
||||
const STUDIO_FILES = new Set([STUDIO_MOTION_PATH, STUDIO_MANUAL_EDITS_PATH]);
|
||||
const STUDIO_FOLDERS = [".hyperframes/prepared-assets", ".hyperframes/requests"];
|
||||
|
||||
/** Segments as Windows opens them: any case, no trailing dots or spaces, no `:stream` suffix. */
|
||||
function segmentsOf(relPath: string): string[] {
|
||||
return relPath
|
||||
.toLowerCase()
|
||||
.split(/[\\/]/)
|
||||
.map((segment) => withoutTrailingDotsOrSpaces(segment.split(":", 1)[0] ?? ""));
|
||||
}
|
||||
|
||||
function withoutTrailingDotsOrSpaces(segment: string): string {
|
||||
let end = segment.length;
|
||||
while (end > 0 && (segment[end - 1] === "." || segment[end - 1] === " ")) end--;
|
||||
return segment.slice(0, end);
|
||||
}
|
||||
|
||||
// Git metadata and env files hold commands other tools run and secrets: no route reads or writes them.
|
||||
const isVcsOrSecretSegment = (segment: string): boolean =>
|
||||
segment === ".git" || segment.startsWith(".env");
|
||||
|
||||
/** For a project-relative path with `/` separators. */
|
||||
export function isPrivateProjectPath(relPath: string): boolean {
|
||||
const path = relPath.toLowerCase();
|
||||
if (segmentsOf(path).some(isVcsOrSecretSegment)) return true;
|
||||
return (
|
||||
(path === ".hyperframes" || path.startsWith(".hyperframes/")) &&
|
||||
!STUDIO_FILES.has(path) &&
|
||||
!STUDIO_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`))
|
||||
);
|
||||
}
|
||||
/** For a project-relative path with `/` separators; the bundler applies the same rule to preview builds. */
|
||||
export const isPrivateProjectPath = isStudioPrivatePath;
|
||||
|
||||
const projectRelatives = (projectDir: string, filePath: string): string[] => {
|
||||
const rel = (from: string, to: string) => relative(from, to).split(sep).join("/");
|
||||
@@ -90,7 +59,7 @@ const WRITABLE_HIDDEN_FOLDERS = new Set([".hyperframes", ".media"]);
|
||||
/** Writes refuse the project folder, node_modules, and hidden paths but Studio's records and the media ledger. */
|
||||
export function isWritableProjectPath(relPath: string): boolean {
|
||||
if (!relPath || isPrivateProjectPath(relPath)) return false;
|
||||
const segments = segmentsOf(relPath);
|
||||
const segments = projectPathSegments(relPath);
|
||||
return segments.every(
|
||||
(segment, at) =>
|
||||
segment !== "" &&
|
||||
|
||||
@@ -654,6 +654,117 @@ describe("registerPreviewRoutes", () => {
|
||||
expect(plugin?.getAttribute("type")).toBe(AFTER_FONTS_SCRIPT_TYPE);
|
||||
});
|
||||
|
||||
it("does not inline project files no route serves", async () => {
|
||||
const projectDir = createProjectDir();
|
||||
mkdirSync(join(projectDir, ".hyperframes"), { recursive: true });
|
||||
writeFileSync(join(projectDir, ".hyperframes", "handoff.json"), '{"note":"PRIVATE_RECORD"}');
|
||||
writeFileSync(join(projectDir, ".env"), "TOKEN=PRIVATE_ENV");
|
||||
writeFileSync(
|
||||
join(projectDir, "index.html"),
|
||||
`<!doctype html><html><head><link rel="stylesheet" href=".env"></head><body>
|
||||
<div data-composition-id="root" data-width="320" data-height="180"></div>
|
||||
<script src=".hyperframes/handoff.json"></script>
|
||||
</body></html>`,
|
||||
);
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
const app = new Hono();
|
||||
registerPreviewRoutes(
|
||||
app,
|
||||
createAdapter(projectDir, {
|
||||
bundle: (dir, options) =>
|
||||
bundleToSingleHtml(dir, { ...PREVIEW_BUNDLE_OPTIONS, ...options }),
|
||||
}),
|
||||
);
|
||||
|
||||
const html = await (await app.request("http://localhost/projects/demo/preview")).text();
|
||||
|
||||
expect(html).toContain('data-composition-id="root"');
|
||||
expect(html).not.toContain("PRIVATE_RECORD");
|
||||
expect(html).not.toContain("PRIVATE_ENV");
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not serve an env file that index.html links to, but still serves a main file linked from outside",
|
||||
async () => {
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
const preview = async (projectDir: string) => {
|
||||
const app = new Hono();
|
||||
registerPreviewRoutes(
|
||||
app,
|
||||
createAdapter(projectDir, {
|
||||
bundle: async (dir, options) => {
|
||||
try {
|
||||
return await bundleToSingleHtml(dir, { ...PREVIEW_BUNDLE_OPTIONS, ...options });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
return (await app.request("http://localhost/projects/demo/preview")).text();
|
||||
};
|
||||
|
||||
const linkedToEnv = createProjectDir();
|
||||
writeFileSync(join(linkedToEnv, ".env"), "TOKEN=LINKED_ENV_SECRET");
|
||||
rmSync(join(linkedToEnv, "index.html"));
|
||||
if (!tryCreateSymlink(".env", join(linkedToEnv, "index.html"), "file")) return;
|
||||
expect(await preview(linkedToEnv)).not.toContain("LINKED_ENV_SECRET");
|
||||
|
||||
const shared = mkdtempSync(join(tmpdir(), "hf-preview-shared-main-"));
|
||||
tempDirs.push(shared);
|
||||
writeFileSync(
|
||||
join(shared, "main.html"),
|
||||
"<html><head></head><body>SHARED_MAIN</body></html>",
|
||||
);
|
||||
const linkedOut = createProjectDir();
|
||||
rmSync(join(linkedOut, "index.html"));
|
||||
if (!tryCreateSymlink(join(shared, "main.html"), join(linkedOut, "index.html"), "file"))
|
||||
return;
|
||||
expect(await preview(linkedOut)).toContain("SHARED_MAIN");
|
||||
},
|
||||
);
|
||||
|
||||
it("asks for private files to be refused with plain data, so a build thread can join same-content builds", async () => {
|
||||
const projectDir = createProjectDir();
|
||||
writeFileSync(
|
||||
join(projectDir, "index.html"),
|
||||
`<!doctype html><html><head></head><body><div data-composition-id="root"></div></body></html>`,
|
||||
);
|
||||
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
|
||||
// A host that builds on another thread: only plain data crosses, and builds with equal data are shared.
|
||||
const shared = new Map<string, Promise<string>>();
|
||||
const sent: unknown[] = [];
|
||||
let builds = 0;
|
||||
const threaded: StudioApiAdapter["bundle"] = (dir, options = {}) => {
|
||||
const { onRead: _onRead, ...data } = options;
|
||||
expect(Object.values(data).some((value) => typeof value === "function")).toBe(false);
|
||||
sent.push(structuredClone(data));
|
||||
const key = `${dir}\0${JSON.stringify(data)}`;
|
||||
let build = shared.get(key);
|
||||
if (!build) {
|
||||
builds++;
|
||||
build = bundleToSingleHtml(dir, { ...PREVIEW_BUNDLE_OPTIONS, ...data });
|
||||
shared.set(key, build);
|
||||
}
|
||||
return build;
|
||||
};
|
||||
const first = new Hono();
|
||||
const second = new Hono();
|
||||
registerPreviewRoutes(first, createAdapter(projectDir, { bundle: threaded }));
|
||||
registerPreviewRoutes(second, createAdapter(projectDir, { bundle: threaded }));
|
||||
|
||||
await Promise.all([
|
||||
first.request("http://localhost/projects/demo/preview"),
|
||||
second.request("http://localhost/projects/demo/preview"),
|
||||
]);
|
||||
|
||||
expect(sent).toEqual([
|
||||
{ stampHfIds: true, privateFiles: "studio" },
|
||||
{ stampHfIds: true, privateFiles: "studio" },
|
||||
]);
|
||||
expect(builds).toBe(1);
|
||||
});
|
||||
|
||||
async function previewScriptSrcs(bodyGsapTag: string) {
|
||||
const projectDir = createProjectDir();
|
||||
writeFileSync(
|
||||
|
||||
@@ -434,13 +434,15 @@ function resolveProjectMainHtml(
|
||||
const blockHtmlPath = join(projectDir, `${projectId}.html`);
|
||||
recordPreviewRead(projectDir, indexPath);
|
||||
recordPreviewRead(projectDir, blockHtmlPath);
|
||||
if (existsSync(indexPath)) {
|
||||
const existsAndNotPrivate = (file: string) =>
|
||||
existsSync(file) && !isPrivateProjectFile(projectDir, file);
|
||||
if (existsAndNotPrivate(indexPath)) {
|
||||
return {
|
||||
html: readFileSync(indexPath, "utf-8"),
|
||||
compositionPath: "index.html",
|
||||
};
|
||||
}
|
||||
if (existsSync(blockHtmlPath)) {
|
||||
if (existsAndNotPrivate(blockHtmlPath)) {
|
||||
return {
|
||||
html: readFileSync(blockHtmlPath, "utf-8"),
|
||||
compositionPath: `${projectId}.html`,
|
||||
@@ -526,6 +528,7 @@ export function registerPreviewRoutes(
|
||||
let bundled = await adapter.bundle(project.dir, {
|
||||
stampHfIds: true,
|
||||
onRead: (filePath) => recordPreviewRead(project.dir, filePath),
|
||||
privateFiles: "studio",
|
||||
});
|
||||
let mainCompositionPath = "index.html";
|
||||
if (!bundled) {
|
||||
|
||||
@@ -118,7 +118,7 @@ export interface StudioApiAdapter {
|
||||
/** Bundle a project directory into a single HTML string, forwarding `options` over the host's own. */
|
||||
bundle(
|
||||
projectDir: string,
|
||||
options?: Pick<BundleOptions, "stampHfIds" | "onRead">,
|
||||
options?: Pick<BundleOptions, "stampHfIds" | "onRead" | "privateFiles">,
|
||||
): Promise<string | null>;
|
||||
|
||||
/** Optional: a cached `createProjectSignature(dir)`; preview caching checks builds against it. */
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
},
|
||||
"@hyperframes/inspector": {
|
||||
"packed": 858046,
|
||||
"unpacked": 3684092
|
||||
"unpacked": 3722000
|
||||
},
|
||||
"@hyperframes/lint": {
|
||||
"packed": 191022,
|
||||
|
||||
Reference in New Issue
Block a user