Compare commits

...

17 Commits

Author SHA1 Message Date
David Blass 94e2b5f6e0 add terrible debugging 2025-10-13 14:19:47 -04:00
David Blass 03810d574e bump version 2025-10-13 14:14:52 -04:00
David Blass f52e94c612 27 2025-10-13 14:08:54 -04:00
David Blass 9444a0e208 iter 2025-10-13 14:04:46 -04:00
David Blass 2296060d04 await top-level runServer 2025-10-13 13:44:29 -04:00
David Blass 458bfe18a0 try different error handling 2025-10-13 13:35:10 -04:00
David Blass 4cfb9b5008 Revert "try adding more debug logging"
This reverts commit 06542e382a.
2025-10-13 13:28:35 -04:00
David Blass 06542e382a try adding more debug logging 2025-10-13 13:22:15 -04:00
David Blass bcdf6ab5fb add debug flag for mcp server 2025-10-13 13:02:04 -04:00
ssalbdivad 314f669f10 add debug logging 2025-10-09 19:28:00 -04:00
ssalbdivad a24275e21b bump version 2025-10-09 18:07:42 -04:00
ssalbdivad 872e620342 Revert "try to add debugging to mcp server"
This reverts commit 6d9c6fd2b1.
2025-10-09 18:07:28 -04:00
ssalbdivad 6d9c6fd2b1 try to add debugging to mcp server 2025-10-09 18:04:00 -04:00
ssalbdivad 008021df1c remove bad error handling 2025-10-09 17:53:22 -04:00
ssalbdivad d6bc0fdd64 iter 2025-10-09 17:45:38 -04:00
ssalbdivad 8fd0328109 propagate GITHUB_REPOSITORY 2025-10-09 17:26:01 -04:00
ssalbdivad a1f87ce118 unify installation token logic 2025-10-09 17:14:34 -04:00
12 changed files with 1583 additions and 1093 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
registry-url: "https://registry.npmjs.org"
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
run: pnpm install --frozen-lockfile
- name: Get package version
id: version
+6 -2
View File
@@ -1,6 +1,10 @@
# Ensure lockfile is up to date
echo "🔒 Updating lockfile..."
pnpm install --lockfile-only
# Build the action before committing
echo "🔨 Building action..."
npm run build
# Add the built files to the commit
git add entry.cjs
# Add the built files and lockfile to the commit
git add entry.cjs pnpm-lock.yaml
+27 -13
View File
@@ -16,7 +16,6 @@ export class ClaudeAgent implements Agent {
startTime: 0,
};
constructor(config: AgentConfig) {
if (!config.apiKey) {
throw new Error("Claude agent requires an API key");
@@ -50,7 +49,10 @@ export class ClaudeAgent implements Agent {
try {
const result = await spawn({
cmd: "bash",
args: ["-c", "curl -fsSL https://claude.ai/install.sh | bash -s 1.0.93"],
args: [
"-c",
"curl -fsSL https://claude.ai/install.sh | bash -s 1.0.93",
],
env: { ANTHROPIC_API_KEY: this.apiKey },
timeout: 120000, // 2 minute timeout
onStdout: () => {},
@@ -58,7 +60,9 @@ export class ClaudeAgent implements Agent {
});
if (result.exitCode !== 0) {
throw new Error(`Installation failed with exit code ${result.exitCode}: ${result.stderr}`);
throw new Error(
`Installation failed with exit code ${result.exitCode}: ${result.stderr}`
);
}
core.info("Claude Code installed successfully");
@@ -74,7 +78,6 @@ export class ClaudeAgent implements Agent {
core.info("Running Claude Code...");
try {
const claudePath = `${process.env.HOME}/.local/bin/claude`;
console.log(boxString(prompt, { title: "Prompt" }));
const args = [
@@ -82,12 +85,15 @@ export class ClaudeAgent implements Agent {
"--output-format",
"stream-json",
"--verbose",
"--debug",
"--permission-mode",
"bypassPermissions",
];
if (!process.env.GITHUB_INSTALLATION_TOKEN) {
throw new Error("GITHUB_INSTALLATION_TOKEN is required for GitHub integration");
throw new Error(
"GITHUB_INSTALLATION_TOKEN is required for GitHub integration"
);
}
const mcpConfig = createMcpConfig(process.env.GITHUB_INSTALLATION_TOKEN);
@@ -152,9 +158,9 @@ export class ClaudeAgent implements Agent {
} catch (error: any) {
try {
core.endGroup();
} catch {
}
const errorMessage = error instanceof Error ? error.message : "Unknown error";
} catch {}
const errorMessage =
error instanceof Error ? error.message : "Unknown error";
return {
success: false,
error: `Failed to execute Claude Code: ${errorMessage}`,
@@ -180,7 +186,12 @@ function processJSONChunk(chunk: string, agent?: ClaudeAgent): void {
["model", parsedChunk.model],
["cwd", parsedChunk.cwd],
["permission_mode", parsedChunk.permissionMode],
["tools", parsedChunk.tools?.length ? `${parsedChunk.tools.length} tools` : "none"],
[
"tools",
parsedChunk.tools?.length
? `${parsedChunk.tools.length} tools`
: "none",
],
[
"mcp_servers",
parsedChunk.mcp_servers?.length
@@ -207,7 +218,9 @@ function processJSONChunk(chunk: string, agent?: ClaudeAgent): void {
for (const content of parsedChunk.message.content) {
if (content.type === "text") {
if (content.text.trim()) {
core.info(boxString(content.text.trim(), { title: "Claude Code" }));
core.info(
boxString(content.text.trim(), { title: "Claude Code" })
);
}
} else if (content.type === "tool_use") {
if (agent) {
@@ -270,7 +283,6 @@ function processJSONChunk(chunk: string, agent?: ClaudeAgent): void {
core.info(` └─ bash_command: ${input.bash_command}`);
}
}
}
}
}
@@ -291,10 +303,12 @@ function processJSONChunk(chunk: string, agent?: ClaudeAgent): void {
case "result":
if (parsedChunk.subtype === "success") {
core.info(
tableString([
["Cost", `$${parsedChunk.total_cost_usd?.toFixed(4) || "0.0000"}`],
[
"Cost",
`$${parsedChunk.total_cost_usd?.toFixed(4) || "0.0000"}`,
],
["Input Tokens", parsedChunk.usage?.input_tokens || 0],
["Output Tokens", parsedChunk.usage?.output_tokens || 0],
["Duration", `${parsedChunk.duration_ms}ms`],
+1145 -770
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -7,10 +7,12 @@
import * as core from "@actions/core";
import { type ExecutionInputs, type MainParams, main } from "./main.ts";
import packageJson from "./package.json" with { type: "json" };
import { setupGitHubInstallationToken } from "./utils/github.ts";
async function run(): Promise<void> {
try {
console.log(`🐸 Running pullfrog/action@${packageJson.version}...`);
const prompt = core.getInput("prompt", { required: true });
const anthropic_api_key = core.getInput("anthropic_api_key");
@@ -44,7 +46,6 @@ async function run(): Promise<void> {
const result = await main(params);
if (!result.success) {
throw new Error(result.error || "Agent execution failed");
}
+13 -1
View File
@@ -1,9 +1,20 @@
/**
* Simple MCP configuration helper for adding our minimal GitHub comment server
*/
const actionPath = process.env.GITHUB_ACTION_PATH || process.cwd();
// const actionPath = process.env.GITHUB_ACTION_PATH || process.cwd();
import { fromHere } from "@ark/fs";
const actionPath = fromHere("..");
export function createMcpConfig(githubInstallationToken: string) {
const githubRepository = process.env.GITHUB_REPOSITORY;
if (!githubRepository) {
throw new Error(
"GITHUB_REPOSITORY environment variable is required for MCP GitHub integration"
);
}
return JSON.stringify(
{
mcpServers: {
@@ -12,6 +23,7 @@ export function createMcpConfig(githubInstallationToken: string) {
args: [`${actionPath}/mcp/server.ts`],
env: {
GITHUB_INSTALLATION_TOKEN: githubInstallationToken,
GITHUB_REPOSITORY: githubRepository,
},
},
},
+134 -70
View File
@@ -1,4 +1,5 @@
#!/usr/bin/env node
import { writeFileSync } from "node:fs";
// Minimal GitHub Issue Comment MCP Server
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -7,10 +8,34 @@ import { type } from "arktype";
import { z } from "zod";
import { resolveRepoContext } from "../utils/repo-context.ts";
const server = new McpServer({
name: "Minimal GitHub Issue Comment Server",
version: "0.0.1",
});
// Simple error logging to file
function logError(message: string, error?: any) {
const timestamp = new Date().toISOString();
const errorText = error ? `\nError: ${error.message}\nStack: ${error.stack}` : "";
const logEntry = `[${timestamp}] ${message}${errorText}\n`;
try {
writeFileSync("/tmp/mcp-error.log", logEntry, { flag: "a" });
console.error(logEntry);
} catch (writeError) {
console.error(`Failed to write error log: ${writeError}`);
console.error(logEntry);
}
}
let server: McpServer;
try {
logError("Creating MCP server...");
server = new McpServer({
name: "Minimal GitHub Issue Comment Server",
version: "0.0.1",
});
logError("MCP server created successfully");
} catch (error) {
logError("Failed to create MCP server", error);
process.exit(1);
}
// Define the schema for creating issue comments
const Comment = type({
@@ -18,75 +43,114 @@ const Comment = type({
body: type.string.describe("the comment body content"),
});
server.tool(
"create_issue_comment",
"Create a comment on a GitHub issue",
{
issueNumber: z.number().describe("the issue number to comment on"),
body: z.string().describe("the comment body content"),
},
async ({ issueNumber, body }) => {
try {
Comment.assert({ issueNumber, body });
try {
logError("Registering create_issue_comment tool...");
const githubInstallationToken = process.env.GITHUB_INSTALLATION_TOKEN;
if (!githubInstallationToken) {
throw new Error("GITHUB_INSTALLATION_TOKEN environment variable is required");
server.tool(
"create_issue_comment",
"Create a comment on a GitHub issue",
{
issueNumber: z.number().describe("the issue number to comment on"),
body: z.string().describe("the comment body content"),
},
async ({ issueNumber, body }) => {
try {
Comment.assert({ issueNumber, body });
const githubInstallationToken = process.env.GITHUB_INSTALLATION_TOKEN;
if (!githubInstallationToken) {
throw new Error("GITHUB_INSTALLATION_TOKEN environment variable is required");
}
// Resolve repository context from environment
const repoContext = resolveRepoContext();
const octokit = new Octokit({
auth: githubInstallationToken,
});
const result = await octokit.rest.issues.createComment({
owner: repoContext.owner,
repo: repoContext.name,
issue_number: issueNumber,
body: body,
});
return {
content: [
{
type: "text",
text: JSON.stringify(
{
success: true,
commentId: result.data.id,
url: result.data.html_url,
body: result.data.body,
},
null,
2
),
},
],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logError("Tool execution failed", error);
return {
content: [
{
type: "text",
text: `Error creating comment: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
// Resolve repository context from environment
const repoContext = resolveRepoContext();
const octokit = new Octokit({
auth: githubInstallationToken,
});
const result = await octokit.rest.issues.createComment({
owner: repoContext.owner,
repo: repoContext.name,
issue_number: issueNumber,
body: body,
});
return {
content: [
{
type: "text",
text: JSON.stringify(
{
success: true,
commentId: result.data.id,
url: result.data.html_url,
body: result.data.body,
},
null,
2
),
},
],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error creating comment: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
}
);
);
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
process.on("exit", () => {
server.close();
});
logError("Tool registered successfully");
} catch (error) {
logError("Failed to register tool", error);
process.exit(1);
}
runServer().catch(console.error);
async function runServer() {
try {
logError("Starting MCP server...");
const transport = new StdioServerTransport();
logError("Transport created, attempting connection...");
await server.connect(transport);
logError("MCP server connected successfully");
process.on("exit", () => {
logError("Process exiting, closing server...");
server.close();
});
process.on("SIGTERM", () => {
logError("SIGTERM received, closing server...");
server.close();
process.exit(0);
});
process.on("SIGINT", () => {
logError("SIGINT received, closing server...");
server.close();
process.exit(0);
});
} catch (error) {
logError("Server startup failed", error);
process.exit(1);
}
}
logError("Initializing MCP server process...");
runServer().catch((error) => {
logError("Unhandled server error", error);
process.exit(1);
});
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@pullfrog/action",
"version": "0.0.14",
"version": "0.0.29",
"type": "module",
"files": [
"index.js",
@@ -27,6 +27,7 @@
"createLockfile": "pnpm --ignore-workspace install"
},
"dependencies": {
"@ark/fs": "0.49.0",
"@actions/core": "^1.11.1",
"@modelcontextprotocol/sdk": "^1.17.5",
"@octokit/rest": "^22.0.0",
@@ -34,7 +35,8 @@
"arktype": "^2.1.22",
"dotenv": "^17.2.2",
"execa": "^9.6.0",
"table": "^6.9.0"
"table": "^6.9.0",
"zod": "^3.24.4"
},
"devDependencies": {
"@types/node": "^20.10.0",
@@ -42,8 +44,7 @@
"esbuild": "^0.25.9",
"husky": "^9.0.0",
"typescript": "^5.3.0",
"zshy": "^0.4.1",
"zod": "^3.24.4"
"zshy": "^0.4.1"
},
"repository": {
"type": "git",
+10 -10
View File
@@ -1,23 +1,23 @@
import { existsSync, readFileSync } from "node:fs";
import { dirname, extname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { extname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { fromHere } from "@ark/fs";
import arg from "arg";
import { config } from "dotenv";
import { main } from "./main.ts";
import packageJson from "./package.json" with { type: "json" };
import { runAct } from "./utils/act.ts";
import { generateInstallationToken } from "./utils/generate-installation-token.ts";
import { setupGitHubInstallationToken } from "./utils/github.ts";
import { setupTestRepo } from "./utils/setup.ts";
config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export async function run(
prompt: string,
options: { act?: boolean } = {}
): Promise<{ success: boolean; output?: string | undefined; error?: string | undefined }> {
try {
console.log(`🐸 Running pullfrog/action@${packageJson.version}...`);
if (options.act) {
console.log("🐳 Running with Docker/act...");
runAct(prompt);
@@ -53,10 +53,10 @@ export async function run(
inputs.github_token = process.env.GITHUB_TOKEN;
}
console.log("🔑 Generating GitHub installation token...");
const installationToken = await generateInstallationToken();
console.log("🔑 Setting up GitHub installation token...");
const installationToken = await setupGitHubInstallationToken();
inputs.github_installation_token = installationToken;
console.log("✅ GitHub installation token generated successfully");
console.log("✅ GitHub installation token setup successfully");
const envWithToken = {
...process.env,
@@ -129,7 +129,7 @@ Examples:
const ext = extname(filePath).toLowerCase();
let resolvedPath: string;
const fixturesPath = join(__dirname, "fixtures", filePath);
const fixturesPath = fromHere("fixtures", filePath);
if (existsSync(fixturesPath)) {
resolvedPath = fixturesPath;
} else if (existsSync(filePath)) {
+11 -3
View File
@@ -11,6 +11,9 @@ importers:
'@actions/core':
specifier: ^1.11.1
version: 1.11.1
'@ark/fs':
specifier: 0.49.0
version: 0.49.0
'@modelcontextprotocol/sdk':
specifier: ^1.17.5
version: 1.19.1
@@ -32,6 +35,9 @@ importers:
table:
specifier: ^6.9.0
version: 6.9.0
zod:
specifier: ^3.24.4
version: 3.25.76
devDependencies:
'@types/node':
specifier: ^20.10.0
@@ -48,9 +54,6 @@ importers:
typescript:
specifier: ^5.3.0
version: 5.9.3
zod:
specifier: ^3.24.4
version: 3.25.76
zshy:
specifier: ^0.4.1
version: 0.4.3(typescript@5.9.3)
@@ -69,6 +72,9 @@ packages:
'@actions/io@1.1.3':
resolution: {integrity: sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==}
'@ark/fs@0.49.0':
resolution: {integrity: sha512-AEjAQS/bu1CGIRiKK/XLaQ73cSJHixfexq28wNt+kBpQ0h1RwVIVzaGsn/+5IWw6DEbR7LB+3hil5gzrzEeyZQ==}
'@ark/schema@0.49.0':
resolution: {integrity: sha512-GphZBLpW72iS0v4YkeUtV3YIno35Gimd7+ezbPO9GwEi9kzdUrPVjvf6aXSBAfHikaFc/9pqZOpv3pOXnC71tw==}
@@ -902,6 +908,8 @@ snapshots:
'@actions/io@1.1.3': {}
'@ark/fs@0.49.0': {}
'@ark/schema@0.49.0':
dependencies:
'@ark/util': 0.49.0
-177
View File
@@ -1,177 +0,0 @@
import { createSign } from "node:crypto";
import { config } from "dotenv";
import { resolveRepoContext } from "./repo-context.ts";
config();
interface GitHubAppConfig {
appId: string;
privateKey: string;
repoOwner: string;
repoName: string;
}
interface Installation {
id: number;
account: {
login: string;
type: string;
};
}
interface Repository {
owner: {
login: string;
};
name: string;
}
interface InstallationTokenResponse {
token: string;
expires_at: string;
}
interface RepositoriesResponse {
repositories: Repository[];
}
const base64UrlEncode = (str: string): string => {
return Buffer.from(str)
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
};
const generateJWT = (appId: string, privateKey: string): string => {
const now = Math.floor(Date.now() / 1000);
const payload = {
iat: now - 60,
exp: now + 5 * 60,
iss: appId,
};
const header = {
alg: "RS256",
typ: "JWT",
};
const encodedHeader = base64UrlEncode(JSON.stringify(header));
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
const signaturePart = `${encodedHeader}.${encodedPayload}`;
const signature = createSign("RSA-SHA256")
.update(signaturePart)
.sign(privateKey, "base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
return `${signaturePart}.${signature}`;
};
const githubRequest = async <T>(
path: string,
options: {
method?: string;
headers?: Record<string, string>;
body?: string;
} = {}
): Promise<T> => {
const { method = "GET", headers = {}, body } = options;
const url = `https://api.github.com${path}`;
const requestHeaders = {
Accept: "application/vnd.github.v3+json",
"User-Agent": "Pullfrog-Installation-Token-Generator/1.0",
...headers,
};
const response = await fetch(url, {
method,
headers: requestHeaders,
...(body && { body }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`GitHub API request failed: ${response.status} ${response.statusText}\n${errorText}`
);
}
return response.json() as T;
};
const checkRepositoryAccess = async (
token: string,
repoOwner: string,
repoName: string
): Promise<boolean> => {
try {
const response = await githubRequest<RepositoriesResponse>("/installation/repositories", {
headers: { Authorization: `token ${token}` },
});
return response.repositories.some(
(repo) => repo.owner.login === repoOwner && repo.name === repoName
);
} catch {
return false;
}
};
const createInstallationToken = async (jwt: string, installationId: number): Promise<string> => {
const response = await githubRequest<InstallationTokenResponse>(
`/app/installations/${installationId}/access_tokens`,
{
method: "POST",
headers: { Authorization: `Bearer ${jwt}` },
}
);
return response.token;
};
const findInstallationId = async (
jwt: string,
repoOwner: string,
repoName: string
): Promise<number> => {
const installations = await githubRequest<Installation[]>("/app/installations", {
headers: { Authorization: `Bearer ${jwt}` },
});
for (const installation of installations) {
try {
const tempToken = await createInstallationToken(jwt, installation.id);
const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName);
if (hasAccess) {
return installation.id;
}
} catch {}
}
throw new Error(
`No installation found with access to ${repoOwner}/${repoName}. ` +
"Ensure the GitHub App is installed on the target repository."
);
};
export const generateInstallationToken = async (): Promise<string> => {
const repoContext = resolveRepoContext();
const config: GitHubAppConfig = {
appId: process.env.GITHUB_APP_ID!,
privateKey: process.env.GITHUB_PRIVATE_KEY?.replace(/\\n/g, "\n")!,
repoOwner: repoContext.owner,
repoName: repoContext.name,
};
const jwt = generateJWT(config.appId, config.privateKey);
const installationId = await findInstallationId(jwt, config.repoOwner, config.repoName);
const token = await createInstallationToken(jwt, installationId);
return token;
};
+229 -41
View File
@@ -1,4 +1,6 @@
import { createSign } from "node:crypto";
import * as core from "@actions/core";
import { resolveRepoContext } from "./repo-context.ts";
export interface InstallationToken {
token: string;
@@ -10,55 +12,241 @@ export interface InstallationToken {
owner?: string;
}
interface GitHubAppConfig {
appId: string;
privateKey: string;
repoOwner: string;
repoName: string;
}
interface Installation {
id: number;
account: {
login: string;
type: string;
};
}
interface Repository {
owner: {
login: string;
};
name: string;
}
interface InstallationTokenResponse {
token: string;
expires_at: string;
}
interface RepositoriesResponse {
repositories: Repository[];
}
function checkExistingToken(): string | null {
const inputToken = core.getInput("github_installation_token");
const envToken = process.env.GITHUB_INSTALLATION_TOKEN;
return inputToken || envToken || null;
}
function isGitHubActionsEnvironment(): boolean {
return Boolean(process.env.GITHUB_ACTIONS);
}
async function acquireTokenViaOIDC(): Promise<string> {
core.info("Generating OIDC token...");
const oidcToken = await core.getIDToken("pullfrog-api");
core.info("OIDC token generated successfully");
const apiUrl = process.env.API_URL || "https://pullfrog.ai";
core.info("Exchanging OIDC token for installation token...");
const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, {
method: "POST",
headers: {
Authorization: `Bearer ${oidcToken}`,
"Content-Type": "application/json",
},
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(
`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText} - ${errorText}`
);
}
const tokenData = (await tokenResponse.json()) as InstallationToken;
core.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`);
return tokenData.token;
}
const base64UrlEncode = (str: string): string => {
return Buffer.from(str)
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
};
const generateJWT = (appId: string, privateKey: string): string => {
const now = Math.floor(Date.now() / 1000);
const payload = {
iat: now - 60,
exp: now + 5 * 60,
iss: appId,
};
const header = {
alg: "RS256",
typ: "JWT",
};
const encodedHeader = base64UrlEncode(JSON.stringify(header));
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
const signaturePart = `${encodedHeader}.${encodedPayload}`;
const signature = createSign("RSA-SHA256")
.update(signaturePart)
.sign(privateKey, "base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
return `${signaturePart}.${signature}`;
};
const githubRequest = async <T>(
path: string,
options: {
method?: string;
headers?: Record<string, string>;
body?: string;
} = {}
): Promise<T> => {
const { method = "GET", headers = {}, body } = options;
const url = `https://api.github.com${path}`;
const requestHeaders = {
Accept: "application/vnd.github.v3+json",
"User-Agent": "Pullfrog-Installation-Token-Generator/1.0",
...headers,
};
const response = await fetch(url, {
method,
headers: requestHeaders,
...(body && { body }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`GitHub API request failed: ${response.status} ${response.statusText}\n${errorText}`
);
}
return response.json() as T;
};
const checkRepositoryAccess = async (
token: string,
repoOwner: string,
repoName: string
): Promise<boolean> => {
try {
const response = await githubRequest<RepositoriesResponse>("/installation/repositories", {
headers: { Authorization: `token ${token}` },
});
return response.repositories.some(
(repo) => repo.owner.login === repoOwner && repo.name === repoName
);
} catch {
return false;
}
};
const createInstallationToken = async (jwt: string, installationId: number): Promise<string> => {
const response = await githubRequest<InstallationTokenResponse>(
`/app/installations/${installationId}/access_tokens`,
{
method: "POST",
headers: { Authorization: `Bearer ${jwt}` },
}
);
return response.token;
};
const findInstallationId = async (
jwt: string,
repoOwner: string,
repoName: string
): Promise<number> => {
const installations = await githubRequest<Installation[]>("/app/installations", {
headers: { Authorization: `Bearer ${jwt}` },
});
for (const installation of installations) {
try {
const tempToken = await createInstallationToken(jwt, installation.id);
const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName);
if (hasAccess) {
return installation.id;
}
} catch {}
}
throw new Error(
`No installation found with access to ${repoOwner}/${repoName}. ` +
"Ensure the GitHub App is installed on the target repository."
);
};
async function acquireTokenViaGitHubApp(): Promise<string> {
const repoContext = resolveRepoContext();
const config: GitHubAppConfig = {
appId: process.env.GITHUB_APP_ID!,
privateKey: process.env.GITHUB_PRIVATE_KEY?.replace(/\\n/g, "\n")!,
repoOwner: repoContext.owner,
repoName: repoContext.name,
};
const jwt = generateJWT(config.appId, config.privateKey);
const installationId = await findInstallationId(jwt, config.repoOwner, config.repoName);
const token = await createInstallationToken(jwt, installationId);
return token;
}
async function acquireNewToken(): Promise<string> {
if (isGitHubActionsEnvironment()) {
return await acquireTokenViaOIDC();
} else {
return await acquireTokenViaGitHubApp();
}
}
/**
* Setup GitHub installation token for the action
*/
export async function setupGitHubInstallationToken(): Promise<string> {
const inputToken = core.getInput("github_installation_token");
const envToken = process.env.GITHUB_INSTALLATION_TOKEN;
const existingToken = inputToken || envToken;
const existingToken = checkExistingToken();
if (existingToken) {
core.setSecret(existingToken);
core.info("Using provided GitHub installation token");
return existingToken;
}
core.info("Generating OIDC token...");
try {
const oidcToken = await core.getIDToken("pullfrog-api");
core.info("OIDC token generated successfully");
const apiUrl = process.env.API_URL || "https://pullfrog.ai";
core.info("Exchanging OIDC token for installation token...");
const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, {
method: "POST",
headers: {
Authorization: `Bearer ${oidcToken}`,
"Content-Type": "application/json",
},
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(
`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText} - ${errorText}`
);
}
const tokenData = (await tokenResponse.json()) as InstallationToken;
core.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`);
core.setSecret(tokenData.token);
process.env.GITHUB_INSTALLATION_TOKEN = tokenData.token;
return tokenData.token;
} catch (error) {
throw new Error(
`Failed to setup GitHub installation token: ${error instanceof Error ? error.message : "Unknown error"}`
);
}
const token = await acquireNewToken();
core.setSecret(token);
process.env.GITHUB_INSTALLATION_TOKEN = token;
return token;
}