fix(studio): check every file a folder move or delete takes along (#8143)

A folder move or delete in Studio checked each file inside only by its
name. A script that package.json runs from a subfolder could be moved
aside or deleted with its folder. A move could also land a file on a
path a direct write refuses, such as a script package.json runs or
mise/config.toml, by moving a folder onto the right name.

Now each entry in the folder is checked at its current path with the
same rules a direct delete or rename uses, including the package.json
scripts. For a move, it is also checked at the path where it would
arrive. Ordinary folder moves still work.
This commit is contained in:
Michael Wang
2026-11-18 08:31:08 +00:00
committed by GitHub
parent 7930525024
commit 7ea0129530
3 changed files with 126 additions and 18 deletions
+28 -15
View File
@@ -146,32 +146,45 @@ const valuesOf = (value: unknown): unknown[] =>
: [];
/**
* The first `toolTrustedFileKind` file, `node_modules` or `.git` below `dir`, which a delete or move of the folder
* would take along. Links are not followed.
* The first entry below `dir` a folder delete or move must not take along: one a direct delete or rename refuses, a
* `toolTrustedFileKind` file or a script package.json runs, or `node_modules` or `.git`. Given `to`, a move's
* destination, also one arriving where a direct write refuses. Links are not followed; an unreadable folder is refused.
*/
export function toolTrustedFileWithin(projectDir: string, dir: string): string | null {
return protectedEntryWithin(dir, projectRelativePath(projectDir, dir));
export function protectedEntryWithin(projectDir: string, dir: string, to?: string): string | null {
const from = projectRelativePath(projectDir, dir);
const places = [dir, ...(to === undefined ? [] : [to])].flatMap((at) =>
projectRelatives(projectDir, at),
);
const runs = scriptsPackageRuns(projectDir);
const refused = (sub: string) =>
places.some((place) => {
const at = place ? `${place}/${sub}` : sub;
return toolTrustedFileKind(at) !== null || runs.has(foldedPath(at));
});
const found = refusedEntryBelow(dir, "", refused);
return found === null ? null : [from, found].filter(Boolean).join("/") || ".";
}
const PROTECTED_FOLDERS = new Set(["node_modules", ".git"]);
function protectedEntryWithin(dir: string, rel: string): string | null {
function refusedEntryBelow(
dir: string,
sub: string,
refused: (sub: string) => boolean,
): string | null {
const entries = folderEntries(dir);
if (!entries) return rel || ".";
if (!entries) return sub;
for (const entry of entries) {
const found = protectedEntry(dir, entry, rel ? `${rel}/${entry.name}` : entry.name);
if (found) return found;
const at = sub ? `${sub}/${entry.name}` : entry.name;
if (refused(at)) 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);
if (inside !== null) return inside;
}
return null;
}
function protectedEntry(dir: string, entry: Dirent, at: string): string | null {
if (!entry.isDirectory()) return toolTrustedFileKind(at) ? at : null;
if (toolTrustedFileKind(at) || PROTECTED_FOLDERS.has(projectPathSegments(entry.name)[0] ?? ""))
return at;
return protectedEntryWithin(join(dir, entry.name), at);
}
function folderEntries(dir: string): Dirent[] | null {
try {
return readdirSync(dir, { withFileTypes: true });
@@ -364,6 +364,101 @@ describe("files other programs run or trust", () => {
expect(existsSync(join(project, "compositions"))).toBe(false);
});
describe("a folder move or delete and the scripts package.json runs", () => {
const move = (app: Hono, from: string, newPath: string) =>
app.request(fileUrl(from), {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ newPath }),
});
const runsScripts = (project: string) =>
writeFileSync(
join(project, "package.json"),
JSON.stringify({
main: "lib/index.js",
bin: { tool: "tools/cli.js" },
scripts: { gen: "tsx scripts/gen.ts --out dist" },
}),
);
const plant = (project: string, file: string, content = "mine") => {
mkdirSync(join(project, file, ".."), { recursive: true });
writeFileSync(join(project, file), content);
};
it("refuses to delete or move a folder holding a script package.json names", async () => {
const { app, project } = fixture();
runsScripts(project);
for (const script of ["scripts/gen.ts", "lib/index.js", "tools/cli.js"])
plant(project, script);
for (const folder of ["scripts", "lib", "tools"]) {
const deleted = await app.request(fileUrl(folder), { method: "DELETE" });
expect(deleted.status).toBe(403);
expect(await deleted.json()).toMatchObject({ why: "protected_path" });
const moved = await move(app, folder, `${folder}-aside`);
expect(moved.status).toBe(403);
expect(await moved.json()).toMatchObject({ why: "protected_path" });
}
expect((await move(app, "scripts", "kept/scripts")).status).toBe(403);
for (const script of ["scripts/gen.ts", "lib/index.js", "tools/cli.js"]) {
expect(readFileSync(join(project, script), "utf8")).toBe("mine");
}
});
it("refuses a folder move that would put a file where package.json runs a script", async () => {
const { app, project } = fixture();
runsScripts(project);
plant(project, "tmp/gen.ts", "planted");
plant(project, "tmp/sub/index.js", "planted");
plant(project, "tmp2/GEN.TS", "planted");
for (const [from, to] of [
["tmp", "scripts"],
["tmp", "Scripts"],
["tmp", "scripts."],
["tmp", "scripts "],
["tmp", "scripts"],
["tmp2", "scripts"],
["tmp/sub", "lib"],
] as const) {
const response = await move(app, from, to);
expect(response.status, `${from} -> ${to}`).toBe(403);
expect(await response.json()).toMatchObject({ why: "protected_path" });
}
expect(readdirSync(project).sort()).toEqual(["inside.txt", "package.json", "tmp", "tmp2"]);
expect(readFileSync(join(project, "tmp", "gen.ts"), "utf8")).toBe("planted");
});
it("refuses a folder move that would put config.toml under mise", async () => {
const { app, project } = fixture();
plant(project, "cfg/config.toml", "[tasks]");
for (const [from, to] of [
["cfg", "mise"],
["cfg", "MISE"],
["cfg", "mise."],
["cfg", "tools/mise"],
] as const) {
const response = await move(app, from, to);
expect(response.status, `${from} -> ${to}`).toBe(403);
expect(await response.json()).toMatchObject({ why: "protected_path" });
}
expect(readFileSync(join(project, "cfg", "config.toml"), "utf8")).toBe("[tasks]");
expect((await move(app, "cfg", "settings")).status).toBe(200);
expect(readFileSync(join(project, "settings", "config.toml"), "utf8")).toBe("[tasks]");
});
it("still moves and deletes ordinary folders, script assets included", async () => {
const { app, project } = fixture();
runsScripts(project);
plant(project, "scenes/a.html", "<div></div>");
plant(project, "scenes/gen.ts", "export {}");
plant(project, "assets/scene.js", "export {}");
expect((await move(app, "scenes", "compositions")).status).toBe(200);
expect(readFileSync(join(project, "compositions", "gen.ts"), "utf8")).toBe("export {}");
expect((await move(app, "assets", "media/assets")).status).toBe(200);
expect((await app.request(fileUrl("compositions"), { method: "DELETE" })).status).toBe(200);
expect(existsSync(join(project, "compositions"))).toBe(false);
});
});
describe("a folder holding a received-files record", () => {
const record = (project: string, folder: string, files: string[]) => {
mkdirSync(join(project, folder, ".hyperframes"), { recursive: true });
+3 -3
View File
@@ -42,9 +42,9 @@ import {
mkdirWithinProject,
pinWithinProject,
pinWritableWithinProject,
protectedEntryWithin,
resolveWithinProject,
resolveWritableWithinProject,
toolTrustedFileWithin,
walkDir,
} from "../helpers/safePath.js";
import { backupPathForResponse, snapshotBeforeWrite } from "../helpers/backupJournal.js";
@@ -3077,7 +3077,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
if ("error" in res) return res.error;
const stat = statSync(res.absPath);
if (stat.isDirectory() && toolTrustedFileWithin(res.project.dir, res.absPath)) {
if (stat.isDirectory() && protectedEntryWithin(res.project.dir, res.absPath)) {
return c.json({ error: "forbidden", why: "protected_path" }, 403);
}
const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
@@ -3777,7 +3777,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
}
const isDirectory = statSync(res.absPath, { throwIfNoEntry: false })?.isDirectory() ?? false;
if (isDirectory && toolTrustedFileWithin(res.project.dir, res.absPath)) {
if (isDirectory && protectedEntryWithin(res.project.dir, res.absPath, newAbs)) {
return c.json({ error: "forbidden", why: "protected_path" }, 403);
}
ensureDir(res.project.dir, newAbs);