import jwt from 'jsonwebtoken'; import axios from 'axios'; export interface GitHubToken { token: string; expiresAt: string | null; } export interface PatLiveness { live: boolean | null; status: 'absent' | 'accepted' | 'rejected' | 'unreachable'; upstreamStatus?: number; detail?: string; } export interface GitHubIssueLabel { name: string; color?: string; } export interface GitHubIssue { number: number; title: string; body: string; html_url: string; labels: GitHubIssueLabel[]; pull_request?: unknown; milestone?: { title: string } | null; } interface ListIssuesOptions { owner?: string; repo?: string; perPage?: number; installationId?: string; forceApp?: boolean; } interface CreateIssueOptions { owner?: string; repo?: string; title: string; body?: string; labels?: string[]; installationId?: string; forceApp?: boolean; } interface IssueCommentOptions { owner?: string; repo?: string; issueNumber: number; body: string; installationId?: string; forceApp?: boolean; } interface CloseIssueOptions { owner?: string; repo?: string; issueNumber: number; comment?: string; installationId?: string; forceApp?: boolean; } interface IssueNumberOptions { owner?: string; repo?: string; issueNumber: number; installationId?: string; forceApp?: boolean; } interface PullRequestOptions { owner?: string; repo?: string; pullNumber: number; installationId?: string; forceApp?: boolean; } interface MergePullRequestOptions extends PullRequestOptions { mergeMethod?: 'merge' | 'squash' | 'rebase'; commitTitle?: string; commitMessage?: string; sha?: string; } type PullReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT'; interface PullDiffOptions { owner?: string; repo?: string; pullNumber: number; } interface PullReviewOptions { owner?: string; repo?: string; pullNumber: number; event: PullReviewEvent; body?: string; installationId?: string; forceApp?: boolean; } interface CreatePullRequestOptions { owner?: string; repo?: string; title: string; head: string; base: string; body?: string; draft?: boolean; installationId?: string; forceApp?: boolean; } /** * GitHubAppService — generates short-lived installation access tokens * using a GitHub App's private key (RS256 JWT). * * Required env vars: * GITHUB_APP_ID — numeric app ID from GitHub App settings * GITHUB_APP_PRIVATE_KEY — PEM private key (from GCP SM) * GITHUB_APP_INSTALLATION_ID_COMMONLY — pre-known installation ID for Team-Commonly/commonly */ class GitHubAppService { /** * Generate a short-lived JWT to authenticate as the GitHub App itself (valid 10 min). * Used as a stepping stone to get installation access tokens. */ static generateAppJWT(): string { const now = Math.floor(Date.now() / 1000); return jwt.sign( { iat: now - 60, exp: now + 600, iss: process.env.GITHUB_APP_ID }, process.env.GITHUB_APP_PRIVATE_KEY as string, { algorithm: 'RS256' }, ); } /** * Exchange an installation ID for a short-lived installation access token (valid 1 hour). * This token is what agents use with `gh` CLI and `git`. */ static async getInstallationToken(installationId: string | number): Promise { const appJWT = this.generateAppJWT(); const res = await axios.post( `https://api.github.com/app/installations/${installationId}/access_tokens`, {}, { headers: { Authorization: `Bearer ${appJWT}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', }, }, ); return { token: res.data.token, expiresAt: res.data.expires_at }; } /** * Look up the installation ID for any repo where the app is installed. * Used for multi-repo support when owner/repo is not Team-Commonly/commonly. */ static async getInstallationIdForRepo(owner: string, repo: string): Promise { const appJWT = this.generateAppJWT(); const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/installation`, { headers: { Authorization: `Bearer ${appJWT}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', }, }, ); return res.data.id; } /** * Check whether a PAT is configured (simpler alternative to GitHub App). */ static isPatConfigured(): boolean { return !!process.env.GITHUB_PAT; } /** * Return the PAT directly as a token response. * PATs don't have a server-issued expiry, so expiresAt is null. */ static getPatToken(): GitHubToken { return { token: process.env.GITHUB_PAT as string, expiresAt: null }; } /** * Ask GitHub whether the PAT is accepted. Presence is not liveness: a token * can be set and still refused (revoked, expired), which is what the * 2026-08-04 outage looked like from inside the pods. * * Kept separate from isPatConfigured, which guards hot request paths and * must stay free of I/O. GET /rate_limit is documented as not counting * against the rate limit, so this diagnostic can be called freely. * * `live: null` means we could not reach a verdict. Only a 401 is a * rejection; anything else (403, 5xx, network) is reported as unknown rather * than guessed, since a false "dead" sends an operator to rotate a good key. */ static async checkPatLiveness(): Promise { if (!this.isPatConfigured()) return { live: false, status: 'absent' }; try { await axios.get('https://api.github.com/rate_limit', { headers: { Authorization: `Bearer ${process.env.GITHUB_PAT}`, Accept: 'application/vnd.github+json' }, timeout: 5000, }); return { live: true, status: 'accepted', upstreamStatus: 200 }; } catch (err) { const e = err as { message?: string; response?: { status?: number } }; const upstreamStatus = e.response?.status; if (upstreamStatus === 401) return { live: false, status: 'rejected', upstreamStatus }; return { live: null, status: 'unreachable', upstreamStatus, detail: e.message }; } } // ─── Issues API ────────────────────────────────────────────────────────── /** * Shared headers for GitHub REST API calls. * * The App installation token is the default credential: it lives an hour and * is scoped to the repos the App is installed on. The shared GITHUB_PAT is a * fallback for instances with no App configured, and using it is logged. * Supplying an installationId (or forceApp) is an app-only request, so a * broker tool stays fail-closed even if its caller forgets to pass forceApp. */ static async _apiHeaders(installationId?: string, forceApp = false): Promise> { // An explicit installationId is app-only even when it is empty, so a blank // value can neither pick the default installation nor reach the PAT. const appOnly = forceApp || installationId !== undefined; if (installationId !== undefined && !installationId) throw new Error('github_not_configured'); const resolvedInstallationId = installationId || process.env.GITHUB_APP_INSTALLATION_ID_COMMONLY; const appConfigured = !!( process.env.GITHUB_APP_ID && process.env.GITHUB_APP_PRIVATE_KEY && resolvedInstallationId ); let credential: string | undefined; if (appConfigured) { credential = (await this.getInstallationToken(resolvedInstallationId as string)).token; } else if (!appOnly && process.env.GITHUB_PAT) { console.warn('[github] GitHub App not configured; falling back to GITHUB_PAT'); credential = process.env.GITHUB_PAT; } if (!credential) throw new Error('github_not_configured'); return { Authorization: `Bearer ${credential}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', }; } /** * List open issues for a repo (excludes pull requests). */ static async listOpenIssues({ owner = 'Team-Commonly', repo = 'commonly', perPage = 20, installationId, forceApp }: ListIssuesOptions = {}): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/issues?state=open&per_page=${perPage}`, { headers }, ); return (res.data as GitHubIssue[]).filter((i) => !i.pull_request); } /** * Create a new GitHub issue. */ static async createIssue({ owner = 'Team-Commonly', repo = 'commonly', title, body, labels, installationId, forceApp }: CreateIssueOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const payload: Record = { title }; if (body) payload.body = body; if (labels?.length) payload.labels = labels; const res = await axios.post( `https://api.github.com/repos/${owner}/${repo}/issues`, payload, { headers }, ); return res.data; } /** * Add a comment to an existing issue. */ static async addIssueComment({ owner = 'Team-Commonly', repo = 'commonly', issueNumber, body, installationId, forceApp }: IssueCommentOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.post( `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body }, { headers }, ); return res.data; } /** * Close an issue (optionally with a final comment). */ static async closeIssue({ owner = 'Team-Commonly', repo = 'commonly', issueNumber, comment, installationId, forceApp }: CloseIssueOptions): Promise { if (comment) { await this.addIssueComment({ owner, repo, issueNumber, body: comment, installationId, forceApp }); } const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.patch( `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}`, { state: 'closed' }, { headers }, ); return res.data; } /** Fetch one issue without exposing the server credential to the caller. */ static async getIssue({ owner = 'Team-Commonly', repo = 'commonly', issueNumber, installationId, forceApp }: IssueNumberOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}`, { headers }, ); return res.data; } /** Fetch one pull request. */ static async getPullRequest({ owner = 'Team-Commonly', repo = 'commonly', pullNumber, installationId, forceApp }: PullRequestOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}`, { headers }, ); return res.data; } /** Create a pull request without returning the App credential to the seat. */ static async createPullRequest({ owner = 'Team-Commonly', repo = 'commonly', title, head, base, body, draft, installationId, forceApp, }: CreatePullRequestOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.post( `https://api.github.com/repos/${owner}/${repo}/pulls`, { title, head, base, ...(body !== undefined ? { body } : {}), ...(draft !== undefined ? { draft } : {}) }, { headers }, ); return res.data; } /** List files changed by one pull request. */ static async listPullRequestFiles({ owner = 'Team-Commonly', repo = 'commonly', pullNumber, installationId, forceApp }: PullRequestOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}/files`, { headers }, ); return res.data; } /** Merge one pull request using the connected GitHub App installation. */ static async mergePullRequest({ owner = 'Team-Commonly', repo = 'commonly', pullNumber, mergeMethod, commitTitle, commitMessage, installationId, forceApp, sha, }: MergePullRequestOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const payload: Record = {}; if (sha) payload.sha = sha; if (mergeMethod) payload.merge_method = mergeMethod; if (commitTitle) payload.commit_title = commitTitle; if (commitMessage) payload.commit_message = commitMessage; const res = await axios.put( `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}/merge`, payload, { headers }, ); return res.data; } // ─── Pull Requests API ───────────────────────────────────────────────────── /** * Fetch the raw unified diff for a pull request. * Uses the `application/vnd.github.v3.diff` media type, which makes the * `GET /repos/.../pulls/{n}` endpoint return the diff text instead of JSON. */ static async getPullDiff({ owner = 'Team-Commonly', repo = 'commonly', pullNumber }: PullDiffOptions): Promise { const headers = await this._apiHeaders(); headers.Accept = 'application/vnd.github.v3.diff'; const res = await axios.get( `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}`, { headers }, ); return res.data as string; } /** * Submit a review on a pull request. * `event` is one of APPROVE | REQUEST_CHANGES | COMMENT. GitHub requires a * non-empty `body` for REQUEST_CHANGES and COMMENT (the route enforces this). */ static async createPullReview({ owner = 'Team-Commonly', repo = 'commonly', pullNumber, event, body, installationId, forceApp, }: PullReviewOptions): Promise { const headers = await this._apiHeaders(installationId, forceApp); const payload: Record = { event }; if (body) payload.body = body; const res = await axios.post( `https://api.github.com/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, payload, { headers }, ); return res.data; } // ───────────────────────────────────────────────────────────────────────── /** * Check whether the GitHub App credentials are configured in env. */ static isConfigured(): boolean { return !!( process.env.GITHUB_APP_ID && process.env.GITHUB_APP_PRIVATE_KEY && process.env.GITHUB_APP_INSTALLATION_ID_COMMONLY ); } } export default GitHubAppService; // CJS compat: let require() return the default export directly // eslint-disable-next-line @typescript-eslint/no-require-imports module.exports = exports["default"]; Object.assign(module.exports, exports);