mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-16 19:59:23 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fa68854da |
+7
-3
@@ -59,9 +59,13 @@ This is general guidance for these event types — see [GitHub's documentation](
|
||||
|
||||
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
|
||||
|
||||
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
|
||||
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head, apart from the files described below. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config.
|
||||
On pull requests from authors without write access, the action also replaces what npm and Bun read from the repository root with the base branch's version, wherever the two differ: `.npmrc`, `bunfig.toml` and tracked files in `node_modules/`. In a `package.json` whose `name`, `bin`, `directories` or `workspaces` change the commands it provides, only those fields are replaced, including in other directories if the base branch uses workspaces. The pull request's versions are kept under `.claude-pr/` for reading, except for `node_modules/`. Claude can't edit `.npmrc`, `bunfig.toml`, `node_modules/` or, where one was replaced, `package.json` on these pull requests. The replaced files stay in the working tree for later steps in the job, and if Claude stages everything, its commit can include them, as with the paths above. `restrict_untrusted_prs: false` turns this off.
|
||||
|
||||
This doesn't cover other package managers, the `.env` files and `tsconfig.json` that Bun loads, other files that a hook's own command reads, or a git command that resets the working tree during the session, so keep hooks self-contained as described above. Files that git doesn't track, such as packages an earlier step installed, stay as they are. A file that is the same link on both branches is left as a link.
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config on pull requests from authors with write access.
|
||||
|
||||
### Running code from pull requests
|
||||
|
||||
@@ -88,7 +92,7 @@ Job logs, and job and step names, are text the pull request controls. To turn of
|
||||
|
||||
Bots often open pull requests from branches in your own repository. Runs there usually need no approval and can get secrets, so these steps don't protect you in that case.
|
||||
|
||||
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
|
||||
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied, and tool config comes from the base branch as described [above](#which-files-come-from-the-base-branch-on-pull-requests). The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
|
||||
|
||||
### What a session can leave behind
|
||||
|
||||
|
||||
+23
-5
@@ -39,6 +39,10 @@ import {
|
||||
snapshotSessionFiles,
|
||||
} from "../github/operations/session-guard";
|
||||
import { restoreConfigFromBase } from "../github/operations/restore-config";
|
||||
import {
|
||||
restoreToolConfigFromBase,
|
||||
toolConfigDenyRules,
|
||||
} from "../github/operations/tool-config";
|
||||
import { validateBranchName } from "../github/operations/branch";
|
||||
import { collectActionInputsPresence } from "./collect-inputs";
|
||||
import { updateCommentLink } from "./update-comment-link";
|
||||
@@ -283,6 +287,13 @@ async function run() {
|
||||
|
||||
validateEnvironmentVariables();
|
||||
|
||||
// Tag mode sets claudeBranch only when it branched from the base instead of
|
||||
// checking out the PR's head, as for a closed or merged PR.
|
||||
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
|
||||
const isUntrustedCheckout =
|
||||
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
|
||||
let restoredToolConfig: string[] = [];
|
||||
|
||||
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
|
||||
// Restore them from the base branch before the CLI reads them.
|
||||
//
|
||||
@@ -304,6 +315,11 @@ async function run() {
|
||||
}
|
||||
if (restoreBase) {
|
||||
restoredConfigPaths = restoreConfigFromBase(restoreBase);
|
||||
// Before plugins are installed, which can already start package managers here.
|
||||
if (isUntrustedCheckout) {
|
||||
restoredToolConfig = restoreToolConfigFromBase(restoreBase);
|
||||
restoredConfigPaths.push(...restoredToolConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,12 +339,14 @@ async function run() {
|
||||
promptFile,
|
||||
});
|
||||
|
||||
// Tag mode sets claudeBranch only when it branched from the base instead of
|
||||
// checking out the PR's head, as for a closed or merged PR. The deny rules are
|
||||
// passed separately because text added to claudeArgs can be lost: a comment at
|
||||
// Passed separately because text added to claudeArgs can be lost: a comment at
|
||||
// the end of the user's claude_args would swallow it.
|
||||
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
|
||||
const disallowedTools = checkedOutPrHead ? untrustedPrDisallowedTools : [];
|
||||
const disallowedTools = isUntrustedCheckout
|
||||
? [
|
||||
...untrustedPrDisallowedTools,
|
||||
...toolConfigDenyRules(restoredToolConfig),
|
||||
]
|
||||
: [];
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: hooksOff }),
|
||||
|
||||
@@ -206,7 +206,7 @@ function snapshotSensitivePath(
|
||||
}
|
||||
}
|
||||
|
||||
function ensureClaudePrExcludedFromGit(): void {
|
||||
export function ensureClaudePrExcludedFromGit(): void {
|
||||
const excludePath = execFileSync(
|
||||
"git",
|
||||
["rev-parse", "--git-path", "info/exclude"],
|
||||
@@ -258,7 +258,8 @@ function ensureClaudePrExcludedFromGit(): void {
|
||||
* extends to the runtime itself: `bunx <tool>` runs the tool under `node` when
|
||||
* `node` is on PATH, but on a Bun-only runner Bun executes the script and reads
|
||||
* `bunfig.toml` (e.g. `preload`) from the checkout, so `bunfig.toml` and
|
||||
* `.npmrc` there are PR-controlled runtime config too.
|
||||
* `.npmrc` there are PR-controlled runtime config too. On PRs from authors without
|
||||
* write access, restoreToolConfigFromBase replaces those.
|
||||
*
|
||||
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
|
||||
* calls validateBranchName on it before returning).
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
rmdirSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { dirname } from "path";
|
||||
import {
|
||||
ensureClaudePrExcludedFromGit,
|
||||
SENSITIVE_PATHS,
|
||||
} from "./restore-config";
|
||||
|
||||
// What npm and Bun read from the repository root to decide which program to run and
|
||||
// where to download it from. Config from the base branch can start them, for example
|
||||
// in a hook or an MCP server. node_modules counts because its .bin comes first on PATH,
|
||||
// and package.json because npx looks for commands there first.
|
||||
const TOOL_CONFIG = [".npmrc", "bunfig.toml", "node_modules"];
|
||||
const PACKAGE_JSON = "package.json";
|
||||
|
||||
// The fields that provide commands. A bin that is a string is named after the package,
|
||||
// and npx looks in workspaces too.
|
||||
const COMMAND_FIELDS = ["name", "bin", "directories", "workspaces"];
|
||||
const NO_COMMANDS = "none";
|
||||
|
||||
const MAX_OUTPUT_BYTES = 1024 ** 3;
|
||||
const MAX_PACKAGE_JSON_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
type Entry = { mode: string; oid: string };
|
||||
type Replacement = { path: string; entry: Entry; content?: Buffer };
|
||||
|
||||
// File names can be any bytes. Latin-1 keeps each one intact.
|
||||
const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
|
||||
// No file name or content, which the pull request controls, reaches the log.
|
||||
function warn(what: string, error: unknown): void {
|
||||
const { code, status } = error as { code?: string; status?: number };
|
||||
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
|
||||
}
|
||||
|
||||
function git(args: string[], input = ""): Buffer {
|
||||
return execFileSync("git", args, {
|
||||
stdio: ["pipe", "pipe", "ignore"],
|
||||
input,
|
||||
env: { ...process.env },
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
// A parent that is a file or a looping link means there is nothing there.
|
||||
function onDisk(path: string) {
|
||||
try {
|
||||
return lstatSync(fsPath(path));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// File systems can ignore case, and some the way a character is encoded.
|
||||
const fold = (path: string): string =>
|
||||
fsPath(path).toString().normalize("NFKC").toLowerCase();
|
||||
|
||||
/** Which tool config a path belongs to. */
|
||||
function rootName(path: string): string | undefined {
|
||||
const folded = fold(path);
|
||||
// A directory with one of these names is in the file's place, whatever it holds.
|
||||
const name = TOOL_CONFIG.find(
|
||||
(name) => folded === name || folded.startsWith(`${name}/`),
|
||||
);
|
||||
if (name) return name;
|
||||
// These come from the base branch already, and the index still has the pull
|
||||
// request's version, so nothing here may be rebuilt from it.
|
||||
const isRestored = SENSITIVE_PATHS.some((restored) =>
|
||||
folded.startsWith(`${fold(restored)}/`),
|
||||
);
|
||||
return !isRestored &&
|
||||
(folded === PACKAGE_JSON || folded.endsWith(`/${PACKAGE_JSON}`))
|
||||
? PACKAGE_JSON
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Whether no parent of a path is a link, which could lead out of the checkout. */
|
||||
function hasRealParents(path: string): boolean {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
if (onDisk(dir)?.isSymbolicLink()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function remove(path: string): void {
|
||||
rmSync(fsPath(path), { recursive: true, force: true });
|
||||
// An empty directory would stand in the way of a file of that name.
|
||||
try {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
rmdirSync(fsPath(dir));
|
||||
}
|
||||
} catch {
|
||||
// It isn't empty.
|
||||
}
|
||||
}
|
||||
|
||||
// Each entry is "<mode> <other fields>\t<path>", relative to the working directory.
|
||||
function parseEntries(listing: Buffer, oidField: number): Map<string, Entry> {
|
||||
const entries = new Map<string, Entry>();
|
||||
for (const line of listing.toString("latin1").split("\0")) {
|
||||
const [info, path] = line.split(/\t(.*)/s);
|
||||
if (!info || !path || !rootName(path)) continue;
|
||||
const fields = info.split(" ");
|
||||
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
const pullRequestEntries = (): Map<string, Entry> =>
|
||||
parseEntries(git(["ls-files", "--stage", "-z"]), 1);
|
||||
|
||||
// A checkout with a narrow refspec has no remote-tracking branch, only FETCH_HEAD.
|
||||
function baseEntries(baseBranch: string): Map<string, Entry> {
|
||||
let ref = `refs/remotes/origin/${baseBranch}`;
|
||||
try {
|
||||
git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
|
||||
} catch {
|
||||
ref = "FETCH_HEAD";
|
||||
}
|
||||
return parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
|
||||
}
|
||||
|
||||
/** The stored content of each entry, which no .gitattributes has been applied to. */
|
||||
function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
const blobs = new Map<string, Buffer>();
|
||||
const oids = [...new Set(entries.map(({ oid }) => oid))];
|
||||
if (oids.length === 0) return blobs;
|
||||
const output = git(["cat-file", "--batch"], `${oids.join("\n")}\n`);
|
||||
// "<oid> <type> <size>\n<content>\n", or "<oid> missing\n"
|
||||
for (let at = 0; at < output.length; ) {
|
||||
const end = output.indexOf("\n", at);
|
||||
const [oid, , size] = output.toString("latin1", at, end).split(" ");
|
||||
at = end + 1;
|
||||
if (size === undefined) continue;
|
||||
blobs.set(oid!, output.subarray(at, at + Number(size)));
|
||||
at += Number(size) + 1;
|
||||
}
|
||||
return blobs;
|
||||
}
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
/** Reads a package.json, or returns undefined if it can't be understood. */
|
||||
function readPackageJson(entry: Entry): Json | undefined {
|
||||
if (!isFile(entry)) return undefined;
|
||||
try {
|
||||
const size = Number(git(["cat-file", "-s", entry.oid]).toString());
|
||||
if (size > MAX_PACKAGE_JSON_BYTES) return undefined;
|
||||
// trimStart also drops a byte order mark.
|
||||
const content = git(["cat-file", "blob", entry.oid]).toString().trimStart();
|
||||
const json = JSON.parse(content);
|
||||
return json && typeof json === "object" ? json : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The commands a package.json provides, or undefined if that can't be told. */
|
||||
function commands(entry: Entry | undefined): string | undefined {
|
||||
if (!entry) return NO_COMMANDS;
|
||||
const json = readPackageJson(entry);
|
||||
if (!json) return undefined;
|
||||
if (!json.bin && !json.directories && !json.workspaces) return NO_COMMANDS;
|
||||
return JSON.stringify(COMMAND_FIELDS.map((field) => json[field] ?? null));
|
||||
}
|
||||
|
||||
/**
|
||||
* The root files that .gitattributes makes git write in another encoding, so that what
|
||||
* is on disk is not what git has. The pull request controls .gitattributes.
|
||||
*/
|
||||
function reencodedFiles(): Set<string> {
|
||||
const names = TOOL_CONFIG.filter((name) => name !== "node_modules");
|
||||
const fields = git([
|
||||
"check-attr",
|
||||
"-z",
|
||||
"working-tree-encoding",
|
||||
"--",
|
||||
...names,
|
||||
])
|
||||
.toString()
|
||||
.split("\0");
|
||||
// "<path> <attribute> <value>", each ended by a NUL
|
||||
return new Set(
|
||||
names.filter((_, i) => {
|
||||
const value = fields[i * 3 + 2];
|
||||
return value !== "unspecified" && value !== "unset";
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function differs(path: string, pr?: Entry, base?: Entry): boolean {
|
||||
if (pr?.oid === base?.oid && pr?.mode === base?.mode) return false;
|
||||
if (rootName(path) !== PACKAGE_JSON) return true;
|
||||
// Only one that provides commands matters, so most pull requests keep their own.
|
||||
const provided = pr ? commands(pr) : NO_COMMANDS;
|
||||
return provided !== NO_COMMANDS && (!provided || provided !== commands(base));
|
||||
}
|
||||
|
||||
/** The pull request's package.json with the base branch's commands. */
|
||||
function withBaseCommands(
|
||||
pr: Entry,
|
||||
base: Entry | undefined,
|
||||
): Buffer | undefined {
|
||||
const json = readPackageJson(pr);
|
||||
const baseJson = base ? readPackageJson(base) : {};
|
||||
if (!json || !baseJson) return undefined;
|
||||
for (const field of COMMAND_FIELDS) {
|
||||
// Without a bin, a new package's name provides no command.
|
||||
if (field === "name" && !base) continue;
|
||||
if (baseJson[field] === undefined) delete json[field];
|
||||
else json[field] = baseJson[field];
|
||||
}
|
||||
return Buffer.from(`${JSON.stringify(json, null, 2)}\n`);
|
||||
}
|
||||
|
||||
/** Keeps the pull request's version readable, as for the other restored config. */
|
||||
function snapshotForReview(path: string, entry: Entry): void {
|
||||
if (!isFile(entry) || rootName(path) === "node_modules") return;
|
||||
try {
|
||||
const content = git(["cat-file", "blob", entry.oid]);
|
||||
const copy = fsPath(`.claude-pr/${path}`);
|
||||
mkdirSync(fsPath(`.claude-pr/${dirname(path)}`), { recursive: true });
|
||||
writeFileSync(copy, content);
|
||||
ensureClaudePrExcludedFromGit();
|
||||
} catch (error) {
|
||||
warn("Could not keep a copy of tool config for review", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the pull request's tool config with the base branch's wherever they differ.
|
||||
* Like restoreConfigFromBase, which must run first because it fetches the base branch,
|
||||
* it changes the working tree and not the index. Only tracked files are replaced, so
|
||||
* what an earlier step created stays. In a package.json only the commands are replaced.
|
||||
*
|
||||
* @returns The names that were replaced, from a fixed list. Callers that stage files
|
||||
* must exclude them.
|
||||
* @throws If the base branch's version can't be put in place. The message holds no
|
||||
* file name, because the pull request controls those.
|
||||
*/
|
||||
export function restoreToolConfigFromBase(baseBranch: string): string[] {
|
||||
try {
|
||||
return restoreToolConfig(baseBranch);
|
||||
} catch (error) {
|
||||
warn("Could not replace tool config", error);
|
||||
throw new Error(
|
||||
"Could not use the base branch's version of the files that npm and Bun read",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function restoreToolConfig(baseBranch: string): string[] {
|
||||
const pr = pullRequestEntries();
|
||||
const base = baseEntries(baseBranch);
|
||||
const all = [...new Set([...pr.keys(), ...base.keys()])];
|
||||
// npx reads the packages in subdirectories only through the root's workspaces, and
|
||||
// a pull request's own are replaced below.
|
||||
const rootJson = base.get(PACKAGE_JSON);
|
||||
const hasWorkspaces =
|
||||
rootJson !== undefined &&
|
||||
readPackageJson(rootJson)?.workspaces !== undefined;
|
||||
const matters = (path: string): boolean =>
|
||||
hasWorkspaces || rootName(path) !== PACKAGE_JSON || !path.includes("/");
|
||||
|
||||
const reencoded = reencodedFiles();
|
||||
// Names that differ only in case can be the same file.
|
||||
const differing = new Set(
|
||||
all
|
||||
.filter(
|
||||
(path) =>
|
||||
matters(path) &&
|
||||
(reencoded.has(path) || differs(path, pr.get(path), base.get(path))),
|
||||
)
|
||||
.map(fold),
|
||||
);
|
||||
const candidates = all.filter((path) => differing.has(fold(path)));
|
||||
|
||||
// A directory where the pull request has a file or link came from an earlier step.
|
||||
const replaced = candidates.filter((path) => {
|
||||
const entry = pr.get(path);
|
||||
const stats = entry && onDisk(path);
|
||||
return (
|
||||
stats &&
|
||||
(!stats.isDirectory() || isSubmodule(entry)) &&
|
||||
hasRealParents(path)
|
||||
);
|
||||
});
|
||||
// All of these go before anything is written.
|
||||
for (const path of replaced) {
|
||||
snapshotForReview(path, pr.get(path)!);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
const removed = new Set(replaced);
|
||||
const toWrite = candidates.flatMap((path): Replacement[] => {
|
||||
const entry = base.get(path);
|
||||
const prEntry = pr.get(path);
|
||||
// One that the pull request has but is not on disk was left out or deleted by the
|
||||
// workflow. One that only the base has matters unless it's a package.json.
|
||||
const wanted = prEntry
|
||||
? removed.has(path)
|
||||
: rootName(path) !== PACKAGE_JSON;
|
||||
if (!wanted || onDisk(path)) return [];
|
||||
const content =
|
||||
prEntry && rootName(path) === PACKAGE_JSON
|
||||
? withBaseCommands(prEntry, entry)
|
||||
: undefined;
|
||||
if (content) return [{ path, entry: prEntry!, content }];
|
||||
return entry && !isSubmodule(entry) ? [{ path, entry, content }] : [];
|
||||
});
|
||||
const blobs = readBlobs(
|
||||
toWrite.flatMap(({ entry, content }) => (content ? [] : [entry])),
|
||||
);
|
||||
const written: string[] = [];
|
||||
for (const { path, entry, content = blobs.get(entry.oid) } of toWrite) {
|
||||
if (!hasRealParents(path)) continue;
|
||||
if (!content) throw new Error("missing object");
|
||||
mkdirSync(fsPath(dirname(path)), { recursive: true });
|
||||
if (isLink(entry)) symlinkSync(content, fsPath(path));
|
||||
else {
|
||||
const mode = entry.mode === "100755" ? 0o755 : 0o644;
|
||||
writeFileSync(fsPath(path), content, { mode, flag: "wx" });
|
||||
}
|
||||
written.push(path);
|
||||
}
|
||||
|
||||
const names = [
|
||||
...new Set([...replaced, ...written].map((path) => rootName(path)!)),
|
||||
];
|
||||
if (names.length > 0) {
|
||||
core.warning(
|
||||
`The pull request and its base branch differ in what npm and Bun read (${names.join(", ")}), so the base branch's version is used and Claude can't edit it. See docs/security.md.`,
|
||||
);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rules that stop a session from editing tool config, for a pull request whose author
|
||||
* doesn't have write access. Other package.json edits are ordinary work.
|
||||
*/
|
||||
export const toolConfigDenyRules = (replaced: string[]): string[] => [
|
||||
...TOOL_CONFIG.map((name) =>
|
||||
name === "node_modules" ? "Edit(./node_modules/**)" : `Edit(./${name})`,
|
||||
),
|
||||
...(replaced.includes(PACKAGE_JSON) ? ["Edit(package.json)"] : []),
|
||||
];
|
||||
@@ -0,0 +1,507 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { dirname, join } from "path";
|
||||
import {
|
||||
toolConfigDenyRules,
|
||||
restoreToolConfigFromBase,
|
||||
} from "../src/github/operations/tool-config";
|
||||
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
|
||||
|
||||
describe("restoreToolConfigFromBase", () => {
|
||||
let originalCwd: string;
|
||||
let tempDir: string;
|
||||
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
|
||||
const write = (path: string, content: string, executable = false) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, content);
|
||||
if (executable) chmodSync(path, 0o755);
|
||||
};
|
||||
const read = (path: string) => readFileSync(path, "utf8");
|
||||
const commit = (message: string) => {
|
||||
git("add", "-A", "-f");
|
||||
git("commit", "-qm", message);
|
||||
};
|
||||
|
||||
// Commits the base branch, pushes it and starts the pull request's branch from it.
|
||||
const startPr = () => {
|
||||
commit("base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
tempDir = mkdtempSync(join(tmpdir(), "tool-config-"));
|
||||
const remote = join(tempDir, "origin.git");
|
||||
const repo = join(tempDir, "repo");
|
||||
execFileSync("git", ["init", "-q", "--bare", remote]);
|
||||
execFileSync("git", ["init", "-q", "-b", "main", repo]);
|
||||
process.chdir(repo);
|
||||
git("config", "user.email", "[email protected]");
|
||||
git("config", "user.name", "Test User");
|
||||
git("remote", "add", "origin", remote);
|
||||
write("src/index.ts", "base\n");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("does nothing when the pull request has the same tool config", () => {
|
||||
write(".npmrc", "base\n");
|
||||
write("package.json", '{"name":"x","bin":"cli.js"}');
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(git("status", "--porcelain")).toBe("");
|
||||
expect(existsSync(".claude-pr")).toBe(false);
|
||||
});
|
||||
|
||||
test("uses the base version of a changed file, and removes an added one", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
write("bunfig.toml", "pr\n");
|
||||
write("node_modules/.bin/node", "#!/bin/sh\n", true);
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main").sort()).toEqual([
|
||||
".npmrc",
|
||||
"bunfig.toml",
|
||||
"node_modules",
|
||||
]);
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
expect(existsSync("bunfig.toml")).toBe(false);
|
||||
expect(existsSync("node_modules")).toBe(false);
|
||||
expect(read(".claude-pr/.npmrc")).toBe("pr\n");
|
||||
// Nothing is staged, so the pull request's versions are still what git has.
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("");
|
||||
});
|
||||
|
||||
test("brings back a file the pull request deleted", () => {
|
||||
write(".npmrc", "base\n");
|
||||
write("node_modules/.bin/tool", "base\n", true);
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
expect(read("node_modules/.bin/tool")).toBe("base\n");
|
||||
expect(lstatSync("node_modules/.bin/tool").mode & 0o111).not.toBe(0);
|
||||
});
|
||||
|
||||
test("leaves untracked files that an earlier step created", () => {
|
||||
write("bunfig.toml", "base\n");
|
||||
startPr();
|
||||
rmSync("bunfig.toml");
|
||||
write(".npmrc.example", "pr\n");
|
||||
commit("pr");
|
||||
write("bunfig.toml", "from a step\n");
|
||||
write(".npmrc", "from a step\n");
|
||||
write("node_modules/.bin/tool", "installed\n", true);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("bunfig.toml")).toBe("from a step\n");
|
||||
expect(read(".npmrc")).toBe("from a step\n");
|
||||
expect(read("node_modules/.bin/tool")).toBe("installed\n");
|
||||
});
|
||||
|
||||
test("keeps a step's change to a file the pull request leaves alone", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
write(".npmrc", "base\nfrom a step\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(".npmrc")).toBe("base\nfrom a step\n");
|
||||
});
|
||||
|
||||
test("keeps a file deleted by an earlier step deleted", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
rmSync(".npmrc");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves a directory an earlier step put in a tracked link's place", () => {
|
||||
startPr();
|
||||
symlinkSync("elsewhere", "node_modules");
|
||||
commit("pr");
|
||||
rmSync("node_modules");
|
||||
write("node_modules/tool/a", "installed\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("node_modules/tool/a")).toBe("installed\n");
|
||||
});
|
||||
|
||||
test("leaves files that a sparse checkout leaves out", () => {
|
||||
write("node_modules/tool/a", "base\n");
|
||||
startPr();
|
||||
write("node_modules/tool/a", "pr\n");
|
||||
commit("pr");
|
||||
git("sparse-checkout", "set", "src");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(existsSync("node_modules/tool/a")).toBe(false);
|
||||
});
|
||||
|
||||
test("replaces links without following them", () => {
|
||||
write("node_modules/.bin/tool", "base\n", true);
|
||||
startPr();
|
||||
const outside = join(tempDir, "outside");
|
||||
write(join(outside, ".bin/tool"), "outside\n");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
symlinkSync(outside, "node_modules");
|
||||
symlinkSync(join(outside, ".bin/tool"), ".npmrc");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(lstatSync("node_modules").isDirectory()).toBe(true);
|
||||
expect(read("node_modules/.bin/tool")).toBe("base\n");
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
expect(read(join(outside, ".bin/tool"))).toBe("outside\n");
|
||||
});
|
||||
|
||||
test("writes and removes nothing through a link an earlier step added", () => {
|
||||
write("node_modules/a/b", "base\n");
|
||||
write("node_modules/c/d", "base\n");
|
||||
startPr();
|
||||
write("node_modules/a/b", "pr\n");
|
||||
rmSync("node_modules/c", { recursive: true });
|
||||
commit("pr");
|
||||
const outside = join(tempDir, "outside");
|
||||
write(join(outside, "a/b"), "outside\n");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
symlinkSync(outside, "node_modules");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(join(outside, "a/b"))).toBe("outside\n");
|
||||
expect(existsSync(join(outside, "c"))).toBe(false);
|
||||
});
|
||||
|
||||
test("brings back a link the base branch has", () => {
|
||||
write("node_modules/tool/cli.js", "base\n");
|
||||
mkdirSync("node_modules/.bin");
|
||||
symlinkSync("../tool/cli.js", "node_modules/.bin/tool");
|
||||
startPr();
|
||||
rmSync("node_modules/.bin/tool");
|
||||
write("node_modules/.bin/tool", "pr\n", true);
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(readlinkSync("node_modules/.bin/tool")).toBe("../tool/cli.js");
|
||||
});
|
||||
|
||||
test("replaces a directory the pull request puts in a file's place", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
write(".npmrc/keep", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("replaces a directory that holds a package.json too", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
write(".npmrc/package.json", "{}");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("rewrites an unchanged file that .gitattributes re-encodes", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
|
||||
git("add", ".gitattributes");
|
||||
git("commit", "-qm", "pr");
|
||||
expect(git("rev-parse", "HEAD:.npmrc")).toBe(
|
||||
git("rev-parse", "main:.npmrc"),
|
||||
);
|
||||
rmSync(".npmrc");
|
||||
git("checkout", "--", ".npmrc");
|
||||
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("matches names without regard to case", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write("BUNFIG.toml", "pr\n");
|
||||
write("Node_Modules/.bin/node", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(existsSync("BUNFIG.toml")).toBe(false);
|
||||
expect(existsSync("Node_Modules/.bin/node")).toBe(false);
|
||||
});
|
||||
|
||||
test("writes the base version as it is, whatever .gitattributes says", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("keeps binary and empty content intact", () => {
|
||||
const content = Buffer.from([0, 10, 255, 10, 13, 0]);
|
||||
mkdirSync("node_modules");
|
||||
writeFileSync("node_modules/a", content);
|
||||
writeFileSync("node_modules/b", "");
|
||||
writeFileSync("node_modules/c", "no newline");
|
||||
startPr();
|
||||
for (const name of ["a", "b", "c"]) write(`node_modules/${name}`, "pr");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(readFileSync("node_modules/a").equals(content)).toBe(true);
|
||||
expect(read("node_modules/b")).toBe("");
|
||||
expect(read("node_modules/c")).toBe("no newline");
|
||||
});
|
||||
|
||||
test("reports names from a fixed list, not the pull request's file names", () => {
|
||||
startPr();
|
||||
write("node_modules/a\n::stop-commands::x", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
const names = restoreToolConfigFromBase("main");
|
||||
|
||||
expect(names).toEqual(["node_modules"]);
|
||||
expect(existsSync("node_modules")).toBe(false);
|
||||
});
|
||||
|
||||
test("handles names that are not valid UTF-8", () => {
|
||||
startPr();
|
||||
const name = Buffer.from([...Buffer.from("node_modules/"), 0xff]);
|
||||
mkdirSync("node_modules");
|
||||
try {
|
||||
writeFileSync(name, "pr\n");
|
||||
} catch {
|
||||
return; // This file system refuses such names.
|
||||
}
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(existsSync(name)).toBe(false);
|
||||
});
|
||||
|
||||
test("is not misled by a local branch with the base's name", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
git("branch", "origin/main");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("works in a checkout with no remote-tracking branch for the base", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
git("fetch", "-q", "origin", "main");
|
||||
git("update-ref", "-d", "refs/remotes/origin/main");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("stops edits to tool config, and to package.json only if replaced", () => {
|
||||
const rules = [
|
||||
"Edit(./.npmrc)",
|
||||
"Edit(./bunfig.toml)",
|
||||
"Edit(./node_modules/**)",
|
||||
];
|
||||
expect(toolConfigDenyRules([])).toEqual(rules);
|
||||
expect(toolConfigDenyRules(["package.json"])).toEqual([
|
||||
...rules,
|
||||
"Edit(package.json)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("matches names a file system can treat as the same", () => {
|
||||
startPr();
|
||||
write("node_module\u017F/.bin/node", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["node_modules"]);
|
||||
});
|
||||
|
||||
test("fails without naming a file if the base version can't be read", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
const oid = git("rev-parse", "main:.npmrc");
|
||||
rmSync(join(".git/objects", oid.slice(0, 2), oid.slice(2)));
|
||||
|
||||
expect(() => restoreToolConfigFromBase("main")).toThrow(
|
||||
/^Could not use the base branch's version/,
|
||||
);
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
});
|
||||
|
||||
describe("package.json", () => {
|
||||
const baseJson = { name: "x", bin: { x: "x.js" }, version: "1.0.0" };
|
||||
const start = (pr: unknown) => {
|
||||
write("package.json", JSON.stringify(baseJson));
|
||||
startPr();
|
||||
write("package.json", typeof pr === "string" ? pr : JSON.stringify(pr));
|
||||
commit("pr");
|
||||
};
|
||||
|
||||
test("keeps the pull request's version when only other fields change", () => {
|
||||
const pr = { ...baseJson, version: "2.0.0", dependencies: { a: "1" } };
|
||||
start(pr);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual(pr);
|
||||
});
|
||||
|
||||
test("keeps the pull request's version when it removes the commands", () => {
|
||||
start({ name: "x" });
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["bin", { bin: { "tool@latest": "a.js" } }],
|
||||
["directories", { directories: { bin: "bin" } }],
|
||||
["name", { name: "tool" }],
|
||||
["workspaces", { workspaces: ["pkgs/*"] }],
|
||||
])("uses only the base's commands when %s changes", (_, change) => {
|
||||
const pr = { ...baseJson, ...change, dependencies: { a: "1" } };
|
||||
start(pr);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual({
|
||||
...baseJson,
|
||||
dependencies: { a: "1" },
|
||||
});
|
||||
expect(JSON.parse(read(".claude-pr/package.json"))).toEqual(pr);
|
||||
});
|
||||
|
||||
test("uses the base version when it can't be understood", () => {
|
||||
start("{");
|
||||
restoreToolConfigFromBase("main");
|
||||
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
|
||||
});
|
||||
|
||||
test("understands a byte order mark", () => {
|
||||
start(`\uFEFF${JSON.stringify({ ...baseJson, version: "2.0.0" })}`);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
});
|
||||
|
||||
test("looks in subdirectories only if the base branch has workspaces", () => {
|
||||
const tool = JSON.stringify({ name: "tool", bin: "x.js", version: "1" });
|
||||
startPr();
|
||||
write("pkgs/p/package.json", tool);
|
||||
commit("pr");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
git("checkout", "-q", "main");
|
||||
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
|
||||
commit("base 2");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-q", "-b", "pr2");
|
||||
write("pkgs/p/package.json", tool);
|
||||
commit("pr2");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("pkgs/p/package.json"))).toEqual({
|
||||
name: "tool",
|
||||
version: "1",
|
||||
});
|
||||
expect(JSON.parse(read(".claude-pr/pkgs/p/package.json")).name).toBe(
|
||||
"tool",
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves what the base branch's .claude and .husky hold", () => {
|
||||
const base = '{"name":"hooks","bin":"a.js","scripts":{"check":"base"}}';
|
||||
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
|
||||
write(".claude/hooks/package.json", base);
|
||||
write(".husky/package.json", base);
|
||||
startPr();
|
||||
for (const dir of [".claude/hooks", ".husky"]) {
|
||||
write(`${dir}/package.json`, '{"bin":"b.js","scripts":{"check":"pr"}}');
|
||||
}
|
||||
commit("pr");
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(".claude/hooks/package.json")).toBe(base);
|
||||
expect(read(".husky/package.json")).toBe(base);
|
||||
});
|
||||
|
||||
test("takes the commands out of a new package.json", () => {
|
||||
startPr();
|
||||
write("package.json", '{"name":"x"}');
|
||||
commit("pr");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
write("package.json", '{"name":"x","version":"1","bin":{"t":"a.js"}}');
|
||||
commit("pr 2");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual({
|
||||
name: "x",
|
||||
version: "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user