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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/packages/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1874,6 +1874,11 @@ lists the newer entries. Run it again with `--just-this` to put back only that
entry's files over the newer edits, or `--back-to-before` to go back to before
it, undoing the newer entries too.

`undo` and `restore` put back only files that Studio itself may write. Package
and lock files, tool and agent configuration, scripts that `package.json` runs,
and hidden or private files keep their current content. Change those in your
editor.

## Render to a file

### `render`
Expand Down
33 changes: 33 additions & 0 deletions packages/core/src/safePath.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,33 @@ describe("toolTrustedFileKind", () => {
["gulpfile.mjs", "tool-config"],
["turbo.json", "tool-config"],
["pyproject.toml", "tool-config"],
["opencode.json", "tool-config"],
["opencode.jsonc", "tool-config"],
["crush.json", "tool-config"],
["docker-compose.override.yml", "tool-config"],
["compose.override.yaml", "tool-config"],
["Dockerfile.dev", "tool-config"],
["web.dockerfile", "tool-config"],
["Containerfile", "tool-config"],
["lefthook-local.yml", "tool-config"],
["lefthook.json", "tool-config"],
["lefthook.toml", "tool-config"],
["Taskfile.dist.yml", "tool-config"],
["nodemon.json", "tool-config"],
["mise.toml", "tool-config"],
["mise.local.toml", "tool-config"],
["mise/config.toml", "tool-config"],
["eslint.config.jsonc", "tool-config"],
["tsconfig.app.json", "tool-config"],
["simple-git-hooks.json", "tool-config"],
["devbox.json", "tool-config"],
["wrangler.jsonc", "tool-config"],
["Gemfile", "tool-config"],
["Vagrantfile", "tool-config"],
["shell.nix", "program"],
["hooks/pre-commit.fish", "program"],
["NODEMON.JSON.", "tool-config"],
["Docker\ufb01le.dev", "tool-config"],
] as const)("names %s %s", (path, kind) => {
expect(toolTrustedFileKind(path)).toBe(kind);
});
Expand All @@ -411,6 +438,12 @@ describe("toolTrustedFileKind", () => {
"media/take~2.mp4",
"assets/scene~10.png",
"assets/config.json",
"compositions/docker.html",
"assets/mise-en-scene.png",
"assets/lefthook.png",
"assets/compose.svg",
"config.toml",
"assets/script.js",
])("leaves %s to the other rules", (path) => {
expect(toolTrustedFileKind(path)).toBeNull();
});
Expand Down
52 changes: 40 additions & 12 deletions packages/core/src/safePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,29 +132,51 @@ const TOOL_CONFIG_FILES = new Set([
"makefile",
"gnumakefile",
"justfile",
"dockerfile",
"procfile",
"lefthook.yml",
"lefthook.yaml",
"turbo.json",
"nx.json",
"docker-compose.yml",
"docker-compose.yaml",
"compose.yml",
"compose.yaml",
"taskfile.yml",
"taskfile.yaml",
"pyproject.toml",
// Agents that read their settings, including commands to run, from the project folder.
"opencode.json",
"opencode.jsonc",
"crush.json",
// Dev servers, environment managers and deploy CLIs that run a command the file names.
"nodemon.json",
"devbox.json",
"devenv.yaml",
"wrangler.toml",
"wrangler.json",
"wrangler.jsonc",
"vercel.json",
"netlify.toml",
"composer.json",
// Ruby and other build files that are code in their own right.
"rakefile",
"gemfile",
"vagrantfile",
"tiltfile",
"earthfile",
"brewfile",
]);
// The same tools' other spellings and the files they load alongside their main config.
const TOOL_CONFIG_FAMILIES = [
/^(?:docker-)?compose(?:\.override)?\.ya?ml$/,
/^(?:dockerfile|containerfile)(?:\..+)?$|\.(?:docker|container)file$/,
/^lefthook(?:-local)?\.(?:ya?ml|jsonc?|toml)$/,
/^taskfile(?:\.dist)?\.ya?ml$/,
/^mise(?:\.[^.]+)*\.toml$/,
/^simple-git-hooks\.(?:json|[cm]?js)$/,
/^[jt]sconfig\..+\.json$/,
];
// Tools load these on their own: vite.config.ts, jest.config.json, docker-compose.yml, gulpfile.js and the like.
const TOOL_CONFIG =
/\.config\.(?:[cm]?[jt]sx?|json5?|ya?ml|toml)$|^(?:gulp|grunt)file\.[cm]?[jt]s$/;
/\.config\.(?:[cm]?[jt]sx?|json[c5]?|ya?ml|toml)$|^(?:gulp|grunt)file\.[cm]?[jt]s$/;
// Coding agents load these on their own, wherever they sit.
const AGENT_INSTRUCTIONS =
/^(agents?|claude|gemini|qwen|crush|warp|conventions|copilot-instructions)(\.[a-z]+)?\.md$/;
// Programs and scripts a shell, an OS or another tool runs; a browser composition never needs them.
const PROGRAM_EXTENSIONS =
"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".split(
"exe com bat cmd ps1 psm1 vbs vbe wsf hta msi scr pif cpl lnk dll so dylib node sh bash zsh fish command jar appimage py rb pl php nix".split(
" ",
);
const PROGRAM = new RegExp(`\\.(?:${PROGRAM_EXTENSIONS.join("|")})$`);
Expand All @@ -174,6 +196,12 @@ function isShortName(segment: string): boolean {
return !extension || TRUSTED_EXTENSIONS.some((trusted) => trusted.startsWith(extension));
}

function isToolConfig(name: string, segments: readonly string[]): boolean {
if (TOOL_CONFIG_FILES.has(name) || TOOL_CONFIG.test(name)) return true;
if (TOOL_CONFIG_FAMILIES.some((family) => family.test(name))) return true;
return name === "config.toml" && segments.at(-2) === "mise";
}

/** What makes a file one another program runs or trusts; see `toolTrustedFileKind`. */
export type ToolTrustedKind =
| "short-name"
Expand All @@ -195,7 +223,7 @@ export function toolTrustedFileKind(relPath: string): ToolTrustedKind | null {
if (segments.some(isShortName)) return "short-name";
if (PROJECT_CONFIG_FILES.has(name)) return "project-config";
if (LOCK_FILES.has(name)) return "lock-file";
if (TOOL_CONFIG_FILES.has(name) || TOOL_CONFIG.test(name)) return "tool-config";
if (isToolConfig(name, segments)) return "tool-config";
if (AGENT_INSTRUCTIONS.test(name)) return "agent-instructions";
if (PROGRAM.test(name)) return "program";
return null;
Expand Down
42 changes: 41 additions & 1 deletion packages/studio-server/src/helpers/safePath.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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, walkDir } from "./safePath";
import { isPrivateProjectFile, isWritableProjectFile, walkDir } from "./safePath";

const hooks = vi.hoisted(() => ({ unreadable: new Map<string, string>() }));
vi.mock("node:fs", async (importOriginal) => {
Expand Down Expand Up @@ -131,3 +131,43 @@ describe("isPrivateProjectFile", () => {
expect(isPrivateProjectFile("/p", "/p/sub/index.html")).toBe(false);
});
});

describe("isWritableProjectFile and the project's package.json", () => {
function projectRunning(pkg: object) {
const projectDir = createProjectDir();
writeFileSync(join(projectDir, "package.json"), JSON.stringify(pkg));
return (path: string) => isWritableProjectFile(projectDir, join(projectDir, path));
}

it("refuses the script files package.json runs, in any spelling the write rule folds", () => {
const writable = projectRunning({
main: "server.js",
bin: { tool: "./bin/tool.mjs" },
scripts: { build: "node ./build.mjs && tsx scripts/gen.ts --out=dist", dev: "vite" },
});
for (const path of ["server.js", "Server.JS", "bin/tool.mjs", "build.mjs", "scripts/gen.ts"])
expect(writable(path), path).toBe(false);
});

it("still writes composition scripts, folders and files package.json does not name", () => {
const writable = projectRunning({ scripts: { build: "vite build --outDir dist" } });
for (const path of ["script.js", "compositions/scene.js", "dist", "index.html"])
expect(writable(path), path).toBe(true);
});

it("reads a package.json changed since the last write", () => {
const projectDir = createProjectDir();
const pkg = join(projectDir, "package.json");
writeFileSync(pkg, JSON.stringify({ scripts: {} }));
expect(isWritableProjectFile(projectDir, join(projectDir, "run.js"))).toBe(true);
writeFileSync(pkg, JSON.stringify({ scripts: { start: "node run.js" } }));
expect(isWritableProjectFile(projectDir, join(projectDir, "run.js"))).toBe(false);
});

it("writes as before when package.json is missing or not JSON", () => {
const projectDir = createProjectDir();
expect(isWritableProjectFile(projectDir, join(projectDir, "server.js"))).toBe(true);
writeFileSync(join(projectDir, "package.json"), "{ not json");
expect(isWritableProjectFile(projectDir, join(projectDir, "server.js"))).toBe(true);
});
});
65 changes: 63 additions & 2 deletions packages/studio-server/src/helpers/safePath.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { lstatSync, readdirSync, type Dirent } from "node:fs";
import { lstatSync, readdirSync, readFileSync, statSync, type Dirent } from "node:fs";
import {
isStudioPrivatePath,
mkdirWithinProject,
Expand Down Expand Up @@ -70,9 +70,70 @@ export function isWritableProjectPath(relPath: string): boolean {
}

export function isWritableProjectFile(projectDir: string, filePath: string): boolean {
return projectRelatives(projectDir, filePath).every(isWritableProjectPath);
return projectRelatives(projectDir, filePath).every((path) =>
isWritableInProject(projectDir, path),
);
}

/** `isWritableProjectPath`, and not a script the project's package.json runs. */
export function isWritableInProject(projectDir: string, relPath: string): boolean {
return isWritableProjectPath(relPath) && !scriptsPackageRuns(projectDir).has(foldedPath(relPath));
}

// A word in package.json that names a JavaScript or TypeScript file: `node server.js`, `tsx ./scripts/build.ts`.
const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
const SHELL_WORD_BREAKS = /[\s;&|()<>"'`=,]+/;
const NO_SCRIPTS: ReadonlySet<string> = new Set();
const packageScripts = new Map<string, { stat: string; files: ReadonlySet<string> }>();

const foldedPath = (path: string): string =>
projectPathSegments(path)
.filter((segment) => segment !== "" && segment !== ".")
.join("/");

/**
* The script files the project's package.json runs (its `main`, `bin` and every script file its scripts name), folded
* as `projectPathSegments` folds. npm, node or a tool runs these with the developer's rights.
*/
function scriptsPackageRuns(projectDir: string): ReadonlySet<string> {
const path = join(projectDir, "package.json");
const stat = statSync(path, { throwIfNoEntry: false });
if (!stat?.isFile()) return NO_SCRIPTS;
const key = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
const cached = packageScripts.get(path);
if (cached?.stat === key) return cached.files;
const files = scriptFilesNamedBy(readPackageJson(path));
packageScripts.set(path, { stat: key, files });
return files;
}

function readPackageJson(path: string): unknown {
try {
return JSON.parse(readFileSync(path, "utf-8"));
} catch {
return null;
}
}

function scriptFilesNamedBy(pkg: unknown): ReadonlySet<string> {
if (!pkg || typeof pkg !== "object") return NO_SCRIPTS;
const { main, bin, scripts }: { main?: unknown; bin?: unknown; scripts?: unknown } = pkg;
const words = [main, ...valuesOf(bin), ...valuesOf(scripts)].flatMap((value) =>
typeof value === "string" ? value.split(SHELL_WORD_BREAKS) : [],
);
const files = words.filter(
(word) => SCRIPT_FILE.test(word) && !word.split(/[\\/]/).includes(".."),
);
return new Set(files.map(foldedPath));
}

const valuesOf = (value: unknown): unknown[] =>
typeof value === "string"
? [value]
: value && typeof value === "object"
? Object.values(value)
: [];

/**
* 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.
Expand Down
Loading
Loading