From 02fbd3979f45dc8773e4747149b574aaae7a02d5 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Tue, 24 Nov 2026 09:54:37 +0000 Subject: [PATCH] fix(studio-server): refuse extensionless files where node tooling may run them (#8682) Below a package.json that does more than run the hyperframes CLI, Studio now refuses an extensionless file name everywhere it refuses .js and .mjs. Node loads an exact extensionless name before its .js, .ts or .json sibling, and a manifest can run one directly. Folders are judged as folders, so renaming, moving and uploading into folders are unchanged. --- docs/packages/cli.mdx | 6 +- .../cli/src/server/followReceivedRecords.ts | 3 +- .../src/helpers/safePath.test.ts | 25 ++++- .../studio-server/src/helpers/safePath.ts | 48 ++++++--- .../src/routes/files.pathSafety.test.ts | 99 +++++++++++++++++++ packages/studio-server/src/routes/files.ts | 12 ++- 6 files changed, 171 insertions(+), 22 deletions(-) diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 614e9a922b..52888fcc61 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -2018,9 +2018,9 @@ and hidden or private files keep their current content. Change those in your editor. Studio never writes TypeScript, JSX or CommonJS files (`.ts`, `.tsx`, `.mts`, -`.cts`, `.jsx`, `.cjs`). It writes `.js` and `.mjs` files only when no -`package.json` in their folder or any folder above it does more than run the -`hyperframes` CLI. A project from `hyperframes init` keeps its composition +`.cts`, `.jsx`, `.cjs`). It writes `.js` and `.mjs` files, and files with no +extension, only when no `package.json` in their folder or any folder above it +does more than run the `hyperframes` CLI. Folders are not affected. A project from `hyperframes init` keeps its composition scripts editable. Once a `package.json` adds its own scripts, an entry point or dependencies, edit that project's scripts in your editor. diff --git a/packages/cli/src/server/followReceivedRecords.ts b/packages/cli/src/server/followReceivedRecords.ts index a3dda9b75d..29422f775c 100644 --- a/packages/cli/src/server/followReceivedRecords.ts +++ b/packages/cli/src/server/followReceivedRecords.ts @@ -60,7 +60,8 @@ async function requestedChange( if (from === null) return null; if (c.req.method !== "PATCH") return { from }; const newPath = textAt(await jsonBody(c), "newPath")[0]; - const to = newPath ? resolveWritableWithinProject(projectDir, newPath) : null; + const kind = statSync(from, { throwIfNoEntry: false })?.isDirectory() ? "folder" : "file"; + const to = newPath ? resolveWritableWithinProject(projectDir, newPath, kind) : null; return to === null ? null : { from, to: onDiskPath(to) }; } diff --git a/packages/studio-server/src/helpers/safePath.test.ts b/packages/studio-server/src/helpers/safePath.test.ts index a91e76d43b..7857fd8669 100644 --- a/packages/studio-server/src/helpers/safePath.test.ts +++ b/packages/studio-server/src/helpers/safePath.test.ts @@ -3,7 +3,12 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { isPrivateProjectFile, isWritableProjectFile, walkDir } from "./safePath"; +import { + isPrivateProjectFile, + isWritableInProject, + isWritableProjectFile, + walkDir, +} from "./safePath"; const hooks = vi.hoisted(() => ({ unreadable: new Map() })); vi.mock("node:fs", async (importOriginal) => { @@ -145,7 +150,8 @@ describe("isWritableProjectFile and Node tooling", () => { mkdirSync(join(projectDir, folder), { recursive: true }); const text = typeof pkg === "string" ? pkg : JSON.stringify(pkg); writeFileSync(join(projectDir, folder, "package.json"), text); - return (path: string) => isWritableProjectFile(projectDir, join(projectDir, path)); + const writable = (path: string) => isWritableProjectFile(projectDir, join(projectDir, path)); + return Object.assign(writable, { projectDir }); } const SCAFFOLD = { name: "demo", @@ -229,6 +235,21 @@ describe("isWritableProjectFile and Node tooling", () => { expect(isWritableProjectFile(projectDir, join(projectDir, "run.js"))).toBe(false); }); + it("refuses extensionless files below a package.json with tooling, but not folders of that name", () => { + const writable = projectWith({ main: "server/start" }); + for (const path of ["server/start", "server/Start.", "bin/www", "config"]) + expect(writable(path), path).toBe(false); + mkdirSync(join(writable.projectDir, "assets")); + expect(writable("assets")).toBe(true); + expect(isWritableInProject(writable.projectDir, "new-folder", "folder")).toBe(true); + expect(isWritableInProject(writable.projectDir, "new-folder", "file")).toBe(false); + }); + + it("writes extensionless files below a package.json that only runs hyperframes", () => { + const writable = projectWith(SCAFFOLD); + for (const path of ["server/start", "notes"]) expect(writable(path), path).toBe(true); + }); + it("writes composition scripts when no package.json covers them", () => { const projectDir = createProjectDir(); expect(isWritableProjectFile(projectDir, join(projectDir, "run.js"))).toBe(true); diff --git a/packages/studio-server/src/helpers/safePath.ts b/packages/studio-server/src/helpers/safePath.ts index 475b3d5b87..842f554a86 100644 --- a/packages/studio-server/src/helpers/safePath.ts +++ b/packages/studio-server/src/helpers/safePath.ts @@ -80,25 +80,41 @@ export function isWritableProjectPath(relPath: string): boolean { ); } -export function isWritableProjectFile(projectDir: string, filePath: string): boolean { +export type EntryKind = "file" | "folder"; + +const entryKindAt = (path: string): EntryKind => + statSync(path, { throwIfNoEntry: false })?.isDirectory() ? "folder" : "file"; + +export function isWritableProjectFile( + projectDir: string, + filePath: string, + kind: EntryKind = entryKindAt(filePath), +): boolean { return projectRelatives(projectDir, filePath).every((path) => - isWritableInProject(projectDir, path), + isWritableInProject(projectDir, path, kind), ); } /** `isWritableProjectPath`, and not a script the project's Node tooling may run. */ -export function isWritableInProject(projectDir: string, relPath: string): boolean { - return isWritableProjectPath(relPath) && !nodeMayRun(projectDir, relPath); +export function isWritableInProject( + projectDir: string, + relPath: string, + kind: EntryKind = entryKindAt(resolve(projectDir, relPath)), +): boolean { + return isWritableProjectPath(relPath) && !nodeMayRun(projectDir, relPath, kind); } const NODE_ONLY_SCRIPT = /\.(?:[cm]?ts|tsx|jsx|cjs)$/; const BROWSER_OR_NODE_SCRIPT = /\.m?js$/; +const isExtensionless = (name: string) => name !== "" && !name.includes("."); -/** A Node-only script, or `.js`/`.mjs` below (at any depth, past the project too) a package.json that is not the scaffold's. */ -function nodeMayRun(projectDir: string, relPath: string): boolean { +/** A Node-only script, or `.js`/`.mjs` or an extensionless file below (at any depth, past the project too) a package.json that is not the scaffold's. */ +function nodeMayRun(projectDir: string, relPath: string, kind: EntryKind): boolean { const name = foldedPath(relPath).split("/").at(-1) ?? ""; if (NODE_ONLY_SCRIPT.test(name)) return true; - if (!BROWSER_OR_NODE_SCRIPT.test(name)) return false; + const sharedWithNode = + BROWSER_OR_NODE_SCRIPT.test(name) || (kind === "file" && isExtensionless(name)); + if (!sharedWithNode) return false; const folder = dirname(resolve(projectDir, relPath)); return [folder, realFilePath(folder)].some((from) => foldersUp(from).some(manifestBringsNode)); } @@ -169,10 +185,10 @@ export function protectedEntryWithin(projectDir: string, dir: string, to?: strin const places = [dir, ...(to === undefined ? [] : [to])].flatMap((at) => projectRelatives(projectDir, at), ); - const refused = (sub: string) => + const refused = (sub: string, kind: EntryKind) => places.some((place) => { const at = place ? `${place}/${sub}` : sub; - return toolTrustedFileKind(at) !== null || nodeMayRun(projectDir, at); + return toolTrustedFileKind(at) !== null || nodeMayRun(projectDir, at, kind); }); const found = refusedEntryBelow(dir, "", refused); return found === null ? null : [from, found].filter(Boolean).join("/") || "."; @@ -180,16 +196,18 @@ export function protectedEntryWithin(projectDir: string, dir: string, to?: strin const PROTECTED_FOLDERS = new Set(["node_modules", ".git"]); +const kindOf = (entry: Dirent): EntryKind => (entry.isDirectory() ? "folder" : "file"); + function refusedEntryBelow( dir: string, sub: string, - refused: (sub: string) => boolean, + refused: (sub: string, kind: EntryKind) => boolean, ): string | null { const entries = folderEntries(dir); if (!entries) return sub; for (const entry of entries) { const at = sub ? `${sub}/${entry.name}` : entry.name; - if (refused(at)) return at; + if (refused(at, kindOf(entry))) return at; if (!entry.isDirectory()) continue; if (PROTECTED_FOLDERS.has(projectPathSegments(entry.name)[0] ?? "")) return at; const inside = refusedEntryBelow(join(dir, entry.name), at, refused); @@ -207,9 +225,13 @@ function folderEntries(dir: string): Dirent[] | null { } } -export function resolveWritableWithinProject(base: string, relativePath: string): string | null { +export function resolveWritableWithinProject( + base: string, + relativePath: string, + kind?: EntryKind, +): string | null { const resolved = resolveWithinProject(base, relativePath); - return resolved && isWritableProjectFile(base, resolved) ? resolved : null; + return resolved && isWritableProjectFile(base, resolved, kind) ? resolved : null; } export function pinWritableWithinProject(base: string, relativePath: string): string | null { diff --git a/packages/studio-server/src/routes/files.pathSafety.test.ts b/packages/studio-server/src/routes/files.pathSafety.test.ts index f1347c98d1..163738c37e 100644 --- a/packages/studio-server/src/routes/files.pathSafety.test.ts +++ b/packages/studio-server/src/routes/files.pathSafety.test.ts @@ -528,6 +528,105 @@ describe("files other programs run or trust", () => { expect(saved.status).toBe(200); }); + const create = (app: Hono, path: string) => + app.request(fileUrl(path), { method: "POST", body: "planted" }); + + // Node loads an exact extensionless name before its `.js`, `.ts` or `.json` sibling. + const SHADOWS = [ + { + name: "server/start beside server/start.js, the manifest's main", + pkg: { main: "server/start", scripts: { start: "node ." } }, + sibling: "server/start.js", + target: "server/start", + }, + { + name: "lib/util beside lib/util.js", + pkg: { scripts: { build: "node lib/build.js" } }, + sibling: "lib/util.js", + target: "lib/util", + }, + { + name: "lib/util beside lib/util.ts", + pkg: { devDependencies: { tsx: "^4.0.0" } }, + sibling: "lib/util.ts", + target: "lib/util", + }, + { + name: "config beside config.json", + pkg: { scripts: { start: "node server.mjs" } }, + sibling: "config.json", + target: "config", + }, + ]; + + it.each(SHADOWS)("never plants $name", async ({ pkg, sibling, target }) => { + const { app, project } = fixture(); + manifest(project, "", pkg); + plant(project, sibling); + await expectRefused(await create(app, target), "create"); + await expectRefused(await move(app, "inside.txt", target), "rename onto"); + plant(project, "incoming/payload", "planted"); + const parent = target.includes("/") ? target.slice(0, target.lastIndexOf("/")) : ""; + await expectRefused( + await move(app, "incoming", parent ? `${parent}/incoming` : "incoming-moved"), + "folder move in", + ); + const uploaded = await upload(app, parent, target.split("/").at(-1)!); + expect((await uploaded.json()).skipped, "upload").toContain(target.split("/").at(-1)); + expect(existsSync(join(project, target))).toBe(false); + expect(readFileSync(join(project, "inside.txt"), "utf8")).toBe("inside"); + }); + + it.each([ + "server/Start", + "server/START", + "server/start.", + "server/start ", + "server/\uff53tart", + ])("refuses %s, a spelling of server/start", async (path) => { + const { app, project } = fixture(); + manifest(project, "", { main: "server/start" }); + plant(project, "server/start.js"); + await expectRefused(await create(app, path), path); + expect(readdirSync(join(project, "server"))).toEqual(["start.js"]); + }); + + it("never overwrites, deletes or moves bin/www, an extensionless script package.json runs", async () => { + const { app, project } = fixture(); + manifest(project, "", { scripts: { start: "node ./bin/www" } }); + plant(project, "bin/www"); + const overwrite = await app.request(fileUrl("bin/www"), { + method: "PUT", + headers: { "If-Match": fileContentVersion("mine") }, + body: "planted", + }); + await expectRefused(overwrite, "overwrite"); + await expectRefused(await app.request(fileUrl("bin/www"), { method: "DELETE" }), "delete"); + await expectRefused(await app.request(fileUrl("bin"), { method: "DELETE" }), "folder delete"); + await expectRefused(await move(app, "bin", "bin-aside"), "folder move away"); + expect(readFileSync(join(project, "bin", "www"), "utf8")).toBe("mine"); + }); + + it("still renames, moves and uploads into folders in a project with Node tooling", async () => { + const { app, project } = fixture(); + manifest(project, "", { main: "server/start", scripts: { start: "node ." } }); + plant(project, "scenes/intro.html", "
"); + plant(project, "media/logo.png", "png"); + expect((await move(app, "scenes", "compositions")).status).toBe(200); + expect((await move(app, "media", "assets/media")).status).toBe(200); + expect((await upload(app, "assets/notes", "credits.txt")).status).toBe(201); + expect(existsSync(join(project, "assets", "notes", "credits.txt"))).toBe(true); + expect((await create(app, "compositions/outro.html")).status).toBe(201); + }); + + it("still writes extensionless files in a default hyperframes init project", async () => { + const { app, project } = fixture(); + manifest(project, "", SCAFFOLD); + plant(project, "server/start.js"); + expect((await create(app, "server/start")).status).toBe(201); + expect((await create(app, "notes")).status).toBe(201); + }); + it("refuses a folder move that would put config.toml under mise", async () => { const { app, project } = fixture(); plant(project, "cfg/config.toml", "[tasks]"); diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 87d5c487bc..b5ad054453 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -3450,13 +3450,17 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { return c.json({ error: "newPath required" }, 400); } - const newAbs = resolveWritableWithinProject(res.project.dir, newPath); + const isDirectory = statSync(res.absPath, { throwIfNoEntry: false })?.isDirectory() ?? false; + const newAbs = resolveWritableWithinProject( + res.project.dir, + newPath, + isDirectory ? "folder" : "file", + ); if (!newAbs) return forbiddenWriteTarget(c, res.project.dir, newPath); if (existsSync(newAbs)) { return c.json({ error: "already exists" }, 409); } - const isDirectory = statSync(res.absPath, { throwIfNoEntry: false })?.isDirectory() ?? false; if (isDirectory && protectedEntryWithin(res.project.dir, res.absPath, newAbs)) { return c.json({ error: "forbidden", why: "protected_path" }, 403); } @@ -3517,7 +3521,9 @@ 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 ? resolveWritableWithinProject(project.dir, subDir) : project.dir; + const targetDir = subDir + ? resolveWritableWithinProject(project.dir, subDir, "folder") + : project.dir; if (!targetDir) return c.json({ error: "forbidden" }, 403); const formData = await c.req.formData();