Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

GitHub runners: run jobs of GitHub repositories on Diffinery's hosted runners

Repositories that stay on GitHub can run Actions jobs on a Diffinery instance's
hosted runners, like Blacksmith or RunsOn: install the instance's GitHub App,
link the installation to the Diffinery account that pays, and set runs-on to
diffinery (or diffinery-medium, -small, -tiny).

- POST /-/github/webhook takes the app's signed workflow_job deliveries. A queued
  job for Diffinery waits in the paying account's GitHubRunnersDO for a hosted
  slot (quotas, kill switches), then gets a just-in-time runner on GitHub and a
  hosted runner container that runs GitHub's own actions/runner for that job.
- Settings → GitHub runners links installations (a signed state bound to the
  person, and GitHub confirming they manage the installation) and lists recent
  runners with their status.
- Idle runners stop after 10 minutes, runners that crash before a job are
  replaced up to 3 times, and account suspension and the compute pause stop
  GitHub runners too.
- The runner image includes actions/runner 2.338.2 (checksum-verified).
- Migration 0044_github_runners.sql; Durable Object migration v7.
- Docs: actions/github-runners, self-hosting configuration for the app, and
  product pages that said Diffinery can't serve repositories on GitHub.
Alan Kernel authored 1 parent 0ffa4efcommit 07c1e0bb047b55ff29ac1b8376f850c21371ed55Browse files
38 files changed+2255−42
Files (38)
modifiedapps/diffinery/docs/actions/compatibility.md+2−0View file
@@ -93,6 +93,8 @@
9393 - Every job starts in a fresh container. Nothing carries over between jobs except caches and artifacts.
9494 - `/dev/kvm` is available, so the Android emulator and other KVM tools run with hardware acceleration. The image has no udev, so leave out the "Enable KVM" udev step that GitHub's Android guides add, and install the emulator's X libraries first. See [Hardware virtualization (KVM)](/docs/actions/runners#hardware-virtualization-kvm).
9595
96+A repository that stays on GitHub can run its jobs on Diffinery's hosted runners with `runs-on: diffinery` (or `diffinery-medium`, `diffinery-small`, `diffinery-tiny`). There GitHub's own runner runs the job, as a self-hosted runner, so GitHub's behavior applies in full; the differences are the image above, `root`, and a workspace under `/opt/actions-runner/_work`. See [GitHub runners](/docs/actions/github-runners).
97+
9698 On self-hosted runners, `runner.os` is always `Linux`, and the setup actions download Linux builds, even on a macOS machine. See [Self-hosted runners](/docs/actions/runners#self-hosted-runners).
9799
98100 ## Jobs and steps
addedapps/diffinery/docs/actions/github-runners.md+131−0View file
@@ -1,0 +1,131 @@
1+---
2+title: GitHub runners
3+description: Keep your code on GitHub and run its Actions jobs on Diffinery's hosted runners: install the app, link the account that pays, and set runs-on to diffinery.
4+updated: 2026-10-30
5+---
6+
7+You don't have to move your code to use Diffinery's runners. Keep your repositories and workflows on GitHub, install Diffinery's GitHub App, and change a job's `runs-on` to `diffinery`. The job then runs on a Diffinery hosted runner (a fresh Ubuntu 24.04 container with 4 vCPUs on Cloudflare) instead of a GitHub-hosted one. Logs, checks, caches, artifacts and `GITHUB_TOKEN` stay on GitHub, as with any self-hosted runner.
8+
9+## How it works
10+
11+1. GitHub tells Diffinery about each queued job of a repository where the app is installed (the `workflow_job` webhook).
12+2. If the job's `runs-on` asks for a Diffinery runner, Diffinery checks the hosted minutes and hosted jobs of the Diffinery account you linked, then registers a [just-in-time runner](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/autoscaling-with-self-hosted-runners#using-just-in-time-runners) for that one job in the repository.
13+3. Diffinery starts a hosted runner container. It runs GitHub's own runner ([actions/runner](https://github.com/actions/runner)), which takes the job, runs it and reports to GitHub.
14+4. When the job ends, the runner removes itself from GitHub and the container stops. Nothing carries over to the next job.
15+
16+Because GitHub's own runner runs the job, everything a GitHub workflow does works the same way: `uses:` actions, service containers, `actions/cache`, artifacts, OIDC, environments and required reviewers, concurrency and re-runs.
17+
18+## Set it up
19+
20+You need a Diffinery account, and on GitHub you must be able to install apps on the user or organization (an organization owner, or the owner of a personal account).
21+
22+1. Open **Settings → GitHub runners**.
23+2. Under **Connect GitHub**, pick the **Account that pays**: yourself, or a Diffinery organization you own or administer. Its hosted minutes pay for the jobs.
24+3. Click **Install on GitHub**. On GitHub, pick the user or organization, and **All repositories** or the repositories that should use Diffinery runners, then click **Install**.
25+4. GitHub asks you to authorize the app: click **Authorize**. This shows Diffinery which installations your GitHub account can manage; Diffinery doesn't keep the token.
26+5. You're back on **Settings → GitHub runners**, with the installation listed under the account that pays.
27+
28+If the app is already installed (for example, someone else installed it), click **Link an existing installation** instead. After you authorize the app, Diffinery lists the installations your GitHub account can manage. Pick one and the account that pays, and click **Link**. Linking an installation that is linked to another Diffinery account moves it.
29+
30+To change which repositories can use Diffinery runners later, click **Choose repositories on GitHub** next to the installation.
31+
32+## Use it in a workflow
33+
34+Set `runs-on` to a Diffinery label:
35+
36+```yaml
37+jobs:
38+ test:
39+ runs-on: diffinery # 4 vCPU, 12 GiB of memory
40+ steps:
41+ - uses: actions/checkout@v4
42+ - run: npm ci && npm test
43+ lint:
44+ runs-on: diffinery-small # 1/2 vCPU, 4 GiB of memory
45+ steps:
46+ - uses: actions/checkout@v4
47+ - run: npm run lint
48+```
49+
50+| `runs-on` | Runner |
51+|---|---|
52+| `diffinery` or `diffinery-large` | large: 4 vCPU, 12 GiB of memory, 20 GB of disk |
53+| `diffinery-medium` | medium: 2 vCPU, 8 GiB, 16 GB |
54+| `diffinery-small` | small: 1/2 vCPU, 4 GiB, 8 GB |
55+| `diffinery-tiny` | tiny: 1/4 vCPU, 1 GiB, 4 GB |
56+
57+Rules:
58+
59+- A job is for Diffinery when its labels include `diffinery` or `diffinery-<size>`, and every other label is one of `self-hosted`, `linux` or `x64`. With several sizes, the largest wins. `runs-on: [self-hosted, linux, diffinery]` works.
60+- Any other label (`ubuntu-latest`, `gpu`, `arm64`, a runner group) leaves the job to GitHub: Diffinery starts no runner for it.
61+- Jobs without a Diffinery label keep running on GitHub-hosted runners, so you can move one job at a time.
62+- Diffinery doesn't pick a smaller size by itself for GitHub jobs, as it does for [jobs of Diffinery repositories](/docs/actions/runners#runner-sizes): the label sets the size.
63+- Matrix legs each get their own runner.
64+
65+## The machine
66+
67+The container runs the same image as Diffinery's own [hosted runners](/docs/actions/runners#hosted-runners): Ubuntu 24.04 on x64 with Git, Node.js 22, Python 3.12, Docker, the GitHub CLI and `/dev/kvm`. Differences from a GitHub-hosted runner:
68+
69+- The image is much smaller than GitHub's: Go, Java, Ruby, Rust, .NET, browsers and cloud CLIs aren't preinstalled. The `actions/setup-*` actions install them. See [The Ubuntu 24.04 image](/docs/actions/runners#the-ubuntu-2404-image).
70+- Jobs run as `root` (`RUNNER_ALLOW_RUNASROOT=1`). `sudo` needs no password, as on GitHub.
71+- The workspace is under `/opt/actions-runner/_work`; use `GITHUB_WORKSPACE` rather than a fixed path.
72+- `runner.environment` is `self-hosted` and the runner's name is `diffinery-<id>-<try>`.
73+- On instances that set [`EGRESS=web`](/docs/self-hosting/configuration#egress), jobs reach only HTTP, HTTPS and DNS.
74+
75+## What it costs, and limits
76+
77+GitHub jobs on Diffinery runners count exactly like hosted jobs of the linked account's own repositories (see [Limits](/docs/reference/limits#account-quotas)):
78+
79+- Their running time counts against the account's **hosted minutes** for the month, from the moment the container starts until it stops.
80+- They count against the account's **hosted jobs at once**. Further jobs wait, oldest first, and start as running ones finish. **Settings → GitHub runners** shows them as **waiting**, with the reason.
81+- When the account has used its hosted minutes for the month, new jobs aren't started: they show as **failed** with the reason, and stay queued on GitHub until GitHub gives up on them (after 24 hours) or you cancel them. Switch `runs-on` back to `ubuntu-latest` to run them on GitHub.
82+- A job runs for at most 6 hours.
83+
84+GitHub doesn't charge minutes for jobs on self-hosted runners, which is what Diffinery runners are to GitHub.
85+
86+## See what ran
87+
88+**Settings → GitHub runners** lists the last 30 runners of each account you manage, newest first, with the job (linked to its log on GitHub), the size, how long it ran and a status:
89+
90+| Status | Meaning |
91+|---|---|
92+| waiting | The job waits for a hosted slot of the account, or for GitHub to register its runner again. |
93+| starting | The runner is registered and its container is starting, or it waits for GitHub to hand it the job. |
94+| running | GitHub handed the runner a job. |
95+| done | The container stopped. The GitHub job's conclusion is shown under it. |
96+| skipped | The job ended before its runner started (cancelled, or another runner took it), or the installation was suspended or unlinked. |
97+| failed | No runner was started: the reason is shown, such as a kill switch, minutes used up, or GitHub refusing to register a runner. |
98+
99+GitHub hands a runner any queued job of the repository whose labels it has, so the job a runner ran may be another one with the same labels than the job it was started for. Each queued job still gets one runner.
100+
101+## Security
102+
103+- Each job gets a new container and a new just-in-time runner, registered in that one repository for that one job. Nothing of one job, not even the runner's credentials, is there for the next.
104+- The just-in-time configuration is the runner's credential. Diffinery passes it only to the container's environment, removes it from the job's environment, and never stores or logs it.
105+- The app asks for these repository permissions: **Administration: Read and write**, which GitHub requires to register and remove a repository's self-hosted runners; **Actions: Read** and **Metadata: Read**. It never reads your code.
106+- Only a person signed in with a passkey can link or unlink an installation, and only for themselves or an organization they own or administer; GitHub must confirm they can manage the installation. Linking and unlinking are in the [audit log](/docs/security/audit-log) as `github_runners.link` and `github_runners.unlink`.
107+- **Public repositories:** anyone who opens a pull request can change a workflow, and a workflow that runs on `diffinery` uses the linked account's minutes. Under the repository's **Settings → Actions → General**, require approval for fork pull request workflows from outside contributors (for example **Require approval for all external contributors**), as GitHub advises for any self-hosted runner.
108+- A site administrator's [kill switches](/docs/admin/site-administration#kill-switches) apply: suspending an account's Actions, or pausing hosted compute, fails the waiting jobs and stops the running runners.
109+
110+## Unlink or uninstall
111+
112+- **Unlink** on **Settings → GitHub runners** stops new runners for the installation. Jobs that wait get none; runners already started finish their jobs.
113+- Uninstalling the app on GitHub (in the user's or organization's settings, under **GitHub Apps** or **Applications → Installed GitHub Apps**) unlinks it too.
114+- Suspending the app on GitHub starts no runners until you unsuspend it.
115+
116+## Troubleshooting
117+
118+**The job stays queued on GitHub with "Waiting for a runner to pick up this job".** Check, in this order:
119+
120+1. The job's labels: every one must be `diffinery`, `diffinery-<size>`, `self-hosted`, `linux` or `x64`.
121+2. The repository is among the installation's repositories (**Choose repositories on GitHub**).
122+3. The installation is linked: it is listed on **Settings → GitHub runners**.
123+4. The job's row on **Settings → GitHub runners** and its message.
124+
125+**"Could not register a runner on GitHub: ... Resource not accessible by integration".** The app lacks the **Administration: Read and write** permission on the repository. An owner of the GitHub account reviews and accepts the app's new permissions in the installation's settings on GitHub (**Choose repositories on GitHub** opens them).
126+
127+**"No job took this runner within 10 minutes".** The job it was started for was cancelled, or ran on another runner with the same labels, and GitHub had no other job for it. Diffinery stopped the runner and removed it from GitHub; nothing to do.
128+
129+**"The runner stopped before it took a job (exit code N); starting another".** GitHub's runner exited before a job started, for example because GitHub was unreachable. Diffinery tries up to 3 runners for a job.
130+
131+**Settings → GitHub runners says "This Diffinery has no GitHub App".** The instance's administrator hasn't set the app up. See [Configuration](/docs/self-hosting/configuration#github-runners).
modifiedapps/diffinery/docs/actions/runners.md+2−0View file
@@ -5,6 +5,8 @@
55
66 A runner is the machine that executes one workflow job. Diffinery offers two kinds: **hosted runners**, which run each job in a fresh Ubuntu 24.04 container on Cloudflare, and **self-hosted runners**, which run jobs on a machine you control (a Mac, a GPU box, a server on a private network) using the `diffinery runner` command. You pick one per job with `runs-on`, the same key GitHub Actions uses.
77
8+Repositories that stay on GitHub can use the same hosted runners too: see [GitHub runners](/docs/actions/github-runners).
9+
810 ## How runs-on picks a runner
911
1012 Diffinery reads the job's `runs-on` labels (case-insensitive) and decides:
modifiedapps/diffinery/docs/admin/site-administration.md+1−0View file
@@ -219,6 +219,7 @@
219219
220220 - Suspending a repository or an account cancels each of its unfinished runs ("Cancelled: Actions are suspended ...", including jobs on self-hosted runners) and closes each of its open sandboxes.
221221 - Pausing hosted compute fails each running hosted job ("The job was stopped: Hosted runners are paused ...") and closes the open sandboxes, in every repository with hosted compute running (Diffinery finds them from the hosted minutes it is counting). Jobs that wait in the queue fail when they would start.
222+- [GitHub jobs on Diffinery runners](/docs/actions/github-runners) count as the linked account's hosted jobs: suspending that account, or pausing hosted compute, fails its GitHub jobs that wait for a runner and stops its running GitHub runners (counted in `jobs`). The jobs on GitHub end as their runner stops.
222223
223224 The answer says what was stopped: `stopped` with `repositories`, `runs`, `jobs`, `sandboxes`, and `failed` for repositories that didn't answer (their work still can't start).
224225
modifiedapps/diffinery/docs/nav.json+1−0View file
@@ -81,6 +81,7 @@
8181 "actions/events",
8282 "actions/expressions",
8383 "actions/runners",
84+ "actions/github-runners",
8485 "actions/docker",
8586 "actions/reusable-workflows",
8687 "actions/secrets-and-variables",
modifiedapps/diffinery/docs/self-hosting/configuration.md+51−3View file
@@ -35,6 +35,8 @@
3535 | `HOSTED_JOBS_LIMIT` | Not set | No | Hosted Actions jobs the whole instance runs at once (default `80`); one account runs at most half of them, accounts run by a site administrator included. Keep it under the runner container classes' `max_instances`. Past it, hosted jobs wait as queued until one finishes. See [Limits](/docs/reference/limits#actions). |
3636 | `IMPORT_GHE_HOST` | Not set | No | The host name of a GitHub Enterprise Server (like `ghe.example.com`) that imports may download release assets from. Without it, imports download release assets only from github.com and its asset hosts, and assets of an Enterprise import are skipped with a warning. |
3737 | `GITHUB_OAUTH_CLIENT_ID` | Not set | No | The client ID of a GitHub OAuth app, for linking GitHub accounts with a GitHub sign-in instead of a gist. Needs `GITHUB_OAUTH_CLIENT_SECRET` too. See [GitHub imports](#github-imports). |
38+| `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID` | Not set | No | The GitHub App that lets GitHub repositories run jobs on this instance's hosted runners: its App ID, its slug (the last part of `https://github.com/apps/<slug>`) and its Client ID. Needs `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY` and `GITHUB_APP_WEBHOOK_SECRET` too. See [GitHub runners](#github-runners). |
39+| `GITHUB_APP_URL` | Not set | No | The origin of a GitHub Enterprise Server for that app, like `https://ghe.example.com`. Default `https://github.com`. |
3840 | `IMPORT_GIT_AGENT` | Not set in production; `external` in the `dev` environment | Never in production | With `external`, an import's Git transfer doesn't start a container: it waits for an import agent started by hand (see [The dev environment](#the-dev-environment)). |
3941 | `SCHEDULE_TICK_MINUTES` | Not set | No | Minutes between the workflow scheduler's checks, a whole number from 1 to 60. Default `5`, GitHub's shortest schedule interval. Anything else counts as not set. The end-to-end tests use `1`. |
4042 | `WAIT_TIMER_MINUTE_MS` | Not set | Never in production | Local development and the end-to-end tests only: how long one minute of a deployment environment's wait timer lasts, in milliseconds, from 1 to `60000` (the default). Anything else counts as not set. It counts only when `PUBLIC_URL` is on this machine (`localhost`, `127.x` or `[::1]`) and `ACCESS_AUD` is empty, as for `DEV_AUTH`; a deployed Worker ignores it. The end-to-end tests use `10000` so a wait timer passes in seconds. |
@@ -176,6 +178,7 @@
176178 | `MASTER_KEY_PREV` | The `MASTER_KEY` you replaced | You, only while [rotating `MASTER_KEY`](#rotating-master_key) | Everything sealed or signed with the old key keeps working: secrets encrypted with it still decrypt, and links and tokens signed with it still verify. Nothing new uses it. | The normal state. Right after a rotation without it, secrets stored under the old key can't be read and links signed with it stop working, as if the old key had been lost. |
177179 | `OIDC_PRIVATE_KEY` | An ECDSA P-256 private key as a JWK (JSON), with a `kid` | `ensure-secrets.sh`, once | Signs the ID tokens that workflow jobs request with `permissions: id-token: write` (ES256). Its public half is served at `/.well-known/jwks`. | Jobs that request an ID token fail with `OIDC is not configured on this Diffinery instance`, `/.well-known/jwks` returns no keys, and `GET /api/v3/meta` returns `"oidc": false`. |
178180 | `GITHUB_OAUTH_CLIENT_SECRET` | The client secret of a GitHub OAuth app | You, optionally | With `GITHUB_OAUTH_CLIENT_ID`, turns on the **Link with GitHub** option on **Settings → Linked accounts**. | People link GitHub accounts with the gist code only. |
181+| `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_APP_WEBHOOK_SECRET` | The GitHub App's client secret, its private key (the PEM file GitHub gives, as it is) and its webhook secret | You, optionally | With `GITHUB_APP_ID`, `GITHUB_APP_SLUG` and `GITHUB_APP_CLIENT_ID`, turns on [GitHub runners](#github-runners). | **Settings → GitHub runners** says the instance has no GitHub App, and `POST /-/github/webhook` answers 404. |
179182 | `MAIL_EVENTS_SECRET` | A random string, at least 32 characters | You, optionally | Turns on `POST /-/email/events`, the signed intake for bounces and complaints from anything other than Cloudflare's own event subscriptions. See [Bounces, complaints and the suppression list](/docs/admin/site-administration#bounces-complaints-and-the-suppression-list). | The endpoint answers 404. Bounces and complaints still arrive through the `diffinery-mail-events` queue. |
180183 | `TURNSTILE_SECRET` | The secret key of a Cloudflare Turnstile widget | The deploy, from its widget (see [Turnstile](#turnstile)) | With `TURNSTILE_SITE_KEY`, checks that whoever asks for a sign-up code (with `SIGNUP=open`), or sends a security report, an early access request or a contact message without signing in, passed the Turnstile widget. See [SIGNUP](#signup) and [Security contact](#security-contact). | With `SIGNUP=open`, sign-up answers `503` "Sign-up needs Turnstile configured", the security report and contact forms take reports and messages only from people who are signed in, and the early access form is closed (local development skips the check). The next deploy sets it when the token has **Account → Turnstile → Edit**. |
181184
@@ -228,7 +231,7 @@
228231
229232 | Binding | Kind | Resource (production) | What Diffinery uses it for |
230233 | --- | --- | --- | --- |
231-| `DB` | D1 database | `diffinery` (migrations in `migrations/`) | Accounts (including each account's appearance setting and profile picture version), organizations, tokens, repository list, topics and access, invitations, sessions and passkeys, notifications, audit log, schedules, organization secrets and variables, the registry index, email settings and log, GitHub imports and linked GitHub accounts. |
234+| `DB` | D1 database | `diffinery` (migrations in `migrations/`) | Accounts (including each account's appearance setting and profile picture version), organizations, tokens, repository list, topics and access, invitations, sessions and passkeys, notifications, audit log, schedules, organization secrets and variables, the registry index, email settings and log, GitHub imports and linked GitHub accounts, and GitHub runners' installations and runners. |
232235 | `BUCKET` | R2 bucket | `diffinery-data` | Large git objects, LFS objects, archived job logs, caches, artifacts, container image layers and manifests, the event archive, release assets, cached source archives (zipball and tarball downloads) and profile pictures. |
233236 | `EVENTS` | Queue producer, with a consumer on the same Worker | `diffinery-events`, dead-letter queue `diffinery-events-dlq` | Repository events for webhooks, notifications and the audit log. Consumer: batches of up to 50, waiting up to 2 seconds, 8 retries. |
234237 | `MAIL` | Queue producer, with a consumer on the same Worker | `diffinery-mail`, dead-letter queue `diffinery-mail-dlq` | Email jobs. Consumer: batches of up to 20, waiting up to 2 seconds, 8 retries. Optional: without it emails are dropped with a warning in the logs. |
@@ -238,13 +241,14 @@
238241 | `REPO` | Durable Object namespace | Class `RepoDO` (SQLite) | One object per repository. |
239242 | `SCHEDULER` | Durable Object namespace | Class `SchedulerDO` (SQLite) | One object that starts scheduled workflow runs on its own alarm. |
240243 | `COMPOSE` | Durable Object namespace | Class `ComposeDO` (SQLite) | Joins the blocks of large artifact and cache uploads, one short-lived object per step, so the copying doesn't slow the repository's object. Without it, `RepoDO` does the joining. |
241-| `RUNNER` | Durable Object namespace with a container | Class `RunnerContainer` (SQLite) | One container per hosted workflow job. |
244+| `RUNNER` | Durable Object namespace with a container | Class `RunnerContainer` (SQLite) | One container per hosted workflow job, and per runner of a [GitHub job](/docs/actions/github-runners). |
245+| `GITHUB_RUNNERS` | Durable Object namespace | Class `GitHubRunnersDO` (SQLite) | One object per account that pays for [GitHub runners](#github-runners): it starts runners for its GitHub jobs on its own alarm. |
242246 | `SANDBOX` | Durable Object namespace with a container | Class `SandboxContainer` (SQLite) | One container per agent sandbox. |
243247 | `RUN_WORKFLOW` | Workflow | `diffinery-run`, class `RunWorkflow` | One durable instance per workflow run. |
244248 | `IMPORTER` | Durable Object namespace with a container | Class `ImportContainer` (SQLite) | One container per Git transfer of a GitHub import. |
245249 | `IMPORT_WORKFLOW` | Workflow | `diffinery-import`, class `ImportWorkflow` | One durable instance per attempt of a GitHub import. |
246250
247-The Durable Object classes are declared in six migrations (`new_sqlite_classes`): tag `v1` for `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` for `ImportContainer`, tag `v3` for `ProjectDO`, tag `v4` for `SchedulerDO`, tag `v5` for `RunnerContainerMedium`, `RunnerContainerSmall` and `RunnerContainerTiny`, and tag `v6` for `ComposeDO`. `wrangler deploy` applies a migration tag the account doesn't have yet.
251+The Durable Object classes are declared in seven migrations (`new_sqlite_classes`): tag `v1` for `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` for `ImportContainer`, tag `v3` for `ProjectDO`, tag `v4` for `SchedulerDO`, tag `v5` for `RunnerContainerMedium`, `RunnerContainerSmall` and `RunnerContainerTiny`, tag `v6` for `ComposeDO`, and tag `v7` for `GitHubRunnersDO`. `wrangler deploy` applies a migration tag the account doesn't have yet.
248252
249253 ## Other Worker settings
250254
@@ -317,6 +321,50 @@
317321
318322 Imports reach GitHub only on HTTPS hosts with public names; a GitHub API URL on a private address, `localhost`, `.local` or `.internal` is refused with `422 github_api_url must be a public host`.
319323
324+## GitHub runners
325+
326+[GitHub runners](/docs/actions/github-runners) let repositories that stay on GitHub run jobs on this instance's hosted runners. They need a GitHub App of your own; the runner containers, the `GITHUB_RUNNERS` Durable Object and the D1 tables of migration `0044_github_runners.sql` come with a normal deploy.
327+
328+Create the app on GitHub under **Settings → Developer settings → GitHub Apps → New GitHub App** (of your user, or of an organization for a shared instance), with these settings. `https://git.example.com` stands for your `PUBLIC_URL`.
329+
330+| Setting | Value |
331+| --- | --- |
332+| **GitHub App name** | Any, such as `Diffinery runners for git.example.com` |
333+| **Homepage URL** | `https://git.example.com` |
334+| **Callback URL** | `https://git.example.com/settings/github-runners/setup` |
335+| **Request user authorization (OAuth) during installation** | Off |
336+| **Setup URL** | `https://git.example.com/settings/github-runners/setup`, with **Redirect on update** on |
337+| **Webhook** | Active, URL `https://git.example.com/-/github/webhook`, and a random secret of at least 32 characters |
338+| **Repository permissions** | **Administration**: Read and write (to register and remove a repository's self-hosted runners). **Actions**: Read-only. **Metadata**: Read-only. Nothing else |
339+| **Subscribe to events** | **Workflow job** |
340+| **Where can this GitHub App be installed?** | **Any account** to let anyone with an account on your instance use it; **Only on this account** for your own repositories only |
341+
342+Then, on the app's page: note the **App ID** and the **Client ID**, click **Generate a new client secret**, and under **Private keys** click **Generate a private key**, which downloads a `.pem` file. Add the IDs and the slug under `vars` in `wrangler.jsonc`:
343+
344+```jsonc
345+"GITHUB_APP_ID": "123456",
346+"GITHUB_APP_SLUG": "diffinery-runners-for-git-example-com",
347+"GITHUB_APP_CLIENT_ID": "Iv23li...",
348+```
349+
350+and store the secrets:
351+
352+```sh
353+cd apps/diffinery
354+printf '%s' "$CLIENT_SECRET" | pnpm exec wrangler secret put GITHUB_APP_CLIENT_SECRET -c wrangler.deploy.jsonc
355+pnpm exec wrangler secret put GITHUB_APP_PRIVATE_KEY -c wrangler.deploy.jsonc < diffinery-runners.private-key.pem
356+printf '%s' "$WEBHOOK_SECRET" | pnpm exec wrangler secret put GITHUB_APP_WEBHOOK_SECRET -c wrangler.deploy.jsonc
357+```
358+
359+After the next deploy, **Settings → GitHub runners** offers **Install on GitHub**. GitHub's **Recent Deliveries** on the app's **Advanced** tab shows each webhook delivery and Diffinery's answer, such as `{"queued":true,"size":"large"}` or `{"ignored":"not for a Diffinery runner"}`.
360+
361+What to know:
362+
363+- Jobs run GitHub's own runner, which the runner image includes (`ACTIONS_RUNNER_VERSION` in `containers/runner/Dockerfile`). GitHub updates a runner that has fallen too far behind as it starts, which adds a few seconds to each job, so keep that version close to [the latest release](https://github.com/actions/runner/releases).
364+- GitHub jobs count against the linked account's quotas and the instance's `HOSTED_JOBS_LIMIT` like any hosted job, and [kill switches](/docs/admin/site-administration#kill-switches) stop them.
365+- The webhook isn't rate limited per address, because GitHub sends every delivery from a few addresses; it refuses any delivery without a good signature.
366+- Containers don't run under `wrangler dev`, so locally a GitHub job's runner fails to start ("Could not start a runner: ...").
367+
320368 ## Deploy script settings
321369
322370 Environment variables the scripts in `scripts/` read. `scripts/setup.sh` reads all of them too, asks for `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`, `DIFFINERY_DOMAIN` and `BOOTSTRAP_ADMINS` in a terminal when they aren't set, and requires `DIFFINERY_DOMAIN` (see [Deploy from your own machine](/docs/self-hosting/deploy#deploy-from-your-own-machine)):
addedapps/diffinery/migrations/0044_github_runners.sql+51−0View file
@@ -1,0 +1,51 @@
1+-- Diffinery runners for GitHub repositories (github-runners/): an instance's GitHub App is installed on a
2+-- GitHub user or organization, the installation is linked to the Diffinery account that pays, and jobs whose
3+-- runs-on asks for a Diffinery runner run in hosted runner containers with GitHub's own runner.
4+
5+-- A GitHub App installation linked to a Diffinery account. Its id is GitHub's installation id.
6+CREATE TABLE IF NOT EXISTS github_installations (
7+ id INTEGER PRIMARY KEY,
8+ account_id TEXT NOT NULL, -- the Diffinery person or organization whose hosted minutes it uses
9+ github_login TEXT NOT NULL, -- the GitHub user or organization it is installed on
10+ github_type TEXT NOT NULL, -- "User" or "Organization"
11+ linked_by TEXT NOT NULL, -- the Diffinery account that linked it
12+ linked_at TEXT NOT NULL,
13+ suspended_at TEXT -- suspended on GitHub: no runners start for it meanwhile
14+);
15+CREATE INDEX IF NOT EXISTS github_installations_account ON github_installations(account_id);
16+
17+-- One runner started (or waiting to start) for a queued GitHub job. GitHub hands a runner any queued job
18+-- of the repository whose labels it has, so the job a runner runs (ran_job_id) may not be the one that
19+-- asked for it (github_job_id).
20+CREATE TABLE IF NOT EXISTS github_runner_jobs (
21+ id TEXT PRIMARY KEY,
22+ account_id TEXT NOT NULL,
23+ installation_id INTEGER NOT NULL,
24+ repo TEXT NOT NULL, -- owner/name on GitHub
25+ github_job_id INTEGER NOT NULL,
26+ run_id INTEGER,
27+ workflow_name TEXT,
28+ job_name TEXT,
29+ html_url TEXT,
30+ labels TEXT NOT NULL, -- JSON: the job's runs-on labels, which the runner registers with
31+ size TEXT NOT NULL, -- runner/sizes.ts
32+ status TEXT NOT NULL, -- queued, starting, running, completed, skipped, failed
33+ tries INTEGER NOT NULL DEFAULT 0,
34+ runner_name TEXT,
35+ github_runner_id INTEGER,
36+ container TEXT,
37+ ran_job_id INTEGER,
38+ ran_job_name TEXT,
39+ conclusion TEXT, -- the GitHub job's conclusion, once GitHub reports it
40+ message TEXT, -- why it waits, was skipped or failed
41+ stop_reason TEXT, -- set when Diffinery stopped the runner itself
42+ exit_code INTEGER,
43+ created_at TEXT NOT NULL,
44+ started_at TEXT,
45+ picked_at TEXT,
46+ ended_at TEXT
47+);
48+CREATE UNIQUE INDEX IF NOT EXISTS github_runner_jobs_job ON github_runner_jobs(installation_id, github_job_id);
49+CREATE INDEX IF NOT EXISTS github_runner_jobs_account ON github_runner_jobs(account_id, status, created_at);
50+CREATE INDEX IF NOT EXISTS github_runner_jobs_installation ON github_runner_jobs(installation_id, created_at);
51+CREATE INDEX IF NOT EXISTS github_runner_jobs_runner ON github_runner_jobs(runner_name);
modifiedapps/diffinery/site/compare/blacksmith.md+11−6View file
@@ -1,16 +1,16 @@
11 ---
22 title: Diffinery vs Blacksmith
33 seo_title: "Diffinery vs Blacksmith: faster GitHub Actions, two approaches"
4-description: Blacksmith speeds up GitHub Actions on its own runners while you stay on GitHub. Diffinery replaces GitHub and Actions together. Specs, prices, trade-offs.
5-updated: 2026-10-25
4+description: Blacksmith runs GitHub Actions jobs on its runners while you stay on GitHub. Diffinery replaces GitHub and Actions, or runs your GitHub jobs itself.
5+updated: 2026-10-30
66 ---
77
8-Blacksmith and Diffinery both make GitHub Actions workflows run faster, in different ways. Blacksmith sells drop-in runners for GitHub Actions: your code, pull requests and workflows stay on GitHub, and jobs run on Blacksmith's machines. Diffinery replaces GitHub and GitHub Actions together, with fast runners built in. Blacksmith is a service that runs the runners for you; Diffinery is free, open-source software (Apache-2.0) that you deploy to your own Cloudflare account, with no hosted service (see [Deploy your own Diffinery](/docs/self-hosting/deploy) and the [source code](https://diffinery.com/codician/diffinery)). Blacksmith facts here are from its own website and documentation, checked on October 16, 2026, and linked below.
8+Blacksmith and Diffinery both make GitHub Actions workflows run faster, in different ways. Blacksmith sells drop-in runners for GitHub Actions: your code, pull requests and workflows stay on GitHub, and jobs run on Blacksmith's machines. Diffinery replaces GitHub and GitHub Actions together, with fast runners built in, and those runners can also run the jobs of repositories that stay on GitHub ([GitHub runners](/docs/actions/github-runners)). Blacksmith is a service that runs the runners for you; Diffinery is free, open-source software (Apache-2.0) that you deploy to your own Cloudflare account, with no hosted service (see [Deploy your own Diffinery](/docs/self-hosting/deploy) and the [source code](https://diffinery.com/codician/diffinery)). Blacksmith facts here are from its own website and documentation, checked on October 16, 2026, and linked below.
99
1010 ## In short
1111
1212 - **Choose Blacksmith** if you want to stay on GitHub and only want faster or cheaper CI. It needs a GitHub App and a new `runs-on` label, and offers Linux, Arm, Windows and macOS runners up to 32 vCPUs, run for you with nothing to deploy.
13-- **Choose Diffinery** if you want one platform for code, reviews and CI, with AI agents as accounts that the server holds to guardrails, and Linux runners that are 4 vCPU by default, and you're happy to run your own instance on Cloudflare.
13+- **Choose Diffinery** if you want one platform for code, reviews and CI, with AI agents as accounts that the server holds to guardrails, and Linux runners that are 4 vCPU by default, and you're happy to run your own instance on Cloudflare. Not ready to move? Your instance's runners work for repositories that stay on GitHub too, with `runs-on: diffinery`.
1414
1515 ## Side by side
1616
@@ -20,7 +20,8 @@
2020 | Who runs it | You: you deploy your instance to your own Cloudflare account and pay Cloudflare for its usage | Blacksmith runs the runners; GitHub runs the rest |
2121 | Where your code lives | Your Diffinery instance | GitHub (github.com, Enterprise Server or Enterprise Cloud) |
2222 | Setup | Deploy your instance ([guide](/docs/self-hosting/deploy)), then import your repositories; workflows run as they are | Install the GitHub App, change `runs-on` to a Blacksmith label such as `blacksmith-2vcpu-ubuntu-2404` |
23-| Personal repositories | Yes | No: GitHub organizations only ([source](https://docs.blacksmith.sh/introduction/quickstart)) |
23+| Runners for repositories on GitHub | Yes: install your instance's GitHub App and set `runs-on: diffinery` ([guide](/docs/actions/github-runners)) | Yes: that's the product |
24+| Personal repositories | Yes, on Diffinery and on GitHub | No: GitHub organizations only ([source](https://docs.blacksmith.sh/introduction/quickstart)) |
2425 | Linux x64 runner sizes | 1/4, 1/2, 2 and 4 vCPU; 4 vCPU and 12 GiB by default, smaller sizes picked per job from its measured runs | 2, 4, 8, 16 and 32 vCPU ([source](https://docs.blacksmith.sh/blacksmith-runners/overview)) |
2526 | Arm, Windows, macOS | Self-hosted runners only | Arm, Windows (public beta) and macOS on Apple M4 ([source](https://docs.blacksmith.sh/blacksmith-runners/overview)) |
2627 | Machines | Cloudflare Containers on AMD EPYC hosts | "Modern gaming CPUs", in Firecracker microVMs ([source](https://docs.blacksmith.sh/blacksmith-runners/overview)) |
@@ -34,7 +35,7 @@
3435
3536 ## Where each one is the better fit
3637
37-**Blacksmith is the better fit when** your team is settled on GitHub, needs macOS, Windows, Arm or runners larger than 4 vCPUs, wants SOC 2 Type 2 today, wants faster CI without moving anything, or doesn't want to run any infrastructure itself.
38+**Blacksmith is the better fit when** your team is settled on GitHub, needs macOS, Windows, Arm or runners larger than 4 vCPUs, wants SOC 2 Type 2 today, or doesn't want to run any infrastructure itself.
3839
3940 **Diffinery is the better fit when** you'd rather have one platform than GitHub plus a runner service and are happy to run it on your own Cloudflare account, your CI is Linux, you work with AI coding agents and want the forge itself to limit what they can do, or you want workflows, `gh`, your editor and your agents to move together.
4041
@@ -44,6 +45,10 @@
4445
4546 No. Blacksmith runners connect to GitHub through its GitHub App. On Diffinery, jobs run on your instance's hosted runners in Cloudflare Containers or on your own machines with `diffinery runner`.
4647
48+### Can Diffinery run jobs for repositories that stay on GitHub, like Blacksmith?
49+
50+Yes. Install your instance's GitHub App on your GitHub user or organization, link it to the Diffinery account whose hosted minutes pay, and set a job's `runs-on` to `diffinery` (or `diffinery-medium`, `diffinery-small`, `diffinery-tiny`). GitHub's own runner then runs the job in a fresh container on your instance. See [GitHub runners](/docs/actions/github-runners).
51+
4752 ### Is Diffinery cheaper than Blacksmith?
4853
4954 Diffinery itself is free and open source; you pay Cloudflare for what your instance uses, on the Workers Paid plan ("a minimum cost of $5 USD per month per account", plus usage above the included amounts; [source](https://developers.cloudflare.com/workers/platform/pricing/), checked October 25, 2026). That bill depends on your usage, so we don't quote a per-minute figure to compare. Blacksmith lists $0.004 per minute for a 2-vCPU Linux runner, against GitHub's $0.006, and runs the machines for you. Diffinery's default runner has 4 vCPUs.
modifiedapps/diffinery/site/compare/depot.md+3−3View file
@@ -2,7 +2,7 @@
22 title: Diffinery vs Depot
33 seo_title: "Diffinery vs Depot: CI runners, Depot CI and Git hosting"
44 description: Depot sells fast GitHub Actions runners, its own Depot CI engine and container builds. How it compares with Diffinery, with specs, prices and trade-offs.
5-updated: 2026-10-25
5+updated: 2026-10-30
66 ---
77
88 Depot started with fast container builds and now sells drop-in runners for GitHub Actions, its own CI engine that runs GitHub Actions YAML (Depot CI), and Git hosting in beta (Depot Code). Diffinery is a git forge with pull requests, issues, GitHub Actions–compatible CI and AI agents in one platform. Depot is a service that runs everything for you; Diffinery is free, open-source software (Apache-2.0) that you deploy to your own Cloudflare account, with no hosted service (see [Deploy your own Diffinery](/docs/self-hosting/deploy) and the [source code](https://diffinery.com/codician/diffinery)). Depot facts here are from its own website and documentation, checked on October 16, 2026, and linked below.
@@ -19,7 +19,7 @@
1919 | Who runs it | You: you deploy your instance to your own Cloudflare account and pay Cloudflare for its usage | Depot |
2020 | What it is | Git hosting, pull requests, issues, releases, a container registry and GitHub Actions–compatible CI | GitHub Actions runners, Depot CI (generally available since March 2026), container builds, a registry, and Depot Code (beta) ([runners](https://depot.dev/docs/github-actions/overview), [Depot CI](https://depot.dev/changelog/2026-03-24-depot-ci-now-available)) |
2121 | Git hosting and pull requests | Yes, with reviews, required checks, auto-merge and a merge queue | Depot Code, in beta: repositories or GitHub mirrors that trigger CI on push; Depot says a code review UI is in progress ([source](https://depot.dev/docs/code/overview)) |
22-| Runners for GitHub-hosted repositories | No (Diffinery runs its own repositories' workflows) | Yes, for repositories owned by GitHub organizations, with a `runs-on: depot-ubuntu-24.04` label ([source](https://depot.dev/docs/github-actions/overview)) |
22+| Runners for GitHub-hosted repositories | Yes, for repositories of GitHub users and organizations: install your instance's GitHub App and set `runs-on: diffinery` ([guide](/docs/actions/github-runners)) | Yes, for repositories owned by GitHub organizations, with a `runs-on: depot-ubuntu-24.04` label ([source](https://depot.dev/docs/github-actions/overview)) |
2323 | Linux x64 runner sizes | 1/4, 1/2, 2 and 4 vCPU; 4 vCPU and 12 GiB by default | 2 to 64 vCPU, 8 to 256 GB, on AMD EPYC Genoa ([source](https://depot.dev/docs/github-actions/runner-types)) |
2424 | Arm, Windows, macOS | Self-hosted runners only | Arm (Graviton4) and Windows; macOS on the Startup and Business plans ([source](https://depot.dev/docs/github-actions/runner-types)) |
2525 | Linux x64 price | Free and open source (Apache-2.0); you pay Cloudflare for your instance's usage, with runner containers billed by the 10 ms while a job runs ([source](https://developers.cloudflare.com/containers/pricing/), checked October 25, 2026) | $0.006 per minute at 2 vCPU, tracked per second; plans from $20 a month with 2,000 runner minutes included ([source](https://depot.dev/pricing)) |
@@ -31,7 +31,7 @@
3131
3232 ## Where each one is the better fit
3333
34-**Depot is the better fit when** container image builds are your bottleneck, you need runners bigger than 4 vCPUs or on macOS, Windows or Arm, you want to keep GitHub as your forge and speed up CI around it, or you don't want to run any infrastructure yourself.
34+**Depot is the better fit when** container image builds are your bottleneck, you need runners bigger than 4 vCPUs or on macOS, Windows or Arm, or you want to keep GitHub as your forge without running any infrastructure yourself.
3535
3636 **Diffinery is the better fit when** you want one place for code, review and CI with a mature pull request workflow, when your CI is Linux, and when AI agents do a growing share of your work and you want the forge to enforce what they can and can't do. You run Diffinery yourself, on your own Cloudflare account.
3737
modifiedapps/diffinery/site/compare/github.md+2−2View file
@@ -2,7 +2,7 @@
22 title: Diffinery vs GitHub
33 seo_title: "Diffinery vs GitHub and GitHub Actions: an honest comparison"
44 description: How Diffinery compares with GitHub and GitHub Actions on CI speed, runners, workflow compatibility, AI agents, security and features, with sources and dates.
5-updated: 2026-10-25
5+updated: 2026-10-30
66 ---
77
88 Diffinery is a git forge and CI platform that runs GitHub Actions workflows as they are. If you're on GitHub today, this page sets out what changes if you move, what gets better, and what GitHub still does that Diffinery doesn't. GitHub facts are from GitHub's own documentation and pricing pages, checked on October 16, 2026, and linked below. Diffinery's speed figures are measured; see [Performance](/performance). Diffinery is free, open-source software (Apache-2.0) that you deploy to your own Cloudflare account and domain; there is no hosted service, so moving from GitHub also means running your own instance. See [Deploy your own Diffinery](/docs/self-hosting/deploy) and the [source code](https://diffinery.com/codician/diffinery), mirrored [on GitHub](https://github.com/codician-team/diffinery). Diffinery is an open-source platform where Git hosting, pull requests with reviews in a web UI and GitHub Actions–compatible CI, marketplace actions included, all run on Cloudflare (checked October 25, 2026; see [Built on Cloudflare](/built-on-cloudflare#other-git-and-ci-projects-on-cloudflare)).
@@ -10,7 +10,7 @@
1010 ## In short
1111
1212 - **Choose Diffinery** if your team runs CI on private repositories and wants faster runners by default, uses AI coding agents and wants the server to enforce limits on them, works on Linux, and is happy to run its own instance on Cloudflare.
13-- **Stay on GitHub** if you need hosted macOS, Windows or Arm runners, forks for outside contributors, GitHub's app marketplace, Codespaces, Pages or Discussions, if you're an open-source project that depends on GitHub's network, or if you'd rather not run anything yourself: GitHub runs github.com for you, while a Diffinery instance is yours to deploy, update and pay Cloudflare for.
13+- **Stay on GitHub** if you need hosted macOS, Windows or Arm runners, forks for outside contributors, GitHub's app marketplace, Codespaces, Pages or Discussions, if you're an open-source project that depends on GitHub's network, or if you'd rather not run anything yourself: GitHub runs github.com for you, while a Diffinery instance is yours to deploy, update and pay Cloudflare for. Staying on GitHub doesn't rule out Diffinery's runners: [GitHub runners](/docs/actions/github-runners) run a GitHub job on your instance when its `runs-on` is `diffinery`.
1414 - **Moving is mostly mechanical.** Diffinery's importer copies repositories with history, issues, pull requests, reviews and releases, workflow files run unchanged, and `gh`, VS Code, Cursor and JetBrains IDEs keep working.
1515
1616 ## CI and runners
modifiedapps/diffinery/site/compare/index.md+5−3View file
@@ -2,7 +2,7 @@
22 title: GitHub and GitHub Actions alternatives, compared
33 seo_title: "GitHub Actions alternatives compared: Diffinery, Blacksmith, Depot"
44 description: How Diffinery compares with GitHub, GitLab, Bitbucket, Gitea, Forgejo, CircleCI, Buildkite and GitHub Actions runner services such as Blacksmith and Depot.
5-updated: 2026-10-25
5+updated: 2026-10-30
66 ---
77
88 Teams that want faster or cheaper CI than GitHub Actions have three kinds of options: keep GitHub and run jobs on another company's runners, keep their Git host and move CI to a separate CI service such as CircleCI or Buildkite, or move to a forge that hosts the code and runs the CI. Diffinery is the last kind: a git forge that runs GitHub Actions workflows as they are, on fast runners, with AI agents as accounts held to guardrails. It is free, open-source software (Apache-2.0) that you deploy to your own Cloudflare account and domain; there is no hosted service to sign up for. See [Deploy your own Diffinery](/docs/self-hosting/deploy) and the [source code](https://diffinery.com/codician/diffinery), mirrored [on GitHub](https://github.com/codician-team/diffinery). Diffinery is an open-source platform where Git hosting, pull requests with reviews in a web UI and GitHub Actions–compatible CI, marketplace actions included, all run on Cloudflare (checked October 25, 2026; see [Built on Cloudflare](/built-on-cloudflare#other-git-and-ci-projects-on-cloudflare)).
@@ -31,6 +31,8 @@
3131 | macOS and Windows | Offered by most runner services | Self-hosted runners only |
3232 | AI agents | Whatever GitHub offers | Agent accounts, server-enforced guardrails, MCP, sandboxes, tasks and review |
3333
34+Diffinery does the first too: your instance's runners can run the jobs of repositories that stay on GitHub, with its GitHub App and `runs-on: diffinery`. See [GitHub runners](/docs/actions/github-runners).
35+
3436 ## GitHub Actions runner services at a glance
3537
3638 Published list prices for a Linux x64 runner with 2 vCPUs, and what each service runs on. Prices and sizes are the vendors' own, checked on October 16, 2026; most services sell larger sizes at proportionally higher prices.
@@ -44,7 +46,7 @@
4446 | WarpBuild | Managed runners, or runners in your own cloud account | $0.004/min ([source](https://www.warpbuild.com/pricing)) | Arm, Windows (from 4 vCPU), macOS | No |
4547 | RunsOn | Runners in your own AWS account, under an annual license | Your AWS bill; RunsOn estimates about $0.0009/min on spot ([source](https://runs-on.com/pricing/)) | Arm, Windows, GPUs; no macOS | No |
4648 | Ubicloud | Managed runners on Ubicloud's open-source cloud in Germany | $0.002/min premium (default), $0.00125/min standard ([source](https://www.ubicloud.com/docs/about/pricing)) | Arm | No |
47-| **Diffinery** | An open-source git forge whose CI runs GitHub Actions workflows, deployed to your own Cloudflare account | Free and open source (Apache-2.0); you pay Cloudflare for your instance's usage. The default runner has 4 vCPU and 12 GiB | Self-hosted runners | Yes (your instance) |
49+| **Diffinery** | An open-source git forge whose CI runs GitHub Actions workflows, deployed to your own Cloudflare account | Free and open source (Apache-2.0); you pay Cloudflare for your instance's usage. The default runner has 4 vCPU and 12 GiB | Self-hosted runners | Yes (your instance); its runners also serve repositories on GitHub |
4850
4951 BuildJet, another runner service, has shut down ([source](https://buildjet.com/for-github-actions)).
5052
@@ -84,7 +86,7 @@
8486
8587 ### What's the best alternative to GitHub Actions?
8688
87-It depends on what you want to keep. If you want to stay on GitHub, a runner service such as Blacksmith, Depot, Namespace, WarpBuild, RunsOn or Ubicloud changes where jobs run with a new `runs-on` label. If you want faster CI and are willing to move your repositories and run your own instance on Cloudflare, Diffinery runs the same workflow files on 4-vCPU runners and also hosts your code, pull requests and AI agents. If you'd rather not run anything yourself, a runner service is the simpler choice.
89+It depends on what you want to keep. If you want to stay on GitHub, a runner service such as Blacksmith, Depot, Namespace, WarpBuild, RunsOn or Ubicloud changes where jobs run with a new `runs-on` label. If you want faster CI and are willing to run your own instance on Cloudflare, Diffinery runs the same workflow files on 4-vCPU runners and can also host your code, pull requests and AI agents; its runners work for repositories that stay on GitHub too, with `runs-on: diffinery` ([GitHub runners](/docs/actions/github-runners)). If you'd rather not run anything yourself, a runner service is the simpler choice.
8890
8991 ### Is there a GitHub alternative that runs GitHub Actions workflows?
9092
modifiedapps/diffinery/site/faq.md+2−2View file
@@ -2,7 +2,7 @@
22 title: Diffinery FAQ
33 seo_title: "Diffinery FAQ: open source, self-hosting, GitHub Actions, AI agents"
44 description: Short answers about Diffinery: open source and self-hosting, cost, GitHub Actions compatibility, runners, Cloudflare, AI agents, security and migration.
5-updated: 2026-10-26
5+updated: 2026-10-30
66 ---
77
88 Short, direct answers to the questions people and AI assistants ask most about Diffinery. Each answer links to the page with the details. Facts about GitHub are from GitHub's own documentation, checked on October 25, 2026.
@@ -27,7 +27,7 @@
2727
2828 ### Is Diffinery an alternative to GitHub Actions?
2929
30-Yes. Diffinery's CI reads the same `.github/workflows/*.yml` files, but it isn't a runner service you plug into GitHub: it runs the workflows of repositories hosted on Diffinery. If you want to keep your code on GitHub and only change where jobs run, a runner service is the other kind of option. See [GitHub Actions alternatives, compared](/compare).
30+Yes. Diffinery's CI reads the same `.github/workflows/*.yml` files and runs the workflows of repositories hosted on Diffinery. To keep your code on GitHub and only change where jobs run, install your instance's GitHub App and set a job's `runs-on` to `diffinery`: GitHub's own runner then runs the job on a Diffinery hosted runner. See [GitHub runners](/docs/actions/github-runners) and [GitHub Actions alternatives, compared](/compare).
3131
3232 ### Do my GitHub Actions workflows run on Diffinery without changes?
3333
modifiedapps/diffinery/site/features.md+2−1View file
@@ -2,7 +2,7 @@
22 title: Git hosting, pull requests and GitHub Actions–compatible CI in one place
33 seo_title: "Features: Git hosting, pull requests, CI and AI agents · Diffinery"
44 description: Everything open-source Diffinery does: Git hosting, pull requests and a merge queue, GitHub Actions–compatible CI, a container registry and AI agents.
5-updated: 2026-10-25
5+updated: 2026-10-30
66 ---
77
88 Diffinery is an open-source (Apache-2.0) git forge for teams of people and AI agents. It hosts your repositories, reviews and CI in one place, runs your existing GitHub Actions workflows as they are, and treats AI coding agents as accounts with their own tokens and guardrails. It runs entirely on Cloudflare: you [deploy your own instance](/docs/self-hosting/deploy) to your own Cloudflare account and domain, and there are no servers to manage. The source code is at [diffinery.com/codician/diffinery](https://diffinery.com/codician/diffinery), mirrored on [GitHub](https://github.com/codician-team/diffinery).
@@ -32,6 +32,7 @@
3232 - **Hosted runners on Cloudflare Containers.** Each job gets a fresh Ubuntu 24.04 x64 container with 4 vCPUs and 12 GiB of memory by default. Jobs start in about 3 to 5 seconds. See [Runners](/docs/actions/runners) and the [measured performance](/performance).
3333 - **Right-sized automatically.** Four sizes, from 1/4 vCPU to 4 vCPUs. Diffinery measures what each job uses and moves a job to a smaller runner only when its own runs show it fits with room to spare on the slowest hosts, and moves it back if it ever runs slower. See [Runner sizes](/docs/actions/runners#runner-sizes).
3434 - **Self-hosted runners** for macOS, Windows, Arm, GPUs or machines on your own network, with `diffinery runner`. See [Self-hosted runners](/docs/actions/runners#self-hosted-runners).
35+- **Runners for repositories that stay on GitHub.** Not ready to move? Install your instance's GitHub App and set a job's `runs-on` to `diffinery`: the job runs on Diffinery's hosted runners and counts against your account's hosted minutes, while code, logs and checks stay on GitHub. See [GitHub runners](/docs/actions/github-runners).
3536 - **Caches and artifacts** with the official `actions/cache` and `upload-artifact` formats. See [Caching and artifacts](/docs/actions/caching-and-artifacts).
3637
3738 ## Container registry
modifiedapps/diffinery/src/app.ts+2−0View file
@@ -35,6 +35,7 @@
3535 import { schedulerStub } from "./lib/schedules.js";
3636 import { mailQueue } from "./mail/send.js";
3737 import { mailEvents, mailEventsQueue } from "./mail/events.js";
38+import { githubWebhook } from "./github-runners/http.js";
3839 import { securityTxtRoutes } from "./http/security-txt.js";
3940 import { mcpRegistryAuthRoutes } from "./http/mcp-registry-auth.js";
4041 import { securityReportsApi } from "./http/security-reports.js";
@@ -134,6 +135,7 @@
134135 app.route("/", contactApi);
135136 app.route("/", statusApi);
136137 app.route("/", mailEvents);
138+app.route("/", githubWebhook);
137139 app.route("/", registry);
138140 app.route("/", packagesApi);
139141 app.route("/", actionsRuntime);
modifiedapps/diffinery/src/docs/reference.ts+1−0View file
@@ -271,6 +271,7 @@
271271 ["GET /.well-known/security.txt", "Where to report a vulnerability (RFC 9116): this instance's report form first, then any `SECURITY_CONTACT` entries. See [Reporting a vulnerability](/docs/security/disclosure)."],
272272 ["GET /.well-known/mcp-registry-auth", "The proof record that lets this instance's MCP server be published to the official MCP registry under its domain; 404 until `MCP_REGISTRY_AUTH` is set. See [MCP](/docs/agents/mcp#list-your-instance-in-the-mcp-registry)."],
273273 ["GET, POST /security/report", "The private security report form: signed in, or anonymously after Cloudflare Turnstile. Only site administrators can read reports. See [Reporting a vulnerability](/docs/security/disclosure)."],
274+ ["POST /-/github/webhook", "The GitHub App's webhook for [GitHub runners](/docs/actions/github-runners): queued `workflow_job` deliveries start Diffinery runners for GitHub jobs. Signed with `GITHUB_APP_WEBHOOK_SECRET` (`X-Hub-Signature-256`); 404 until the app is configured. See [Configuration](/docs/self-hosting/configuration#github-runners)."],
274275 ["POST /-/email/events", "Signed bounce and complaint intake for the email suppression list; 404 until `MAIL_EVENTS_SECRET` is set. See [Site administration](/docs/admin/site-administration#bounces-complaints-and-the-suppression-list)."],
275276 ["GET, POST /-/unsubscribe/{token}", "One-click unsubscribe from a notification email (RFC 8058): a POST with `List-Unsubscribe=One-Click` turns that kind of email off. See [Notifications](/docs/accounts/notifications)."],
276277 ["GET /status", "The status page: each component's status and the incidents site administrators posted, for anyone without signing in. As JSON at `GET /api/v3/diffinery/status`. See [Status page](/docs/self-hosting/status-page)."],
modifiedapps/diffinery/src/env.ts+20−0View file
@@ -8,6 +8,7 @@
88 import type { ProjectDO } from "./agentic/ProjectDO.js";
99 import type { ExportJob } from "./accounts/export.js";
1010 import type { DeletionCleanup } from "./accounts/lifecycle.js";
11+import type { GitHubRunnersDO } from "./github-runners/GitHubRunnersDO.js";
1112
1213 export interface Env {
1314 DB: D1Database;
@@ -32,6 +33,8 @@
3233 RUNNER_SMALL?: DurableObjectNamespace<RunnerContainer>;
3334 RUNNER_TINY?: DurableObjectNamespace<RunnerContainer>;
3435 SANDBOX: DurableObjectNamespace<SandboxContainer>;
36+ /** GitHub jobs on Diffinery runners, one per paying account (github-runners/GitHubRunnersDO.ts). */
37+ GITHUB_RUNNERS?: DurableObjectNamespace<GitHubRunnersDO>;
3538 /** One per repository: its agent tasks (agentic/ProjectDO.ts). */
3639 PROJECT: DurableObjectNamespace<ProjectDO>;
3740 /**
@@ -80,6 +83,17 @@
8083 /** Optional GitHub OAuth app, for linking an account through the web flow instead of a gist. */
8184 GITHUB_OAUTH_CLIENT_ID?: string;
8285 GITHUB_OAUTH_CLIENT_SECRET?: string;
86+ /**
87+ * The GitHub App that lets GitHub repositories run jobs on this Diffinery's hosted runners
88+ * (github-runners/github.ts, docs/actions/github-runners.md). The feature is off until all of
89+ * GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and the secrets GITHUB_APP_CLIENT_SECRET,
90+ * GITHUB_APP_PRIVATE_KEY and GITHUB_APP_WEBHOOK_SECRET are set.
91+ */
92+ GITHUB_APP_ID?: string;
93+ GITHUB_APP_SLUG?: string;
94+ GITHUB_APP_CLIENT_ID?: string;
95+ /** A GitHub Enterprise Server origin for the app; default https://github.com. */
96+ GITHUB_APP_URL?: string;
8397
8498 /** Canonical origin, e.g. https://diffinery.com */
8599 PUBLIC_URL: string;
@@ -139,6 +153,12 @@
139153 MAIL_EVENTS_SECRET?: string;
140154 /** Secret: Cloudflare Turnstile secret key, to check the widget on the sign-up page and the security report form (siteverify). */
141155 TURNSTILE_SECRET?: string;
156+ /** Secret: the GitHub App's client secret, to check who links an installation. */
157+ GITHUB_APP_CLIENT_SECRET?: string;
158+ /** Secret: the GitHub App's private key (PEM, as GitHub gives it). */
159+ GITHUB_APP_PRIVATE_KEY?: string;
160+ /** Secret: the GitHub App's webhook secret, which signs deliveries to /-/github/webhook. */
161+ GITHUB_APP_WEBHOOK_SECRET?: string;
142162 /** Optional GitHub Enterprise host (e.g. github.example.com) the importer may download release assets from. */
143163 IMPORT_GHE_HOST?: string;
144164 }
addedapps/diffinery/src/github-runners/GitHubRunnersDO.ts+63−0View file
@@ -1,0 +1,63 @@
1+import { DurableObject } from "cloudflare:workers";
2+import type { Env } from "../env.js";
3+import type { RunnerSize } from "../runner/sizes.js";
4+import { GitHubAppClient, githubApp } from "./github.js";
5+import { GitHubRunners, containerHost, type JobEvent, type QueuedJob } from "./service.js";
6+
7+/**
8+ * One per Diffinery account that pays for GitHub jobs on Diffinery runners (named by the account id).
9+ * Webhooks and container stops only record what happened and set the alarm; the alarm starts runners
10+ * and stops idle ones (GitHubRunners.pump), one pass at a time, so a webhook never waits on a container
11+ * start and GitHub's 10-second delivery timeout is never at risk.
12+ */
13+export class GitHubRunnersDO extends DurableObject<Env> {
14+ private client: GitHubAppClient | null = null;
15+
16+ private runners(): GitHubRunners | null {
17+ const app = githubApp(this.env);
18+ if (!app) return null;
19+ this.client ??= new GitHubAppClient(app);
20+ return new GitHubRunners(this.env, this.client, containerHost(this.env));
21+ }
22+
23+ /** Sets the alarm `ms` from now unless it is already due sooner. */
24+ private async wake(accountId: string, ms: number): Promise<void> {
25+ await this.ctx.storage.put("account", accountId);
26+ const at = Date.now() + ms;
27+ const cur = await this.ctx.storage.getAlarm();
28+ if (cur === null || cur > at) await this.ctx.storage.setAlarm(at);
29+ }
30+
31+ async queued(accountId: string, job: QueuedJob, size: RunnerSize): Promise<void> {
32+ const r = this.runners();
33+ if (r && (await r.queued(accountId, job, size))) await this.wake(accountId, 0);
34+ }
35+
36+ async jobEvent(accountId: string, ev: JobEvent): Promise<void> {
37+ const r = this.runners();
38+ if (!r) return;
39+ await r.jobEvent(ev);
40+ await this.wake(accountId, 0);
41+ }
42+
43+ /** A runner's container stopped (runner/containers.ts onStop). */
44+ async stopped(accountId: string, runnerId: string, exitCode: number | null): Promise<void> {
45+ const r = this.runners();
46+ if (!r) return;
47+ await r.stopped(runnerId, exitCode);
48+ await this.wake(accountId, 0);
49+ }
50+
51+ /** A kill switch (lib/killswitch.ts stopGitHubRunners). */
52+ async stopAll(accountId: string, message: string): Promise<number> {
53+ return (await this.runners()?.stopAll(accountId, message)) ?? 0;
54+ }
55+
56+ override async alarm(): Promise<void> {
57+ const accountId = await this.ctx.storage.get<string>("account");
58+ const r = this.runners();
59+ if (!accountId || !r) return;
60+ const { next } = await r.pump(accountId);
61+ if (next !== null) await this.wake(accountId, next);
62+ }
63+}
addedapps/diffinery/src/github-runners/github.ts+245−0View file
@@ -1,0 +1,245 @@
1+import type { Env } from "../env.js";
2+import { b64url, fromB64, hmacSha256Hex, safeEqual } from "../lib/util.js";
3+
4+/**
5+ * The instance's GitHub App, which lets GitHub repositories run jobs on Diffinery runners
6+ * (docs/actions/github-runners.md). It needs these repository permissions: Administration (read and
7+ * write), to register a just-in-time runner for one job; Actions (read); Metadata (read). It subscribes
8+ * to the Workflow job event; GitHub sends installation events to every app.
9+ */
10+export interface GitHubAppConfig {
11+ appId: string;
12+ slug: string;
13+ clientId: string;
14+ clientSecret: string;
15+ privateKey: string;
16+ webhookSecret: string;
17+ /** https://github.com, or a GitHub Enterprise Server origin. */
18+ webUrl: string;
19+ /** https://api.github.com, or <webUrl>/api/v3 on GitHub Enterprise Server. */
20+ apiUrl: string;
21+}
22+
23+/** The app's settings, or null when this Diffinery has no GitHub App (the feature is then off). */
24+export function githubApp(env: Env): GitHubAppConfig | null {
25+ const { GITHUB_APP_ID: appId, GITHUB_APP_SLUG: slug, GITHUB_APP_CLIENT_ID: clientId, GITHUB_APP_CLIENT_SECRET: clientSecret, GITHUB_APP_PRIVATE_KEY: privateKey, GITHUB_APP_WEBHOOK_SECRET: webhookSecret } = env;
26+ if (!appId || !slug || !clientId || !clientSecret || !privateKey || !webhookSecret) return null;
27+ const webUrl = (env.GITHUB_APP_URL || "https://github.com").replace(/\/+$/, "");
28+ const apiUrl = webUrl === "https://github.com" ? "https://api.github.com" : `${webUrl}/api/v3`;
29+ return { appId, slug, clientId, clientSecret, privateKey, webhookSecret, webUrl, apiUrl };
30+}
31+
32+/** Whether a webhook body carries GitHub's signature (X-Hub-Signature-256) made with the app's webhook secret. */
33+export async function webhookSigned(secret: string, header: string | undefined, body: string): Promise<boolean> {
34+ if (!header?.startsWith("sha256=")) return false;
35+ return safeEqual(header.slice(7).toLowerCase(), await hmacSha256Hex(secret, body));
36+}
37+
38+// ---------------------------------------------------------------- the app's JWT
39+
40+/** DER length bytes. */
41+function derLength(n: number): number[] {
42+ if (n < 0x80) return [n];
43+ const out: number[] = [];
44+ for (let v = n; v > 0; v >>= 8) out.unshift(v & 0xff);
45+ return [0x80 | out.length, ...out];
46+}
47+
48+function der(tag: number, body: Uint8Array): Uint8Array {
49+ const len = derLength(body.length);
50+ const out = new Uint8Array(1 + len.length + body.length);
51+ out[0] = tag;
52+ out.set(len, 1);
53+ out.set(body, 1 + len.length);
54+ return out;
55+}
56+
57+/** rsaEncryption's AlgorithmIdentifier: SEQUENCE { OID 1.2.840.113549.1.1.1, NULL }. */
58+const RSA_ALGORITHM = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]);
59+
60+/**
61+ * A PEM private key as PKCS#8 DER. GitHub gives an app's key as PKCS#1 ("BEGIN RSA PRIVATE KEY"), which
62+ * Web Crypto doesn't read, so that one is wrapped: SEQUENCE { INTEGER 0, rsaEncryption, OCTET STRING key }.
63+ * Escaped newlines (a key pasted into one line of a secret) are accepted.
64+ */
65+export function pkcs8FromPem(pem: string): Uint8Array {
66+ const text = pem.replace(/\\n/g, "\n").trim();
67+ const m = /-----BEGIN (RSA )?PRIVATE KEY-----([\s\S]+?)-----END (RSA )?PRIVATE KEY-----/.exec(text);
68+ if (!m) throw new Error("GITHUB_APP_PRIVATE_KEY is not a PEM private key");
69+ const body = fromB64(m[2]!.replace(/\s+/g, ""));
70+ if (!m[1]) return body;
71+ const version = new Uint8Array([0x02, 0x01, 0x00]);
72+ const key = der(0x04, body);
73+ const inner = new Uint8Array(version.length + RSA_ALGORITHM.length + key.length);
74+ inner.set(version, 0);
75+ inner.set(RSA_ALGORITHM, version.length);
76+ inner.set(key, version.length + RSA_ALGORITHM.length);
77+ return der(0x30, inner);
78+}
79+
80+/** The app's JWT (RS256), valid for 9 minutes; issued a minute in the past for clock drift, as GitHub suggests. */
81+export async function appJwt(app: Pick<GitHubAppConfig, "appId" | "privateKey">, nowSeconds = Math.floor(Date.now() / 1000)): Promise<string> {
82+ const key = await crypto.subtle.importKey("pkcs8", pkcs8FromPem(app.privateKey) as BufferSource, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
83+ const enc = (o: unknown) => b64url(new TextEncoder().encode(JSON.stringify(o)));
84+ const head = enc({ alg: "RS256", typ: "JWT" });
85+ const body = enc({ iat: nowSeconds - 60, exp: nowSeconds + 540, iss: app.appId });
86+ const sig = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, new TextEncoder().encode(`${head}.${body}`)));
87+ return `${head}.${body}.${b64url(sig)}`;
88+}
89+
90+// ---------------------------------------------------------------- API calls
91+
92+export class GitHubApiError extends Error {
93+ constructor(
94+ readonly status: number,
95+ message: string,
96+ ) {
97+ super(message);
98+ }
99+}
100+
101+export interface JitRunner {
102+ runnerId: number;
103+ /** The runner's whole configuration and credentials: never logged or stored. */
104+ encodedJitConfig: string;
105+}
106+
107+export interface GitHubInstallation {
108+ id: number;
109+ login: string;
110+ type: string;
111+}
112+
113+export interface GitHubRunnerState {
114+ busy: boolean;
115+ status: string;
116+}
117+
118+/** The calls Diffinery makes to GitHub for runners. One per Durable Object, which keeps installation tokens for their hour. */
119+export class GitHubAppClient {
120+ private tokens = new Map<number, { token: string; expires: number }>();
121+
122+ constructor(
123+ readonly app: GitHubAppConfig,
124+ private readonly fetcher: typeof fetch = (input, init) => fetch(input, init),
125+ ) {}
126+
127+ private async call<T>(method: string, path: string, auth: string, body?: unknown): Promise<T> {
128+ const res = await this.fetcher(`${this.app.apiUrl}/${path.replace(/^\//, "")}`, {
129+ method,
130+ headers: {
131+ accept: "application/vnd.github+json",
132+ authorization: auth,
133+ "x-github-api-version": "2022-11-28",
134+ "user-agent": "Diffinery",
135+ ...(body === undefined ? {} : { "content-type": "application/json" }),
136+ },
137+ body: body === undefined ? undefined : JSON.stringify(body),
138+ signal: AbortSignal.timeout(30_000),
139+ });
140+ if (res.status === 204) return undefined as T;
141+ const text = await res.text();
142+ if (!res.ok) {
143+ let message = text.slice(0, 300);
144+ try {
145+ message = (JSON.parse(text) as { message?: string }).message ?? message;
146+ } catch {
147+ /* not JSON */
148+ }
149+ throw new GitHubApiError(res.status, `GitHub answered ${res.status} to ${method} ${path.split("?")[0]}: ${message}`);
150+ }
151+ return JSON.parse(text) as T;
152+ }
153+
154+ private async asApp<T>(method: string, path: string, body?: unknown): Promise<T> {
155+ return this.call<T>(method, path, `Bearer ${await appJwt(this.app)}`, body);
156+ }
157+
158+ /** An installation token, reused until 5 minutes before it expires. */
159+ private async installationToken(installationId: number): Promise<string> {
160+ const kept = this.tokens.get(installationId);
161+ if (kept && kept.expires - Date.now() > 5 * 60_000) return kept.token;
162+ const r = await this.asApp<{ token: string; expires_at: string }>("POST", `app/installations/${installationId}/access_tokens`, {});
163+ this.tokens.set(installationId, { token: r.token, expires: Date.parse(r.expires_at) || Date.now() + 50 * 60_000 });
164+ return r.token;
165+ }
166+
167+ private async asInstallation<T>(installationId: number, method: string, path: string, body?: unknown): Promise<T> {
168+ return this.call<T>(method, path, `Bearer ${await this.installationToken(installationId)}`, body);
169+ }
170+
171+ /** The GitHub account an installation is on. */
172+ async installation(installationId: number): Promise<GitHubInstallation> {
173+ const r = await this.asApp<{ id: number; account: { login: string; type: string } | null }>("GET", `app/installations/${installationId}`);
174+ return { id: r.id, login: r.account?.login ?? "", type: r.account?.type ?? "User" };
175+ }
176+
177+ /**
178+ * Registers a just-in-time runner in the repository for one job: GitHub gives it to a queued job whose
179+ * labels it has, and removes it once that job ends. Runner group 1 is a repository's default group.
180+ */
181+ async jitRunner(installationId: number, repo: string, name: string, labels: string[]): Promise<JitRunner> {
182+ const r = await this.asInstallation<{ runner: { id: number }; encoded_jit_config: string }>(installationId, "POST", `repos/${repo}/actions/runners/generate-jitconfig`, { name, runner_group_id: 1, labels });
183+ return { runnerId: r.runner.id, encodedJitConfig: r.encoded_jit_config };
184+ }
185+
186+ /** Whether a registered runner is running a job; null once GitHub no longer has it. */
187+ async runner(installationId: number, repo: string, runnerId: number): Promise<GitHubRunnerState | null> {
188+ try {
189+ return await this.asInstallation<GitHubRunnerState>(installationId, "GET", `repos/${repo}/actions/runners/${runnerId}`);
190+ } catch (e) {
191+ if (e instanceof GitHubApiError && e.status === 404) return null;
192+ throw e;
193+ }
194+ }
195+
196+ /** Removes a runner that never took a job (one that did removes itself). */
197+ async removeRunner(installationId: number, repo: string, runnerId: number): Promise<void> {
198+ try {
199+ await this.asInstallation<void>(installationId, "DELETE", `repos/${repo}/actions/runners/${runnerId}`);
200+ } catch (e) {
201+ if (!(e instanceof GitHubApiError && e.status === 404)) throw e;
202+ }
203+ }
204+
205+ // ---------------------------------------------------------------- a person's GitHub sign-in, to link an installation
206+
207+ /** Where a person authorizes the app, which proves which installations they can manage. */
208+ authorizeUrl(redirectUri: string, state: string): string {
209+ const u = new URL(`${this.app.webUrl}/login/oauth/authorize`);
210+ u.searchParams.set("client_id", this.app.clientId);
211+ u.searchParams.set("redirect_uri", redirectUri);
212+ u.searchParams.set("state", state);
213+ u.searchParams.set("allow_signup", "false");
214+ return u.toString();
215+ }
216+
217+ /** Where a person installs the app; GitHub passes `state` on to the app's setup URL. */
218+ installUrl(state: string): string {
219+ return `${this.app.webUrl}/apps/${encodeURIComponent(this.app.slug)}/installations/new?state=${encodeURIComponent(state)}`;
220+ }
221+
222+ /** Trades the code GitHub sent back for the person's user token (used at once, never kept). */
223+ async userToken(code: string, redirectUri: string): Promise<string> {
224+ const res = await this.fetcher(`${this.app.webUrl}/login/oauth/access_token`, {
225+ method: "POST",
226+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "Diffinery" },
227+ body: JSON.stringify({ client_id: this.app.clientId, client_secret: this.app.clientSecret, code, redirect_uri: redirectUri }),
228+ signal: AbortSignal.timeout(30_000),
229+ });
230+ const r = (await res.json().catch(() => ({}))) as { access_token?: string; error_description?: string };
231+ if (!r.access_token) throw new GitHubApiError(422, `GitHub did not sign you in: ${r.error_description ?? "no access token"}`);
232+ return r.access_token;
233+ }
234+
235+ /** The app's installations the signed-in GitHub user can manage (at most 500). */
236+ async userInstallations(userToken: string): Promise<GitHubInstallation[]> {
237+ const out: GitHubInstallation[] = [];
238+ for (let page = 1; page <= 5; page++) {
239+ const r = await this.call<{ installations: Array<{ id: number; account: { login: string; type: string } | null }> }>("GET", `user/installations?per_page=100&page=${page}`, `Bearer ${userToken}`);
240+ out.push(...r.installations.map((i) => ({ id: i.id, login: i.account?.login ?? "", type: i.account?.type ?? "User" })));
241+ if (r.installations.length < 100) break;
242+ }
243+ return out;
244+ }
245+}
addedapps/diffinery/src/github-runners/http.ts+97−0View file
@@ -1,0 +1,97 @@
1+import { Hono } from "hono";
2+import type { AppVars } from "../auth/principal.js";
3+import type { Env } from "../env.js";
4+import { now } from "../lib/util.js";
5+import { githubApp, webhookSigned } from "./github.js";
6+import { runnerFor, type JobEvent, type QueuedJob } from "./service.js";
7+
8+/**
9+ * POST /-/github/webhook: the GitHub App's webhook (github-runners/github.ts). Off (404) until the app is
10+ * configured; every delivery must carry GitHub's signature made with GITHUB_APP_WEBHOOK_SECRET.
11+ *
12+ * - workflow_job: a queued job whose runs-on asks for a Diffinery runner waits for one in the GitHubRunnersDO
13+ * of the account its installation is linked to; in_progress and completed say which job a Diffinery
14+ * runner took, and drop queued jobs that no longer need one.
15+ * - installation and installation_target: an uninstalled app's link goes, a suspended one starts nothing,
16+ * and a renamed GitHub account keeps its link under the new name.
17+ */
18+
19+/** Largest delivery read, in bytes: workflow_job deliveries are a few kilobytes, installation ones list repositories. */
20+export const MAX_WEBHOOK_BODY = 5 << 20;
21+
22+export const githubWebhook = new Hono<{ Bindings: Env; Variables: AppVars }>();
23+
24+interface WorkflowJobPayload {
25+ action: string;
26+ workflow_job: { id: number; run_id?: number; name?: string; workflow_name?: string | null; labels?: string[]; runner_name?: string | null; conclusion?: string | null; html_url?: string };
27+ repository: { full_name: string };
28+ installation?: { id: number };
29+}
30+
31+interface InstallationPayload {
32+ action: string;
33+ installation: { id: number; account?: { login?: string } | null };
34+}
35+
36+githubWebhook.post("/-/github/webhook", async (c) => {
37+ const app = githubApp(c.env);
38+ if (!app || !c.env.GITHUB_RUNNERS) return c.json({ message: "GitHub runners are off: this Diffinery has no GitHub App" }, 404);
39+ if (Number(c.req.header("content-length") ?? 0) > MAX_WEBHOOK_BODY) return c.json({ message: "body too large" }, 413);
40+ const body = await c.req.text();
41+ if (body.length > MAX_WEBHOOK_BODY) return c.json({ message: "body too large" }, 413);
42+ if (!(await webhookSigned(app.webhookSecret, c.req.header("x-hub-signature-256"), body))) return c.json({ message: "missing or bad signature" }, 401);
43+ let payload: unknown;
44+ try {
45+ payload = JSON.parse(body);
46+ } catch {
47+ return c.json({ message: "body must be JSON" }, 400);
48+ }
49+ const event = c.req.header("x-github-event") ?? "";
50+ const db = c.env.DB;
51+ if (event === "ping") return c.json({ ok: true });
52+
53+ if (event === "installation" || event === "installation_target") {
54+ const p = payload as InstallationPayload;
55+ const id = p.installation?.id;
56+ if (typeof id !== "number") return c.json({ message: "no installation" }, 400);
57+ if (event === "installation" && p.action === "deleted") await db.prepare("DELETE FROM github_installations WHERE id = ?").bind(id).run();
58+ else if (event === "installation" && p.action === "suspend") await db.prepare("UPDATE github_installations SET suspended_at = ? WHERE id = ?").bind(now(), id).run();
59+ else if (event === "installation" && p.action === "unsuspend") await db.prepare("UPDATE github_installations SET suspended_at = NULL WHERE id = ?").bind(id).run();
60+ else if (event === "installation_target" && p.action === "renamed" && p.installation.account?.login) await db.prepare("UPDATE github_installations SET github_login = ? WHERE id = ?").bind(p.installation.account.login, id).run();
61+ return c.json({ ok: true });
62+ }
63+
64+ if (event !== "workflow_job") return c.json({ ignored: `event ${event}` });
65+ const p = payload as WorkflowJobPayload;
66+ const job = p.workflow_job;
67+ const installationId = p.installation?.id;
68+ if (!job || typeof job.id !== "number" || typeof installationId !== "number" || !p.repository?.full_name) return c.json({ message: "not a workflow_job delivery" }, 400);
69+ const labels = (job.labels ?? []).filter((l): l is string => typeof l === "string").slice(0, 100);
70+ const size = runnerFor(labels);
71+ const ours = typeof job.runner_name === "string" && job.runner_name.startsWith("diffinery-");
72+ // Most jobs of an installed repository aren't for Diffinery: nothing to look up for those.
73+ if (!size && !ours) return c.json({ ignored: "not for a Diffinery runner" });
74+ const link = await db.prepare("SELECT account_id FROM github_installations WHERE id = ?").bind(installationId).first<{ account_id: string }>();
75+ if (!link) return c.json({ ignored: "this installation isn't linked to a Diffinery account" });
76+ const stub = c.env.GITHUB_RUNNERS.get(c.env.GITHUB_RUNNERS.idFromName(link.account_id));
77+
78+ if (p.action === "queued" && size) {
79+ const q: QueuedJob = {
80+ installationId,
81+ repo: p.repository.full_name,
82+ githubJobId: job.id,
83+ runId: typeof job.run_id === "number" ? job.run_id : null,
84+ workflowName: job.workflow_name ?? null,
85+ jobName: job.name ?? null,
86+ htmlUrl: typeof job.html_url === "string" && job.html_url.startsWith(app.webUrl + "/") ? job.html_url : null,
87+ labels,
88+ };
89+ await stub.queued(link.account_id, q, size);
90+ return c.json({ queued: true, size });
91+ }
92+ if (p.action === "in_progress" || p.action === "completed") {
93+ const ev: JobEvent = { installationId, githubJobId: job.id, action: p.action, runnerName: ours ? job.runner_name! : null, jobName: job.name ?? null, conclusion: job.conclusion ?? null };
94+ await stub.jobEvent(link.account_id, ev);
95+ }
96+ return c.json({ ok: true });
97+});
addedapps/diffinery/src/github-runners/links.ts+204−0View file
@@ -1,0 +1,204 @@
1+import type { Env } from "../env.js";
2+import { hmacSha256, matchesAnyKey, signingSecrets } from "../lib/crypto.js";
3+import type { Account, Directory } from "../lib/directory.js";
4+import { HttpError, b64url, fromB64url, now } from "../lib/util.js";
5+import { GitHubApiError, GitHubAppClient, githubApp, type GitHubInstallation } from "./github.js";
6+import type { RunnerJobRow } from "./service.js";
7+
8+/**
9+ * Linking a GitHub App installation to the Diffinery account that pays for its jobs. Whoever links one
10+ * must manage that account (themselves, or an organization they own or administer) and, as GitHub
11+ * tells the app when they authorize it, be able to manage the installation on GitHub: anyone else could
12+ * otherwise spend their own minutes on another's jobs, read which jobs a private repository runs, or
13+ * unlink them.
14+ *
15+ * The flow (web/github-runners.tsx): Install on GitHub carries a signed `state` naming the person and the
16+ * paying account; GitHub returns to the setup URL with the installation id, the state and, with "Request
17+ * user authorization (OAuth) during installation" on, a code. Without a code the person is sent to authorize
18+ * the app first. The code becomes a user token, used once to list the installations they can manage. Link
19+ * existing installations authorizes the app and lists those installations; the person picks one and who pays.
20+ */
21+
22+/** Where GitHub sends people back to: the app's setup URL and its callback URL. */
23+export const SETUP_PATH = "/settings/github-runners/setup";
24+/** How long a state or a proof is good for. */
25+const TTL_SECONDS = 3600;
26+
27+/** What a state or proof says: who started, which account pays, and (once known) the installation. */
28+interface Claims {
29+ /** "state" for a flow under way, "proof" once GitHub said the person manages installation i. */
30+ k: "state" | "proof";
31+ u: string;
32+ /** The paying account a state was started for. */
33+ a?: string;
34+ i?: number;
35+ login?: string;
36+ type?: string;
37+ x: number;
38+}
39+
40+export interface LinkedInstallation {
41+ id: number;
42+ account_id: string;
43+ github_login: string;
44+ github_type: string;
45+ linked_by: string;
46+ linked_at: string;
47+ suspended_at: string | null;
48+}
49+
50+export type SetupResult = { linked: LinkedInstallation } | { redirect: string } | { choose: Array<GitHubInstallation & { proof: string; linkedTo: string | null }>; payer: Account };
51+
52+export class GitHubRunnerLinks {
53+ readonly client: GitHubAppClient | null;
54+
55+ constructor(
56+ private readonly env: Env,
57+ private readonly dir: Directory,
58+ fetcher?: typeof fetch,
59+ ) {
60+ const app = githubApp(env);
61+ this.client = app ? new GitHubAppClient(app, fetcher) : null;
62+ }
63+
64+ get enabled(): boolean {
65+ return !!this.client && !!this.env.GITHUB_RUNNERS;
66+ }
67+
68+ private gh(): GitHubAppClient {
69+ if (!this.enabled) throw new HttpError(404, "GitHub runners are off: this Diffinery has no GitHub App");
70+ return this.client!;
71+ }
72+
73+ private get redirectUri(): string {
74+ return `${this.env.PUBLIC_URL}${SETUP_PATH}`;
75+ }
76+
77+ private secrets(): string[] {
78+ return signingSecrets(this.env, this.env.DEV_AUTH ? "dev" : null, "MASTER_KEY is not set");
79+ }
80+
81+ private async mac(secret: string, payload: string): Promise<string> {
82+ return b64url(await hmacSha256(secret, `github-runners:${payload}`));
83+ }
84+
85+ private async sign(c: Omit<Claims, "x">): Promise<string> {
86+ const payload = b64url(new TextEncoder().encode(JSON.stringify({ ...c, x: Math.floor(Date.now() / 1000) + TTL_SECONDS })));
87+ return `${payload}.${await this.mac(this.secrets()[0]!, payload)}`;
88+ }
89+
90+ private async open(token: string, kind: Claims["k"], me: Account): Promise<Claims> {
91+ const [payload, tag] = token.split(".");
92+ if (!payload || !tag || !(await matchesAnyKey(this.secrets(), tag, (s) => this.mac(s, payload)))) throw new HttpError(422, "this link to GitHub is not valid; start again from Settings → GitHub runners");
93+ const c = JSON.parse(new TextDecoder().decode(fromB64url(payload))) as Claims;
94+ if (c.k !== kind || c.u !== me.id) throw new HttpError(422, "this link to GitHub was made for someone else; start again from Settings → GitHub runners");
95+ if (c.x < Date.now() / 1000) throw new HttpError(422, "this link to GitHub has expired; start again from Settings → GitHub runners");
96+ return c;
97+ }
98+
99+ /** The accounts a person may make pay: themselves and the organizations they own or administer. */
100+ async payers(me: Account): Promise<Account[]> {
101+ const orgs = (await this.dir.orgsFor(me.id)).filter((o) => o.role === "owner" || o.role === "admin");
102+ return [me, ...orgs];
103+ }
104+
105+ private async payer(me: Account, accountId: string): Promise<Account> {
106+ const a = (await this.payers(me)).find((p) => p.id === accountId);
107+ if (!a) throw new HttpError(403, "you can link GitHub runners only to your own account or an organization you own or administer");
108+ return a;
109+ }
110+
111+ /** Install on GitHub: the app's install page, with a state naming who pays. */
112+ async installUrl(me: Account, accountId: string): Promise<string> {
113+ const gh = this.gh();
114+ await this.payer(me, accountId);
115+ return gh.installUrl(await this.sign({ k: "state", u: me.id, a: accountId }));
116+ }
117+
118+ /** Link an installation that already exists: authorize the app, then pick it. */
119+ async authorizeUrl(me: Account, accountId: string): Promise<string> {
120+ const gh = this.gh();
121+ await this.payer(me, accountId);
122+ return gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: accountId }));
123+ }
124+
125+ /**
126+ * GitHub sent the person back (after installing, or after authorizing the app). A code is only used with a
127+ * state this person started here (signed, bound to them): one that came without, or with someone else's,
128+ * could be another GitHub user's, sent to make this person pay for that user's installation.
129+ */
130+ async setup(me: Account, q: { installationId: number | null; code: string | null; state: string | null }): Promise<SetupResult> {
131+ const gh = this.gh();
132+ // Installed or configured from GitHub itself: authorize, then pick the installation and who pays.
133+ if (!q.state) return { redirect: gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: me.id })) };
134+ const claims = await this.open(q.state, "state", me);
135+ const payer = await this.payer(me, claims.a ?? me.id);
136+ const installationId = claims.i ?? q.installationId ?? null;
137+ if (!q.code) {
138+ if (!installationId) throw new HttpError(422, "GitHub sent no installation; start again from Settings → GitHub runners");
139+ return { redirect: gh.authorizeUrl(this.redirectUri, await this.sign({ k: "state", u: me.id, a: payer.id, i: installationId })) };
140+ }
141+ let mine: GitHubInstallation[];
142+ try {
143+ mine = await gh.userInstallations(await gh.userToken(q.code, this.redirectUri));
144+ } catch (e) {
145+ throw new HttpError(e instanceof GitHubApiError && e.status < 500 ? 422 : 502, (e as Error).message);
146+ }
147+ if (installationId) {
148+ const inst = mine.find((i) => i.id === installationId);
149+ if (!inst) throw new HttpError(403, "your GitHub account can't manage that installation of the app; ask an owner of the GitHub organization to link it");
150+ return { linked: await this.save(me, payer, inst) };
151+ }
152+ const linked = new Map<number, string>();
153+ if (mine.length) {
154+ const rows = await this.env.DB.prepare(`SELECT g.id, a.login FROM github_installations g JOIN accounts a ON a.id = g.account_id WHERE g.id IN (${mine.map(() => "?").join(",")})`)
155+ .bind(...mine.map((i) => i.id))
156+ .all<{ id: number; login: string }>();
157+ for (const r of rows.results) linked.set(r.id, r.login);
158+ }
159+ const choose = await Promise.all(mine.map(async (i) => ({ ...i, linkedTo: linked.get(i.id) ?? null, proof: await this.sign({ k: "proof", u: me.id, i: i.id, login: i.login, type: i.type }) })));
160+ return { choose, payer };
161+ }
162+
163+ /** Links an installation the person picked (with the proof setup made that they manage it) to an account they pick. */
164+ async linkWithProof(me: Account, proof: string, accountId: string): Promise<LinkedInstallation> {
165+ this.gh();
166+ const c = await this.open(proof, "proof", me);
167+ return this.save(me, await this.payer(me, accountId), { id: c.i!, login: c.login ?? "", type: c.type ?? "User" });
168+ }
169+
170+ private async save(me: Account, payer: Account, inst: GitHubInstallation): Promise<LinkedInstallation> {
171+ const before = await this.env.DB.prepare("SELECT account_id FROM github_installations WHERE id = ?").bind(inst.id).first<{ account_id: string }>();
172+ await this.env.DB.prepare(
173+ "INSERT INTO github_installations (id, account_id, github_login, github_type, linked_by, linked_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET account_id = excluded.account_id, github_login = excluded.github_login, github_type = excluded.github_type, linked_by = excluded.linked_by, linked_at = excluded.linked_at",
174+ )
175+ .bind(inst.id, payer.id, inst.login, inst.type, me.id, now())
176+ .run();
177+ await this.dir.audit({ actorId: me.id, actorLogin: me.login, action: "github_runners.link", target: payer.login, detail: { installation: inst.id, github: inst.login, ...(before && before.account_id !== payer.id ? { from: before.account_id } : {}) } });
178+ return (await this.env.DB.prepare("SELECT * FROM github_installations WHERE id = ?").bind(inst.id).first<LinkedInstallation>())!;
179+ }
180+
181+ /** Unlinks an installation: its queued jobs get no runner; runners already started finish their jobs. */
182+ async unlink(me: Account, installationId: number): Promise<void> {
183+ const row = await this.env.DB.prepare("SELECT * FROM github_installations WHERE id = ?").bind(installationId).first<LinkedInstallation>();
184+ if (!row) throw new HttpError(404, "that installation isn't linked");
185+ const payer = await this.payer(me, row.account_id);
186+ await this.env.DB.prepare("DELETE FROM github_installations WHERE id = ?").bind(installationId).run();
187+ await this.env.DB.prepare("UPDATE github_runner_jobs SET status = 'skipped', message = 'The GitHub installation was unlinked', ended_at = ? WHERE installation_id = ? AND status = 'queued'").bind(now(), installationId).run();
188+ await this.dir.audit({ actorId: me.id, actorLogin: me.login, action: "github_runners.unlink", target: payer.login, detail: { installation: installationId, github: row.github_login } });
189+ }
190+
191+ /** The person's paying accounts with their linked installations and recent runner jobs, for the settings page. */
192+ async overview(me: Account, jobs = 30): Promise<Array<{ account: Account; installations: LinkedInstallation[]; jobs: RunnerJobRow[] }>> {
193+ const payers = await this.payers(me);
194+ return Promise.all(
195+ payers.map(async (account) => {
196+ const [installations, recent] = await Promise.all([
197+ this.env.DB.prepare("SELECT * FROM github_installations WHERE account_id = ? ORDER BY github_login").bind(account.id).all<LinkedInstallation>(),
198+ this.env.DB.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? ORDER BY created_at DESC LIMIT ?").bind(account.id, jobs).all<RunnerJobRow>(),
199+ ]);
200+ return { account, installations: installations.results, jobs: recent.results };
201+ }),
202+ );
203+ }
204+}
addedapps/diffinery/src/github-runners/service.ts+369−0View file
@@ -1,0 +1,369 @@
1+import type { Env } from "../env.js";
2+import { egressFor, type Egress } from "../lib/egress.js";
3+import { accountKillSwitches, blockedBy } from "../lib/killswitch.js";
4+import { MAX_RUN_MS, endCompute, mayStart, startCompute } from "../lib/quotas.js";
5+import { newId, now } from "../lib/util.js";
6+import { RETRYABLE_START } from "../repo/actions.js";
7+import { RUNNER_SIZES, sizeLabel, sizeOfContainer, type RunnerSize } from "../runner/sizes.js";
8+import { GitHubApiError, type GitHubAppClient } from "./github.js";
9+
10+/**
11+ * GitHub jobs on Diffinery runners (docs/actions/github-runners.md). GitHub tells Diffinery about each
12+ * queued job of a repository where the instance's GitHub App is installed (the workflow_job webhook);
13+ * when its runs-on asks for a Diffinery runner, the job waits here, one row per job, until the account
14+ * the installation is linked to may start a hosted job (lib/quotas.ts, lib/killswitch.ts). Diffinery
15+ * then registers a just-in-time runner with the job's labels in the repository and starts a hosted runner
16+ * container that runs GitHub's own runner with it. GitHub hands that runner a queued job with those labels,
17+ * the runner runs it and exits, and the container stops.
18+ *
19+ * The rows are in D1 (github_runner_jobs), for the settings page; each account's are changed by its own
20+ * GitHubRunnersDO, which calls this class.
21+ */
22+
23+/** Labels a Diffinery runner has besides its own: GitHub's usual self-hosted labels. */
24+const COMPANION_LABELS = new Set(["self-hosted", "linux", "x64"]);
25+
26+/**
27+ * The runner size a GitHub job's runs-on asks for, or null when it isn't for Diffinery: it needs
28+ * `diffinery` or `diffinery-<size>`, and any other label must be one a Diffinery runner has, or the
29+ * runner registered for it could never take it. `diffinery` alone is a large runner.
30+ */
31+export function runnerFor(labels: readonly string[]): RunnerSize | null {
32+ let ours = false;
33+ for (const l of labels) {
34+ const low = l.trim().toLowerCase();
35+ if (low === "diffinery" || sizeLabel([low])) ours = true;
36+ else if (!COMPANION_LABELS.has(low)) return null;
37+ }
38+ return ours ? (sizeLabel(labels) ?? "large") : null;
39+}
40+
41+/** A runner that took no job within this long is stopped: its job was cancelled or ran on another runner. */
42+export const IDLE_MS = 10 * 60_000;
43+/** How often a queued job asks again for a hosted slot, while the account is at its hosted jobs at once. */
44+export const WAIT_RETRY_MS = 15_000;
45+/** Starts of one job's runner that may fail for a passing reason before the job is given up on. */
46+export const MAX_TRIES = 3;
47+/** Queued jobs one pass looks at; the rest wait for the next pass, right after. */
48+const BATCH = 20;
49+
50+export interface QueuedJob {
51+ installationId: number;
52+ repo: string;
53+ githubJobId: number;
54+ runId: number | null;
55+ workflowName: string | null;
56+ jobName: string | null;
57+ htmlUrl: string | null;
58+ labels: string[];
59+}
60+
61+export interface JobEvent {
62+ installationId: number;
63+ githubJobId: number;
64+ action: "in_progress" | "completed";
65+ runnerName: string | null;
66+ jobName: string | null;
67+ conclusion: string | null;
68+}
69+
70+export interface RunnerJobRow {
71+ id: string;
72+ account_id: string;
73+ installation_id: number;
74+ repo: string;
75+ github_job_id: number;
76+ run_id: number | null;
77+ workflow_name: string | null;
78+ job_name: string | null;
79+ html_url: string | null;
80+ labels: string;
81+ size: RunnerSize;
82+ status: "queued" | "starting" | "running" | "completed" | "skipped" | "failed";
83+ tries: number;
84+ runner_name: string | null;
85+ github_runner_id: number | null;
86+ container: string | null;
87+ ran_job_id: number | null;
88+ ran_job_name: string | null;
89+ conclusion: string | null;
90+ message: string | null;
91+ stop_reason: string | null;
92+ exit_code: number | null;
93+ created_at: string;
94+ started_at: string | null;
95+ picked_at: string | null;
96+ ended_at: string | null;
97+}
98+
99+/** What starts and stops runner containers: the hosted runner classes (runner/containers.ts), or a test's stand-in. */
100+export interface RunnerHost {
101+ start(container: string, input: { accountId: string; runnerId: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void>;
102+ stop(container: string): Promise<void>;
103+ has(size: RunnerSize): boolean;
104+}
105+
106+/** The hosted runner container classes, picked by the size at the end of a container's name. */
107+export function containerHost(env: Env): RunnerHost {
108+ const ns = (container: string) => env[RUNNER_SIZES[sizeOfContainer(container)].binding] ?? env.RUNNER;
109+ return {
110+ start: (container, input) => ns(container).get(ns(container).idFromName(container)).startGitHubRunner(input),
111+ stop: (container) => ns(container).get(ns(container).idFromName(container)).stopJob(false),
112+ has: (size) => size === "large" || !!env[RUNNER_SIZES[size].binding],
113+ };
114+}
115+
116+/** A GitHub runner's container: `gh-<row>-<try>`, with the size after a dot as for Actions jobs (runner/sizes.ts). */
117+export function githubContainerName(rowId: string, tries: number, size: RunnerSize): string {
118+ return `gh-${rowId}-${tries}${size === "large" ? "" : `.${size}`}`;
119+}
120+
121+/** The compute_usage repo_id of a GitHub runner: it has no Diffinery repository (lib/killswitch.ts runningCompute). */
122+export const githubComputeRepo = (installationId: number): string => `github:${installationId}`;
123+
124+const ENDED = new Set(["completed", "skipped", "failed"]);
125+
126+type Placement = { row: RunnerJobRow; container: string; jitConfig: string; egress: Egress };
127+
128+export class GitHubRunners {
129+ private readonly db: D1Database;
130+
131+ constructor(
132+ private readonly env: Env,
133+ private readonly gh: GitHubAppClient,
134+ private readonly host: RunnerHost,
135+ private readonly clock: () => number = () => Date.now(),
136+ ) {
137+ this.db = env.DB;
138+ }
139+
140+ private at(ms = this.clock()): string {
141+ return new Date(ms).toISOString();
142+ }
143+
144+ private row(id: string): Promise<RunnerJobRow | null> {
145+ return this.db.prepare("SELECT * FROM github_runner_jobs WHERE id = ?").bind(id).first<RunnerJobRow>();
146+ }
147+
148+ /** Records a queued job for a Diffinery runner; false when GitHub sent the same job before. */
149+ async queued(accountId: string, job: QueuedJob, size: RunnerSize): Promise<boolean> {
150+ const r = await this.db
151+ .prepare(
152+ "INSERT OR IGNORE INTO github_runner_jobs (id, account_id, installation_id, repo, github_job_id, run_id, workflow_name, job_name, html_url, labels, size, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)",
153+ )
154+ .bind(newId(), accountId, job.installationId, job.repo, job.githubJobId, job.runId, job.workflowName, job.jobName, job.htmlUrl, JSON.stringify(job.labels), size, this.at())
155+ .run();
156+ return (r.meta.changes ?? 0) > 0;
157+ }
158+
159+ /** A job started on a runner or ended: which job a Diffinery runner took, or a queued job that no longer needs one. */
160+ async jobEvent(ev: JobEvent): Promise<void> {
161+ if (ev.runnerName) {
162+ if (ev.action === "in_progress") {
163+ await this.db
164+ .prepare("UPDATE github_runner_jobs SET status = CASE WHEN status = 'starting' THEN 'running' ELSE status END, picked_at = coalesce(picked_at, ?), ran_job_id = ?, ran_job_name = ? WHERE installation_id = ? AND runner_name = ?")
165+ .bind(this.at(), ev.githubJobId, ev.jobName, ev.installationId, ev.runnerName)
166+ .run();
167+ } else {
168+ await this.db
169+ .prepare("UPDATE github_runner_jobs SET conclusion = ?, ran_job_id = coalesce(ran_job_id, ?), ran_job_name = coalesce(ran_job_name, ?) WHERE installation_id = ? AND runner_name = ?")
170+ .bind(ev.conclusion, ev.githubJobId, ev.jobName, ev.installationId, ev.runnerName)
171+ .run();
172+ }
173+ }
174+ // Cancelled before its runner started, or taken by another runner (one started for another job with the same labels):
175+ // a runner started for it now would only wait for IDLE_MS.
176+ if (ev.action === "completed" || ev.runnerName) {
177+ await this.db
178+ .prepare("UPDATE github_runner_jobs SET status = 'skipped', message = ?, conclusion = ?, ended_at = ? WHERE installation_id = ? AND github_job_id = ? AND status = 'queued'")
179+ .bind(ev.runnerName ? `The job ran on ${ev.runnerName} before a runner started for it` : "The job ended before a runner started for it", ev.conclusion, this.at(), ev.installationId, ev.githubJobId)
180+ .run();
181+ }
182+ }
183+
184+ /**
185+ * Starts runners for the account's queued jobs, oldest first, and stops runners that took no job or ran too
186+ * long. Returns how soon to look again: null when nothing waits or runs.
187+ */
188+ async pump(accountId: string): Promise<{ next: number | null }> {
189+ await this.sweep(accountId);
190+ const queued = (await this.db.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? AND status = 'queued' ORDER BY created_at LIMIT ?").bind(accountId, BATCH).all<RunnerJobRow>()).results;
191+ const placements: Placement[] = [];
192+ let waiting = false;
193+ for (const row of queued) {
194+ const r = await this.admit(row);
195+ if (r === "wait") {
196+ waiting = true;
197+ break;
198+ }
199+ if (r) placements.push(r);
200+ }
201+ // A start that failed for a passing reason is tried again after a pause, not at once.
202+ if ((await Promise.all(placements.map((p) => this.place(p)))).some(Boolean)) waiting = true;
203+ return { next: await this.nextLook(accountId, waiting) };
204+ }
205+
206+ private async nextLook(accountId: string, waiting: boolean): Promise<number | null> {
207+ const counts = await this.db
208+ .prepare("SELECT status, count(*) AS n, min(started_at) AS oldest FROM github_runner_jobs WHERE account_id = ? AND status IN ('queued', 'starting', 'running') GROUP BY status")
209+ .bind(accountId)
210+ .all<{ status: string; n: number; oldest: string | null }>();
211+ const by = new Map(counts.results.map((c) => [c.status, c]));
212+ const looks: number[] = [];
213+ if (by.has("queued")) looks.push(waiting ? WAIT_RETRY_MS : 0);
214+ const starting = by.get("starting");
215+ if (starting?.oldest) looks.push(Math.max(5_000, Date.parse(starting.oldest) + IDLE_MS - this.clock()));
216+ if (by.has("running")) looks.push(IDLE_MS);
217+ return looks.length ? Math.min(...looks) : null;
218+ }
219+
220+ private async finish(row: RunnerJobRow, status: "skipped" | "failed", message: string): Promise<void> {
221+ await this.db.prepare("UPDATE github_runner_jobs SET status = ?, message = ?, ended_at = ? WHERE id = ? AND status = 'queued'").bind(status, message, this.at(), row.id).run();
222+ }
223+
224+ /** Everything before a queued job's container starts: null when it doesn't start, "wait" when the account must wait for a slot. */
225+ private async admit(row: RunnerJobRow): Promise<Placement | "wait" | null> {
226+ const inst = await this.db.prepare("SELECT account_id, suspended_at FROM github_installations WHERE id = ?").bind(row.installation_id).first<{ account_id: string; suspended_at: string | null }>();
227+ if (!inst || inst.account_id !== row.account_id) {
228+ await this.finish(row, "skipped", "The GitHub installation is no longer linked to this account");
229+ return null;
230+ }
231+ if (inst.suspended_at) {
232+ await this.finish(row, "skipped", "The app's installation is suspended on GitHub");
233+ return null;
234+ }
235+ const block = blockedBy(await accountKillSwitches(this.env, row.account_id), "hosted-job");
236+ if (block) {
237+ await this.finish(row, "failed", `The runner was not started: ${block}`);
238+ return null;
239+ }
240+ const quota = await mayStart(this.env, row.account_id, "job").catch((e: unknown) => {
241+ console.error("quota check failed", e);
242+ return { ok: true } as const;
243+ });
244+ if (!quota.ok) {
245+ if (!quota.wait) {
246+ await this.finish(row, "failed", `The runner was not started: ${quota.message}`);
247+ return null;
248+ }
249+ await this.db.prepare("UPDATE github_runner_jobs SET message = ? WHERE id = ?").bind(`Waiting: ${quota.message}`, row.id).run();
250+ return "wait";
251+ }
252+ const tries = row.tries + 1;
253+ const size = this.host.has(row.size) ? row.size : "large";
254+ const name = `diffinery-${row.id}-${tries}`;
255+ let jit;
256+ try {
257+ jit = await this.gh.jitRunner(row.installation_id, row.repo, name, JSON.parse(row.labels) as string[]);
258+ } catch (e) {
259+ const message = (e as Error).message;
260+ // GitHub refusing (no permission, a repository gone) won't change by asking again.
261+ if ((e instanceof GitHubApiError && e.status < 500 && e.status !== 429) || tries >= MAX_TRIES) await this.finish(row, "failed", `Could not register a runner on GitHub: ${message}`);
262+ else {
263+ await this.db.prepare("UPDATE github_runner_jobs SET tries = ?, message = ? WHERE id = ?").bind(tries, `Registering a runner on GitHub failed; trying again: ${message}`, row.id).run();
264+ return "wait";
265+ }
266+ return null;
267+ }
268+ const container = githubContainerName(row.id, tries, size);
269+ const claimed = await this.db
270+ .prepare("UPDATE github_runner_jobs SET status = 'starting', tries = ?, runner_name = ?, github_runner_id = ?, container = ?, size = ?, message = NULL, stop_reason = NULL, started_at = ?, picked_at = NULL WHERE id = ? AND status = 'queued'")
271+ .bind(tries, name, jit.runnerId, container, size, this.at(), row.id)
272+ .run();
273+ if (!claimed.meta.changes) {
274+ // Stopped or ended meanwhile (a kill switch, the job cancelled).
275+ await this.gh.removeRunner(row.installation_id, row.repo, jit.runnerId).catch(() => {});
276+ return null;
277+ }
278+ await startCompute(this.env, { id: container, accountId: row.account_id, repoId: githubComputeRepo(row.installation_id), kind: "job" }).catch((e: unknown) => console.error("compute usage failed", e));
279+ return { row: { ...row, tries, container, runner_name: name, github_runner_id: jit.runnerId, size }, container, jitConfig: jit.encodedJitConfig, egress: await egressFor(this.env, row.account_id) };
280+ }
281+
282+ /**
283+ * Starts an admitted runner's container; one that failed for a passing reason goes back in line, up to
284+ * MAX_TRIES starts. Returns whether it went back in line.
285+ */
286+ private async place(p: Placement): Promise<boolean> {
287+ try {
288+ await this.host.start(p.container, { accountId: p.row.account_id, runnerId: p.row.id, jitConfig: p.jitConfig, egress: p.egress, vcpu: RUNNER_SIZES[p.row.size].vcpu });
289+ return false;
290+ } catch (e) {
291+ const message = (e as Error).message;
292+ const row = await this.row(p.row.id);
293+ if (!row || row.status !== "starting" || row.container !== p.container) return false;
294+ await endCompute(this.env, p.container).catch(() => {});
295+ await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id!).catch(() => {});
296+ const again = (RETRYABLE_START.test(message) || (e as { retryable?: unknown }).retryable === true) && row.tries < MAX_TRIES;
297+ await this.db
298+ .prepare("UPDATE github_runner_jobs SET status = ?, message = ?, container = NULL, ended_at = ? WHERE id = ? AND status = 'starting'")
299+ .bind(again ? "queued" : "failed", again ? `Starting a runner failed; trying again: ${message}` : `Could not start a runner: ${message}`, again ? null : this.at(), row.id)
300+ .run();
301+ return again;
302+ }
303+ }
304+
305+ /** Runners that took no job within IDLE_MS (unless GitHub says they are busy), and runners past the longest a job runs. */
306+ private async sweep(accountId: string): Promise<void> {
307+ const t = this.clock();
308+ const rows = (await this.db.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? AND status IN ('starting', 'running') AND started_at < ?").bind(accountId, this.at(t - IDLE_MS)).all<RunnerJobRow>()).results;
309+ for (const row of rows) {
310+ if (Date.parse(row.started_at!) + MAX_RUN_MS.job < t) {
311+ await this.stopRunner(row, "The runner ran past the longest a job may run");
312+ continue;
313+ }
314+ if (row.status !== "starting") continue;
315+ // The in_progress webhook may be late or lost: GitHub knows whether the runner has a job.
316+ const state = await this.gh.runner(row.installation_id, row.repo, row.github_runner_id!).catch(() => undefined);
317+ if (state?.busy) {
318+ await this.db.prepare("UPDATE github_runner_jobs SET status = 'running', picked_at = coalesce(picked_at, ?) WHERE id = ? AND status = 'starting'").bind(this.at(t), row.id).run();
319+ continue;
320+ }
321+ if (state === undefined) continue;
322+ await this.stopRunner(row, `No job took this runner within ${IDLE_MS / 60_000} minutes: the job it was started for was cancelled or ran on another runner`);
323+ }
324+ }
325+
326+ /** Stops a runner's container and ends its row with `reason`. */
327+ private async stopRunner(row: RunnerJobRow, reason: string): Promise<void> {
328+ await this.db.prepare("UPDATE github_runner_jobs SET stop_reason = ? WHERE id = ?").bind(reason, row.id).run();
329+ if (row.container) await this.host.stop(row.container).catch((e: unknown) => console.error(`stopping GitHub runner ${row.id} failed`, e));
330+ await this.ended(row.id, null);
331+ }
332+
333+ /** A runner's container stopped (runner/containers.ts onStop), or Diffinery stopped it. */
334+ async stopped(rowId: string, exitCode: number | null): Promise<void> {
335+ const row = await this.row(rowId);
336+ if (!row) return;
337+ // A runner that crashed before it took a job (nothing of the job ran) is replaced, a few times.
338+ if (row.status === "starting" && !row.stop_reason && exitCode !== 0 && exitCode !== null && row.tries < MAX_TRIES) {
339+ if (row.container) await endCompute(this.env, row.container).catch(() => {});
340+ if (row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
341+ await this.db
342+ .prepare("UPDATE github_runner_jobs SET status = 'queued', container = NULL, message = ? WHERE id = ? AND status = 'starting'")
343+ .bind(`The runner stopped before it took a job (exit code ${exitCode}); starting another`, row.id)
344+ .run();
345+ return;
346+ }
347+ await this.ended(rowId, exitCode);
348+ }
349+
350+ private async ended(rowId: string, exitCode: number | null): Promise<void> {
351+ const row = await this.row(rowId);
352+ if (!row) return;
353+ if (row.container) await endCompute(this.env, row.container).catch((e: unknown) => console.error("compute usage failed", e));
354+ if (ENDED.has(row.status)) return;
355+ const neverPicked = row.status === "starting";
356+ // A just-in-time runner removes itself after its job; one that never took a job is removed here.
357+ if (neverPicked && row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
358+ const message = row.stop_reason ?? (neverPicked && exitCode ? `The runner stopped before it took a job (exit code ${exitCode})` : null);
359+ await this.db.prepare("UPDATE github_runner_jobs SET status = 'completed', exit_code = ?, message = ?, ended_at = ? WHERE id = ?").bind(exitCode, message, this.at(), rowId).run();
360+ }
361+
362+ /** A kill switch: queued jobs fail and running runners stop, with `message`. Returns the runners stopped. */
363+ async stopAll(accountId: string, message: string): Promise<number> {
364+ await this.db.prepare("UPDATE github_runner_jobs SET status = 'failed', message = ?, ended_at = ? WHERE account_id = ? AND status = 'queued'").bind(message, this.at(), accountId).run();
365+ const rows = (await this.db.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? AND status IN ('starting', 'running')").bind(accountId).all<RunnerJobRow>()).results;
366+ for (const row of rows) await this.stopRunner(row, message);
367+ return rows.length;
368+ }
369+}
modifiedapps/diffinery/src/index.ts+1−0View file
@@ -14,6 +14,7 @@
1414 export { AccountWorkflow } from "./accounts/workflow.js";
1515 export { ImportContainer } from "./imports/container.js";
1616 export { ProjectDO } from "./agentic/ProjectDO.js";
17+export { GitHubRunnersDO } from "./github-runners/GitHubRunnersDO.js";
1718 // Carries hosted containers' HTTP and HTTPS out under EGRESS=web (lib/egress.ts).
1819 export { ContainerProxy } from "@cloudflare/containers";
1920
modifiedapps/diffinery/src/lib/killswitch.ts+45−0View file
@@ -17,6 +17,9 @@
1717 * running then (RepoDO.stopActions); lifting one only allows new work again. Nobody is exempt,
1818 * not even site administrators' own accounts. A suspended person (lib/moderation.ts) counts as an
1919 * account whose Actions are suspended, with the suspension's reason.
20+ *
21+ * GitHub jobs on Diffinery runners (github-runners/) count as the linked account's hosted jobs: its
22+ * suspension and the instance's pause stop them too (accountKillSwitches, stopGitHubRunners).
2023 */
2124
2225 export const PAUSE_FLAG = "hosted_compute_paused";
@@ -62,6 +65,20 @@
6265 };
6366 }
6467
68+/**
69+ * The switches over an account's work outside its repositories (GitHub jobs on Diffinery runners): its own
70+ * suspension (or the person's, lib/moderation.ts) and the instance's pause.
71+ */
72+export async function accountKillSwitches(env: Env, accountId: string): Promise<KillSwitches> {
73+ const a = await env.DB.prepare(
74+ "SELECT login, actions_suspended_at AS a_at, actions_suspended_by AS a_by, actions_suspended_reason AS a_reason, suspended_at AS s_at, suspended_by AS s_by, suspended_reason AS s_reason FROM accounts WHERE id = ?",
75+ )
76+ .bind(accountId)
77+ .first<Record<string, string | null>>();
78+ const account = a?.a_at ? { at: a.a_at, by: a.a_by ?? null, reason: a.a_reason ?? null, login: a.login! } : a?.s_at ? { at: a.s_at, by: a.s_by ?? null, reason: a.s_reason ?? null, login: a.login! } : null;
79+ return { repo: null, account, paused: await computePause(env) };
80+}
81+
6582 /** Why `work` may not start under these switches (a sentence without a final period), or null when it may. */
6683 export function blockedBy(k: KillSwitches, work: Work): string | null {
6784 if (k.repo) return `Actions are suspended for this repository by a site administrator${tail(k.repo.reason)}`;
@@ -121,6 +138,8 @@
121138 const out = new Map<string, { jobs: string[]; sandboxes: string[] }>();
122139 for (const r of rows.results) {
123140 if (Date.parse(r.started_at) + MAX_RUN_MS[r.kind] <= at.getTime()) continue;
141+ // GitHub runners have no Diffinery repository (stopGitHubRunners stops them).
142+ if (r.repo_id.startsWith(GITHUB_COMPUTE)) continue;
124143 const e = out.get(r.repo_id) ?? { jobs: [], sandboxes: [] };
125144 const id = r.kind === "sandbox" ? r.id.split(":")[0]! : r.id;
126145 const list = r.kind === "job" ? e.jobs : e.sandboxes;
@@ -167,6 +186,30 @@
167186 return out;
168187 }
169188
189+/** compute_usage.repo_id of GitHub runners starts with this (github-runners/service.ts githubComputeRepo). */
190+const GITHUB_COMPUTE = "github:";
191+
192+/**
193+ * Stops the GitHub jobs on Diffinery runners of these accounts (all accounts running one when null):
194+ * queued ones fail and running runners stop, with `message`. Returns the runners stopped.
195+ */
196+export async function stopGitHubRunners(env: Env, accountIds: string[] | null, message: string): Promise<number> {
197+ const ns = env.GITHUB_RUNNERS;
198+ if (!ns) return 0;
199+ const ids =
200+ accountIds ??
201+ (await env.DB.prepare("SELECT DISTINCT account_id FROM github_runner_jobs WHERE status IN ('queued', 'starting', 'running')").all<{ account_id: string }>()).results.map((r) => r.account_id);
202+ let n = 0;
203+ for (const id of ids) {
204+ try {
205+ n += await ns.get(ns.idFromName(id)).stopAll(id, message);
206+ } catch (e) {
207+ console.error(`kill switch: stopping GitHub runners of ${id} failed`, e);
208+ }
209+ }
210+ return n;
211+}
212+
170213 type Actor = { id: string; login: string };
171214 type Audit = (entry: { actorId?: string; actorLogin?: string; action: string; target?: string; detail?: unknown }) => Promise<void>;
172215
@@ -199,6 +242,7 @@
199242 try {
200243 const ids = target.kind === "repo" ? [target.id] : (await env.DB.prepare("SELECT id FROM repos WHERE owner_id = ?").bind(target.id).all<{ id: string }>()).results.map((r) => r.id);
201244 stopped = await stopIn(env, ids, { hostedOnly: false, message });
245+ if (target.kind === "account") stopped.jobs += await stopGitHubRunners(env, [target.id], message);
202246 } finally {
203247 // The switch is on even if stopping what ran failed: it is recorded either way.
204248 await audit({ actorId: actor.id, actorLogin: actor.login, action: "actions.suspend", target: label, detail: { kind: target.kind, reason, via, stopped } });
@@ -223,6 +267,7 @@
223267 let stopped: Stopped | null = null;
224268 try {
225269 stopped = await stopIn(env, [...(await runningCompute(env)).keys()], { hostedOnly: true, message });
270+ stopped.jobs += await stopGitHubRunners(env, null, message);
226271 } finally {
227272 await audit({ actorId: actor.id, actorLogin: actor.login, action: "compute.pause", detail: { reason, via, stopped } });
228273 }
modifiedapps/diffinery/src/lib/rate-limit.ts+5−2View file
@@ -34,8 +34,11 @@
3434 export const RATE_LIMITS: Record<Bucket, number> = { RL_AUTH: 20, RL_ANON: 300, RL_ACCOUNT: 2000, RL_CREATE: 60 };
3535 export const RATE_PERIOD_S = 60;
3636
37-/** Paths that never count: health checks, avatars, and the Actions runtime and runners (their own credentials). */
38-const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/)/;
37+/**
38+ * Paths that never count: health checks, avatars, the Actions runtime and runners (their own credentials), and
39+ * the GitHub App's signed webhook, which GitHub sends from a few addresses for every job of every installation.
40+ */
41+const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/|-\/github\/webhook$)/;
3942 const AUTH = /^\/(?:auth\/passkey\/|invite\/|signin\/|login(?:$|\/)|signup(?:$|\/)|security\/report$|early-access(?:\/confirm|\/remove(?:\/confirm)?)?$|contact(?:\/confirm)?$|-\/cli\/device$|oauth\/register$)/;
4043 const CREATE: Array<[method: string, path: RegExp]> = [
4144 ["POST", /^\/api\/v3\/(?:user|orgs\/[^/]+)\/repos$/],
modifiedapps/diffinery/src/lib/retention.ts+7−2View file
@@ -10,6 +10,8 @@
1010 * - notifications older than NOTIFICATION_RETENTION_DAYS, as GitHub drops them after five months;
1111 * - hosted compute records (lib/quotas.ts) ended more than COMPUTE_RETENTION_DAYS ago, past any month
1212 * the usage pages show;
13+ * - GitHub jobs' runner rows (github-runners/) ended more than GITHUB_RUNNER_RETENTION_DAYS ago: the
14+ * settings page shows the latest few, and their minutes stay in compute_usage;
1315 * - early access requests (lib/early-access.ts) never confirmed within UNCONFIRMED_DAYS of their last
1416 * submission, and the form's daily-limit rows once they are a day old;
1517 * - contact messages (lib/contact.ts) never confirmed within CONTACT_UNCONFIRMED_DAYS, marked spam more
@@ -18,12 +20,13 @@
1820 */
1921 export const NOTIFICATION_RETENTION_DAYS = 180;
2022 export const COMPUTE_RETENTION_DAYS = 400;
23+export const GITHUB_RUNNER_RETENTION_DAYS = 30;
2124 /** Rows deleted per table per run: an hourly run keeps up with 120,000 new rows a day per table. */
2225 export const RETENTION_BATCH = 5000;
2326
24-export async function pruneExpired(db: D1Database, at = new Date(), batch = RETENTION_BATCH): Promise<Record<"sessions" | "notifications" | "compute_usage" | "early_access" | "early_access_attempts" | "contact_messages" | "contact_attempts", number>> {
27+export async function pruneExpired(db: D1Database, at = new Date(), batch = RETENTION_BATCH): Promise<Record<"sessions" | "notifications" | "compute_usage" | "early_access" | "early_access_attempts" | "contact_messages" | "contact_attempts" | "github_runner_jobs", number>> {
2528 const ago = (days: number) => new Date(at.getTime() - days * 86400_000).toISOString();
26- const [sessions, notifications, compute, early, attempts, contact, contactAttempts] = await db.batch([
29+ const [sessions, notifications, compute, early, attempts, contact, contactAttempts, githubRunners] = await db.batch([
2730 db.prepare("DELETE FROM sessions WHERE id IN (SELECT id FROM sessions WHERE expires_at < ? LIMIT ?)").bind(ago(1), batch),
2831 db.prepare("DELETE FROM notifications WHERE id IN (SELECT id FROM notifications WHERE created_at < ? LIMIT ?)").bind(ago(NOTIFICATION_RETENTION_DAYS), batch),
2932 db.prepare("DELETE FROM compute_usage WHERE id IN (SELECT id FROM compute_usage WHERE ended_at < ? LIMIT ?)").bind(ago(COMPUTE_RETENTION_DAYS), batch),
@@ -33,6 +36,7 @@
3336 .prepare("DELETE FROM contact_messages WHERE id IN (SELECT id FROM contact_messages WHERE (state = 'unconfirmed' AND created_at < ?) OR (state = 'spam' AND handled_at < ?) OR (state = 'handled' AND handled_at < ?) LIMIT ?)")
3437 .bind(ago(CONTACT_UNCONFIRMED_DAYS), ago(SPAM_DAYS), ago(HANDLED_DAYS), batch),
3538 db.prepare("DELETE FROM contact_attempts WHERE id IN (SELECT id FROM contact_attempts WHERE created_at < ? LIMIT ?)").bind(ago(1), batch),
39+ db.prepare("DELETE FROM github_runner_jobs WHERE id IN (SELECT id FROM github_runner_jobs WHERE ended_at < ? LIMIT ?)").bind(ago(GITHUB_RUNNER_RETENTION_DAYS), batch),
3640 ]);
3741 return {
3842 sessions: sessions!.meta.changes ?? 0,
@@ -42,5 +46,6 @@
4246 early_access_attempts: attempts!.meta.changes ?? 0,
4347 contact_messages: contact!.meta.changes ?? 0,
4448 contact_attempts: contactAttempts!.meta.changes ?? 0,
49+ github_runner_jobs: githubRunners!.meta.changes ?? 0,
4550 };
4651 }
modifiedapps/diffinery/src/repo/actions.ts+1−1View file
@@ -146,7 +146,7 @@
146146 * 2026-10-24 on a Typecheck job; its re-run started at once). The runtime marks other errors of its
147147 * own that pass as `retryable`.
148148 */
149-const RETRYABLE_START = /no container instance|is shutting down|network connection lost|durable object reset|no longer active|overloaded|too many containers|aborted waiting for container to start|container did not start after|internal error|out of memory|sqlite_nomem/i;
149+export const RETRYABLE_START = /no container instance|is shutting down|network connection lost|durable object reset|no longer active|overloaded|too many containers|aborted waiting for container to start|container did not start after|internal error|out of memory|sqlite_nomem/i;
150150 /**
151151 * Of those, the ones that say nothing about free machines (the runtime failing under one start): the
152152 * first is retried after QUICK_RETRY_SECONDS, like a fresh container's early stop, rather than waiting
modifiedapps/diffinery/src/runner/containers.ts+31−11View file
@@ -39,6 +39,8 @@
3939
4040 /** The job a runner container runs; stopRequested once Diffinery asked it to stop (stopJob). */
4141 type RunnerJob = { repoId: string; jobId: string; container?: string; stopRequested?: boolean };
42+/** A GitHub job's runner (github-runners/): GitHub's own runner, for the account that pays. */
43+type GitHubRunner = { accountId: string; runnerId: string };
4244
4345 /** How long a job's container may take to come up, and how often it is checked meanwhile. */
4446 const START_WAIT_MS = 180_000;
@@ -54,18 +56,29 @@
5456
5557 async startJob(input: { repoId: string; jobId: string; container?: string; token: string; apiUrl: string; egress?: Egress; vcpu?: number }): Promise<void> {
5658 await this.ctx.storage.put("job", { repoId: input.repoId, jobId: input.jobId, container: input.container });
57- const egressEnv = await this.useEgress(input.egress ?? "open");
59+ await this.startRunner({
60+ DIFFINERY_API_URL: input.apiUrl,
61+ DIFFINERY_JOB_ID: input.jobId,
62+ DIFFINERY_JOB_TOKEN: input.token,
63+ // The runner's share of CPU, which the agent measures the job's use against (runner/sizes.ts).
64+ ...(input.vcpu ? { DIFFINERY_RUNNER_VCPU: String(input.vcpu) } : {}),
65+ ...(await this.useEgress(input.egress ?? "open")),
66+ });
67+ }
68+
69+ /**
70+ * A GitHub job's runner (github-runners/service.ts): the agent runs GitHub's runner with the just-in-time
71+ * configuration GitHub made for it, which holds the runner's credentials, so it is only ever in the
72+ * container's environment.
73+ */
74+ async startGitHubRunner(input: { accountId: string; runnerId: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void> {
75+ await this.ctx.storage.put("github", { accountId: input.accountId, runnerId: input.runnerId } satisfies GitHubRunner);
76+ await this.startRunner({ DIFFINERY_GITHUB_JIT_CONFIG: input.jitConfig, DIFFINERY_RUNNER_VCPU: String(input.vcpu), ...(await this.useEgress(input.egress)) });
77+ }
78+
79+ private async startRunner(envVars: Record<string, string>): Promise<void> {
5880 await this.start(
59- {
60- envVars: {
61- DIFFINERY_API_URL: input.apiUrl,
62- DIFFINERY_JOB_ID: input.jobId,
63- DIFFINERY_JOB_TOKEN: input.token,
64- // The runner's share of CPU, which the agent measures the job's use against (runner/sizes.ts).
65- ...(input.vcpu ? { DIFFINERY_RUNNER_VCPU: String(input.vcpu) } : {}),
66- ...egressEnv,
67- },
68- },
81+ { envVars },
6982 // The library gives up after 8 s and reports "no container instance", but a container on a host
7083 // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
7184 // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
@@ -91,6 +104,13 @@
91104 }
92105
93106 override async onStop(params: StopParams): Promise<void> {
107+ const gh = await this.ctx.storage.get<GitHubRunner>("github");
108+ if (gh) {
109+ const ns = this.env.GITHUB_RUNNERS;
110+ if (ns) await ns.get(ns.idFromName(gh.accountId)).stopped(gh.accountId, gh.runnerId, params.exitCode ?? null);
111+ await this.ctx.storage.delete("github");
112+ return;
113+ }
94114 const job = await this.ctx.storage.get<RunnerJob>("job");
95115 if (!job) return;
96116 const repo = this.env.REPO.get(this.env.REPO.idFromName(job.repoId));
modifiedapps/diffinery/src/web/account.tsx+4−1View file
@@ -635,7 +635,7 @@
635635 { value: "rebase", label: "Rebase and merge" },
636636 ];
637637
638-export type SettingsTab = "profile" | "account" | "appearance" | "pull-requests" | "security" | "tokens" | "apps" | "installations" | "agents" | "model-access" | "orgs" | "invitations" | "notifications" | "email-address" | "blocked" | "linked" | "admin" | "reports" | "email" | "audit" | "kill-switches" | "errors" | "security-reports" | "status" | "early-access" | "contact" | "search-engines";
638+export type SettingsTab = "profile" | "account" | "appearance" | "pull-requests" | "security" | "tokens" | "apps" | "installations" | "github-runners" | "agents" | "model-access" | "orgs" | "invitations" | "notifications" | "email-address" | "blocked" | "linked" | "admin" | "reports" | "email" | "audit" | "kill-switches" | "errors" | "security-reports" | "status" | "early-access" | "contact" | "search-engines";
639639 /** The site administration pages: they show when hosted compute is paused. */
640640 export const ADMIN_TABS: readonly SettingsTab[] = ["admin", "early-access", "contact", "reports", "email", "audit", "kill-switches", "errors", "security-reports", "status", "search-engines"];
641641
@@ -719,6 +719,9 @@
719719 <a href="/settings/apps" class={tab === "apps" ? "on" : ""}>
720720 Apps
721721 </a>
722+ <a href="/settings/github-runners" class={tab === "github-runners" ? "on" : ""}>
723+ GitHub runners
724+ </a>
722725 <a href="/settings/model-access" class={tab === "model-access" ? "on" : ""}>
723726 Model access
724727 </a>
addedapps/diffinery/src/web/github-runners.tsx+285−0View file
@@ -1,0 +1,285 @@
1+/** @jsxImportSource hono/jsx */
2+import type { FC } from "hono/jsx";
3+import { requireAccount, type AppContext } from "../auth/principal.js";
4+import { GitHubRunnerLinks, SETUP_PATH, type LinkedInstallation } from "../github-runners/links.js";
5+import type { RunnerJobRow } from "../github-runners/service.js";
6+import { computeUsage, quotasFor } from "../lib/quotas.js";
7+import type { Account } from "../lib/directory.js";
8+import { HttpError } from "../lib/util.js";
9+import { SettingsNav } from "./account.js";
10+import { csrfToken } from "./csrf.js";
11+import { KSelect } from "./kumo.js";
12+import { Form, Time, act, flash, post, render, type WebApp } from "./ui.js";
13+
14+/**
15+ * Settings → GitHub runners: link a GitHub App installation to the Diffinery account that pays, and see the
16+ * runners its jobs got (github-runners/). Linking and unlinking need a person signed in with a passkey:
17+ * no token or agent can make an account pay for GitHub jobs.
18+ */
19+
20+const links = (c: AppContext) => new GitHubRunnerLinks(c.env, c.get("dir"));
21+
22+/** A person (not an agent, token or app) signed in with a passkey in a browser. */
23+function person(c: AppContext, what: string): Account {
24+ const p = c.get("principal");
25+ if (p.type === "anonymous") throw new HttpError(401, "sign in required");
26+ if (p.type === "account" && (p.via === "session" || p.via === "dev")) {
27+ const a = requireAccount(c);
28+ if (a.kind === "user") return a;
29+ }
30+ throw new HttpError(403, `only a person signed in with a passkey in a browser can ${what}`);
31+}
32+
33+const page = (c: AppContext, me: Account, title: string, body: unknown) =>
34+ render(
35+ c,
36+ { title },
37+ <div class="grid left">
38+ <SettingsNav me={me} tab="github-runners" db={c.env.DB} />
39+ <div style="max-width:880px">{body}</div>
40+ </div>,
41+ );
42+
43+const STATUS: Record<RunnerJobRow["status"], [string, string]> = {
44+ queued: ["waiting", "badge amber"],
45+ starting: ["starting", "badge blue"],
46+ running: ["running", "badge blue"],
47+ completed: ["done", "badge green"],
48+ skipped: ["skipped", "badge"],
49+ failed: ["failed", "badge red"],
50+};
51+
52+function duration(from: string | null, to: string | null): string {
53+ if (!from || !to) return "";
54+ const s = Math.max(0, Math.round((Date.parse(to) - Date.parse(from)) / 1000));
55+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
56+}
57+
58+const Jobs: FC<{ jobs: RunnerJobRow[] }> = ({ jobs }) =>
59+ jobs.length ? (
60+ <table class="tbl">
61+ <thead>
62+ <tr>
63+ <th>Job</th>
64+ <th>Runner</th>
65+ <th>Status</th>
66+ <th>Queued</th>
67+ <th>Ran for</th>
68+ </tr>
69+ </thead>
70+ <tbody>
71+ {jobs.map((j) => {
72+ const [label, cls] = STATUS[j.status] ?? [j.status, "badge"];
73+ return (
74+ <tr>
75+ <td>
76+ <div>{j.html_url ? <a href={j.html_url}>{j.ran_job_name ?? j.job_name ?? `job ${j.github_job_id}`}</a> : (j.ran_job_name ?? j.job_name ?? `job ${j.github_job_id}`)}</div>
77+ <div class="meta">
78+ {j.repo}
79+ {j.workflow_name ? ` · ${j.workflow_name}` : ""}
80+ </div>
81+ {j.message ? <div class="meta">{j.message}</div> : null}
82+ </td>
83+ <td class="small">{j.size}</td>
84+ <td>
85+ <span class={cls}>{label}</span>
86+ {j.conclusion ? <div class="meta">{j.conclusion}</div> : null}
87+ </td>
88+ <td class="small nowrap">
89+ <Time at={j.created_at} />
90+ </td>
91+ <td class="small nowrap">{duration(j.started_at, j.ended_at)}</td>
92+ </tr>
93+ );
94+ })}
95+ </tbody>
96+ </table>
97+ ) : (
98+ <div class="empty">No jobs yet. Set a job's runs-on to diffinery and push.</div>
99+ );
100+
101+const Installation: FC<{ inst: LinkedInstallation; webUrl: string; t: string }> = ({ inst, webUrl, t }) => {
102+ const configure = inst.github_type === "Organization" ? `${webUrl}/organizations/${encodeURIComponent(inst.github_login)}/settings/installations/${inst.id}` : `${webUrl}/settings/installations/${inst.id}`;
103+ return (
104+ <li>
105+ <div class="grow">
106+ <a href={`${webUrl}/${encodeURIComponent(inst.github_login)}`}>
107+ <b>{inst.github_login}</b>
108+ </a>{" "}
109+ <span class="badge">{inst.github_type === "Organization" ? "organization" : "user"}</span> {inst.suspended_at ? <span class="badge amber">suspended on GitHub</span> : null}
110+ <div class="meta">
111+ Linked <Time at={inst.linked_at} /> · <a href={configure}>Choose repositories on GitHub</a>
112+ </div>
113+ </div>
114+ <Form action="/settings/github-runners/unlink" t={t} confirm={`Unlink ${inst.github_login}? Its jobs that wait for a runner won't get one.`} class="inline">
115+ <input type="hidden" name="installation" value={String(inst.id)} />
116+ <button class="btn sm">Unlink</button>
117+ </Form>
118+ </li>
119+ );
120+};
121+
122+async function overviewPage(c: AppContext) {
123+ const me = requireAccount(c);
124+ const l = links(c);
125+ const t = csrfToken(c);
126+ const overview = l.enabled ? await l.overview(me) : [];
127+ const payers = overview.map((o) => o.account);
128+ const minutes = await Promise.all(
129+ overview.map(async (o) => {
130+ const [q, u] = await Promise.all([quotasFor(c.env, o.account.id), computeUsage(c.env, o.account.id)]);
131+ return q.hosted_minutes < 0 ? `${u.hosted_minutes} hosted minutes this month` : `${u.hosted_minutes} of ${q.hosted_minutes} hosted minutes this month`;
132+ }),
133+ );
134+ return page(
135+ c,
136+ me,
137+ "GitHub runners",
138+ <>
139+ <h1>GitHub runners</h1>
140+ <p class="muted">
141+ Keep your code on GitHub and run its Actions jobs on this Diffinery's hosted runners. Install the app on a GitHub account or organization, link it to the Diffinery account whose hosted minutes pay for the jobs, and set a job's{" "}
142+ <code>runs-on</code> to <code>diffinery</code> (4 vCPU) or <code>diffinery-medium</code>, <code>diffinery-small</code>, <code>diffinery-tiny</code>. See <a href="/docs/actions/github-runners">GitHub runners</a>.
143+ </p>
144+ {!l.enabled ? (
145+ <div class="flash notice">This Diffinery has no GitHub App, so GitHub runners are off. A site administrator can set one up: see <a href="/docs/self-hosting/configuration#github-runners">Configuration</a>.</div>
146+ ) : (
147+ <>
148+ <Form action="/settings/github-runners/connect" t={t} class="box mb">
149+ <div class="head">
150+ <h2>Connect GitHub</h2>
151+ </div>
152+ <div class="body fbody">
153+ <div class="field">
154+ <label>Account that pays</label>
155+ <KSelect name="account" options={payers.map((p) => ({ value: p.id, label: p.kind === "org" ? `${p.login} (organization)` : `${p.login} (you)` }))} value={me.id} block />
156+ </div>
157+ <div class="factions">
158+ <button class="btn primary" name="mode" value="install">
159+ Install on GitHub
160+ </button>
161+ <button class="btn" name="mode" value="existing">
162+ Link an existing installation
163+ </button>
164+ </div>
165+ </div>
166+ </Form>
167+ <div class="box mb">
168+ <div class="head">
169+ <h2>In a workflow</h2>
170+ </div>
171+ <div class="body">
172+ <pre class="code">{"jobs:\n test:\n runs-on: diffinery # or diffinery-medium, diffinery-small, diffinery-tiny\n steps:\n - uses: actions/checkout@v4\n - run: npm test\n"}</pre>
173+ </div>
174+ </div>
175+ {overview.map((o, i) =>
176+ o.installations.length || o.jobs.length ? (
177+ <div class="box mb">
178+ <div class="head row between">
179+ <h2>{o.account.login}</h2>
180+ <span class="muted small">{minutes[i]}</span>
181+ </div>
182+ {o.installations.length ? (
183+ <ul class="list">
184+ {o.installations.map((inst) => (
185+ <Installation inst={inst} webUrl={l.client!.app.webUrl} t={t} />
186+ ))}
187+ </ul>
188+ ) : (
189+ <div class="empty">No installation is linked to {o.account.login}.</div>
190+ )}
191+ <Jobs jobs={o.jobs} />
192+ </div>
193+ ) : null,
194+ )}
195+ </>
196+ )}
197+ </>,
198+ );
199+}
200+
201+export function registerGitHubRunners(web: WebApp): void {
202+ web.get("/settings/github-runners", overviewPage);
203+
204+ post(web, "/settings/github-runners/connect", async (c, f) =>
205+ act(c, "/settings/github-runners", async () => {
206+ const me = person(c, "link GitHub runners");
207+ const l = links(c);
208+ return f.s("mode") === "existing" ? l.authorizeUrl(me, f.s("account") || me.id) : l.installUrl(me, f.s("account") || me.id);
209+ }),
210+ );
211+
212+ // GitHub's setup URL and callback URL: after installing the app, or after authorizing it.
213+ web.get(SETUP_PATH, async (c) => {
214+ const installation = Number(c.req.query("installation_id"));
215+ let me: Account;
216+ let r;
217+ try {
218+ me = person(c, "link GitHub runners");
219+ r = await links(c).setup(me, { installationId: Number.isSafeInteger(installation) && installation > 0 ? installation : null, code: c.req.query("code") || null, state: c.req.query("state") || null });
220+ } catch (e) {
221+ if (!(e instanceof HttpError) || e.status >= 500) throw e;
222+ flash(c, "error", e.message);
223+ return c.redirect("/settings/github-runners", 303);
224+ }
225+ if ("redirect" in r) return c.redirect(r.redirect, 302);
226+ if ("linked" in r) {
227+ flash(c, "notice", `Linked ${r.linked.github_login}. Its jobs with runs-on: diffinery now run here.`);
228+ return c.redirect("/settings/github-runners", 303);
229+ }
230+ const t = csrfToken(c);
231+ const payers = await links(c).payers(me);
232+ return page(
233+ c,
234+ me,
235+ "Link a GitHub installation",
236+ <>
237+ <h1>Link a GitHub installation</h1>
238+ <p class="muted">These are the installations of the app your GitHub account can manage. Pick one and the Diffinery account that pays for its jobs.</p>
239+ {r.choose.length ? (
240+ <ul class="list box">
241+ {r.choose.map((i) => (
242+ <li>
243+ <div class="grow">
244+ <b>{i.login}</b> <span class="badge">{i.type === "Organization" ? "organization" : "user"}</span>
245+ {i.linkedTo ? <div class="meta">Linked to {i.linkedTo}; linking it here moves it.</div> : null}
246+ </div>
247+ <Form action="/settings/github-runners/link" t={t} class="row" style="gap:8px">
248+ <input type="hidden" name="proof" value={i.proof} />
249+ <KSelect name="account" size="sm" options={payers.map((p) => ({ value: p.id, label: p.login }))} value={r.payer.id} />
250+ <button class="btn sm primary">Link</button>
251+ </Form>
252+ </li>
253+ ))}
254+ </ul>
255+ ) : (
256+ <div class="empty">
257+ Your GitHub account can't manage any installation of the app yet. <a href="/settings/github-runners">Install it first</a>.
258+ </div>
259+ )}
260+ </>,
261+ );
262+ });
263+
264+ post(web, "/settings/github-runners/link", async (c, f) =>
265+ act(c, "/settings/github-runners", async () => {
266+ const me = person(c, "link GitHub runners");
267+ const linked = await links(c).linkWithProof(me, f.s("proof"), f.s("account") || me.id);
268+ flash(c, "notice", `Linked ${linked.github_login}. Its jobs with runs-on: diffinery now run here.`);
269+ }),
270+ );
271+
272+ post(web, "/settings/github-runners/unlink", async (c, f) =>
273+ act(
274+ c,
275+ "/settings/github-runners",
276+ async () => {
277+ const me = person(c, "unlink GitHub runners");
278+ const id = Number(f.s("installation"));
279+ if (!Number.isSafeInteger(id) || id <= 0) throw new HttpError(422, "no installation given");
280+ await links(c).unlink(me, id);
281+ },
282+ "Unlinked. Runners already started finish their jobs.",
283+ ),
284+ );
285+}
modifiedapps/diffinery/src/web/routes.tsx+3−0View file
@@ -33,6 +33,7 @@
3333 import { registerDocs } from "../docs/web.js";
3434 import { registerModeration } from "./moderation.js";
3535 import { registerApps } from "./apps.js";
36+import { registerGitHubRunners } from "./github-runners.js";
3637
3738 /**
3839 * Server-rendered web UI. Mount at "/" after the API, Git and runner routes:
@@ -96,6 +97,8 @@
9697 registerAccountLifecycle(web);
9798 // Settings → Apps and Installed apps, and /apps/:slug: fixed paths, before /:owner.
9899 registerApps(web);
100+// Settings → GitHub runners: fixed /settings paths, before /:owner.
101+registerGitHubRunners(web);
99102 // /-/report and /:owner/:repo/comments/:id/...: before the /:owner and /:owner/:repo catch-alls.
100103 registerModeration(web);
101104 registerAccount(web);
addedapps/diffinery/test/unit/github-runners.test.ts+446−0View file
@@ -1,0 +1,446 @@
1+import { createHmac, createVerify, generateKeyPairSync } from "node:crypto";
2+import { describe, expect, it } from "vitest";
3+import type { Env } from "../../src/env.js";
4+import { GitHubApiError, appJwt, githubApp, pkcs8FromPem, webhookSigned, type GitHubAppClient } from "../../src/github-runners/github.js";
5+import { githubWebhook } from "../../src/github-runners/http.js";
6+import { GitHubRunnerLinks } from "../../src/github-runners/links.js";
7+import { GitHubRunners, IDLE_MS, MAX_TRIES, WAIT_RETRY_MS, runnerFor, type QueuedJob, type RunnerHost, type RunnerJobRow } from "../../src/github-runners/service.js";
8+import type { Directory } from "../../src/lib/directory.js";
9+import { testD1 } from "./stubs/d1.js";
10+
11+const at = "2026-10-01T00:00:00.000Z";
12+const { privateKey: PKCS1, publicKey: SPKI } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs1", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
13+
14+const APP_VARS = {
15+ GITHUB_APP_ID: "123",
16+ GITHUB_APP_SLUG: "diffinery-runners",
17+ GITHUB_APP_CLIENT_ID: "Iv1.abc",
18+ GITHUB_APP_CLIENT_SECRET: "client-secret",
19+ GITHUB_APP_PRIVATE_KEY: PKCS1,
20+ GITHUB_APP_WEBHOOK_SECRET: "hook-secret",
21+ PUBLIC_URL: "https://diffinery.test",
22+ MASTER_KEY: Buffer.alloc(32, 7).toString("base64"),
23+};
24+
25+/** A D1 with ann (a person), acme (her organization) and bob (another person), and GitHub installation 11 linked to ann. */
26+function setup(vars: Record<string, unknown> = {}) {
27+ const DB = testD1();
28+ const add = (id: string, kind: string) => DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, status, site_admin, created_at) VALUES (?, ?, ?, 'active', 0, ?)").run(id, id, kind, at);
29+ add("ann", "user");
30+ add("acme", "org");
31+ add("bob", "user");
32+ DB.sqlite.prepare("INSERT INTO org_members (org_id, user_id, role, created_at) VALUES ('acme', 'ann', 'owner', ?)").run(at);
33+ DB.sqlite.prepare("INSERT INTO github_installations (id, account_id, github_login, github_type, linked_by, linked_at) VALUES (11, 'ann', 'ann-gh', 'User', 'ann', ?)").run(at);
34+ return { DB, env: { DB, ...vars } as unknown as Env };
35+}
36+
37+/** GitHub as the service sees it: just-in-time runners, a runner's state, removals. */
38+function fakeGitHub() {
39+ const calls: Array<{ op: string; args: unknown[] }> = [];
40+ let next = 500;
41+ const gh = {
42+ fail: null as Error | null,
43+ busy: false as boolean | null,
44+ async jitRunner(installationId: number, repo: string, name: string, labels: string[]) {
45+ calls.push({ op: "jit", args: [installationId, repo, name, labels] });
46+ if (gh.fail) throw gh.fail;
47+ return { runnerId: ++next, encodedJitConfig: `jit-${next}` };
48+ },
49+ async runner(installationId: number, repo: string, runnerId: number) {
50+ calls.push({ op: "runner", args: [installationId, repo, runnerId] });
51+ return gh.busy === null ? null : { busy: gh.busy, status: "online" };
52+ },
53+ async removeRunner(installationId: number, repo: string, runnerId: number) {
54+ calls.push({ op: "remove", args: [installationId, repo, runnerId] });
55+ },
56+ };
57+ return { gh, calls, client: gh as unknown as GitHubAppClient };
58+}
59+
60+function fakeHost(sizes: string[] = ["large", "medium", "small", "tiny"]) {
61+ const started: Array<{ container: string; input: Parameters<RunnerHost["start"]>[1] }> = [];
62+ const stopped: string[] = [];
63+ const host = {
64+ fail: null as Error | null,
65+ async start(container: string, input: Parameters<RunnerHost["start"]>[1]) {
66+ if (host.fail) throw host.fail;
67+ started.push({ container, input });
68+ },
69+ async stop(container: string) {
70+ stopped.push(container);
71+ },
72+ has: (size: string) => sizes.includes(size),
73+ };
74+ return { host: host as RunnerHost & { fail: Error | null }, started, stopped };
75+}
76+
77+const job = (id: number, labels = ["diffinery"]): QueuedJob => ({ installationId: 11, repo: "ann-gh/app", githubJobId: id, runId: 7, workflowName: "CI", jobName: `test ${id}`, htmlUrl: `https://github.com/ann-gh/app/actions/runs/7/job/${id}`, labels });
78+
79+function world(vars: Record<string, unknown> = {}, sizes?: string[]) {
80+ const s = setup(vars);
81+ const g = fakeGitHub();
82+ const h = fakeHost(sizes);
83+ let t = Date.parse("2026-10-30T12:00:00.000Z");
84+ const clock = { now: () => t, advance: (ms: number) => (t += ms) };
85+ const svc = new GitHubRunners(s.env, g.client, h.host, clock.now);
86+ const rows = () => s.DB.sqlite.prepare("SELECT * FROM github_runner_jobs ORDER BY created_at, github_job_id").all() as unknown as RunnerJobRow[];
87+ const compute = () => s.DB.sqlite.prepare("SELECT * FROM compute_usage").all() as Array<{ id: string; repo_id: string; ended_at: string | null }>;
88+ return { ...s, ...g, ...h, svc, clock, rows, compute };
89+}
90+
91+describe("the GitHub App", () => {
92+ it("is off until every setting is there", () => {
93+ expect(githubApp({ ...APP_VARS } as unknown as Env)).toMatchObject({ appId: "123", webUrl: "https://github.com", apiUrl: "https://api.github.com" });
94+ expect(githubApp({ ...APP_VARS, GITHUB_APP_URL: "https://ghe.example.com/" } as unknown as Env)).toMatchObject({ webUrl: "https://ghe.example.com", apiUrl: "https://ghe.example.com/api/v3" });
95+ expect(githubApp({ ...APP_VARS, GITHUB_APP_WEBHOOK_SECRET: "" } as unknown as Env)).toBeNull();
96+ });
97+
98+ it("signs its JWT with the PKCS#1 key GitHub gives, also pasted on one line", async () => {
99+ for (const key of [PKCS1, PKCS1.replace(/\n/g, "\\n")]) {
100+ const jwt = await appJwt({ appId: "123", privateKey: key }, 1_800_000_000);
101+ const [h, p, sig] = jwt.split(".");
102+ expect(JSON.parse(Buffer.from(p!, "base64url").toString())).toEqual({ iat: 1_799_999_940, exp: 1_800_000_540, iss: "123" });
103+ expect(createVerify("RSA-SHA256").update(`${h}.${p}`).verify(SPKI, Buffer.from(sig!, "base64url"))).toBe(true);
104+ }
105+ const { privateKey: pkcs8 } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs8", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
106+ expect(pkcs8FromPem(pkcs8)[0]).toBe(0x30);
107+ expect(() => pkcs8FromPem("not a key")).toThrow(/not a PEM private key/);
108+ });
109+
110+ it("takes only webhooks GitHub signed with the app's secret", async () => {
111+ const body = '{"action":"queued"}';
112+ const sig = `sha256=${createHmac("sha256", "hook-secret").update(body).digest("hex")}`;
113+ expect(await webhookSigned("hook-secret", sig, body)).toBe(true);
114+ expect(await webhookSigned("hook-secret", sig, body + " ")).toBe(false);
115+ expect(await webhookSigned("other", sig, body)).toBe(false);
116+ expect(await webhookSigned("hook-secret", undefined, body)).toBe(false);
117+ });
118+});
119+
120+describe("runs-on labels", () => {
121+ it("are for Diffinery with diffinery or a size, and only labels a Diffinery runner has", () => {
122+ expect(runnerFor(["diffinery"])).toBe("large");
123+ expect(runnerFor(["Diffinery-Medium"])).toBe("medium");
124+ expect(runnerFor(["self-hosted", "linux", "x64", "diffinery-tiny"])).toBe("tiny");
125+ expect(runnerFor(["diffinery-small", "diffinery-medium"])).toBe("medium");
126+ expect(runnerFor(["ubuntu-latest"])).toBeNull();
127+ expect(runnerFor(["self-hosted"])).toBeNull();
128+ expect(runnerFor(["diffinery", "gpu"])).toBeNull();
129+ expect(runnerFor(["diffinery", "arm64"])).toBeNull();
130+ expect(runnerFor([])).toBeNull();
131+ });
132+});
133+
134+describe("GitHub jobs on Diffinery runners", () => {
135+ it("start a runner for a queued job, follow it through its job and end when its container stops", async () => {
136+ const w = world();
137+ expect(await w.svc.queued("ann", job(1001, ["self-hosted", "diffinery-small"]), "small")).toBe(true);
138+ // GitHub delivers a webhook again after a timeout: the same job doesn't get a second runner.
139+ expect(await w.svc.queued("ann", job(1001, ["self-hosted", "diffinery-small"]), "small")).toBe(false);
140+ expect((await w.svc.pump("ann")).next).toBe(IDLE_MS);
141+ const [row] = w.rows();
142+ expect(row).toMatchObject({ status: "starting", tries: 1, size: "small", runner_name: `diffinery-${row!.id}-1`, github_runner_id: 501, container: `gh-${row!.id}-1.small` });
143+ expect(w.calls[0]).toEqual({ op: "jit", args: [11, "ann-gh/app", `diffinery-${row!.id}-1`, ["self-hosted", "diffinery-small"]] });
144+ expect(w.started).toEqual([{ container: `gh-${row!.id}-1.small`, input: { accountId: "ann", runnerId: row!.id, jitConfig: "jit-501", egress: "open", vcpu: 0.5 } }]);
145+ // It counts as one of ann's hosted jobs, under no Diffinery repository.
146+ expect(w.compute()).toEqual([expect.objectContaining({ id: `gh-${row!.id}-1.small`, repo_id: "github:11", ended_at: null })]);
147+
148+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1001, action: "in_progress", runnerName: `diffinery-${row!.id}-1`, jobName: "test 1001", conclusion: null });
149+ expect(w.rows()[0]).toMatchObject({ status: "running", ran_job_id: 1001 });
150+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1001, action: "completed", runnerName: `diffinery-${row!.id}-1`, jobName: "test 1001", conclusion: "success" });
151+ await w.svc.stopped(row!.id, 0);
152+ expect(w.rows()[0]).toMatchObject({ status: "completed", conclusion: "success", exit_code: 0, message: null });
153+ expect(w.compute()[0]!.ended_at).not.toBeNull();
154+ // A runner that ran its job removes itself from GitHub.
155+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([]);
156+ expect((await w.svc.pump("ann")).next).toBeNull();
157+ });
158+
159+ it("wait while the account runs as many hosted jobs as it may, and start once one ends", async () => {
160+ const w = world({ QUOTA_HOSTED_JOBS: "1" });
161+ w.DB.sqlite.prepare("INSERT INTO compute_usage (id, account_id, repo_id, kind, started_at) VALUES ('other', 'ann', 'r', 'job', ?)").run(new Date().toISOString());
162+ await w.svc.queued("ann", job(1), "large");
163+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
164+ expect(w.rows()[0]).toMatchObject({ status: "queued", message: expect.stringMatching(/^Waiting: waiting for one of this account's 1 hosted jobs/) });
165+ expect(w.started).toEqual([]);
166+ w.DB.sqlite.prepare("UPDATE compute_usage SET ended_at = ? WHERE id = 'other'").run(new Date().toISOString());
167+ await w.svc.pump("ann");
168+ expect(w.rows()[0]!.status).toBe("starting");
169+ });
170+
171+ it("don't start while the account's Actions are suspended or hosted compute is paused", async () => {
172+ const w = world();
173+ w.DB.sqlite.prepare("UPDATE accounts SET actions_suspended_at = ?, actions_suspended_reason = 'mining' WHERE id = 'ann'").run(at);
174+ await w.svc.queued("ann", job(1), "large");
175+ await w.svc.pump("ann");
176+ expect(w.rows()[0]).toMatchObject({ status: "failed", message: "The runner was not started: Actions are suspended for every repository of ann by a site administrator: mining" });
177+ w.DB.sqlite.prepare("UPDATE accounts SET actions_suspended_at = NULL WHERE id = 'ann'").run();
178+ w.DB.sqlite.prepare("INSERT INTO site_flags (key, value, updated_at, updated_by) VALUES ('hosted_compute_paused', 'maintenance', ?, 'root')").run(at);
179+ await w.svc.queued("ann", job(2), "large");
180+ await w.svc.pump("ann");
181+ expect(w.rows()[1]!.message).toMatch(/^The runner was not started: Hosted runners are paused on this instance by a site administrator: maintenance/);
182+ expect(w.started).toEqual([]);
183+ });
184+
185+ it("skip jobs that end before their runner starts, and jobs of an installation no longer linked or suspended", async () => {
186+ const w = world({ QUOTA_HOSTED_JOBS: "0" });
187+ await w.svc.queued("ann", job(1), "large");
188+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "completed", runnerName: null, jobName: "test 1", conclusion: "cancelled" });
189+ expect(w.rows()[0]).toMatchObject({ status: "skipped", conclusion: "cancelled", message: "The job ended before a runner started for it" });
190+ // Another Diffinery runner, started for another job with the same labels, took it.
191+ await w.svc.queued("ann", job(2), "large");
192+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: "diffinery-other-1", jobName: "test 2", conclusion: null });
193+ expect(w.rows()[1]).toMatchObject({ status: "skipped", message: "The job ran on diffinery-other-1 before a runner started for it" });
194+
195+ const v = world();
196+ v.DB.sqlite.prepare("UPDATE github_installations SET suspended_at = ?").run(at);
197+ await v.svc.queued("ann", job(1), "large");
198+ await v.svc.pump("ann");
199+ expect(v.rows()[0]).toMatchObject({ status: "skipped", message: "The app's installation is suspended on GitHub" });
200+ v.DB.sqlite.prepare("DELETE FROM github_installations").run();
201+ await v.svc.queued("ann", job(2), "large");
202+ await v.svc.pump("ann");
203+ expect(v.rows()[1]).toMatchObject({ status: "skipped", message: "The GitHub installation is no longer linked to this account" });
204+ });
205+
206+ it("run a size this Diffinery doesn't have on a large runner", async () => {
207+ const w = world({}, ["large"]);
208+ await w.svc.queued("ann", job(1, ["diffinery-tiny"]), "tiny");
209+ await w.svc.pump("ann");
210+ expect(w.rows()[0]).toMatchObject({ size: "large" });
211+ expect(w.started[0]!.container).not.toContain(".");
212+ expect(w.started[0]!.input.vcpu).toBe(4);
213+ });
214+
215+ it("give up when GitHub refuses the runner, and try again later when GitHub is down", async () => {
216+ const w = world();
217+ w.gh.fail = new GitHubApiError(403, "GitHub answered 403 to POST repos/ann-gh/app/actions/runners/generate-jitconfig: Resource not accessible by integration");
218+ await w.svc.queued("ann", job(1), "large");
219+ await w.svc.pump("ann");
220+ expect(w.rows()[0]).toMatchObject({ status: "failed", message: expect.stringMatching(/^Could not register a runner on GitHub: .*Resource not accessible/) });
221+
222+ w.gh.fail = new GitHubApiError(502, "bad gateway");
223+ await w.svc.queued("ann", job(2), "large");
224+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
225+ expect(w.rows()[1]).toMatchObject({ status: "queued", tries: 1 });
226+ w.gh.fail = null;
227+ await w.svc.pump("ann");
228+ expect(w.rows()[1]).toMatchObject({ status: "starting", tries: 2 });
229+ });
230+
231+ it("put a runner whose container got no machine back in line, and fail one whose start can't work", async () => {
232+ const w = world();
233+ w.host.fail = new Error("there is no container instance that can be provided to this durable object");
234+ await w.svc.queued("ann", job(1), "large");
235+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
236+ const row = w.rows()[0]!;
237+ expect(row).toMatchObject({ status: "queued", container: null, message: expect.stringMatching(/^Starting a runner failed; trying again/) });
238+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([{ op: "remove", args: [11, "ann-gh/app", 501] }]);
239+ expect(w.compute()[0]!.ended_at).not.toBeNull();
240+ w.host.fail = new Error("image not found");
241+ await w.svc.pump("ann");
242+ expect(w.rows()[0]).toMatchObject({ status: "failed", message: "Could not start a runner: image not found" });
243+ });
244+
245+ it("replace a runner that crashed before it took a job, a few times", async () => {
246+ const w = world();
247+ await w.svc.queued("ann", job(1), "large");
248+ for (let i = 1; i < MAX_TRIES; i++) {
249+ await w.svc.pump("ann");
250+ await w.svc.stopped(w.rows()[0]!.id, 1);
251+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: i, message: "The runner stopped before it took a job (exit code 1); starting another" });
252+ }
253+ await w.svc.pump("ann");
254+ await w.svc.stopped(w.rows()[0]!.id, 1);
255+ expect(w.rows()[0]).toMatchObject({ status: "completed", tries: MAX_TRIES, message: "The runner stopped before it took a job (exit code 1)" });
256+ expect(w.compute().every((c) => c.ended_at)).toBe(true);
257+ expect(w.started.map((s) => s.container)).toEqual([1, 2, 3].map((n) => `gh-${w.rows()[0]!.id}-${n}`));
258+ });
259+
260+ it("stop a runner no job took within the idle time, unless GitHub says it is busy", async () => {
261+ const w = world();
262+ await w.svc.queued("ann", job(1), "large");
263+ await w.svc.queued("ann", job(2), "large");
264+ await w.svc.pump("ann");
265+ w.clock.advance(IDLE_MS + 1000);
266+ // The first runner's in_progress webhook never came, but it has a job; the second has none.
267+ let n = 0;
268+ const runner = w.gh.runner.bind(w.gh);
269+ w.gh.runner = async (...a) => ((w.gh.busy = n++ === 0), runner(...a));
270+ await w.svc.pump("ann");
271+ const [a, b] = w.rows();
272+ expect(a).toMatchObject({ status: "running" });
273+ expect(b).toMatchObject({ status: "completed", message: expect.stringMatching(/^No job took this runner within 10 minutes/) });
274+ expect(w.stopped).toEqual([b!.container]);
275+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([{ op: "remove", args: [11, "ann-gh/app", b!.github_runner_id] }]);
276+ // Its container's stop arrives afterwards and changes nothing.
277+ await w.svc.stopped(b!.id, 137);
278+ expect(w.rows()[1]).toMatchObject({ status: "completed", exit_code: null });
279+ });
280+
281+ it("stop everything for a kill switch", async () => {
282+ const w = world({ QUOTA_HOSTED_JOBS: "1" });
283+ await w.svc.queued("ann", job(1), "large");
284+ await w.svc.queued("ann", job(2), "large");
285+ await w.svc.pump("ann");
286+ expect(await w.svc.stopAll("ann", "paused")).toBe(1);
287+ expect(w.rows().map((r) => [r.status, r.message])).toEqual([
288+ ["completed", "paused"],
289+ ["failed", "paused"],
290+ ]);
291+ expect(w.stopped).toHaveLength(1);
292+ });
293+});
294+
295+// ---------------------------------------------------------------- the webhook
296+
297+function hookEnv(DB: D1Database, vars: Record<string, unknown> = APP_VARS) {
298+ const calls: Array<{ op: string; name: string; args: unknown[] }> = [];
299+ const stub = (name: string) => ({
300+ queued: async (...args: unknown[]) => void calls.push({ op: "queued", name, args }),
301+ jobEvent: async (...args: unknown[]) => void calls.push({ op: "jobEvent", name, args }),
302+ });
303+ const GITHUB_RUNNERS = { idFromName: (n: string) => n, get: (n: string) => stub(n) };
304+ return { env: { DB, GITHUB_RUNNERS, ...vars } as unknown as Env, calls };
305+}
306+
307+async function deliver(env: Env, event: string, payload: unknown, secret = "hook-secret") {
308+ const body = JSON.stringify(payload);
309+ return githubWebhook.request("/-/github/webhook", { method: "POST", body, headers: { "x-github-event": event, "x-hub-signature-256": `sha256=${createHmac("sha256", secret).update(body).digest("hex")}` } }, env);
310+}
311+
312+const queuedPayload = (labels: string[], installation = 11, action = "queued", runner_name: string | null = null) => ({
313+ action,
314+ workflow_job: { id: 99, run_id: 7, name: "test", workflow_name: "CI", labels, runner_name, conclusion: null, html_url: "https://github.com/ann-gh/app/actions/runs/7/job/99" },
315+ repository: { full_name: "ann-gh/app" },
316+ installation: { id: installation },
317+});
318+
319+describe("the GitHub App's webhook", () => {
320+ it("is off without the app and refuses unsigned deliveries", async () => {
321+ const { DB } = setup();
322+ expect((await deliver(hookEnv(DB, { PUBLIC_URL: "https://diffinery.test" }).env, "ping", {})).status).toBe(404);
323+ const { env } = hookEnv(DB);
324+ expect((await deliver(env, "ping", {}, "wrong")).status).toBe(401);
325+ expect((await deliver(env, "ping", {})).status).toBe(200);
326+ });
327+
328+ it("hands queued jobs for Diffinery to the linked account, and nothing else", async () => {
329+ const { DB } = setup();
330+ const { env, calls } = hookEnv(DB);
331+ expect(await (await deliver(env, "workflow_job", queuedPayload(["diffinery-medium"]))).json()).toEqual({ queued: true, size: "medium" });
332+ expect(calls).toEqual([{ op: "queued", name: "ann", args: ["ann", expect.objectContaining({ installationId: 11, repo: "ann-gh/app", githubJobId: 99, labels: ["diffinery-medium"] }), "medium"] }]);
333+ expect(await (await deliver(env, "workflow_job", queuedPayload(["ubuntu-latest"]))).json()).toEqual({ ignored: "not for a Diffinery runner" });
334+ expect(await (await deliver(env, "workflow_job", queuedPayload(["diffinery"], 12))).json()).toEqual({ ignored: "this installation isn't linked to a Diffinery account" });
335+ await deliver(env, "workflow_job", queuedPayload(["diffinery"], 11, "in_progress", "diffinery-abc-1"));
336+ expect(calls[1]).toEqual({ op: "jobEvent", name: "ann", args: ["ann", { installationId: 11, githubJobId: 99, action: "in_progress", runnerName: "diffinery-abc-1", jobName: "test", conclusion: null }] });
337+ // Another provider's runner doesn't count as Diffinery's.
338+ await deliver(env, "workflow_job", queuedPayload(["diffinery"], 11, "completed", "hosted-runner-7"));
339+ expect(calls[2]!.args[1]).toMatchObject({ action: "completed", runnerName: null });
340+ expect(calls).toHaveLength(3);
341+ });
342+
343+ it("follows the installation: suspended, renamed, uninstalled", async () => {
344+ const { DB } = setup();
345+ const { env } = hookEnv(DB);
346+ const inst = () => DB.sqlite.prepare("SELECT * FROM github_installations WHERE id = 11").get() as { suspended_at: string | null; github_login: string } | undefined;
347+ await deliver(env, "installation", { action: "suspend", installation: { id: 11 } });
348+ expect(inst()!.suspended_at).not.toBeNull();
349+ await deliver(env, "installation", { action: "unsuspend", installation: { id: 11 } });
350+ expect(inst()!.suspended_at).toBeNull();
351+ await deliver(env, "installation_target", { action: "renamed", installation: { id: 11, account: { login: "ann-new" } } });
352+ expect(inst()!.github_login).toBe("ann-new");
353+ await deliver(env, "installation", { action: "deleted", installation: { id: 11 } });
354+ expect(inst()).toBeUndefined();
355+ });
356+});
357+
358+// ---------------------------------------------------------------- linking an installation
359+
360+function linking(installations: Array<{ id: number; account: { login: string; type: string } }>) {
361+ const s = setup({ ...APP_VARS, GITHUB_RUNNERS: {} });
362+ const audits: Array<{ action: string; target?: string; detail?: unknown }> = [];
363+ const accounts = { ann: { id: "ann", login: "ann", kind: "user" }, bob: { id: "bob", login: "bob", kind: "user" } } as const;
364+ const dir = {
365+ orgsFor: async (id: string) => (id === "ann" ? [{ id: "acme", login: "acme", kind: "org", role: "owner" }] : []),
366+ audit: async (e: { action: string; target?: string; detail?: unknown }) => void audits.push(e),
367+ } as unknown as Directory;
368+ const requests: string[] = [];
369+ const fetcher = (async (input: string, init?: RequestInit) => {
370+ requests.push(`${init?.method ?? "GET"} ${input}`);
371+ if (input === "https://github.com/login/oauth/access_token") {
372+ const code = (JSON.parse(String(init!.body)) as { code: string }).code;
373+ return Response.json(code === "good" ? { access_token: "ghu_x" } : { error_description: "bad code" });
374+ }
375+ if (input.startsWith("https://api.github.com/user/installations")) return Response.json({ installations });
376+ return new Response("not found", { status: 404 });
377+ }) as typeof fetch;
378+ const links = new GitHubRunnerLinks(s.env, dir, fetcher);
379+ const stateOf = (url: string) => new URL(url).searchParams.get("state")!;
380+ const linked = () => s.DB.sqlite.prepare("SELECT id, account_id, github_login FROM github_installations ORDER BY id").all();
381+ return { ...s, links, audits, requests, stateOf, linked, ann: accounts.ann as never, bob: accounts.bob as never };
382+}
383+
384+describe("linking an installation", () => {
385+ it("installs on GitHub for an account the person manages, and links what GitHub says they can manage", async () => {
386+ const l = linking([{ id: 42, account: { login: "acme-gh", type: "Organization" } }]);
387+ const install = await l.links.installUrl(l.ann, "acme");
388+ expect(install).toMatch(/^https:\/\/github\.com\/apps\/diffinery-runners\/installations\/new\?state=/);
389+ // No code (user authorization during installation is off): authorize the app first.
390+ const r1 = await l.links.setup(l.ann, { installationId: 42, code: null, state: l.stateOf(install) });
391+ if (!("redirect" in r1)) throw new Error("expected a redirect");
392+ expect(r1.redirect).toMatch(/^https:\/\/github\.com\/login\/oauth\/authorize\?client_id=Iv1\.abc&redirect_uri=https%3A%2F%2Fdiffinery\.test%2Fsettings%2Fgithub-runners%2Fsetup/);
393+ const r2 = await l.links.setup(l.ann, { installationId: null, code: "good", state: l.stateOf(r1.redirect) });
394+ expect(r2).toMatchObject({ linked: { id: 42, account_id: "acme", github_login: "acme-gh", github_type: "Organization", linked_by: "ann" } });
395+ expect(l.audits).toEqual([{ actorId: "ann", actorLogin: "ann", action: "github_runners.link", target: "acme", detail: { installation: 42, github: "acme-gh" } }]);
396+ });
397+
398+ it("refuses an installation the person can't manage on GitHub, an account they don't manage, and someone else's state", async () => {
399+ const l = linking([{ id: 42, account: { login: "acme-gh", type: "Organization" } }]);
400+ const state = l.stateOf(await l.links.installUrl(l.ann, "ann"));
401+ await expect(l.links.setup(l.ann, { installationId: 43, code: "good", state })).rejects.toThrow(/can't manage that installation/);
402+ await expect(l.links.installUrl(l.bob, "acme")).rejects.toThrow(/only to your own account or an organization you own or administer/);
403+ await expect(l.links.setup(l.bob, { installationId: 42, code: "good", state })).rejects.toThrow(/made for someone else/);
404+ await expect(l.links.setup(l.ann, { installationId: 42, code: "good", state: state.slice(0, -2) + "xx" })).rejects.toThrow(/not valid/);
405+ await expect(l.links.setup(l.ann, { installationId: 42, code: "bad", state })).rejects.toThrow(/did not sign you in: bad code/);
406+ expect(l.linked()).toEqual([{ id: 11, account_id: "ann", github_login: "ann-gh" }]);
407+ });
408+
409+ it("never uses a code that came without the person's own state, and links a picked installation to the account they pick", async () => {
410+ const l = linking([
411+ { id: 11, account: { login: "ann-gh", type: "User" } },
412+ { id: 42, account: { login: "acme-gh", type: "Organization" } },
413+ ]);
414+ // A code without a state may be another GitHub user's: authorize again with the person's own.
415+ const r1 = await l.links.setup(l.ann, { installationId: 42, code: "someone-elses", state: null });
416+ if (!("redirect" in r1)) throw new Error("expected a redirect");
417+ expect(l.requests).toEqual([]);
418+ const r2 = await l.links.setup(l.ann, { installationId: null, code: "good", state: l.stateOf(r1.redirect) });
419+ if (!("choose" in r2)) throw new Error("expected a choice");
420+ expect(r2.choose.map((i) => [i.id, i.login, i.linkedTo])).toEqual([
421+ [11, "ann-gh", "ann"],
422+ [42, "acme-gh", null],
423+ ]);
424+ expect(l.linked()).toHaveLength(1);
425+ const proof = r2.choose[1]!.proof;
426+ await expect(l.links.linkWithProof(l.bob, proof, "bob")).rejects.toThrow(/made for someone else/);
427+ await expect(l.links.linkWithProof(l.ann, proof, "bob")).rejects.toThrow(/only to your own account/);
428+ await l.links.linkWithProof(l.ann, proof, "acme");
429+ expect(l.linked()).toEqual([
430+ { id: 11, account_id: "ann", github_login: "ann-gh" },
431+ { id: 42, account_id: "acme", github_login: "acme-gh" },
432+ ]);
433+ });
434+
435+ it("unlinks: jobs waiting for a runner get none", async () => {
436+ const l = linking([]);
437+ l.DB.sqlite
438+ .prepare("INSERT INTO github_runner_jobs (id, account_id, installation_id, repo, github_job_id, labels, size, status, created_at) VALUES ('j', 'ann', 11, 'ann-gh/app', 1, '[\"diffinery\"]', 'large', 'queued', ?)")
439+ .run(at);
440+ await expect(l.links.unlink(l.bob, 11)).rejects.toThrow(/only to your own account/);
441+ await l.links.unlink(l.ann, 11);
442+ expect(l.linked()).toEqual([]);
443+ expect(l.DB.sqlite.prepare("SELECT status, message FROM github_runner_jobs").get()).toEqual({ status: "skipped", message: "The GitHub installation was unlinked" });
444+ expect(l.audits.at(-1)).toMatchObject({ action: "github_runners.unlink", target: "ann", detail: { installation: 11, github: "ann-gh" } });
445+ });
446+});
modifiedapps/diffinery/test/unit/killswitch.test.ts+22−0View file
@@ -126,4 +126,26 @@
126126 expect(() => cleanReason("x".repeat(501))).toThrow(/at most 500/);
127127 expect(cleanReason(" too many\nspaces ")).toBe("too many spaces");
128128 });
129+ it("reach GitHub jobs on Diffinery runners: an account's suspension stops its own, the pause everyone's", async () => {
130+ const { env, DB, audit } = setup();
131+ const stopAll: Array<{ account: string; message: string }> = [];
132+ (env as unknown as Record<string, unknown>).GITHUB_RUNNERS = {
133+ idFromName: (n: string) => n,
134+ get: (n: string) => ({ stopAll: async (account: string, message: string) => (stopAll.push({ account, message }), n === "acme" ? 2 : 1) }),
135+ };
136+ const job = (id: string, account: string, status: string) =>
137+ DB.sqlite.prepare("INSERT INTO github_runner_jobs (id, account_id, installation_id, repo, github_job_id, labels, size, status, created_at) VALUES (?, ?, 1, 'o/r', ?, '[]', 'large', ?, ?)").run(id, account, id.length, status, at);
138+ job("a", "acme", "running");
139+ job("bb", "ann", "queued");
140+ job("ccc", "ann", "completed");
141+ // A GitHub runner counts as hosted compute but has no Diffinery repository to stop it through.
142+ DB.sqlite.prepare("INSERT INTO compute_usage (id, account_id, repo_id, kind, started_at) VALUES ('gh-a-1', 'acme', 'github:1', 'job', ?)").run(new Date().toISOString());
143+ expect([...(await runningCompute(env)).keys()]).toEqual([]);
144+
145+ expect((await changeSuspension(env, audit, ann, { kind: "account", id: "acme", login: "acme" }, "abuse", "api"))!.jobs).toBe(2 * 2 + 2);
146+ expect(stopAll).toEqual([{ account: "acme", message: "Actions are suspended for every repository of acme by a site administrator: abuse" }]);
147+ stopAll.length = 0;
148+ expect((await changePause(env, audit, ann, "maintenance", "api"))!.jobs).toBe(3);
149+ expect(stopAll.map((s) => s.account).sort()).toEqual(["acme", "ann"]);
150+ });
129151 });
modifiedapps/diffinery/test/unit/retention.test.ts+1−1View file
@@ -19,7 +19,7 @@
1919 usage.run("old-job", ago(COMPUTE_RETENTION_DAYS + 2), ago(COMPUTE_RETENTION_DAYS + 1));
2020 usage.run("recent-job", ago(30), ago(30));
2121 usage.run("running", ago(0), null);
22- expect(await pruneExpired(DB, at)).toEqual({ sessions: 1, notifications: 1, compute_usage: 1, early_access: 0, early_access_attempts: 0, contact_messages: 0, contact_attempts: 0 });
22+ expect(await pruneExpired(DB, at)).toEqual({ sessions: 1, notifications: 1, compute_usage: 1, early_access: 0, early_access_attempts: 0, contact_messages: 0, contact_attempts: 0, github_runner_jobs: 0 });
2323 const ids = (t: string) => (DB.sqlite.prepare(`SELECT id FROM ${t} ORDER BY id`).all() as Array<{ id: string }>).map((r) => r.id);
2424 expect(ids("sessions")).toEqual(["just-expired", "live"]);
2525 expect(ids("notifications")).toEqual(["recent"]);
modifiedapps/diffinery/wrangler.jsonc+8−3View file
@@ -70,7 +70,9 @@
7070 { "name": "RUNNER_TINY", "class_name": "RunnerContainerTiny" },
7171 { "name": "SANDBOX", "class_name": "SandboxContainer" },
7272 { "name": "IMPORTER", "class_name": "ImportContainer" },
73- { "name": "PROJECT", "class_name": "ProjectDO" }
73+ { "name": "PROJECT", "class_name": "ProjectDO" },
74+ // GitHub jobs on Diffinery runners, one per paying account (src/github-runners/GitHubRunnersDO.ts).
75+ { "name": "GITHUB_RUNNERS", "class_name": "GitHubRunnersDO" }
7476 ]
7577 },
7678 "migrations": [
@@ -83,7 +85,9 @@
8385 // Smaller hosted runner sizes (src/runner/sizes.ts).
8486 { "tag": "v5", "new_sqlite_classes": ["RunnerContainerMedium", "RunnerContainerSmall", "RunnerContainerTiny"] },
8587 // Joining large uploads' blocks, a step per object (compose.ts).
86- { "tag": "v6", "new_sqlite_classes": ["ComposeDO"] }
88+ { "tag": "v6", "new_sqlite_classes": ["ComposeDO"] },
89+ // GitHub jobs on Diffinery runners (src/github-runners/GitHubRunnersDO.ts).
90+ { "tag": "v7", "new_sqlite_classes": ["GitHubRunnersDO"] }
8791 ],
8892 "workflows": [
8993 { "name": "diffinery-run", "binding": "RUN_WORKFLOW", "class_name": "RunWorkflow" },
@@ -163,7 +167,8 @@
163167 // Sandboxes run in an `agent.mjs --sandbox-pool` process (SANDBOX_POOL_URL), not containers.
164168 { "name": "SANDBOX", "class_name": "SandboxPoolDO" },
165169 { "name": "IMPORTER", "class_name": "ImportContainer" },
166- { "name": "PROJECT", "class_name": "ProjectDO" }
170+ { "name": "PROJECT", "class_name": "ProjectDO" },
171+ { "name": "GITHUB_RUNNERS", "class_name": "GitHubRunnersDO" }
167172 ]
168173 },
169174 "workflows": [
modifiedcontainers/runner/Dockerfile+8−0View file
@@ -74,6 +74,14 @@
7474 apt-get clean; \
7575 rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
7676
77+# GitHub's own runner, for jobs of GitHub repositories that run on Diffinery runners
78+# (apps/diffinery/docs/actions/github-runners.md; the agent starts it with a just-in-time
79+# configuration). A fixed release, checked against its published SHA-256. GitHub updates a runner
80+# that falls too far behind as it starts, so keep this close to the latest release.
81+ARG ACTIONS_RUNNER_VERSION=2.338.2
82+ARG ACTIONS_RUNNER_SHA256=baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40
83+RUN set -eux; mkdir -p /opt/actions-runner; cd /tmp; file="actions-runner-linux-x64-${ACTIONS_RUNNER_VERSION}.tar.gz"; curl -fsSLo "${file}" "https://github.com/actions/runner/releases/download/v${ACTIONS_RUNNER_VERSION}/${file}"; echo "${ACTIONS_RUNNER_SHA256} ${file}" | sha256sum -c -; tar -xzf "${file}" -C /opt/actions-runner --no-same-owner; rm -f "${file}"; /opt/actions-runner/bin/installdependencies.sh; apt-get clean; rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
84+
7785 # Docker Engine, started on first use by the /usr/local/bin/docker wrapper. Cloudflare
7886 # Containers run it rootful with iptables, so bridge networks, service DNS, port
7987 # publishing and builds all work like on GitHub's hosted runners.
addedcontainers/runner/src/github-runner.ts+61−0View file
@@ -1,0 +1,61 @@
1+import { spawn } from "node:child_process";
2+
3+/** Where the image puts GitHub's runner (Dockerfile). */
4+export const ACTIONS_RUNNER_DIR = "/opt/actions-runner";
5+
6+/**
7+ * How long a platform rollout's SIGTERM waits before it reaches the job, as for Diffinery's own jobs
8+ * (main.ts drainOnSigtermMs): Cloudflare gives a container 15 minutes after SIGTERM.
9+ */
10+export const DRAIN_ON_SIGTERM_MS = 13 * 60_000;
11+
12+export interface GitHubRunnerOptions {
13+ /** The just-in-time configuration GitHub made for this runner: its credentials. Never logged. */
14+ jitConfig: string;
15+ runnerDir?: string;
16+ env?: NodeJS.ProcessEnv;
17+ drainOnSigtermMs?: number;
18+}
19+
20+/**
21+ * A GitHub job on a Diffinery runner (apps/diffinery/src/github-runners/): runs GitHub's own runner with
22+ * its just-in-time configuration. GitHub hands it one queued job, it runs the job and exits, and the
23+ * container stops. Returns the runner's exit code.
24+ *
25+ * Jobs run as root, as Diffinery's own hosted jobs do (the image's tools and caches are root's). SIGINT
26+ * (Diffinery stopping the runner) reaches the runner at once, which cancels the job; SIGTERM (a platform
27+ * rollout) waits up to drainOnSigtermMs for the job to finish first.
28+ */
29+export function runGitHubRunner(o: GitHubRunnerOptions): Promise<number> {
30+ const dir = o.runnerDir ?? ACTIONS_RUNNER_DIR;
31+ const env: NodeJS.ProcessEnv = { ...(o.env ?? process.env), RUNNER_ALLOW_RUNASROOT: "1" };
32+ // The job's steps inherit the runner's environment: the configuration stays out of it.
33+ delete env.DIFFINERY_GITHUB_JIT_CONFIG;
34+ const child = spawn(`${dir}/run.sh`, ["--jitconfig", o.jitConfig], { cwd: dir, env, stdio: ["ignore", "inherit", "inherit"] });
35+ let draining: NodeJS.Timeout | null = null;
36+ const forward = (sig: NodeJS.Signals) => {
37+ if (child.exitCode === null) child.kill(sig);
38+ };
39+ const onInt = () => forward("SIGINT");
40+ const onTerm = () => {
41+ if (draining) return forward("SIGTERM");
42+ process.stderr.write(`[diffinery-runner] the platform is stopping this runner; the job keeps running for up to ${Math.round((o.drainOnSigtermMs ?? DRAIN_ON_SIGTERM_MS) / 60_000)} minutes\n`);
43+ draining = setTimeout(() => forward("SIGTERM"), o.drainOnSigtermMs ?? DRAIN_ON_SIGTERM_MS);
44+ draining.unref();
45+ };
46+ process.on("SIGINT", onInt);
47+ process.on("SIGTERM", onTerm);
48+ return new Promise((resolve) => {
49+ const done = (code: number) => {
50+ if (draining) clearTimeout(draining);
51+ process.off("SIGINT", onInt);
52+ process.off("SIGTERM", onTerm);
53+ resolve(code);
54+ };
55+ child.on("error", (e) => {
56+ process.stderr.write(`[diffinery-runner] could not start GitHub's runner: ${e.message}\n`);
57+ done(2);
58+ });
59+ child.on("exit", (code, signal) => done(code ?? (signal ? 1 : 0)));
60+ });
61+}
modifiedcontainers/runner/src/main.ts+11−1View file
@@ -12,7 +12,9 @@
1212 * image layer uploads to the Diffinery registry (see relay.ts)
1313 *
1414 * With DIFFINERY_IMPORT_ID and DIFFINERY_IMPORT_TOKEN set (instead of a job), it
15- * runs a GitHub import's Git transfer (see importer.ts) and exits.
15+ * runs a GitHub import's Git transfer (see importer.ts) and exits. With
16+ * DIFFINERY_GITHUB_JIT_CONFIG set, it runs GitHub's own runner for one job of a
17+ * GitHub repository (see github-runner.ts) and exits.
1618 */
1719 import { readFile } from "node:fs/promises";
1820 import type { JobSpec } from "@diffinery/shared";
@@ -25,6 +27,7 @@
2527 import { startSandbox } from "./sandbox.js";
2628 import { startSandboxPool } from "./sandbox-pool.js";
2729 import { startRelay } from "./relay.js";
30+import { runGitHubRunner } from "./github-runner.js";
2831
2932 interface Args {
3033 spec?: string;
@@ -101,6 +104,13 @@
101104 return;
102105 }
103106
107+ if (env.DIFFINERY_GITHUB_JIT_CONFIG) {
108+ const code = await runGitHubRunner({ jitConfig: env.DIFFINERY_GITHUB_JIT_CONFIG });
109+ process.stdout.write(`[diffinery-runner] GitHub's runner exited with code ${code}
110+`);
111+ process.exit(code);
112+ }
113+
104114 if (env.DIFFINERY_IMPORT_ID) {
105115 const api = env.DIFFINERY_API_URL;
106116 const token = env.DIFFINERY_IMPORT_TOKEN;
addedcontainers/runner/test/github-runner.test.ts+51−0View file
@@ -1,0 +1,51 @@
1+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2+import { tmpdir } from "node:os";
3+import { join } from "node:path";
4+import { afterEach, describe, expect, it } from "vitest";
5+import { runGitHubRunner } from "../src/github-runner.js";
6+
7+const dirs: string[] = [];
8+afterEach(async () => {
9+ for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true });
10+});
11+
12+/** A stand-in for GitHub's run.sh that records its arguments and environment, then exits with `code`. */
13+async function fakeRunner(script: string): Promise<string> {
14+ const dir = await mkdtemp(join(tmpdir(), "gh-runner-"));
15+ dirs.push(dir);
16+ await writeFile(join(dir, "run.sh"), `#!/bin/sh\n${script}\n`);
17+ await chmod(join(dir, "run.sh"), 0o755);
18+ return dir;
19+}
20+
21+describe.skipIf(process.platform === "win32")("GitHub's runner", () => {
22+ it("runs with the just-in-time configuration, as root, without the configuration in the job's environment", async () => {
23+ const dir = await fakeRunner('echo "$1 $2" > args; env > env; exit 3');
24+ const code = await runGitHubRunner({ jitConfig: "abc==", runnerDir: dir, env: { PATH: process.env.PATH, DIFFINERY_GITHUB_JIT_CONFIG: "abc==", KEEP: "1" } });
25+ expect(code).toBe(3);
26+ expect((await readFile(join(dir, "args"), "utf8")).trim()).toBe("--jitconfig abc==");
27+ const env = await readFile(join(dir, "env"), "utf8");
28+ expect(env).toContain("RUNNER_ALLOW_RUNASROOT=1");
29+ expect(env).toContain("KEEP=1");
30+ expect(env).not.toContain("DIFFINERY_GITHUB_JIT_CONFIG");
31+ });
32+
33+ it("passes SIGINT on at once and holds SIGTERM back while the job may finish", async () => {
34+ const dir = await fakeRunner('trap "echo int > got; exit 130" INT; trap "echo term > got; exit 143" TERM; touch ready; while true; do sleep 0.05; done');
35+ const running = runGitHubRunner({ jitConfig: "x", runnerDir: dir, env: { PATH: process.env.PATH }, drainOnSigtermMs: 60_000 });
36+ // Its traps are set once it says it is ready.
37+ while (!(await readFile(join(dir, "ready")).then(() => true, () => false))) await new Promise((r) => setTimeout(r, 20));
38+ process.emit("SIGTERM");
39+ await new Promise((r) => setTimeout(r, 300));
40+ await expect(readFile(join(dir, "got"), "utf8")).rejects.toThrow();
41+ process.emit("SIGINT");
42+ expect(await running).toBe(130);
43+ expect((await readFile(join(dir, "got"), "utf8")).trim()).toBe("int");
44+ });
45+
46+ it("reports a runner that isn't there", async () => {
47+ const dir = await mkdtemp(join(tmpdir(), "gh-runner-"));
48+ dirs.push(dir);
49+ expect(await runGitHubRunner({ jitConfig: "x", runnerDir: dir, env: { PATH: process.env.PATH } })).toBe(2);
50+ });
51+});