Getting a GitHub App installation token on the command-line
This post's featured URL for sharing metadata is https://www.jvt.me/img/profile.jpg.
When using GitHub App authentication, there's a slightly more complex setup for authenticating.
Depending on what you're doing you can simply use the GitHub SDKs, but sometimes you just want an installation access token, for instance to clone a repository as the app.
To do this, I've found that a straightforward command-line app is best:
import { createAppAuth } from '@octokit/auth-app'
import { App } from '@octokit/app'
(async () => {
const appId = process.env.GITHUB_APP_ID ?? ''
const privateKey = (process.env.GITHUB_APP_KEY ?? '').replaceAll(/\\n/g, '\n')
const installationId = process.env.GITHUB_INSTALLATION_ID ?? ''
const auth = createAppAuth({
appId,
privateKey
})
const app = new App({
appId,
privateKey
})
for await (const { installation } of app.eachInstallation.iterator()) {
if (installationId !== '' && Number(installationId) !== installation.id) {
continue
}
const resp = await auth({
type: 'installation',
installationId: installation.id,
})
console.log(`${installation.id} => ${resp.token}`)
}
})().catch((e) => {
console.error(e)
process.exit(1)
})
This requires the following setup:
package.json
{
"dependencies": {
"@octokit/app": "^13.1.2",
"@octokit/auth-app": "^4.0.9"
},
"devDependencies": {
"@tsconfig/node16": "^1.0.3",
"typescript": "^4.8.4"
},
"bin": "dist/index.js",
"scripts": {
"build": "tsc"
}
}
tsconfig.json
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@tsconfig/node16/tsconfig.json",
"include": [
"./*"
],
"compilerOptions": {
"outDir": "dist"
}
}
But then can be run with:
npm i
npm run build
# Encode the private key for an environment variable via https://www.jvt.me/posts/2023/02/11/pem-environment-variable/
env GITHUB_APP_ID=... GITHUB_APP_KEY="$(sed ':a;N;$!ba;s/\n/\\n/g' key.pem)" GITHUB_INSTALLATION_ID=... node dist/index.js
# alternatively, to list all installations and their access tokens, omit `GITHUB_INSTALLATION_ID`
env GITHUB_APP_ID=... GITHUB_APP_KEY="$(sed ':a;N;$!ba;s/\n/\\n/g' key.pem)" node dist/index.js