mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-23 06:09:37 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80b3182633 | ||
|
|
360be9c8fc | ||
|
|
e452eb9dce | ||
|
|
6b8063043e | ||
|
|
30544b6743 | ||
|
|
2fee155104 | ||
|
|
51705da45e | ||
|
|
806af32823 | ||
|
|
0a08a86780 | ||
|
|
9dd8b95a39 | ||
|
|
4d7e1f0cd8 | ||
|
|
3d9f0dc7dc | ||
|
|
a5e5d3b82e | ||
|
|
d5726de019 |
@@ -145,7 +145,7 @@ runs:
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||
run: |
|
||||
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||
CLAUDE_CODE_VERSION="2.1.176"
|
||||
CLAUDE_CODE_VERSION="2.1.187"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
|
||||
+10
-10
@@ -6,7 +6,7 @@
|
||||
"name": "@anthropic-ai/claude-code-base-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.176",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.187",
|
||||
"shell-quote": "^1.8.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -27,23 +27,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]6", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.176", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.176" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-uN7XatzLYFackK4WH43iCfW+QPi21zgavG2ZdY1gMbYKFrhbchVX1U0BBbFq8sFy1zqNc3WZ4GCHAdjOAHQe0A=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]87", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.187", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.187" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-HHkuC3he/Wi8fX/WjfS8mJr4TFPGoAd1QyxOuTwjnyOLboGkX1H+UhBYLxHX1ouFvHnYVJglB2wsuWemVQgahQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZLVv9Hlo5W7YEV23eTsAKYQTkA1V7TG4Z5oFESgvkVfx02TxguZKtUbqlpmzZ9JqXRu+qMY9iIpIgbI3PwRJw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0DNzATzaRmjS/Q1T4T9SLP/VT67gRX7J4reYPnEdcTm91lJwjqOPkHr17+sv+7DoerZ421ZG38dPsQd/V67qQw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]6", "", { "os": "darwin", "cpu": "x64" }, "sha512-rN1Jj0r0AGIU3x3KXgXWrIQz/NO2jiPmlsJS0lhr08KwteBXqK2+oWPf7oyD33ExQIOj/CZDCqQbSnYv6ttfFQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]87", "", { "os": "darwin", "cpu": "x64" }, "sha512-Va3O8lTDa9IHq/DbSJwU63JJknNV3YCBh4PEznOHXJtyFoXHgRjrks4QQvN3baZm79avVq2sn+6tvpTz9CuY8A=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "arm64" }, "sha512-3peVLOJCtUP883To+LCFaeT00uP+wcb1nrMrrAa92HBOnRVtnQAPEjpsItmIEGErc91YhV9cpliwoTZam1fBlQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "arm64" }, "sha512-VEvrs3MgwckdWRNa7+2rJdyOBbCWGoRaM6OnL+/n9qi4gKlZnXZlj/90Tw9o8ttcN260Opz120/SE1fYwzu/JA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "arm64" }, "sha512-8YeGD2ePf+SW1i9IjSYyJlpcSKymGRMBGZv7AibF6I7PuQEAHtfuBlYBv9a59T/s3kHyQdu3bZb0DUZUXXfhcA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "arm64" }, "sha512-XQ7w2pX0mjPYUC7ayTKiHeAbePOny/ezBATxTWt5JVDZZPfljzvHA0jyXHsN8aLphbgRUfbUpdrtt5b57Bhx5g=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "x64" }, "sha512-nu378rqSXa9sAb1+P8jXjCUre2qPG1I6eBWiMMXSTCQE7sphUa/dKoLUh2L+E/S6/s/hA1kRm+PO389fPKw/Uw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "x64" }, "sha512-s/Fmg29tzMrbdeCbseTpL3DlzfWineSQ3bDPvhdKw4jcsgLC1YgQhIkAyE8WlceUyhQyw82NAUgYoPwfGny6hQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "x64" }, "sha512-jcPb+L+D7TmihtfBO9quzVjR52hLqM+XKRXg9eMJpYH/T4DtVsFAQhdZ/Yf2dV2wNCcQeTtn7K//ghEXnO6jtA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "x64" }, "sha512-yi2/L5oztFqTDnAZl4mWOINr+r7WBot70gYUxG2jOoqdYUl6j50vG/ME605X80v+l2qBmKjSGxb5trY/6DkRzQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "win32", "cpu": "arm64" }, "sha512-XiJHXo9+rCJGFriZQmGBKC0pZG+ZQgYv1PEtewbxcgbquJYnWPGIS2Itvg5sEVK0CxLQ3WO1Rgg69iqVFxo/OQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "win32", "cpu": "arm64" }, "sha512-HjEl3cDRLAWKopdlrLI54fxTVWq4lZpWA4bTTBVc9UDdDj6AmJIRHKxaCCYLQRvnoswbAUF1sJmJ8EFJ+b6lfw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]6", "", { "os": "win32", "cpu": "x64" }, "sha512-8UlbhNCVEsfTmFNUOBdS6/7GTOtbkl2gI1nsrX2dgHLHxNIqjgJOkbysFBLtwssm2X3l6d4QRMFrHjJ8mDjGfA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]87", "", { "os": "win32", "cpu": "x64" }, "sha512-FnrLhoZ8y/+gkZynL12UeQ8pWKCu6B/8myyRrYMNJRZqFw4DZlPvPCywAjFZf1e1hiXCoiSK0Orl5wzKfAeQsQ=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.176",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.187",
|
||||
"shell-quote": "^1.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -24,6 +24,35 @@ const ACCUMULATING_FLAGS = new Set([
|
||||
// Delimiter used to join accumulated flag values
|
||||
const ACCUMULATE_DELIMITER = "\x00";
|
||||
|
||||
// shell-quote treats ()|&;<> as control operators and splits adjacent text
|
||||
// around them into separate tokens (returned as `{op}` objects, which we then
|
||||
// dropped). For CLI args these must be literal characters — e.g. unquoted
|
||||
// `--allowedTools Bash(gh:*)` was being mangled into bare `Bash`, silently
|
||||
// widening a scoped permission rule to Bash(*). We escape each metachar to a
|
||||
// Unicode private-use codepoint before parsing and restore it afterward,
|
||||
// keeping shell-quote's quote/whitespace handling intact.
|
||||
const SHELL_META_PAIRS: [string, string][] = [
|
||||
["(", ""],
|
||||
[")", ""],
|
||||
["|", ""],
|
||||
["&", ""],
|
||||
[";", ""],
|
||||
["<", ""],
|
||||
[">", ""],
|
||||
];
|
||||
const SHELL_META_ESCAPE = new Map(SHELL_META_PAIRS);
|
||||
const SHELL_META_UNESCAPE = new Map(SHELL_META_PAIRS.map(([k, v]) => [v, k]));
|
||||
const SHELL_META_ESCAPE_RE = /[()|&;<>]/g;
|
||||
const SHELL_META_UNESCAPE_RE = /[-]/g;
|
||||
|
||||
function escapeShellMeta(s: string): string {
|
||||
return s.replace(SHELL_META_ESCAPE_RE, (c) => SHELL_META_ESCAPE.get(c)!);
|
||||
}
|
||||
|
||||
function unescapeShellMeta(s: string): string {
|
||||
return s.replace(SHELL_META_UNESCAPE_RE, (c) => SHELL_META_UNESCAPE.get(c)!);
|
||||
}
|
||||
|
||||
type McpConfig = {
|
||||
mcpServers?: Record<string, unknown>;
|
||||
};
|
||||
@@ -106,9 +135,19 @@ function parseClaudeArgsToExtraArgs(
|
||||
if (!claudeArgs?.trim()) return {};
|
||||
|
||||
const result: Record<string, string | null> = {};
|
||||
const args = parseShellArgs(stripShellComments(claudeArgs)).filter(
|
||||
(arg): arg is string => typeof arg === "string",
|
||||
);
|
||||
const args = parseShellArgs(escapeShellMeta(stripShellComments(claudeArgs)))
|
||||
.map((arg) => {
|
||||
if (typeof arg === "string") return unescapeShellMeta(arg);
|
||||
// With control metachars escaped above, the only non-string shell-quote
|
||||
// can still emit is a glob op (bareword containing *, ?, or [). Its
|
||||
// `pattern` field is the verbatim token text — use it as-is so values
|
||||
// like `Bash(cmd:*)` and `Read(path/**)` round-trip intact.
|
||||
if (typeof arg === "object" && arg !== null && "pattern" in arg) {
|
||||
return unescapeShellMeta((arg as { pattern: string }).pattern);
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((arg): arg is string => typeof arg === "string");
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
@@ -137,6 +137,110 @@ describe("parseSdkOptions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("should preserve unquoted Bash(cmd:*) rules instead of collapsing to bare Bash", () => {
|
||||
// Regression: shell-quote tokenizes unquoted `(`/`)` as control ops and
|
||||
// `*` as a glob, which were filtered out — collapsing scoped rules like
|
||||
// `Bash(gh:*)` into bare `Bash` (= Bash(*), unrestricted shell).
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: "--allowedTools View,Bash(gh:*),Bash(cat:*)",
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.allowedTools).toEqual([
|
||||
"View",
|
||||
"Bash(gh:*)",
|
||||
"Bash(cat:*)",
|
||||
]);
|
||||
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
|
||||
});
|
||||
|
||||
test("should preserve unquoted space-separated Bash(cmd:*) rules", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: "--allowed-tools Bash(gh:*) Bash(cat:*) Read(//tmp/**)",
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.allowedTools).toEqual([
|
||||
"Bash(gh:*)",
|
||||
"Bash(cat:*)",
|
||||
"Read(//tmp/**)",
|
||||
]);
|
||||
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
|
||||
});
|
||||
|
||||
test("should preserve unquoted Tool(content) rules without glob chars", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs:
|
||||
"--allowedTools Read(~/file),WebFetch(domain:example.com),Edit",
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.allowedTools).toEqual([
|
||||
"Read(~/file)",
|
||||
"WebFetch(domain:example.com)",
|
||||
"Edit",
|
||||
]);
|
||||
});
|
||||
|
||||
test("should still preserve quoted Bash(cmd:*) rules (no regression)", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: '--allowedTools "Bash(gh:*),Bash(cat:*)"',
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.allowedTools).toEqual([
|
||||
"Bash(gh:*)",
|
||||
"Bash(cat:*)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("should merge quoted tag-mode tools with unquoted user tools without widening", () => {
|
||||
// Real-world shape: the action's tag mode wraps its own --allowedTools in
|
||||
// double quotes, then appends the user's claude_args (typically unquoted
|
||||
// in workflow YAML). Both halves must round-trip.
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs:
|
||||
'--permission-mode acceptEdits --allowedTools "Glob,Grep,Read,Bash(git add:*),Bash(git commit:*)" ' +
|
||||
"--model claude-opus-4-7\n" +
|
||||
"--allowedTools View,Bash(gh:*),Bash(printf:*),Bash(cat:*)",
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.allowedTools).toEqual([
|
||||
"Glob",
|
||||
"Grep",
|
||||
"Read",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)",
|
||||
"View",
|
||||
"Bash(gh:*)",
|
||||
"Bash(printf:*)",
|
||||
"Bash(cat:*)",
|
||||
]);
|
||||
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
|
||||
});
|
||||
|
||||
test("should preserve unquoted disallowedTools rules without widening", () => {
|
||||
// Same bug class on the deny side: a scoped deny collapsing to bare
|
||||
// `Bash` would block all shell instead of the intended prefix.
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: "--disallowedTools Bash(rm:*),Bash(sudo:*)",
|
||||
};
|
||||
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.disallowedTools).toEqual([
|
||||
"Bash(rm:*)",
|
||||
"Bash(sudo:*)",
|
||||
]);
|
||||
expect(result.sdkOptions.disallowedTools).not.toContain("Bash");
|
||||
});
|
||||
|
||||
test("should handle mixed camelCase and hyphenated allowedTools flags", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: '--allowedTools "Edit,Read" --allowed-tools "Write,Glob"',
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.176",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.187",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
@@ -37,23 +37,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]6", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.176", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.176", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.176", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.176" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-uN7XatzLYFackK4WH43iCfW+QPi21zgavG2ZdY1gMbYKFrhbchVX1U0BBbFq8sFy1zqNc3WZ4GCHAdjOAHQe0A=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]87", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.187", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.187", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.187", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.187" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-HHkuC3he/Wi8fX/WjfS8mJr4TFPGoAd1QyxOuTwjnyOLboGkX1H+UhBYLxHX1ouFvHnYVJglB2wsuWemVQgahQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZLVv9Hlo5W7YEV23eTsAKYQTkA1V7TG4Z5oFESgvkVfx02TxguZKtUbqlpmzZ9JqXRu+qMY9iIpIgbI3PwRJw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0DNzATzaRmjS/Q1T4T9SLP/VT67gRX7J4reYPnEdcTm91lJwjqOPkHr17+sv+7DoerZ421ZG38dPsQd/V67qQw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]6", "", { "os": "darwin", "cpu": "x64" }, "sha512-rN1Jj0r0AGIU3x3KXgXWrIQz/NO2jiPmlsJS0lhr08KwteBXqK2+oWPf7oyD33ExQIOj/CZDCqQbSnYv6ttfFQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]87", "", { "os": "darwin", "cpu": "x64" }, "sha512-Va3O8lTDa9IHq/DbSJwU63JJknNV3YCBh4PEznOHXJtyFoXHgRjrks4QQvN3baZm79avVq2sn+6tvpTz9CuY8A=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "arm64" }, "sha512-3peVLOJCtUP883To+LCFaeT00uP+wcb1nrMrrAa92HBOnRVtnQAPEjpsItmIEGErc91YhV9cpliwoTZam1fBlQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "arm64" }, "sha512-VEvrs3MgwckdWRNa7+2rJdyOBbCWGoRaM6OnL+/n9qi4gKlZnXZlj/90Tw9o8ttcN260Opz120/SE1fYwzu/JA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "arm64" }, "sha512-8YeGD2ePf+SW1i9IjSYyJlpcSKymGRMBGZv7AibF6I7PuQEAHtfuBlYBv9a59T/s3kHyQdu3bZb0DUZUXXfhcA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "arm64" }, "sha512-XQ7w2pX0mjPYUC7ayTKiHeAbePOny/ezBATxTWt5JVDZZPfljzvHA0jyXHsN8aLphbgRUfbUpdrtt5b57Bhx5g=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "x64" }, "sha512-nu378rqSXa9sAb1+P8jXjCUre2qPG1I6eBWiMMXSTCQE7sphUa/dKoLUh2L+E/S6/s/hA1kRm+PO389fPKw/Uw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "x64" }, "sha512-s/Fmg29tzMrbdeCbseTpL3DlzfWineSQ3bDPvhdKw4jcsgLC1YgQhIkAyE8WlceUyhQyw82NAUgYoPwfGny6hQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]6", "", { "os": "linux", "cpu": "x64" }, "sha512-jcPb+L+D7TmihtfBO9quzVjR52hLqM+XKRXg9eMJpYH/T4DtVsFAQhdZ/Yf2dV2wNCcQeTtn7K//ghEXnO6jtA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]87", "", { "os": "linux", "cpu": "x64" }, "sha512-yi2/L5oztFqTDnAZl4mWOINr+r7WBot70gYUxG2jOoqdYUl6j50vG/ME605X80v+l2qBmKjSGxb5trY/6DkRzQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]6", "", { "os": "win32", "cpu": "arm64" }, "sha512-XiJHXo9+rCJGFriZQmGBKC0pZG+ZQgYv1PEtewbxcgbquJYnWPGIS2Itvg5sEVK0CxLQ3WO1Rgg69iqVFxo/OQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]87", "", { "os": "win32", "cpu": "arm64" }, "sha512-HjEl3cDRLAWKopdlrLI54fxTVWq4lZpWA4bTTBVc9UDdDj6AmJIRHKxaCCYLQRvnoswbAUF1sJmJ8EFJ+b6lfw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]6", "", { "os": "win32", "cpu": "x64" }, "sha512-8UlbhNCVEsfTmFNUOBdS6/7GTOtbkl2gI1nsrX2dgHLHxNIqjgJOkbysFBLtwssm2X3l6d4QRMFrHjJ8mDjGfA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]87", "", { "os": "win32", "cpu": "x64" }, "sha512-FnrLhoZ8y/+gkZynL12UeQ8pWKCu6B/8myyRrYMNJRZqFw4DZlPvPCywAjFZf1e1hiXCoiSK0Orl5wzKfAeQsQ=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.176",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.187",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
@@ -68,7 +68,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.176";
|
||||
const claudeCodeVersion = "2.1.187";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
|
||||
+23
-26
@@ -378,34 +378,26 @@ export async function fetchGitHubData({
|
||||
body: c.body,
|
||||
}));
|
||||
|
||||
// Filter review bodies to trigger time
|
||||
const filteredReviewBodies = reviewData?.nodes
|
||||
? filterReviewsToTriggerTime(reviewData.nodes, triggerTime).filter(
|
||||
(r) => r.body,
|
||||
)
|
||||
: [];
|
||||
|
||||
const reviewBodies: CommentWithImages[] = filteredReviewBodies.map((r) => ({
|
||||
type: "review_body" as const,
|
||||
id: r.databaseId,
|
||||
pullNumber: prNumber,
|
||||
body: r.body,
|
||||
}));
|
||||
|
||||
// Filter review comments to trigger time and by actor
|
||||
// Filter reviews and inline review comments to trigger time and by actor
|
||||
// before building anything from them. The trigger-time filter is the TOCTOU
|
||||
// protection applied to issue/PR comments and the body above: it drops
|
||||
// anything submitted, created, or edited at/after the trigger so an attacker
|
||||
// cannot inject content into the prompt after an authorized trigger. Without
|
||||
// it, review bodies and inline review comments would reach the prompt
|
||||
// verbatim regardless of when they landed.
|
||||
if (reviewData && reviewData.nodes) {
|
||||
// Filter reviews by actor
|
||||
// Drop reviews submitted or edited after the trigger, then filter by actor.
|
||||
reviewData.nodes = filterCommentsByActor(
|
||||
reviewData.nodes,
|
||||
filterReviewsToTriggerTime(reviewData.nodes, triggerTime),
|
||||
includeCommentsByActor,
|
||||
excludeCommentsByActor,
|
||||
);
|
||||
|
||||
// Also filter inline review comments within each review
|
||||
// Apply the same trigger-time + actor filtering to inline review comments.
|
||||
reviewData.nodes.forEach((review) => {
|
||||
if (review.comments?.nodes) {
|
||||
review.comments.nodes = filterCommentsByActor(
|
||||
review.comments.nodes,
|
||||
filterCommentsToTriggerTime(review.comments.nodes, triggerTime),
|
||||
includeCommentsByActor,
|
||||
excludeCommentsByActor,
|
||||
);
|
||||
@@ -413,14 +405,19 @@ export async function fetchGitHubData({
|
||||
});
|
||||
}
|
||||
|
||||
const allReviewComments =
|
||||
reviewData?.nodes?.flatMap((r) => r.comments?.nodes ?? []) ?? [];
|
||||
const filteredReviewComments = filterCommentsToTriggerTime(
|
||||
allReviewComments,
|
||||
triggerTime,
|
||||
);
|
||||
// Build the image-processing lists from the already-filtered review nodes,
|
||||
// so reviews/comments excluded from the prompt are not processed for images.
|
||||
const reviewBodies: CommentWithImages[] = (reviewData?.nodes ?? [])
|
||||
.filter((r) => r.body)
|
||||
.map((r) => ({
|
||||
type: "review_body" as const,
|
||||
id: r.databaseId,
|
||||
pullNumber: prNumber,
|
||||
body: r.body,
|
||||
}));
|
||||
|
||||
const reviewComments: CommentWithImages[] = filteredReviewComments
|
||||
const reviewComments: CommentWithImages[] = (reviewData?.nodes ?? [])
|
||||
.flatMap((r) => r.comments?.nodes ?? [])
|
||||
.filter((c) => c.body && !c.isMinimized)
|
||||
.map((c) => ({
|
||||
type: "review_comment" as const,
|
||||
|
||||
@@ -27,14 +27,15 @@ function extractFirstLabel(githubData: FetchDataResult): string | undefined {
|
||||
* This prevents command injection by ensuring only safe characters are used.
|
||||
*
|
||||
* Valid branch names:
|
||||
* - Start with alphanumeric character (not dash, to prevent option injection)
|
||||
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, or hash (#)
|
||||
* - Start with alphanumeric character or @ (not dash, to prevent option injection)
|
||||
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, hash (#), plus (+), comma (,), or at sign (@)
|
||||
* - Do not start or end with a period
|
||||
* - Do not end with a slash
|
||||
* - Do not contain '..' (path traversal)
|
||||
* - Do not contain '//' (consecutive slashes)
|
||||
* - Do not end with '.lock'
|
||||
* - Do not contain '@{'
|
||||
* - Are not the single character '@' (HEAD shorthand in git revision syntax)
|
||||
* - Do not contain control characters or special git characters (~^:?*[\])
|
||||
*/
|
||||
export function validateBranchName(branchName: string): void {
|
||||
@@ -58,18 +59,21 @@ export function validateBranchName(branchName: string): void {
|
||||
);
|
||||
}
|
||||
|
||||
// Strict whitelist pattern: alphanumeric start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma.
|
||||
// Strict whitelist pattern: alphanumeric or @ start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma/at-sign.
|
||||
// # is valid per git-check-ref-format and commonly used in branch names like "fix/#123-description".
|
||||
// + is valid per git-check-ref-format and generated by Claude Code's EnterWorktree tool when
|
||||
// converting worktree names containing "/" (e.g. "feat/foo" becomes "worktree-feat+foo").
|
||||
// , is valid per git-check-ref-format and commonly appears in branch names derived from titles
|
||||
// or external identifiers (e.g. place names like "feature/paris,france").
|
||||
// @ is valid per git-check-ref-format anywhere in a ref name, including the first character
|
||||
// (e.g. ticket conventions like "TICKET-123@add-feature" or prefixes like "@hotfix/...");
|
||||
// the bare name "@" (HEAD shorthand) and the "@{" sequence (reflog syntax) are rejected below.
|
||||
// All git calls use execFileSync (not shell interpolation), so none of these characters carry injection risk.
|
||||
const validPattern = /^[a-zA-Z0-9][a-zA-Z0-9/_.#+,-]*$/;
|
||||
const validPattern = /^[a-zA-Z0-9@][a-zA-Z0-9/_.#+,@-]*$/;
|
||||
|
||||
if (!validPattern.test(branchName)) {
|
||||
throw new Error(
|
||||
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), or commas (,).`,
|
||||
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character or '@' and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), commas (,), or at signs (@).`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,6 +116,15 @@ export function validateBranchName(branchName: string): void {
|
||||
`Invalid branch name: "${branchName}". Branch names cannot contain '@{'`,
|
||||
);
|
||||
}
|
||||
|
||||
// Per git-check-ref-format, a refname cannot be the single character "@"; "@" also
|
||||
// resolves to HEAD in git revision syntax, so a bare "@" must never reach git as a
|
||||
// branch argument where it could be interpreted as a revision instead.
|
||||
if (branchName === "@") {
|
||||
throw new Error(
|
||||
`Invalid branch name: "@". Branch names cannot be the single character '@'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+50
-20
@@ -10,6 +10,49 @@ export class WorkflowValidationSkipError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
type AppTokenExchangeErrorResponse = {
|
||||
error?: {
|
||||
message?: string;
|
||||
details?: {
|
||||
error_code?: string;
|
||||
};
|
||||
};
|
||||
type?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const WORKFLOW_VALIDATION_ERROR_CODES = new Set([
|
||||
"workflow_not_found_on_default_branch",
|
||||
]);
|
||||
|
||||
function getAppTokenExchangeErrorMessage(
|
||||
responseJson: AppTokenExchangeErrorResponse,
|
||||
): string {
|
||||
return responseJson.error?.message ?? responseJson.message ?? "Unknown error";
|
||||
}
|
||||
|
||||
function isWorkflowValidationError(
|
||||
status: number,
|
||||
responseJson: AppTokenExchangeErrorResponse,
|
||||
): boolean {
|
||||
const errorCode = responseJson.error?.details?.error_code;
|
||||
if (
|
||||
errorCode !== undefined &&
|
||||
WORKFLOW_VALIDATION_ERROR_CODES.has(errorCode)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (status !== 401) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const workflowValidationMessage = "workflow validation failed";
|
||||
return [responseJson.message, responseJson.error?.message].some((message) =>
|
||||
message?.toLowerCase().includes(workflowValidationMessage),
|
||||
);
|
||||
}
|
||||
|
||||
async function getOidcToken(): Promise<string> {
|
||||
try {
|
||||
const oidcToken = await core.getIDToken("claude-code-github-action");
|
||||
@@ -80,25 +123,11 @@ async function exchangeForAppToken(
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const responseJson = (await response.json()) as {
|
||||
error?: {
|
||||
message?: string;
|
||||
details?: {
|
||||
error_code?: string;
|
||||
};
|
||||
};
|
||||
type?: string;
|
||||
message?: string;
|
||||
};
|
||||
const responseJson =
|
||||
(await response.json()) as AppTokenExchangeErrorResponse;
|
||||
|
||||
// Check for specific workflow validation error codes that should skip the action
|
||||
const errorCode = responseJson.error?.details?.error_code;
|
||||
|
||||
if (errorCode === "workflow_not_found_on_default_branch") {
|
||||
const message =
|
||||
responseJson.message ??
|
||||
responseJson.error?.message ??
|
||||
"Workflow validation failed";
|
||||
if (isWorkflowValidationError(response.status, responseJson)) {
|
||||
const message = getAppTokenExchangeErrorMessage(responseJson);
|
||||
core.warning(`Skipping action due to workflow validation: ${message}`);
|
||||
console.log(
|
||||
"Action skipped due to workflow validation error. This is expected when adding Claude Code workflows to new repositories or on PRs with workflow changes. If you're seeing this, your workflow will begin working once you merge your PR.",
|
||||
@@ -106,10 +135,11 @@ async function exchangeForAppToken(
|
||||
throw new WorkflowValidationSkipError(message);
|
||||
}
|
||||
|
||||
const message = getAppTokenExchangeErrorMessage(responseJson);
|
||||
console.error(
|
||||
`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson?.error?.message ?? "Unknown error"}`,
|
||||
`App token exchange failed: ${response.status} ${response.statusText} - ${message}`,
|
||||
);
|
||||
throw new Error(`${responseJson?.error?.message ?? "Unknown error"}`);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const appTokenData = (await response.json()) as {
|
||||
|
||||
@@ -1,29 +1,77 @@
|
||||
export function parseAllowedTools(claudeArgs: string): string[] {
|
||||
// Match --allowedTools or --allowed-tools followed by the value
|
||||
// Handle both quoted and unquoted values
|
||||
// Use /g flag to find ALL occurrences, not just the first one
|
||||
const patterns = [
|
||||
/--(?:allowedTools|allowed-tools)\s+"([^"]+)"/g, // Double quoted
|
||||
/--(?:allowedTools|allowed-tools)\s+'([^']+)'/g, // Single quoted
|
||||
/--(?:allowedTools|allowed-tools)\s+([^'"\s][^\s]*)/g, // Unquoted (must not start with quote)
|
||||
];
|
||||
import { parse as parseShellArgs } from "shell-quote";
|
||||
|
||||
// Flags whose values make up the allowed-tools list.
|
||||
// Include both camelCase and hyphenated variants for CLI compatibility.
|
||||
const ALLOWED_TOOLS_FLAGS = new Set(["allowedTools", "allowed-tools"]);
|
||||
|
||||
/**
|
||||
* Strip comment lines from a shell argument string.
|
||||
* Lines whose first non-whitespace character is `#` are removed entirely.
|
||||
* Mirrors stripShellComments in base-action/src/parse-sdk-options.ts.
|
||||
*/
|
||||
function stripShellComments(input: string): string {
|
||||
return input
|
||||
.split("\n")
|
||||
.filter((line) => !line.trim().startsWith("#"))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenize a claude_args string the same way base-action/src/parse-sdk-options.ts
|
||||
* does: strip full comment lines, then run shell-quote. shell-quote returns
|
||||
* unquoted glob patterns (e.g. `mcp__github__*`) as `{ op: "glob", pattern }`
|
||||
* objects rather than strings, so recover their literal text; drop operator
|
||||
* tokens (`|`, `>`, `;`, ...) which carry no value.
|
||||
*/
|
||||
function tokenize(claudeArgs: string): string[] {
|
||||
return parseShellArgs(stripShellComments(claudeArgs))
|
||||
.map((token) => {
|
||||
if (typeof token === "string") return token;
|
||||
if (token && typeof token === "object" && "pattern" in token) {
|
||||
return (token as { pattern: string }).pattern;
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter((token): token is string => token !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the list of allowed tool names from a user-provided claude_args string.
|
||||
*
|
||||
* This is used to decide which GitHub MCP servers to install. It MUST stay in
|
||||
* agreement with how the actual tool list is built for the SDK in
|
||||
* base-action/src/parse-sdk-options.ts (parseClaudeArgsToExtraArgs): otherwise a
|
||||
* tool can be granted to Claude without its MCP server being installed, or a
|
||||
* server can be installed for a tool that was never granted (#1357).
|
||||
*
|
||||
* To stay in agreement it uses the same shell-quote tokenizer and the same
|
||||
* "an accumulating flag consumes all consecutive non-flag values" semantics,
|
||||
* so `--allowedTools "Read" "Grep" "mcp__github__get_commit"` captures all
|
||||
* three values, and commented-out lines are ignored.
|
||||
*/
|
||||
export function parseAllowedTools(claudeArgs: string): string[] {
|
||||
if (!claudeArgs?.trim()) return [];
|
||||
|
||||
const args = tokenize(claudeArgs);
|
||||
const tools: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const pattern of patterns) {
|
||||
for (const match of claudeArgs.matchAll(pattern)) {
|
||||
if (match[1]) {
|
||||
// Don't add if the value starts with -- (another flag)
|
||||
if (match[1].startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
for (const tool of match[1].split(",")) {
|
||||
const trimmed = tool.trim();
|
||||
if (trimmed && !seen.has(trimmed)) {
|
||||
seen.add(trimmed);
|
||||
tools.push(trimmed);
|
||||
}
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (!arg?.startsWith("--")) continue;
|
||||
|
||||
const flag = arg.slice(2);
|
||||
if (!ALLOWED_TOOLS_FLAGS.has(flag)) continue;
|
||||
|
||||
// Consume all consecutive non-flag values, e.g.
|
||||
// --allowedTools "Read" "Grep" "mcp__github__get_commit"
|
||||
while (i + 1 < args.length && !args[i + 1]!.startsWith("--")) {
|
||||
i++;
|
||||
for (const tool of args[i]!.split(",")) {
|
||||
const trimmed = tool.trim();
|
||||
if (trimmed && !seen.has(trimmed)) {
|
||||
seen.add(trimmed);
|
||||
tools.push(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+83
-13
@@ -723,16 +723,17 @@ describe("fetchGitHubData integration with time filtering", () => {
|
||||
triggerTime: "2024-01-15T12:00:00Z",
|
||||
});
|
||||
|
||||
// The reviewData field returns all reviews (not filtered), but the filtering
|
||||
// happens when processing review bodies for download
|
||||
// We can check the image download map to verify filtering
|
||||
expect(result.reviewData?.nodes?.length).toBe(3); // All reviews are returned
|
||||
// Only the review submitted before the trigger and not edited afterward
|
||||
// reaches the prompt. The review submitted after the trigger and the one
|
||||
// edited after the trigger are dropped (TOCTOU protection), matching the
|
||||
// issue/PR comment and body handling.
|
||||
expect(result.reviewData?.nodes?.length).toBe(1);
|
||||
expect(result.reviewData?.nodes?.[0]?.databaseId).toBe("1");
|
||||
|
||||
// Check that only the first review's body would be downloaded (filtered)
|
||||
// Only that surviving review's body is queued for image download.
|
||||
const reviewsInMap = Object.keys(result.imageUrlMap).filter((key) =>
|
||||
key.startsWith("review_body"),
|
||||
);
|
||||
// Only review 1 should have its body processed (before trigger and not edited after)
|
||||
expect(reviewsInMap.length).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
@@ -805,14 +806,83 @@ describe("fetchGitHubData integration with time filtering", () => {
|
||||
triggerTime: "2024-01-15T12:00:00Z",
|
||||
});
|
||||
|
||||
// The imageUrlMap contains processed comments for image downloading
|
||||
// We should have processed review comments, but only those before trigger time
|
||||
// The exact check depends on how imageUrlMap is structured, but we can verify
|
||||
// that filtering occurred by checking the review data still has all nodes
|
||||
expect(result.reviewData?.nodes?.length).toBe(1); // Original review is kept
|
||||
// The review itself is pre-trigger and kept, but its inline comments are
|
||||
// filtered to trigger time: the comment created after the trigger (id 11)
|
||||
// and the one edited after the trigger (id 12) are dropped, leaving only
|
||||
// the pre-trigger comment (id 10).
|
||||
expect(result.reviewData?.nodes?.length).toBe(1);
|
||||
const reviewCommentIds =
|
||||
result.reviewData?.nodes?.[0]?.comments?.nodes?.map((c) => c.databaseId);
|
||||
expect(reviewCommentIds).toEqual(["10"]);
|
||||
});
|
||||
|
||||
// The actual filtering happens during processing for image download
|
||||
// Since the mock doesn't actually download images, we verify the input was correct
|
||||
it("should filter reviews by both trigger time and actor", async () => {
|
||||
const mockOctokits = {
|
||||
graphql: jest.fn().mockResolvedValue({
|
||||
repository: {
|
||||
pullRequest: {
|
||||
number: 321,
|
||||
title: "Test PR",
|
||||
body: "PR body",
|
||||
author: { login: "author" },
|
||||
comments: { nodes: [] },
|
||||
files: { nodes: [] },
|
||||
reviews: {
|
||||
nodes: [
|
||||
{
|
||||
id: "1",
|
||||
databaseId: "1",
|
||||
author: { login: "reviewer1" },
|
||||
body: "Pre-trigger human review",
|
||||
state: "APPROVED",
|
||||
submittedAt: "2024-01-15T11:00:00Z",
|
||||
comments: { nodes: [] },
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
databaseId: "2",
|
||||
author: { login: "scanner[bot]" },
|
||||
body: "Pre-trigger bot review",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2024-01-15T11:00:00Z",
|
||||
comments: { nodes: [] },
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
databaseId: "3",
|
||||
author: { login: "reviewer3" },
|
||||
body: "Post-trigger human review",
|
||||
state: "CHANGES_REQUESTED",
|
||||
submittedAt: "2024-01-15T13:00:00Z",
|
||||
comments: { nodes: [] },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
user: { login: "trigger-user" },
|
||||
}),
|
||||
rest: {
|
||||
pulls: {
|
||||
listFiles: jest.fn().mockResolvedValue({ data: [] }),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = await fetchGitHubData({
|
||||
octokits: mockOctokits as any,
|
||||
repository: "test-owner/test-repo",
|
||||
prNumber: "321",
|
||||
isPR: true,
|
||||
triggerUsername: "trigger-user",
|
||||
triggerTime: "2024-01-15T12:00:00Z",
|
||||
excludeCommentsByActor: "*[bot]",
|
||||
});
|
||||
|
||||
// The trigger-time and actor filters compose: the pre-trigger human review
|
||||
// is kept, the pre-trigger bot review is dropped by actor, and the
|
||||
// post-trigger human review is dropped by trigger time.
|
||||
expect(result.reviewData?.nodes?.map((r) => r.databaseId)).toEqual(["1"]);
|
||||
});
|
||||
|
||||
it("should handle backward compatibility when no trigger time provided", async () => {
|
||||
|
||||
@@ -437,3 +437,51 @@ describe("integration tests", () => {
|
||||
expect(actualOutput).toBe(expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectContentType fallbacks", () => {
|
||||
test("falls back to text for malformed JSON objects", () => {
|
||||
// Looks like an object (starts with { ends with }) but does not parse.
|
||||
expect(detectContentType("{not valid json}")).toBe("text");
|
||||
});
|
||||
|
||||
test("falls back to text for malformed JSON arrays", () => {
|
||||
// Looks like an array (starts with [ ends with ]) but does not parse.
|
||||
expect(detectContentType("[not, valid, json]")).toBe("text");
|
||||
});
|
||||
|
||||
test("classifies non-python, non-js code keywords as python by default", () => {
|
||||
// Contains a code keyword ("class ") but matches neither the python-specific
|
||||
// nor the javascript-specific checks, so it hits the default branch.
|
||||
expect(detectContentType("class Foo {}")).toBe("python");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatResultContent non-string input", () => {
|
||||
test("handles a numeric (non-string) result value", () => {
|
||||
const result = formatResultContent(42);
|
||||
expect(result).toContain("42");
|
||||
});
|
||||
|
||||
test("handles a plain object (non-string, non-text-array) result value", () => {
|
||||
const result = formatResultContent({ status: "ok" });
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("system_other handling", () => {
|
||||
test("groups a non-init system turn as system_other", () => {
|
||||
const systemTurn: Turn = { type: "system", subtype: "some_other_subtype" };
|
||||
const grouped = groupTurnsNaturally([systemTurn]);
|
||||
expect(grouped).toHaveLength(1);
|
||||
expect(grouped[0]?.type).toBe("system_other");
|
||||
expect(grouped[0]?.data).toEqual(systemTurn);
|
||||
});
|
||||
|
||||
test("renders a system_other group as a System Message section", () => {
|
||||
const markdown = formatGroupedContent([
|
||||
{ type: "system_other", data: { type: "system" } as Turn },
|
||||
]);
|
||||
expect(markdown).toContain("## ⚙️ System Message");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,9 +37,43 @@ describe("parseAllowedTools", () => {
|
||||
|
||||
test("handles --allowedTools followed by another --allowedTools flag", () => {
|
||||
const args = "--allowedTools --allowedTools mcp__github__*";
|
||||
// The second --allowedTools is consumed as a value of the first, then skipped.
|
||||
// This is an edge case with malformed input - returns empty.
|
||||
expect(parseAllowedTools(args)).toEqual([]);
|
||||
// The first --allowedTools has no value (the next token is another flag);
|
||||
// the second consumes mcp__github__*. This matches how the SDK option
|
||||
// parser (parse-sdk-options.ts) reads the same input.
|
||||
expect(parseAllowedTools(args)).toEqual(["mcp__github__*"]);
|
||||
});
|
||||
|
||||
test("captures multiple values after a single --allowedTools flag", () => {
|
||||
// Regression for #1357: the install-decision parser must capture every
|
||||
// value, not just the first, so it agrees with the tools actually granted
|
||||
// to Claude. Previously only "Read" was seen, so the github MCP server was
|
||||
// not installed even though mcp__github__get_commit was granted.
|
||||
const args = '--allowedTools "Read" "Grep" "mcp__github__get_commit"';
|
||||
expect(parseAllowedTools(args)).toEqual([
|
||||
"Read",
|
||||
"Grep",
|
||||
"mcp__github__get_commit",
|
||||
]);
|
||||
});
|
||||
|
||||
test("captures multiple values spread across lines under one flag", () => {
|
||||
const args = `--allowedTools
|
||||
"Read"
|
||||
"Grep"
|
||||
"mcp__github__get_commit"`;
|
||||
expect(parseAllowedTools(args)).toEqual([
|
||||
"Read",
|
||||
"Grep",
|
||||
"mcp__github__get_commit",
|
||||
]);
|
||||
});
|
||||
|
||||
test("ignores commented-out lines", () => {
|
||||
// Regression for #1357: a commented-out flag must not be counted, matching
|
||||
// the SDK parser which strips comment lines before parsing.
|
||||
const args = `# --allowedTools "mcp__github__get_commit"
|
||||
--allowedTools "Read"`;
|
||||
expect(parseAllowedTools(args)).toEqual(["Read"]);
|
||||
});
|
||||
|
||||
test("parses multiple separate --allowed-tools flags", () => {
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { describe, expect, test, beforeEach, afterEach, spyOn } from "bun:test";
|
||||
import * as core from "@actions/core";
|
||||
import {
|
||||
setupGitHubToken,
|
||||
WorkflowValidationSkipError,
|
||||
} from "../src/github/token";
|
||||
|
||||
describe("setupGitHubToken", () => {
|
||||
let originalOverrideToken: string | undefined;
|
||||
let originalAdditionalPermissions: string | undefined;
|
||||
let getIDTokenSpy: any;
|
||||
let setSecretSpy: any;
|
||||
let warningSpy: any;
|
||||
let fetchSpy: any;
|
||||
let setTimeoutSpy: any;
|
||||
let consoleLogSpy: any;
|
||||
let consoleErrorSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
originalOverrideToken = process.env.OVERRIDE_GITHUB_TOKEN;
|
||||
originalAdditionalPermissions = process.env.ADDITIONAL_PERMISSIONS;
|
||||
delete process.env.OVERRIDE_GITHUB_TOKEN;
|
||||
delete process.env.ADDITIONAL_PERMISSIONS;
|
||||
|
||||
getIDTokenSpy = spyOn(core, "getIDToken").mockResolvedValue("oidc-token");
|
||||
setSecretSpy = spyOn(core, "setSecret").mockImplementation(() => {});
|
||||
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
|
||||
fetchSpy = spyOn(global, "fetch").mockResolvedValue(
|
||||
new Response(JSON.stringify({ token: "app-token" }), {
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
}),
|
||||
);
|
||||
setTimeoutSpy = spyOn(global, "setTimeout").mockImplementation(((
|
||||
handler: any,
|
||||
) => {
|
||||
handler();
|
||||
return 0 as any;
|
||||
}) as any);
|
||||
consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
|
||||
consoleErrorSpy = spyOn(console, "error").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalOverrideToken === undefined) {
|
||||
delete process.env.OVERRIDE_GITHUB_TOKEN;
|
||||
} else {
|
||||
process.env.OVERRIDE_GITHUB_TOKEN = originalOverrideToken;
|
||||
}
|
||||
|
||||
if (originalAdditionalPermissions === undefined) {
|
||||
delete process.env.ADDITIONAL_PERMISSIONS;
|
||||
} else {
|
||||
process.env.ADDITIONAL_PERMISSIONS = originalAdditionalPermissions;
|
||||
}
|
||||
|
||||
getIDTokenSpy.mockRestore();
|
||||
setSecretSpy.mockRestore();
|
||||
warningSpy.mockRestore();
|
||||
fetchSpy.mockRestore();
|
||||
setTimeoutSpy.mockRestore();
|
||||
consoleLogSpy.mockRestore();
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("returns app token from OIDC exchange", async () => {
|
||||
await expect(setupGitHubToken()).resolves.toBe("app-token");
|
||||
|
||||
expect(getIDTokenSpy).toHaveBeenCalledWith("claude-code-github-action");
|
||||
expect(setSecretSpy).toHaveBeenCalledWith("app-token");
|
||||
});
|
||||
|
||||
test("skips without retrying when workflow is missing from default branch", async () => {
|
||||
const message =
|
||||
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
|
||||
fetchSpy.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message,
|
||||
details: {
|
||||
error_code: "workflow_not_found_on_default_branch",
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 401, statusText: "Unauthorized" },
|
||||
),
|
||||
);
|
||||
|
||||
await expect(setupGitHubToken()).rejects.toBeInstanceOf(
|
||||
WorkflowValidationSkipError,
|
||||
);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
expect(warningSpy).toHaveBeenCalledWith(
|
||||
`Skipping action due to workflow validation: ${message}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("skips without retrying when workflow validation message has no error code", async () => {
|
||||
const message =
|
||||
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
|
||||
fetchSpy.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message,
|
||||
},
|
||||
}),
|
||||
{ status: 401, statusText: "Unauthorized" },
|
||||
),
|
||||
);
|
||||
|
||||
await expect(setupGitHubToken()).rejects.toBeInstanceOf(
|
||||
WorkflowValidationSkipError,
|
||||
);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||
expect(warningSpy).toHaveBeenCalledWith(
|
||||
`Skipping action due to workflow validation: ${message}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("retries ordinary token exchange errors instead of skipping", async () => {
|
||||
const message = "Bad credentials";
|
||||
fetchSpy.mockImplementation(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message,
|
||||
},
|
||||
}),
|
||||
{ status: 401, statusText: "Unauthorized" },
|
||||
),
|
||||
);
|
||||
|
||||
await expect(setupGitHubToken()).rejects.toThrow(message);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does not skip message-only workflow validation errors with unexpected status", async () => {
|
||||
const message =
|
||||
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
|
||||
fetchSpy.mockImplementation(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
message,
|
||||
},
|
||||
}),
|
||||
{ status: 500, statusText: "Internal Server Error" },
|
||||
),
|
||||
);
|
||||
|
||||
await expect(setupGitHubToken()).rejects.toThrow(message);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(3);
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -64,6 +64,16 @@ describe("validateBranchName", () => {
|
||||
expect(() => validateBranchName("feature/paris,france")).not.toThrow();
|
||||
expect(() => validateBranchName("fix/issue-1,2,3")).not.toThrow();
|
||||
});
|
||||
|
||||
it("should accept branch names containing @ (git-valid, used in team and tooling conventions)", () => {
|
||||
// Reported in #998: branches like "TICKET-123@add-feature" were rejected, even
|
||||
// though git check-ref-format and GitHub both accept @ anywhere in a ref name.
|
||||
// Also common as a leading prefix (e.g. "@hotfix/...") and in agent-generated
|
||||
// names ("task@sessionid"). Bare "@" and "@{" are still rejected.
|
||||
expect(() => validateBranchName("TICKET-123@add-feature")).not.toThrow();
|
||||
expect(() => validateBranchName("@hotfix/login-timeout")).not.toThrow();
|
||||
expect(() => validateBranchName("agent/task@abc123")).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("command injection attempts", () => {
|
||||
@@ -137,6 +147,12 @@ describe("validateBranchName", () => {
|
||||
expect(() => validateBranchName("HEAD@{yesterday}")).toThrow(/@{/);
|
||||
});
|
||||
|
||||
it("should reject the single character @", () => {
|
||||
// Per git-check-ref-format, a refname cannot be the single character "@";
|
||||
// "@" also resolves to HEAD in git revision syntax.
|
||||
expect(() => validateBranchName("@")).toThrow(/single character '@'/);
|
||||
});
|
||||
|
||||
it("should reject .lock suffix", () => {
|
||||
expect(() => validateBranchName("branch.lock")).toThrow(/\.lock/);
|
||||
expect(() => validateBranchName("feature.lock")).toThrow(/\.lock/);
|
||||
|
||||
Reference in New Issue
Block a user