From b96c82b785ab8fbd9c030c093de9c39e5dc39342 Mon Sep 17 00:00:00 2001 From: James Russo Date: Wed, 11 Nov 2026 07:53:52 +0000 Subject: [PATCH] fix(cli,studio-server): limit registry installs and Studio file writes to project content folders (#7523) * fix(cli,studio-server): limit registry installs and Studio file writes to project content folders Registry blocks and components now install only into the project's compositions, components and assets folders (plus models/ and lib/, which the catalog uses, and notes at the root). node_modules, agent instruction files and programs or scripts are refused at any depth, matched case-insensitively with either separator, and checked again on the path the project's own links lead to. Studio's file routes never read or write git metadata or env files, and every route that writes, renames, deletes, copies or uploads a request-named path refuses the project folder itself, node_modules and hidden files or folders other than .hyperframes/ and .media/, on both the spelled and the link-resolved path. Co-Authored-By: Claude Opus 5.5 * chore(cli,studio-server): trim comments added by the write allowlist Co-Authored-By: Claude Opus 5.5 * fix(cli,studio-server): trim path segments in linear time The trailing dot/space and :stream trims used anchored regexes that backtrack quadratically on long runs of spaces, dots or colons in a request path. Trim with a plain scan instead. Co-Authored-By: Claude Opus 5.5 * fix(cli): refuse example dependencies in add and allow only TEMPLATE.md at the root - addToProject now refuses a block or component that depends on an example, not only an example asked for by name. The installer lets an example write at the project root, so a dependency must not carry that through. - The only file a block may write at the project root is TEMPLATE.md, the catalog's usage note. Any other .md or .txt name could be one a tool loads. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- packages/cli/src/commands/add.test.ts | 23 +++ packages/cli/src/commands/add.ts | 11 ++ packages/cli/src/registry/installer.test.ts | 112 ++++++++++++-- packages/cli/src/registry/installer.ts | 110 +++++++++++-- .../studio-server/src/helpers/safePath.ts | 54 ++++++- .../src/routes/files.pathSafety.test.ts | 146 +++++++++++++++++- packages/studio-server/src/routes/files.ts | 39 +++-- .../studio-server/src/routes/freezeFrame.ts | 8 +- packages/studio-server/src/routes/media.ts | 13 +- 9 files changed, 470 insertions(+), 46 deletions(-) diff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.ts index fd9c55cf0c..b75c60cce7 100644 --- a/packages/cli/src/commands/add.test.ts +++ b/packages/cli/src/commands/add.test.ts @@ -38,6 +38,7 @@ const MANIFEST: RegistryManifest = { { name: "base-component", type: "hyperframes:component" }, { name: "my-component", type: "hyperframes:component" }, { name: "my-example", type: "hyperframes:example" }, + { name: "example-dep-block", type: "hyperframes:block" }, ], }; @@ -152,7 +153,14 @@ const EXAMPLE_ITEM: RegistryItem = { files: [{ path: "index.html", target: "index.html", type: "hyperframes:composition" }], }; +const EXAMPLE_DEP_BLOCK_ITEM: RegistryItem = { + ...BLOCK_ITEM, + name: "example-dep-block", + registryDependencies: ["my-example"], +}; + const ITEM_BY_NAME: Record = { + "example-dep-block": EXAMPLE_DEP_BLOCK_ITEM, "my-block": BLOCK_ITEM, "deprecated-block": DEPRECATED_BLOCK_ITEM, "future-block": FUTURE_BLOCK_ITEM, @@ -472,6 +480,21 @@ describe("runAdd (integration, mocked registry)", () => { } }); + it("refuses a block that depends on an example, before writing anything", async () => { + const dir = tmp(); + try { + writeRegistryConfig(dir); + + await expect( + runAdd({ name: "example-dep-block", projectDir: dir, skipClipboard: true }), + ).rejects.toMatchObject({ code: "example-type" }); + expect(existsSync(join(dir, "index.html"))).toBe(false); + expect(existsSync(join(dir, "compositions"))).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it("throws AddError with code 'unknown-item' for a missing name", async () => { const dir = tmp(); try { diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index a995239e67..bd2968114f 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -304,6 +304,7 @@ async function installAll( force: boolean, requestedName: string, variableValues: Record | null, + installDirs: string[], ): Promise<{ written: string[]; preserved: string[]; @@ -325,6 +326,7 @@ async function installAll( // Only the item the user named. A dependency dragged in behind it never // declared these variables and must not be rewritten by them. variableValues: planItem.name === requestedName ? variableValues : null, + installDirs, }), ); } @@ -415,6 +417,14 @@ export async function addToProject( "example-type", ); } + // An example lays out a whole project, so the installer trusts it with the root; a block may not bring one along. + const exampleDependency = resolved.find((dep) => dep.type === "hyperframes:example"); + if (exampleDependency) { + throw new AddError( + `"${item.name}" depends on the example "${exampleDependency.name}", which \`add\` does not install.`, + "example-type", + ); + } // 3. Compatibility-gate every item we're about to install (dependencies // included) before writing anything. @@ -438,6 +448,7 @@ export async function addToProject( opts.force ?? false, item.name, variableValues, + [config.paths.blocks, config.paths.components, config.paths.assets], ); // Report what landed, not what was asked for: a failed install throws above, diff --git a/packages/cli/src/registry/installer.test.ts b/packages/cli/src/registry/installer.test.ts index e127e987c9..b29a78c2e4 100644 --- a/packages/cli/src/registry/installer.test.ts +++ b/packages/cli/src/registry/installer.test.ts @@ -3,13 +3,15 @@ import { mkdirSync, mkdtempSync, readFileSync, + readdirSync, writeFileSync, symlinkSync, rmSync, existsSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { describe, expect, it, onTestFinished, vi } from "vitest"; import type { RegistryItem } from "@hyperframes/core"; @@ -35,11 +37,15 @@ const item = { description: "Chart component", type: "hyperframes:component", files: [ - { path: "data-chart.html", target: "components/data-chart.html", type: "hyperframes:snippet" }, + { + path: "data-chart.html", + target: "compositions/data-chart.html", + type: "hyperframes:snippet", + }, ], } as unknown as RegistryItem; -const target = "components/data-chart.html"; +const target = "compositions/data-chart.html"; describe("hasLocalEdits", () => { it("treats a file with no record as edited", () => { @@ -64,7 +70,7 @@ describe("installItem", () => { it("rejects a target directory symlink that escapes the project even with force", async () => { const dir = project(); const outside = project(); - symlinkSync(outside, join(dir, "components"), "junction"); + symlinkSync(outside, join(dir, "compositions"), "junction"); await expect(installItem(item, { destDir: dir, force: true })).rejects.toThrow(/Unsafe target/); expect(existsSync(join(outside, "data-chart.html"))).toBe(false); }); @@ -92,6 +98,88 @@ describe("installItem", () => { expect(existsSync(join(dir, configTarget))).toBe(false); }); + it.each([ + "node_modules/@hyperframes/core/audio-carve.js", + "compositions/node_modules/pkg/index.js", + "Node_Modules\\pkg\\index.js", + "compositions/CLAUDE.md", + "compositions\\AGENTS.md", + "assets/Claude.local.md", + "GEMINI.md", + "QWEN.md", + "CONVENTIONS.md", + "notes.txt", + "whisper-cli.exe", + "assets/whisper-cli.EXE", + "compositions/conftest.py", + "lib/install.sh", + "vite.config.js", + "index.html", + "src/index.js", + "scripts\\postinstall.js", + ])("refuses the install target %s before writing anything", async (planted) => { + const dir = project(); + const hostile = { ...item, files: [{ ...item.files[0]!, target: planted }] }; + await expect(installItem(hostile, { destDir: dir, force: true })).rejects.toThrow( + /Unsafe target/, + ); + expect(readdirSync(dir)).toEqual([]); + }); + + it("writes into the standard folders, the configured ones and root notes", async () => { + const dir = project(); + const targets = [ + "compositions/a.html", + "compositions/components/b.html", + "assets/fonts/c.woff2", + "models/d.glb", + "lib/e.iife.js", + "TEMPLATE.md", + "scenes/f.html", + ]; + const files = targets.map((name) => ({ ...item.files[0]!, path: name, target: name })); + await expect(installItem({ ...item, files }, { destDir: dir })).rejects.toThrow( + /scenes\/f\.html.*outside the project's blocks/, + ); + await installItem({ ...item, files }, { destDir: dir, installDirs: ["scenes/"] }); + for (const name of targets) expect(existsSync(join(dir, name))).toBe(true); + }); + + it.each([".", "", "node_modules", ".claude", "./"])( + "opens nothing for the configured folder %j", + async (configured) => { + const dir = project(); + const hostile = { ...item, files: [{ ...item.files[0]!, target: "settings.json" }] }; + await expect( + installItem(hostile, { destDir: dir, installDirs: [configured] }), + ).rejects.toThrow(/Unsafe target/); + }, + ); + + it("refuses a target that the project's own link leads into node_modules", async () => { + const dir = project(); + mkdirSync(join(dir, "node_modules", "pkg"), { recursive: true }); + symlinkSync(join(dir, "node_modules", "pkg"), join(dir, "compositions"), "junction"); + await expect(installItem(item, { destDir: dir, force: true })).rejects.toThrow(/node_modules/); + expect(readdirSync(join(dir, "node_modules", "pkg"))).toEqual([]); + }); + + it("accepts every target in the official catalog", async () => { + const registry = join(dirname(fileURLToPath(import.meta.url)), "../../../../registry"); + const dir = project(); + let checked = 0; + for (const kind of ["blocks", "components", "examples"]) { + for (const name of readdirSync(join(registry, kind))) { + const manifest = join(registry, kind, name, "registry-item.json"); + if (!existsSync(manifest)) continue; + const official = JSON.parse(readFileSync(manifest, "utf8")) as RegistryItem; + await prepareItem(official, { destDir: dir }); + checked += official.files.length; + } + } + expect(checked).toBeGreaterThan(1000); + }); + it("lets an example bring its own package.json and .gitignore", async () => { const dir = project(); const example = { @@ -113,7 +201,7 @@ describe("installItem", () => { it("preserves directory symlinks whose destination stays inside the project", async () => { const dir = project(); mkdirSync(join(dir, "actual")); - symlinkSync(join(dir, "actual"), join(dir, "components"), "junction"); + symlinkSync(join(dir, "actual"), join(dir, "compositions"), "junction"); await installItem(item, { destDir: dir, force: true }); expect(readFileSync(join(dir, "actual/data-chart.html"), "utf8")).toContain("REGISTRY VERSION"); }); @@ -129,12 +217,12 @@ describe("installItem", () => { const dir = project(); const conflicting = { ...item, - files: names.map((name) => ({ ...item.files[0]!, target: `components/${name}` })), + files: names.map((name) => ({ ...item.files[0]!, target: `compositions/${name}` })), }; await expect(installItem(conflicting, { destDir: dir, force: true })).rejects.toThrow( /duplicate/, ); - expect(existsSync(join(dir, "components"))).toBe(false); + expect(existsSync(join(dir, "compositions"))).toBe(false); } } finally { vi.restoreAllMocks(); @@ -192,7 +280,7 @@ describe("installItem", () => { it("keeps a file that was there before any install", async () => { const dir = project(); - mkdirSync(join(dir, "components"), { recursive: true }); + mkdirSync(join(dir, "compositions"), { recursive: true }); writeFileSync(join(dir, target), "PRE-EXISTING\n", "utf-8"); const result = await installItem(item, { destDir: dir }); @@ -222,7 +310,9 @@ describe("installItem", () => { dimensions: { width: 100, height: 100 }, duration: 1, type: "hyperframes:block", - files: [{ path: "hero.html", target: "blocks/hero.html", type: "hyperframes:composition" }], + files: [ + { path: "hero.html", target: "compositions/hero.html", type: "hyperframes:composition" }, + ], } as unknown as RegistryItem; const dir = project(); @@ -243,13 +333,13 @@ describe("installing several items, as a dependency plan does", () => { files: [ { path: "shared-caption.html", - target: "components/shared-caption.html", + target: "compositions/shared-caption.html", type: "hyperframes:snippet", }, ], } as unknown as RegistryItem; - const otherTarget = "components/shared-caption.html"; + const otherTarget = "compositions/shared-caption.html"; it("keeps a record for every item, not just the last one installed", () => { // `add` installs dependencies first and the requested item last. A record diff --git a/packages/cli/src/registry/installer.ts b/packages/cli/src/registry/installer.ts index 650b88697a..ec3960208f 100644 --- a/packages/cli/src/registry/installer.ts +++ b/packages/cli/src/registry/installer.ts @@ -33,6 +33,11 @@ export interface InstallOptions { * per-mount values are strictly better when a mount exists. */ variableValues?: Record | null; + /** + * Project folders a block or component may write into, on top of the standard layout: the project's configured + * `paths` from hyperframes.json. + */ + installDirs?: string[]; } export interface InstallResult { @@ -140,6 +145,53 @@ const EXAMPLE_DOTFILES = new Set([".gitignore"]); // A Windows short name such as `CLAUDE~1` or `PACKAG~1.JSO` can open any long name on NTFS. const isShortName = (part: string): boolean => /~\d+(\.|$)/.test(part); +// Where a block or component may write: the standard project layout (the official catalog's 3D models and vendored +// browser scripts sit in `models/` and `lib/`), plus the project's configured folders. Anything else in a project is +// someone else's: installed packages, tool settings, scripts other programs run. +const STANDARD_INSTALL_DIRS = ["compositions", "assets", "models", "lib"]; +// The one file a block may leave at the project root: the catalog's usage note. Any other name could be one a tool loads. +const ROOT_NOTES = new Set(["template.md"]); +// Coding agents load these on their own, wherever they sit. +const AGENT_INSTRUCTIONS = /^(agents?|claude|gemini|copilot-instructions)(\.[a-z]+)?\.md$/; +// Programs and scripts a shell, an OS or another tool runs; a browser composition never needs them. +const EXECUTABLE = + /\.(exe|com|bat|cmd|ps1|psm1|vbs|vbe|wsf|hta|msi|scr|pif|cpl|lnk|dll|so|dylib|node|sh|bash|zsh|command|jar|appimage|py|rb|pl|php)$/; + +function withoutTrailingDotsOrSpaces(part: string): string { + let end = part.length; + while (end > 0 && (part[end - 1] === "." || part[end - 1] === " ")) end--; + return part.slice(0, end); +} + +/** Path segments as a case-insensitive file system compares them, either separator, no trailing dots or spaces. */ +function targetSegments(path: string): string[] { + return path + .normalize("NFC") + .toLowerCase() + .split(/[\\/]/) + .map(withoutTrailingDotsOrSpaces) + .filter((part, at, parts) => part !== "" || at === parts.length - 1); +} + +/** Configured folders as segment lists; one that names the root, a hidden folder or node_modules opens nothing. */ +function installDirSegments(dirs: string[]): string[][] { + return dirs + .map((dir) => targetSegments(dir).filter((part) => part !== "")) + .filter( + (parts) => + parts.length > 0 && + parts.every( + (part) => !part.startsWith(".") && part !== "node_modules" && !isShortName(part), + ), + ); +} + +function inInstallDir(dirs: string[], installDirs: string[][]): boolean { + return installDirs.some( + (allowed) => allowed.length <= dirs.length && allowed.every((part, at) => dirs[at] === part), + ); +} + function isHiddenConfigFile(file: string, example: boolean): boolean { if (file === ".gitkeep" || (example && EXAMPLE_DOTFILES.has(file))) return false; return file.startsWith("."); @@ -147,7 +199,12 @@ function isHiddenConfigFile(file: string, example: boolean): boolean { type TargetRule = [ reason: string, - applies: (dirs: string[], file: string, example: boolean) => boolean, + applies: ( + dirs: string[], + file: string, + example: boolean, + installDirs: string[][] | null, + ) => boolean, ]; const CONFIG_TARGET_RULES: TargetRule[] = [ @@ -162,13 +219,32 @@ const CONFIG_TARGET_RULES: TargetRule[] = [ "it would replace project configuration", (_dirs, file, example) => !example && PROJECT_FILES.has(file), ], + ["it writes into node_modules", (dirs) => dirs.includes("node_modules")], + ["it writes an agent instruction file", (_dirs, file) => AGENT_INSTRUCTIONS.test(file)], + ["it writes a program or script", (_dirs, file) => EXECUTABLE.test(file)], + [ + "it writes outside the project's blocks, components and assets folders", + (dirs, file, example, installDirs) => + !example && + installDirs !== null && + !inInstallDir(dirs, installDirs) && + !(dirs.length === 0 && ROOT_NOTES.has(file)), + ], ]; -function configTargetError(target: string, type: RegistryItem["type"]): string | null { - const parts = target.split(/[\\/]/).map((part) => part.toLowerCase()); +/** Why a target is refused, or null. `installDirs` null skips the folder allowlist, for a path links already moved. */ +function configTargetError( + target: string, + type: RegistryItem["type"], + installDirs: string[][] | null, +): string | null { + const parts = targetSegments(target); const file = parts.pop() ?? ""; const example = type === "hyperframes:example"; - return CONFIG_TARGET_RULES.find(([, applies]) => applies(parts, file, example))?.[0] ?? null; + return ( + CONFIG_TARGET_RULES.find(([, applies]) => applies(parts, file, example, installDirs))?.[0] ?? + null + ); } /** @@ -177,7 +253,12 @@ function configTargetError(target: string, type: RegistryItem["type"]): string | * install time so a registry that bypasses schema validation still can't write * outside the project. */ -function assertSafeTarget(destDir: string, target: string, type: RegistryItem["type"]): void { +function assertSafeTarget( + destDir: string, + target: string, + type: RegistryItem["type"], + installDirs: string[][], +): void { if (isAbsolute(target)) { throw new Error(`Unsafe target "${target}": absolute paths are not allowed.`); } @@ -192,7 +273,7 @@ function assertSafeTarget(destDir: string, target: string, type: RegistryItem["t if (rel.startsWith("..") || isAbsolute(rel)) { throw new Error(`Unsafe target "${target}": resolves outside destDir ${destDir}.`); } - const configError = configTargetError(target, type); + const configError = configTargetError(target, type, installDirs); if (configError) throw new Error(`Unsafe target "${target}": ${configError}.`); } @@ -312,12 +393,16 @@ export async function prepareItem( const destDir = resolve(options.destDir); // Validate all targets up-front so a malformed item fails before any write. + const installDirs = installDirSegments([ + ...STANDARD_INSTALL_DIRS, + ...(options.installDirs ?? []), + ]); for (const file of item.files) { - assertSafeTarget(destDir, file.target, item.type); + assertSafeTarget(destDir, file.target, item.type, installDirs); } const root = registryRoot(destDir); - validatePhysicalTargets(root, item.files); + validatePhysicalTargets(root, item.files, item.type); const record = readInstallRecord(root); const budget = { remainingBytes: 512 * 1024 * 1024 }; @@ -369,7 +454,11 @@ export function publishItem({ root, outcomes: prepared, force }: PreparedItem): }; } -function validatePhysicalTargets(root: string, files: FileTarget[]): void { +function validatePhysicalTargets( + root: string, + files: FileTarget[], + type: RegistryItem["type"], +): void { const targets = new Set(); const aliasKey = (path: string): string => process.platform === "win32" || process.platform === "darwin" @@ -378,6 +467,9 @@ function validatePhysicalTargets(root: string, files: FileTarget[]): void { const recordKey = aliasKey(registryTargetPath(root, INSTALL_RECORD)); for (const file of files) { const path = registryTargetPath(root, file.target); + // Where the project's own links lead: still never into node_modules, hidden folders, agent files or programs. + const configError = configTargetError(relative(root, path), type, null); + if (configError) throw new Error(`Unsafe target "${file.target}": ${configError}.`); const key = aliasKey(path); if (targets.has(key) || key === recordKey) throw new Error("Unsafe target: duplicate or reserved install record"); diff --git a/packages/studio-server/src/helpers/safePath.ts b/packages/studio-server/src/helpers/safePath.ts index 82be9b11dd..b017b57161 100644 --- a/packages/studio-server/src/helpers/safePath.ts +++ b/packages/studio-server/src/helpers/safePath.ts @@ -47,9 +47,28 @@ export function realFilePath(filePath: string): string { 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) && @@ -57,13 +76,42 @@ export function isPrivateProjectPath(relPath: string): boolean { ); } -export function isPrivateProjectFile(projectDir: string, filePath: string): boolean { +const projectRelatives = (projectDir: string, filePath: string): string[] => { const rel = (from: string, to: string) => relative(from, to).split(sep).join("/"); - return [rel(projectDir, filePath), rel(realFilePath(projectDir), realFilePath(filePath))].some( - isPrivateProjectPath, + return [rel(projectDir, filePath), rel(realFilePath(projectDir), realFilePath(filePath))]; +}; + +export function isPrivateProjectFile(projectDir: string, filePath: string): boolean { + return projectRelatives(projectDir, filePath).some(isPrivateProjectPath); +} + +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); + return segments.every( + (segment, at) => + segment !== "" && + segment !== "node_modules" && + (!segment.startsWith(".") || (at === 0 && WRITABLE_HIDDEN_FOLDERS.has(segment))), ); } +export function isWritableProjectFile(projectDir: string, filePath: string): boolean { + return projectRelatives(projectDir, filePath).every(isWritableProjectPath); +} + +export function resolveWritableWithinProject(base: string, relativePath: string): string | null { + const resolved = resolveWithinProject(base, relativePath); + return resolved && isWritableProjectFile(base, resolved) ? resolved : null; +} + +export function pinWritableWithinProject(base: string, relativePath: string): string | null { + return pinResolved(base, resolveWritableWithinProject(base, relativePath)); +} + /** * `resolveWithinProject` with every link inside the project resolved now, so a write to the result lands on the * file checked here even if a link on the way is retargeted before the write. diff --git a/packages/studio-server/src/routes/files.pathSafety.test.ts b/packages/studio-server/src/routes/files.pathSafety.test.ts index 9f11493b2f..e0aa597cd2 100644 --- a/packages/studio-server/src/routes/files.pathSafety.test.ts +++ b/packages/studio-server/src/routes/files.pathSafety.test.ts @@ -18,7 +18,11 @@ import { registerFileRoutes } from "./files"; import { createStudioApi } from "../createStudioApi"; import { fileContentVersion } from "../helpers/fileVersion"; import { ProjectRootMissingError } from "@hyperframes/core"; -import { mkdirWithinProject } from "../helpers/safePath"; +import { + isPrivateProjectPath, + isWritableProjectPath, + mkdirWithinProject, +} from "../helpers/safePath"; import type { StudioApiAdapter } from "../types"; const tempDirs: string[] = []; @@ -610,7 +614,8 @@ describe("upload collision races", () => { expect(readFileSync(join(project, "upload (2).txt"), "utf8")).toBe("new upload"); }); - it.each([".gitignore", "archive.tar.txt"])( + // A hidden name such as `.gitignore` is refused outright (see "git, env and tool files"). + it.each(["archive.tar.txt"])( "retries suffix races without changing extension rules: %s", async (name) => { const { app, project } = fixture(); @@ -816,3 +821,140 @@ describe("routes that write a path from the request", () => { expect((await fine.json()).files).toEqual(["notes.txt"]); }); }); + +describe("git, env and tool files", () => { + const GIT_CONFIG = "[core]\n\tbare = false\n\turl = https://user:token@example.com/repo\n"; + function gitFixture() { + const fx = fixture(); + mkdirSync(join(fx.project, ".git", "hooks"), { recursive: true }); + writeFileSync(join(fx.project, ".git", "config"), GIT_CONFIG); + writeFileSync(join(fx.project, ".env"), "TOKEN=token"); + mkdirSync(join(fx.project, "node_modules", "pkg"), { recursive: true }); + writeFileSync(join(fx.project, "node_modules", "pkg", "index.js"), "module.exports = 1;"); + return fx; + } + const put = (app: Hono, path: string, headers: Record = {}) => + app.request(fileUrl(path), { method: "PUT", headers, body: "planted" }); + const json = (body: unknown) => ({ + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); + + it.each([".git/config", ".GIT/config", ".git\\config", ".git./config", "sub/../.git/config"])( + "never reads or overwrites %s", + async (path) => { + const { app, project } = gitFixture(); + const read = await app.request(fileUrl(path)); + expect([403, 404]).toContain(read.status); + expect(await read.text()).not.toContain("token"); + const write = await put(app, path, { "If-Match": fileContentVersion(GIT_CONFIG) }); + expect([403, 404]).toContain(write.status); + expect((await app.request(fileUrl(path), { method: "DELETE" })).status).toBe(403); + expect(readFileSync(join(project, ".git", "config"), "utf8")).toBe(GIT_CONFIG); + }, + ); + + it.each([ + ".git/hooks/post-checkout", + ".Git/Hooks/pre-commit", + ".env.local", + "node_modules/pkg/evil.js", + "Node_Modules/pkg/evil.js", + "assets\\node_modules\\pkg\\evil.js", + ".claude/settings.json", + ".vscode/settings.json", + "nested/.git/config", + "nested/.envrc", + ])("never creates %s", async (path) => { + const { app, project } = gitFixture(); + expect((await put(app, path, { "If-None-Match": "*" })).status).toBe(403); + expect((await app.request(fileUrl(path), { method: "POST", body: "planted" })).status).toBe( + 403, + ); + const rename = await app.request(fileUrl("inside.txt"), { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ newPath: path }), + }); + expect(rename.status).toBe(403); + expect(existsSync(join(project, path))).toBe(false); + expect(readFileSync(join(project, "inside.txt"), "utf8")).toBe("inside"); + }); + + it("refuses to delete or rename the project folder or anything in node_modules or .git", async () => { + const { app, project } = gitFixture(); + expect((await app.request(fileUrl(""), { method: "DELETE" })).status).toBe(403); + expect((await app.request(fileUrl("node_modules"), { method: "DELETE" })).status).toBe(403); + const moveHooks = await app.request(fileUrl(".git/hooks"), { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ newPath: "hooks" }), + }); + expect([403, 404]).toContain(moveHooks.status); + expect(existsSync(join(project, ".git", "hooks"))).toBe(true); + expect(existsSync(join(project, "node_modules", "pkg", "index.js"))).toBe(true); + }); + + it("does not copy, upload or patch into protected paths", async () => { + const { app, project } = gitFixture(); + writeFileSync(join(project, "node_modules", "pkg", "index.html"), "
"); + const copy = await app.request( + "/projects/p/duplicate-file", + json({ path: "node_modules/pkg/index.js" }), + ); + expect(copy.status).toBe(403); + expect(readdirSync(join(project, "node_modules", "pkg")).sort()).toEqual([ + "index.html", + "index.js", + ]); + for (const dir of [".git/hooks", "node_modules/pkg", ".Claude"]) + expect((await upload(app, dir)).status).toBe(403); + for (const name of [".env", ".gitignore", ".npmrc"]) + expect((await (await upload(app, "", name)).json()).files).toEqual([]); + expect(readFileSync(join(project, ".env"), "utf8")).toBe("TOKEN=token"); + const rollback = await app.request( + `/projects/p/gsap-mutation-rollback/${encodeURIComponent("node_modules/pkg/index.html")}`, + json({ expected: "
", restore: "planted" }), + ); + expect(rollback.status).toBe(403); + expect(readFileSync(join(project, "node_modules", "pkg", "index.html"), "utf8")).toBe( + "
", + ); + }); + + it("refuses a write through an in-project link into .git or node_modules", async (context) => { + const { app, project } = gitFixture(); + linkOrSkip(context, join(project, ".git"), join(project, "scenes"), "dir"); + linkOrSkip(context, join(project, "node_modules", "pkg"), join(project, "lib"), "dir"); + expect((await put(app, "scenes/hooks/pre-commit", { "If-None-Match": "*" })).status).toBe(403); + const viaLink = await put(app, "lib/index.js", { + "If-Match": fileContentVersion("module.exports = 1;"), + }); + expect(viaLink.status).toBe(403); + expect(existsSync(join(project, ".git", "hooks", "pre-commit"))).toBe(false); + expect(readFileSync(join(project, "node_modules", "pkg", "index.js"), "utf8")).toBe( + "module.exports = 1;", + ); + }); + + it("checks a long run of spaces, dots or colons in linear time", () => { + const started = performance.now(); + for (const filler of [" ", ".", ":"]) { + const long = `a${filler.repeat(200_000)}b`; + expect(isPrivateProjectPath(long)).toBe(false); + expect(isWritableProjectPath(`${long}/x.html`)).toBe(true); + expect(isWritableProjectPath(`.git${filler.repeat(200_000)}/config`)).toBe(false); + } + expect(performance.now() - started).toBeLessThan(1_000); + }); + + it("still reads node_modules and writes Studio's own hidden files", async () => { + const { app, project } = gitFixture(); + expect((await app.request(fileUrl("node_modules/pkg/index.js"))).status).toBe(200); + for (const path of [".hyperframes/studio-motion.json", ".media/clip.json"]) { + expect((await put(app, path, { "If-None-Match": "*" })).status).toBe(200); + expect(readFileSync(join(project, path), "utf8")).toBe("planted"); + } + }); +}); diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 72419ab5d2..8e0becca4c 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -36,11 +36,13 @@ import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js"; import { folderGone, isInHiddenOrVendorDir, - isPrivateProjectFile, isSafePath, + isWritableProjectFile, mkdirWithinProject, pinWithinProject, + pinWritableWithinProject, resolveWithinProject, + resolveWritableWithinProject, walkDir, } from "../helpers/safePath.js"; import { backupPathForResponse, snapshotBeforeWrite } from "../helpers/backupJournal.js"; @@ -203,7 +205,7 @@ async function resolveProjectPath( c: RouteContext, adapter: StudioApiAdapter, route: string, - opts?: { mustExist?: boolean; pin?: boolean }, + opts?: { mustExist?: boolean; pin?: boolean; write?: boolean }, ) { const id = c.req.param("id"); const project = await adapter.resolveProject(id); @@ -236,6 +238,9 @@ async function resolveProjectPath( } return { error: c.json({ error: "forbidden", why: "outside_project" }, 403) } as const; } + if (opts?.write && !isWritableProjectFile(project.dir, absPath)) { + return { error: c.json({ error: "forbidden", why: "protected_path" }, 403) } as const; + } if (opts?.mustExist && !existsSync(absPath)) { return { error: c.json({ error: "not found" }, 404) } as const; @@ -247,13 +252,13 @@ async function resolveProjectPath( function resolveProjectFile( c: RouteContext, adapter: StudioApiAdapter, - opts?: { mustExist?: boolean; pin?: boolean }, + opts?: { mustExist?: boolean; pin?: boolean; write?: boolean }, ) { return resolveProjectPath(c, adapter, "files", opts); } function resolveFileMutationContext(c: RouteContext, adapter: StudioApiAdapter, operation: string) { - return resolveProjectPath(c, adapter, `file-mutations/${operation}`, { pin: true }); + return resolveProjectPath(c, adapter, `file-mutations/${operation}`, { pin: true, write: true }); } type MutationTarget = { @@ -452,7 +457,7 @@ function foldAndCommitElementPatchBatches( }> = []; for (const batch of batches) { - const absPath = pinWithinProject(projectDir, batch.sourceFile); + const absPath = pinWritableWithinProject(projectDir, batch.sourceFile); if (!absPath) return { error: "forbidden", sourceFile: batch.sourceFile }; if (resolvedPaths.has(absPath)) return { error: "duplicate", sourceFile: batch.sourceFile }; resolvedPaths.add(absPath); @@ -1055,7 +1060,7 @@ function updateReferences( const rewrite = referenceRewriter(oldPath, newPath, isDirectory, projectPaths(projectDir)); let updatedCount = 0; for (const file of textFiles) { - if (!isSafePath(projectDir, file) || isPrivateProjectFile(projectDir, file)) continue; + if (!isSafePath(projectDir, file) || !isWritableProjectFile(projectDir, file)) continue; const content = readableText(file); if (content === null) continue; @@ -2743,7 +2748,8 @@ async function processUploadedFiles( // The collision suffix chooses a different path; validate that destination // too, including dangling symlinks that existsSync treats as absent. - if (!isSafePath(projectDir, finalPath) || isPrivateProjectFile(projectDir, finalPath)) continue; + if (!isSafePath(projectDir, finalPath) || !isWritableProjectFile(projectDir, finalPath)) + continue; const buffer = Buffer.from(await value.arrayBuffer()); const validation = validateUploadedMediaBuffer(finalName, buffer); @@ -2856,7 +2862,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // ── Write (overwrite) ── api.put("/projects/:id/files/*", async (c) => { - const res = await resolveProjectFile(c, adapter, { pin: true }); + const res = await resolveProjectFile(c, adapter, { pin: true, write: true }); if ("error" in res) return res.error; const body = Buffer.from(await c.req.arrayBuffer()); @@ -2963,7 +2969,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // ── Create (fail if exists) ── api.post("/projects/:id/files/*", async (c) => { - const res = await resolveProjectFile(c, adapter); + const res = await resolveProjectFile(c, adapter, { write: true }); if ("error" in res) return res.error; ensureDir(res.project.dir, res.absPath); @@ -2983,7 +2989,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // ── Delete ── api.delete("/projects/:id/files/*", async (c) => { - const res = await resolveProjectFile(c, adapter, { mustExist: true }); + const res = await resolveProjectFile(c, adapter, { mustExist: true, write: true }); if ("error" in res) return res.error; const stat = statSync(res.absPath); @@ -3165,7 +3171,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { const seen = new Set(); const prepared: FoldedAtomicCutFile[] = []; for (const file of files) { - const absPath = pinWithinProject(project.dir, file.path); + const absPath = pinWritableWithinProject(project.dir, file.path); if (!absPath) return c.json({ error: `forbidden path: ${file.path}` }, 403); if (seen.has(absPath)) return c.json({ error: `duplicate path: ${file.path}` }, 400); seen.add(absPath); @@ -3662,7 +3668,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // ── Rename / Move ── api.patch("/projects/:id/files/*", async (c) => { - const res = await resolveProjectFile(c, adapter, { mustExist: true }); + const res = await resolveProjectFile(c, adapter, { mustExist: true, write: true }); if ("error" in res) return res.error; const body: unknown = await c.req.json(); @@ -3677,7 +3683,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { return c.json({ error: "newPath required" }, 400); } - const newAbs = resolveWithinProject(res.project.dir, newPath); + const newAbs = resolveWritableWithinProject(res.project.dir, newPath); if (!newAbs) { return c.json({ error: "forbidden" }, 403); } @@ -3712,7 +3718,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { } const copyPath = generateCopyPath(project.dir, body.path); - const destAbs = resolveWithinProject(project.dir, copyPath); + const destAbs = resolveWritableWithinProject(project.dir, copyPath); if (!destAbs) { return c.json({ error: "forbidden" }, 403); } @@ -3745,7 +3751,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // Optional subdirectory within the project (e.g. "assets/audio") const subDir = c.req.query("dir") ?? ""; - const targetDir = subDir ? resolveWithinProject(project.dir, subDir) : project.dir; + const targetDir = subDir ? resolveWritableWithinProject(project.dir, subDir) : project.dir; if (!targetDir) return c.json({ error: "forbidden" }, 403); const formData = await c.req.formData(); @@ -3805,6 +3811,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { const res = await resolveProjectPath(c, adapter, "gsap-mutations", { mustExist: true, pin: true, + write: true, }); if ("error" in res) return res.error; @@ -3819,6 +3826,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { const res = await resolveProjectPath(c, adapter, "gsap-mutations-batch", { mustExist: true, pin: true, + write: true, }); if ("error" in res) return res.error; @@ -3842,6 +3850,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { const res = await resolveProjectPath(c, adapter, "gsap-mutation-rollback", { mustExist: true, pin: true, + write: true, }); if ("error" in res) return res.error; diff --git a/packages/studio-server/src/routes/freezeFrame.ts b/packages/studio-server/src/routes/freezeFrame.ts index d8c3484c70..14d0193e9c 100644 --- a/packages/studio-server/src/routes/freezeFrame.ts +++ b/packages/studio-server/src/routes/freezeFrame.ts @@ -4,7 +4,11 @@ import { basename, dirname, join, relative, sep } from "node:path"; import type { Hono } from "hono"; import { findFfBinary } from "@hyperframes/parsers/ff-binaries"; import type { StudioApiAdapter } from "../types.js"; -import { mkdirWithinProject, pinWithinProject } from "../helpers/safePath.js"; +import { + mkdirWithinProject, + pinWithinProject, + pinWritableWithinProject, +} from "../helpers/safePath.js"; import { atomicTempPath, createFileAtomically, @@ -189,7 +193,7 @@ export function registerFreezeFrameRoutes( } const project = await adapter.resolveProject(c.req.param("id")); if (!project) return c.json({ error: "not found" }, 404); - const absPath = pinWithinProject(project.dir, body.path); + const absPath = pinWritableWithinProject(project.dir, body.path); if (!absPath) return c.json({ error: `forbidden path: ${body.path}` }, 403); const read = readExpected(absPath, body.expectedVersion); diff --git a/packages/studio-server/src/routes/media.ts b/packages/studio-server/src/routes/media.ts index d1e993308f..47515434b3 100644 --- a/packages/studio-server/src/routes/media.ts +++ b/packages/studio-server/src/routes/media.ts @@ -4,7 +4,12 @@ import { existsSync } from "node:fs"; import { basename, dirname, extname, join, posix } from "node:path"; import type { MediaProcessingJobState, StudioApiAdapter } from "../types.js"; import { requestedProjectPath } from "../helpers/requestSubPath.js"; -import { mkdirWithinProject, pinWithinProject, resolveWithinProject } from "../helpers/safePath.js"; +import { + mkdirWithinProject, + pinWritableWithinProject, + resolveWithinProject, + resolveWritableWithinProject, +} from "../helpers/safePath.js"; import { probeMediaMetadata } from "../helpers/mediaMetadata.js"; import { forgetJobsFinishedLongerThan } from "../helpers/finishedJobs.js"; @@ -195,14 +200,14 @@ export function registerMediaRoutes( if (requestedOutput && containsNullByte(requestedOutput)) { return c.json({ error: "forbidden" }, 403); } - if (requestedOutput && !resolveWithinProject(project.dir, requestedOutput)) { + if (requestedOutput && !resolveWritableWithinProject(project.dir, requestedOutput)) { return c.json({ error: "forbidden" }, 403); } const taken = outputsInFlight(mediaJobs); const outputAssetPath = requestedOutput ? uniqueAssetPath(project.dir, requestedOutput, taken) : defaultOutputPath(project.dir, inputAssetPath, taken); - const outputPath = pinWithinProject(project.dir, outputAssetPath); + const outputPath = pinWritableWithinProject(project.dir, outputAssetPath); if (!outputPath) return c.json({ error: "forbidden" }, 403); if (inputIsVideo && !VIDEO_OUTPUT_EXTENSIONS.has(extname(outputAssetPath).toLowerCase())) { return c.json({ error: "video background removal output must be .webm or .mov" }, 400); @@ -220,7 +225,7 @@ export function registerMediaRoutes( taken.add(outputAssetPath); backgroundOutputAssetPath = defaultPlatePath(project.dir, inputAssetPath, taken); backgroundOutputPath = - pinWithinProject(project.dir, backgroundOutputAssetPath) ?? undefined; + pinWritableWithinProject(project.dir, backgroundOutputAssetPath) ?? undefined; if (!backgroundOutputPath) { return c.json({ error: "forbidden" }, 403); }