|
| 1 | +import jwt from '@tsndr/cloudflare-worker-jwt'; |
| 2 | +import { Octokit } from 'octokit'; |
| 3 | + |
| 4 | +import { ExposableError, Logger } from '@gitbook/runtime'; |
| 5 | +import { GitHubIssuesRepository, GitHubIssuesRuntimeContext } from './types'; |
| 6 | + |
| 7 | +const logger = Logger('github-issues:github-client'); |
| 8 | + |
| 9 | +const GITBOOK_INTEGRATION_USER_AGENT = 'GitBook-GitHub-Issues-Integration'; |
| 10 | +const GITHUB_API_VERSION = '2022-11-28'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Fetch repositories with issues from a specific GitHub App installation |
| 14 | + */ |
| 15 | +export async function fetchGitHubReposForInstallation( |
| 16 | + octokit: Octokit, |
| 17 | + installationId: string, |
| 18 | +): Promise<GitHubIssuesRepository[]> { |
| 19 | + try { |
| 20 | + const response = await octokit.request('GET /installation/repositories', { |
| 21 | + per_page: 100, |
| 22 | + headers: { |
| 23 | + 'X-GitHub-Api-Version': GITHUB_API_VERSION, |
| 24 | + }, |
| 25 | + }); |
| 26 | + |
| 27 | + const repositories = response.data.repositories; |
| 28 | + |
| 29 | + return repositories.filter((repo) => repo.has_issues); |
| 30 | + } catch (error) { |
| 31 | + logger.error( |
| 32 | + `Failed to fetch GitHub repositories with issue for installation ${installationId}: `, |
| 33 | + error instanceof Error ? error.message : String(error), |
| 34 | + ); |
| 35 | + return []; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Get an authenticated Octokit instance for a GitHub app installation. |
| 41 | + */ |
| 42 | +export async function getOctokitClientForInstallation( |
| 43 | + context: GitHubIssuesRuntimeContext, |
| 44 | + githubInstallationId: string, |
| 45 | +): Promise<Octokit> { |
| 46 | + const { installation } = context.environment; |
| 47 | + if (!installation) { |
| 48 | + throw new ExposableError(`GitBook installation not found`); |
| 49 | + } |
| 50 | + |
| 51 | + const config = getGitHubAppConfig(context); |
| 52 | + if (!config.appId || !config.privateKey) { |
| 53 | + throw new ExposableError('GitHub App credentials not configured'); |
| 54 | + } |
| 55 | + |
| 56 | + const token = await getGitHubInstallationAccessToken({ |
| 57 | + githubInstallationId, |
| 58 | + appId: config.appId, |
| 59 | + privateKey: config.privateKey, |
| 60 | + }); |
| 61 | + |
| 62 | + return new Octokit({ |
| 63 | + auth: token, |
| 64 | + userAgent: GITBOOK_INTEGRATION_USER_AGENT, |
| 65 | + }); |
| 66 | +} |
| 67 | +/** |
| 68 | + * Generate a JWT token for GitHub App authentication. |
| 69 | + */ |
| 70 | +async function generateGitHubAppJWT(appId: string, privateKey: string): Promise<string> { |
| 71 | + const now = Math.floor(Date.now() / 1000); |
| 72 | + |
| 73 | + const payload = { |
| 74 | + iat: now - 60, // Issued 60 seconds ago (for clock drift) |
| 75 | + exp: now + 60 * 10, |
| 76 | + iss: appId, |
| 77 | + }; |
| 78 | + |
| 79 | + return await jwt.sign(payload, privateKey, { algorithm: 'RS256' }); |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Get an access token for a GitHub App installation. |
| 84 | + */ |
| 85 | +async function getGitHubInstallationAccessToken(args: { |
| 86 | + githubInstallationId: string; |
| 87 | + appId: string; |
| 88 | + privateKey: string; |
| 89 | +}): Promise<string> { |
| 90 | + const { githubInstallationId, appId, privateKey } = args; |
| 91 | + const jwtToken = await generateGitHubAppJWT(appId, privateKey); |
| 92 | + |
| 93 | + const octokit = new Octokit({ |
| 94 | + auth: jwtToken, |
| 95 | + userAgent: GITBOOK_INTEGRATION_USER_AGENT, |
| 96 | + }); |
| 97 | + |
| 98 | + try { |
| 99 | + const response = await octokit.request( |
| 100 | + 'POST /app/installations/{installation_id}/access_tokens', |
| 101 | + { |
| 102 | + installation_id: parseInt(githubInstallationId), |
| 103 | + headers: { |
| 104 | + 'X-GitHub-Api-Version': GITHUB_API_VERSION, |
| 105 | + }, |
| 106 | + }, |
| 107 | + ); |
| 108 | + |
| 109 | + return response.data.token; |
| 110 | + } catch (error) { |
| 111 | + const errorMessage = error instanceof Error ? error.message : String(error); |
| 112 | + throw new Error(`Failed to get installation access token: ${errorMessage}`); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Get GitHub App configuration for installation-based authentication. |
| 118 | + */ |
| 119 | +export function getGitHubAppConfig(context: GitHubIssuesRuntimeContext) { |
| 120 | + return { |
| 121 | + appId: context.environment.secrets.GITHUB_APP_ID, |
| 122 | + privateKey: context.environment.secrets.GITHUB_PRIVATE_KEY, |
| 123 | + installationIds: context.environment.installation?.configuration?.installation_ids, |
| 124 | + }; |
| 125 | +} |
0 commit comments