(
creds: GithubAppCredentials,
org: string,
)
| 200 | * used as `Authorization: token <token>` against the REST and GraphQL APIs. |
| 201 | */ |
| 202 | export async function getInstallationToken( |
| 203 | creds: GithubAppCredentials, |
| 204 | org: string, |
| 205 | ): Promise<string> { |
| 206 | if (cached && cached.expiresAtMs - Date.now() > REFRESH_SKEW_MS) { |
| 207 | return cached.token; |
| 208 | } |
| 209 | |
| 210 | const jwt = await mintAppJwt(creds); |
| 211 | const installationId = await resolveInstallationId(jwt, org); |
| 212 | |
| 213 | const res = await fetch( |
| 214 | `${GITHUB_API}/app/installations/${installationId}/access_tokens`, |
| 215 | { |
| 216 | method: "POST", |
| 217 | headers: { |
| 218 | Authorization: `Bearer ${jwt}`, |
| 219 | Accept: "application/vnd.github+json", |
| 220 | "X-GitHub-Api-Version": "2022-11-28", |
| 221 | "User-Agent": USER_AGENT, |
| 222 | }, |
| 223 | }, |
| 224 | ); |
| 225 | if (res.status !== 201) { |
| 226 | throw new Error( |
| 227 | `GitHub installation token mint -> ${res.status}: ${await res.text()}`, |
| 228 | ); |
| 229 | } |
| 230 | const body = (await res.json()) as { token: string; expires_at: string }; |
| 231 | cached = { |
| 232 | token: body.token, |
| 233 | expiresAtMs: new Date(body.expires_at).getTime(), |
| 234 | installationId, |
| 235 | }; |
| 236 | return cached.token; |
| 237 | } |
| 238 | |
| 239 | /** Read App credentials off a Worker env. Throws if either is missing. */ |
| 240 | export function githubAppCredentialsFromEnv(env: { |
no test coverage detected