Getting a GitHub App installation token on the command-line

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

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #typescript #github.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.