# GitHub

A program's side of GitHub, from the back end: repositories and their
files read and written, issues and pull requests and their comments,
reviews, check runs and commit statuses, releases and their assets, Actions
workflows dispatched and their runs listed, over GitHub's REST API page by
page; GitHub's GraphQL API through [graphql](graphql.md); a GitHub App's
own token and its installations' tokens; and GitHub's webhooks, checked and
done once in a job. An [extension](../extensions/README.md): ordinary Mote
in `extensions/github/`. Back to the [map](README.md).

```mote
use "pkg:github/webhooks.mote"
use "pkg:github/app.mote"

// A report from the program's page becomes an issue, written as the App.
server fn report(title: string, words: string): number requires signedIn limit 5 per hour
  let me = auth.me()?
  return githubIssueCreate(env("SHOP_REPO"), {title, body: `${words}\n\nFrom ${me?.email ?? "someone"}.`, labels: ["from-the-site"]}, `installation:${env("SHOP_INSTALLATION")}`)?.number

// Each push to main: a check run on its commit, done when the program has looked.
fn githubPushed(p: GithubPush): bool
  if p.branch != "main" return true
  let token = `installation:${p.installation}`
  let c = githubCheckCreate(p.repo, {name: "shop/links", sha: p.after, status: "in_progress"}, token)?
  githubCheckUpdate(p.repo, c.id, {status: "completed", conclusion: "success", output: {title: "Links", summary: "Every link answers."}}, token)?
  return true
```

```toml
[packages]
github = "../mote/extensions/github"
graphql = "../mote/extensions/graphql"
```

```sh
GITHUB_APP_ID=123456 GITHUB_APP_KEY="$(cat app.private-key.pem)" GITHUB_WEBHOOK_SECRET=… \
  SHOP_REPO=acme/shop SHOP_INSTALLATION=4242 bun dist/server/main.js
```

A program that acts as itself with one token says `GITHUB_TOKEN` (a
fine-grained personal access token, `github_pat_…`) and passes `""` as
each call's token.

**Not met GitHub.** Written from GitHub's REST reference (API version
`2022-11-28`, sent as `X-GitHub-Api-Version`) and its GraphQL and webhook
docs as of 2026, and run against a stand-in that answers in GitHub's shapes,
pages two at a time, keeps files' shas, refuses what GitHub refuses
(a check run from a person's token, a stale sha, a missing field) and checks
the App's JWT with the App's public key (`tests/svc_standin.mjs code`). The
webhook's signature is checked against GitHub's own published example. The
steps to check it with a real App are [below](#checking-it-against-github).

## The settings

| | |
|---|---|
| `GITHUB_TOKEN` | A token (a secret), read by the default `fn githubToken()`: for the calls whose token is `""`. A program that only acts as an App, or with people's own tokens, declares its own `githubToken` and needs none. |
| `GITHUB_APP_ID` | With `app.mote`: the App's id (its Client ID is taken too). |
| `GITHUB_APP_KEY` | With `app.mote`: the App's private key, the `.pem` GitHub gave (PKCS #1) or PKCS #8. A secret, read by `fn githubAppKey()`. |
| `GITHUB_WEBHOOK_SECRET` | With `webhooks.mote`: the webhook's secret. |
| `GITHUB_API` | Another address: GitHub Enterprise Server's (`https://ghe.example/api/v3`), or a stand-in. |
| `GITHUB_GRAPHQL` | The GraphQL address (unsaid: `<GITHUB_API>/graphql`; Enterprise Server's is `/api/graphql`). |
| `GITHUB_WAIT` | The longest wait for a spent limit, in seconds (60 unsaid). |
| `GITHUB_AGENT` | The User-Agent GitHub asks for (`mote-github` unsaid: say the app's name). |

## Tokens

Every call takes a `token` last:

| | |
|---|---|
| `""` | `githubToken()`: `GITHUB_TOKEN` unless the program says otherwise. |
| `"installation:4242"` | That installation's token, with `app.mote`: made from the App's JWT (`POST /app/installations/4242/access_tokens`), kept in the program's database (`GithubInstallToken`) and used by every call and every back end until five minutes before its hour ends, then made again. A webhook's event says its installation (`e.installation`, `p.installation`). |
| anything else | Used as it is: a person's OAuth token (from the [oauth](oauth.md) extension's `oauthToken(githubProvider(), user)`, [below](#in-a-persons-name)), an installation token made elsewhere. |

It is sent as `Authorization: Bearer …`, never logged.

`app.mote` also gives `githubAppJwt()` (RS256, a minute back, nine ahead,
`iss` the App's id), `githubInstallationOf(repo)` and
`githubInstallations(most)`. A key GitHub gives is PKCS #1, which
`crypto.jwt.sign` takes as it is (PKCS #8 too). An installation's token is
kept in the database for its hour sealed (`crypto.seal`, bound to its
installation) with `fn githubSealWith()`, which is the App's key unless the
program declares another secret; one that no longer opens (the key was
changed) is asked for again.

### In a person's name

With the [oauth](oauth.md) extension's GitHub sign-in set to keep its
token (`GITHUB_KEEP=1`, `GITHUB_SCOPES=repo`), a person who has connected
GitHub can have the program act as them: the issue is theirs, and GitHub's
limits are theirs too. `oauthToken` gives a token good for a minute more,
refreshed if it must be; it fails with the kind `"connect"` when the person
has not connected GitHub (or took it back), which the page can answer with
a link to `/auth/github/start`.

```mote
use "pkg:oauth/github.mote"
use "pkg:oauth/tokens.mote"
use "pkg:github/github.mote"

server fn reportBug(title: string, body: string): number requires signedIn
  let token = oauthToken(githubProvider(), auth.me()?.id ?? "")?
  let made = githubIssueCreate("acme/shop", {title, body, labels: ["from the app"]}, token)?
  return made.number
```

## The calls

Each `repo` is `"owner/name"`. Lists are read page by page by their `Link`
header, 100 a page, up to `most`.

| | |
|---|---|
| `githubMe(token)` · `githubRepo(repo, token)` · `githubRepos(most, token)` · `githubReposOf(owner, org, most, token)` | `GithubUser`, `GithubRepo` (`name`, `branch` the default one, `private`, …). `githubRepos` of an installation's token lists what the App may see. |
| `githubFile(repo, path, ref, token)` | `GithubFile`: `text`, `data` (bytes), `sha`. Over a megabyte it is read raw. |
| `githubFolder(repo, path, ref, token)` | `[{name, path, type, sha, size}]`. |
| `githubFilePut(repo, path, data, {message, sha?, branch?, author?}, token)` | A file made, or changed when `sha` is its latest: `{sha, commit}`. A sha that is not the latest is `"conflict"`: read it again. |
| `githubFileDelete(repo, path, {message, sha, …}, token)` | The commit's sha. |
| `githubIssues(repo, filter, most, token)` | `GithubIssue[]`, newest first; `filter` as GitHub takes it (`{state: "all", labels: "bug", assignee: "ada"}`). Pull requests are among them, `pull` true. |
| `githubIssue` · `githubIssueCreate(repo, {title, body?, labels?, assignees?, milestone?}, token)` · `githubIssueUpdate(repo, number, change, token)` · `githubLabelsAdd` | `change` is what changes: `{state: "closed", state_reason: "not_planned"}`. |
| `githubComment(repo, number, body, token)` · `githubComments` · `githubCommentEdit` | On an issue or a pull request's conversation. |
| `githubPulls` · `githubPull` · `githubPullCreate(repo, {title, head, base, body?, draft?}, token)` · `githubPullFiles` · `githubReview(repo, number, event, body, token)` · `githubMerge(repo, number, method, sha, token)` | `GithubPull` (`head`, `headSha`, `base`, `merged`, `mergeable`). |
| `githubCheckCreate(repo, {name, sha, status?, conclusion?, output?, url?, external?}, token)` · `githubCheckUpdate(repo, id, change, token)` · `githubChecks(repo, ref, most, token)` | Check runs: an App's token only (GitHub refuses a person's: `"refused"`). `output` is `{title, summary, text?, annotations?}`. |
| `githubStatus(repo, sha, state, context, description, url, token)` | A commit status, for any token. |
| `githubReleaseCreate(repo, {tag, name?, body?, target?, draft?, prerelease?, notes?}, token)` · `githubReleases` · `githubReleaseLatest` · `githubReleaseUpload(release, name, data, type, token)` | `notes: true` has GitHub write them. An asset goes to the release's `uploads` address. |
| `githubDispatch(repo, workflow, ref, inputs, token)` · `githubRepositoryDispatch(repo, event, payload, token)` · `githubRuns(repo, workflow, filter, most, token)` | Actions: a `workflow_dispatch` (GitHub answers with no run id), a `repository_dispatch`, the runs. |
| `githubGraphql(query, variables, token)` · `githubGraphqlAll(query, variables, at, most, token)` | [graphql](graphql.md) at GitHub's address, with the token. |
| `githubCall(method, path, body, token)` · `githubSend(…)` · `githubAll(path, key, most, token)` | Anything else, with the same headers, limits and failures. |

| Kind | |
|---|---|
| `"auth"` (401), `"refused"` (403), `"missing"` (404, 410), `"invalid"` (422: `data.errors`), `"conflict"` (409), `"limited"`, `"github"` (5xx), `"offline"` | The sentence is GitHub's message and, for a 422, which field (`GitHub: Validation Failed: title is missing_field`). `data.request` is GitHub's request id. |

## Limits

A spent primary limit (`x-ratelimit-remaining: 0`, until
`x-ratelimit-reset`) or a secondary one (`retry-after`, or a 403 that says
"rate limit", a minute) is kept by a hash of the token (`GithubHold`), so
that every caller with that token waits, not only the one that was told;
a wait within `GITHUB_WAIT` is waited out and the request made once more,
a longer one fails `"limited"` with `data.reset` (milliseconds) at once,
without asking GitHub. `GET`, `PUT` and `DELETE` are asked again on 5xx and
when no answer came; `POST` and `PATCH` only on 429 (GitHub keeps no
idempotency keys). Nothing paces requests ahead of a limit: GitHub's
advice (no more than about a request a second for writes, nothing in
parallel per token) is the program's to follow for now.

## Webhooks

`use "pkg:github/webhooks.mote"`: `POST /github/webhook` checks
`X-Hub-Signature-256` (`sha256=` and the HMAC-SHA256 of the body under
`GITHUB_WEBHOOK_SECRET`, in constant time: [`webhook.check`](back-end.md#webhooks)'s `"github"`) first; answers a `ping`; keeps
each delivery once by `X-GitHub-Delivery` (`GithubDelivery`, a month);
answers 202 at once (GitHub gives ten seconds); and hands the event to
`job fn githubDeliver`, which calls, each optional:

| | |
|---|---|
| `fn githubPushed(p: GithubPush): bool` | A push: `branch` or `tag`, `before`, `after`, `commits`, `installation`. |
| `fn githubIssueChanged(action, repo, i: GithubIssue): bool` | `issues`: opened, closed, labeled, … |
| `fn githubPullChanged(action, repo, p: GithubPull): bool` | `pull_request`: opened, synchronize, closed, … |
| `fn githubCommented(repo, number, c: GithubComment, pull): bool` | `issue_comment` created. |
| `fn githubInstalled(action, installation, account): bool` | `installation`; a deleted or suspended one's kept token is let go of. |
| `fn githubEvent(e: GithubEventIn): bool` | Every event, after the above: `type`, `action`, `repo`, `installation`, `sender`, `payload`. |

GitHub signs no time, so an old delivery replayed is told apart by its id
alone: it is answered and not done again. A body sent as a form
(`payload=…`) is read too.

## Left out

GitHub Apps' manifest flow and the user-to-server OAuth flow (the `oauth`
extension's); git's own data (trees, blobs, refs, commits made by hand);
code search, projects (v2 is GraphQL: `githubGraphql`), packages,
deployments and environments, secrets for Actions (they need sealing with
the repository's key), Codespaces, gists; GitHub Enterprise's admin API;
paced writes ahead of a limit.

## Checking it against GitHub

1. A fine-grained token on a test repository (Issues, Contents, Pull
   requests, Commit statuses, Actions read and write): `GITHUB_TOKEN=…`.
   `githubIssueCreate`, `githubIssues` with more than 100 issues (two
   pages), `githubFile` and `githubFilePut` with its sha, then again with
   the old sha (`"conflict"`), `githubReleaseCreate` with `notes: true` and
   an asset, `githubDispatch` of a workflow that says `on:
   workflow_dispatch`.
2. A GitHub App (Settings → Developer settings → GitHub Apps) with Checks,
   Issues and Contents, installed on the repository: `GITHUB_APP_ID`,
   `GITHUB_APP_KEY` the `.pem` as GitHub gave it. `githubInstallationOf`,
   then `githubCheckCreate` as `installation:<id>`: the check shows on the
   commit. Twice within the hour: one token made.
3. The App's webhook (or a repository's) at `https://<site>/github/webhook`
   with a secret: push, open an issue, comment; each hook is told once;
   "Redeliver" in the webhook's Recent Deliveries answers `again: true`.
4. `githubGraphqlAll` over a repository's issues with `first: 50`: every
   page.
5. Spend a limit on purpose (a loop of `githubRepo` with
   `GITHUB_WAIT=1` until GitHub answers 403 with
   `x-ratelimit-remaining: 0`): the call after says `"limited"` without
   asking.

Recorded in `tests/expect/real_svc_code.txt` (`tests/all.sh
real_svc_code`).
