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.

Merge pull request #16 from codician-team/claude/runner-start-race

GitHub runners: replace a runner whose container stopped before it took a job
altugank authored · GitHub committed 2 parents 0ffa4ef0980195commit 06d010101c4b12b289b6c6dd42fd89fded9ffb88Browse files
73 files changed+4061−117
Files (73)
modified.github/workflows/deploy.yml+10−4View file
@@ -7,6 +7,8 @@
77 # DIFFINERY_ZONE the Cloudflare zone for the route (default: the domain's last two labels)
88 # MAIL_DOMAIN sends from notifications@<MAIL_DOMAIN> (default DIFFINERY_DOMAIN)
99 # ACCESS_TEAM_DOMAIN e.g. example.cloudflareaccess.com
10+# DIFFINERY_GITHUB_APP_ID, DIFFINERY_GITHUB_APP_SLUG, DIFFINERY_GITHUB_APP_CLIENT_ID,
11+# DIFFINERY_GITHUB_APP_URL the GitHub App of GitHub runners (docs/self-hosting/configuration.md)
1012 #
1113 # It deploys a main commit only once CI (typecheck, unit tests and the Worker bundle) has
1214 # passed on it, so it doesn't run those itself. End-to-end tests run alongside the deploy.
@@ -32,10 +34,9 @@
3234 jobs:
3335 gate:
3436 name: Main's current tip
35- # Production deploys from Diffinery itself, on its own hosted runners (any
36- # Diffinery, so self-hosted copies deploy themselves too). Running this
37- # workflow by hand on GitHub still deploys, as a fallback.
38- if: ${{ github.event_name == 'workflow_dispatch' || (github.server_url != 'https://github.com' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') }}
37+ # Every push to main deploys once CI passes on it, on GitHub or on a Diffinery
38+ # instance, and so does running this workflow by hand.
39+ if: ${{ github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') }}
3940 runs-on: ubuntu-latest
4041 timeout-minutes: 5
4142 outputs:
@@ -78,6 +79,11 @@
7879 ACCESS_TEAM_DOMAIN: ${{ vars.ACCESS_TEAM_DOMAIN }}
7980 # Who becomes site administrator on first sign-in. Unset keeps the deployed Worker's list (scripts/bootstrap-admins.sh).
8081 BOOTSTRAP_ADMINS: ${{ vars.BOOTSTRAP_ADMINS }}
82+ # The GitHub App's IDs, for scripts/render-config.mjs. Repository variables can't start with GITHUB_.
83+ GITHUB_APP_ID: ${{ vars.DIFFINERY_GITHUB_APP_ID }}
84+ GITHUB_APP_SLUG: ${{ vars.DIFFINERY_GITHUB_APP_SLUG }}
85+ GITHUB_APP_CLIENT_ID: ${{ vars.DIFFINERY_GITHUB_APP_CLIENT_ID }}
86+ GITHUB_APP_URL: ${{ vars.DIFFINERY_GITHUB_APP_URL }}
8187 steps:
8288 - uses: actions/checkout@v4
8389 with:
modified.gitignore+2−0View file
@@ -7,3 +7,5 @@
77 coverage/
88 .DS_Store
99 wrangler.deploy.jsonc
10+wrangler.celld.jsonc
11+.celld/
modifiedAGENTS.md+5−0View file
@@ -55,6 +55,11 @@
5555 - **Follow GitHub where GitHub has an API, event or workflow feature**, so git, `gh`,
5656 Octokit and actions keep working. Document any difference in
5757 `apps/diffinery/docs/actions/compatibility.md` or the relevant page.
58+- **Keep it running on celld**, the open-source Workers runtime
59+ (`apps/diffinery/docs/self-hosting/celld.md`). Make a binding celld lacks optional (and list it in
60+ `CELLD_ABSENT_BINDINGS`), map any new `wrangler.jsonc` key in `scripts/celld-config.mjs`, and import only
61+ `cloudflare:workers`, `cloudflare:workflows`, `cloudflare:sockets` and the `node:` modules celld has. Never return a stream or a
62+ `Response` from a Durable Object RPC method: stream through its `fetch()`. `test/unit/celld.test.ts` checks it.
5863 - **D1 migrations** live in `apps/diffinery/migrations`. Use the next free number and never
5964 edit a migration that has shipped.
6065 - **Security:** guardrails for agents are enforced on the server for git, REST, MCP and the
modifiedCONTRIBUTING.md+4−0View file
@@ -75,6 +75,10 @@
7575 - **GitHub compatibility.** Where GitHub has an API, a workflow feature or an event,
7676 Diffinery follows it, so existing tools (git, `gh`, Octokit, actions) work unchanged.
7777 When Diffinery has to differ, say so in the docs.
78+- **Open-source runtime.** Diffinery also runs on [celld](https://celld.dev), the open-source
79+ Workers runtime. A Cloudflare feature celld lacks must be optional, a new `wrangler.jsonc`
80+ key must be mapped in `scripts/celld-config.mjs`, and the unit test `celld.test.ts` checks
81+ both. See [Run on celld](https://diffinery.com/docs/self-hosting/celld).
7882 - **Database migrations.** D1 migrations live in `apps/diffinery/migrations`. Use the next
7983 free number and never edit a migration that has shipped.
8084 - **Security first.** Agents never get a bypass: guardrails are enforced on the server for
modifiedREADME.md+2−0View file
@@ -210,6 +210,8 @@
210210
211211 You can also deploy from CI with the included [Deploy workflow](.github/workflows/deploy.yml) on Diffinery or GitHub Actions. The full guide, including email sending, DNS, Access and troubleshooting, is [Deploy your own Diffinery](https://diffinery.com/docs/self-hosting/deploy), and every setting is described in [Configuration](https://diffinery.com/docs/self-hosting/configuration).
212212
213+Diffinery also targets [celld](https://celld.dev), the open-source Workers and Durable Objects runtime, so the same repository can run on your own machines if you leave Cloudflare. See [Run on celld](https://diffinery.com/docs/self-hosting/celld).
214+
213215 ## How it runs on Cloudflare
214216
215217 | Piece | Cloudflare product |
modifiedapps/diffinery/docs/accounts/notifications.md+1−1View file
@@ -381,7 +381,7 @@
381381 | `turned off <group> emails` | You turned off that group (for example `turned off watching emails`). |
382382 | `no email address` | Your account has no email address. |
383383 | `account disabled` | Disabled accounts only get the email saying they were disabled or enabled. |
384-| `email sending is not configured (no EMAIL binding)` | The instance can't send email; ask a site administrator. |
384+| `email sending is not configured (no EMAIL binding or SMTP_URL)` | The instance can't send email; ask a site administrator. |
385385 | `address is suppressed: ...` | Email to your address bounced or was reported as spam, or a site administrator suppressed it. See [When Diffinery stops emailing you](#when-diffinery-stops-emailing-you). |
386386
387387 ## How notifications differ from GitHub
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+133−0View file
@@ -1,0 +1,133 @@
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-31
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 run by a runner that isn't one of this account's Diffinery runners), 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 a runner may run a different queued job with the same labels instead of the one it was started for. Each queued job still gets one runner: the runner's row then shows the job it ran, and the job it was started for waits for the next runner, in its place in line, with its own labels and size.
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. This also happens, rarely, when a job is cancelled just as the runner started for it takes a different queued job: Diffinery then starts one more runner for the cancelled job. 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+**"The runner's container stopped before it took a job; starting another".** The runner's container stopped without an error before GitHub handed it a job, for example because Cloudflare lost the machine it ran on. GitHub still had the job queued, so Diffinery started another runner for it. As with a runner that exited with an error, Diffinery tries up to 3 runners for a job.
132+
133+**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+11−6View 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
@@ -299,7 +300,7 @@
299300
300301 | Item | What it shows |
301302 | --- | --- |
302-| **Sending** | "Cloudflare Email Sending is bound", or "not configured (no EMAIL binding): emails are logged, not sent" |
303+| **Sending** | "Cloudflare Email Sending is bound"; "over SMTP: smtps://user@host:465", the server in `SMTP_URL` (never the password); "SMTP_URL is set but can't be used: ..." with the reason; or "not configured (no EMAIL binding or SMTP_URL): emails are logged, not sent". See [SMTP](/docs/self-hosting/configuration#smtp). |
303304 | **Queue** | `diffinery-mail`, or "not bound: emails are dropped" |
304305 | **From** | The address emails are sent from: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty (see [Configuration](/docs/self-hosting/configuration)) |
305306 | **Bounces and complaints** | Where they come from: the `diffinery-mail-events` queue, and whether the signed endpoint is on (`MAIL_EVENTS_SECRET` set) |
@@ -314,7 +315,7 @@
314315
315316 **Suppressed addresses** lists every address Diffinery sends nothing to, newest first, with why (`hard-bounce`, `complaint` or `manual`), where that came from and since when. **Remove** sends email to the address again; **Suppress an address** adds one by hand, with an optional note. Both are recorded in the audit log. See [Bounces, complaints and the suppression list](#bounces-complaints-and-the-suppression-list).
316317
317-**Recent emails** lists the last 100 emails sent to anyone, with the time, recipient address, subject, template kind, Cloudflare's message ID, the status (`sent`, `failed` or `skipped`) and the reason when it wasn't sent. The log keeps 90 days.
318+**Recent emails** lists the last 100 emails sent to anyone, with the time, recipient address, subject, template kind, the message ID (Cloudflare's, or the `Message-ID` Diffinery gave an email sent over SMTP), the status (`sent`, `failed` or `skipped`) and the reason when it wasn't sent. The log keeps 90 days.
318319
319320 See [Notifications](/docs/accounts/notifications#every-email-diffinery-sends) for when each email is sent.
320321
@@ -322,7 +323,7 @@
322323
323324 | Method and path | Description | Needs |
324325 | --- | --- | --- |
325-| `GET /api/v3/diffinery/admin/email` | `sending` and `queue` (whether they are configured), `from` (the sender address: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty), `last_24h` counts (`sent`, `failed`, `skipped`) and the `last` email logged | site administrator, any token scope |
326+| `GET /api/v3/diffinery/admin/email` | `sending` and `queue` (whether they are configured), `transport` (`email-sending`, `smtp` or `null`), `smtp` (`url`, the server without the password, and `error`, why `SMTP_URL` can't be used; `null` unless `transport` is `smtp`), `from` (the sender address: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty), `last_24h` counts (`sent`, `failed`, `skipped`) and the `last` email logged | site administrator, any token scope |
326327 | `POST /api/v3/diffinery/admin/emails/samples` | Send every template to yourself now, or only some with `{"only": ["signin", "invite-org"]}`. Returns `to`, `sent`, `total` and each result. | site administrator, with an `admin` token for all repositories or a browser session |
327328 | `GET /api/v3/diffinery/admin/email/suppressions` | The suppression list, newest first: `email`, `reason`, `detail`, `source` (`cloudflare`, `webhook`, `send` or `admin`), `created_by`, `created_at` and `owner_can_lift` | site administrator, any token scope |
328329 | `PUT /api/v3/diffinery/admin/email/suppressions/{email}` | Suppress an address by hand, with an optional `{"note": "..."}`. Audited as `email.suppression.add`. | site administrator, with an `admin` token or a browser session |
@@ -337,7 +338,7 @@
337338
338339 | Reason | How |
339340 | --- | --- |
340-| `hard-bounce` | Email to it bounced permanently (the mailbox or domain doesn't exist, or the receiving server refuses it for good), or Email Sending refused to send to it for good (`E_RECIPIENT_SUPPRESSED`, source `send`). Soft bounces, delays and temporary send errors (rate and daily limits, delivery errors) change nothing. |
341+| `hard-bounce` | Email to it bounced permanently (the mailbox or domain doesn't exist, or the receiving server refuses it for good), or Email Sending refused to send to it for good (`E_RECIPIENT_SUPPRESSED`, source `send`), or the SMTP server refused the recipient for good (`E_SMTP_RECIPIENT_REJECTED`, source `send`). Soft bounces, delays and temporary send errors (rate and daily limits, delivery errors) change nothing. |
341342 | `complaint` | Its owner marked an email from Diffinery as spam. |
342343 | `manual` | A site administrator added it, under **Suppress an address** or with the API. |
343344
@@ -514,8 +515,12 @@
514515 | "enable this account first" | Sign-in links can't be created for disabled accounts. Set the status to `active`, then create the link. |
515516 | "enter a valid email address" | The invite form needs an address like `[email protected]`. |
516517 | `403 only site admins can invite people without an organization` | Instance invites from the CLI or API need a site administrator; others must pass `--org`. |
517-| **Sending** says "not configured" | The Worker has no `send_email` binding, so emails are logged as skipped. See [Configuration](/docs/self-hosting/configuration). |
518-| Emails show as `failed` | The **Recent emails** detail has Cloudflare's error. Check the sending domain's DNS records and the queue. |
518+| **Sending** says "not configured" | The Worker has neither a `send_email` binding nor `SMTP_URL`, so emails are logged as skipped. See [Configuration](/docs/self-hosting/configuration) and [SMTP](/docs/self-hosting/configuration#smtp). |
519+| **Sending** says "SMTP_URL is set but can't be used" | Fix what it names, such as a password in the URL (it belongs in the `SMTP_PASSWORD` secret) or a missing `SMTP_PASSWORD`. Until then emails fail with `E_SMTP_CONFIG`. |
520+| `E_SMTP_REJECTED: SMTP AUTH: 535 ...` | The SMTP server refused the user or password. Check the user in `SMTP_URL` and the `SMTP_PASSWORD` secret. |
521+| `E_SMTP_REJECTED: SMTP MAIL FROM: 5...` | The SMTP user may not send from `MAIL_FROM`. Use an address the server allows. |
522+| `gave up after 6 attempts: SMTP ...` | The SMTP server kept answering `4xx`, or couldn't be reached in time. Check the host and port in `SMTP_URL`; port 25 is blocked on Cloudflare. |
523+| Emails show as `failed` | The **Recent emails** detail has Cloudflare's or the SMTP server's error. Check the sending domain's DNS records and the queue. |
519524 | Emails show as `skipped` with "address is suppressed" | The address bounced, reported spam or was suppressed by hand. See [Bounces, complaints and the suppression list](#bounces-complaints-and-the-suppression-list). |
520525 | `E_RECIPIENT_SUPPRESSED` | The address is on Cloudflare's own suppression list. Remove it in the Cloudflare dashboard. |
521526 | `401 missing or bad signature` from `/-/email/events` | The `X-Diffinery-Signature` header is missing, signed with another secret, or more than 5 minutes old. |
modifiedapps/diffinery/docs/nav.json+2−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",
@@ -132,6 +133,7 @@
132133 "self-hosting/deploy",
133134 "self-hosting/configuration",
134135 "self-hosting/architecture",
136+ "self-hosting/celld",
135137 "self-hosting/status-page"
136138 ]
137139 },
modifiedapps/diffinery/docs/self-hosting.md+5−1View file
@@ -1,7 +1,7 @@
11 ---
22 title: Self-hosting
33 description: Diffinery is open source (Apache-2.0) and runs on your own Cloudflare account. What an instance needs, what it costs, the steps to deploy one, and where to go next.
4-updated: 2026-10-25
4+updated: 2026-10-30
55 ---
66
77 Diffinery is open-source software under the Apache License 2.0, and the way to use it is to run your own instance on your own Cloudflare account and domain. There's no hosted service to sign up for: diffinery.com is the project's own instance. This page is the overview; [Deploy your own Diffinery](/docs/self-hosting/deploy) is the step-by-step guide.
@@ -59,6 +59,10 @@
5959 - **Your team's tools.** The CLI, the Claude Code and Codex plugins, the MCP server and the editor extensions all work with your instance. People install the CLI from it and run `diffinery setup` with its URL, which signs them in and points git, gh, the Claude Code plugins and Codex at it: `curl -fsSL https://git.example.com/install | bash`, then `diffinery setup --url https://git.example.com`. AI apps connect to `https://git.example.com/mcp`. See [Claude Code](/docs/connect/claude-code#self-hosted-diffinery), [Codex](/docs/connect/codex#self-hosted-diffinery), [Clone in your editor](/docs/repositories/clone-in-your-editor) and [Clone in JetBrains IDEs](/docs/repositories/clone-in-jetbrains-ides).
6060 - **How it fits together.** [Architecture](/docs/self-hosting/architecture) maps each part of Diffinery to the Cloudflare product that runs it.
6161
62+## Without Cloudflare
63+
64+The same repository also targets [celld](https://celld.dev), the open-source Workers and Durable Objects runtime, which runs on your own machines with an object storage bucket. `scripts/celld-config.mjs` turns `wrangler.jsonc` into a configuration celld accepts, and the unit tests keep Diffinery inside what celld supports. celld is beta and a few things work differently there, such as email and rate limits; see [Run on celld](/docs/self-hosting/celld).
65+
6266 ## Get help and contribute
6367
6468 Report bugs and send pull requests on [the GitHub mirror](https://github.com/codician-team/diffinery) or [the Diffinery repository](https://diffinery.com/codician/diffinery). Report security problems privately with the [report form](https://diffinery.com/security/report); see [Vulnerability disclosure](/docs/security/disclosure).
modifiedapps/diffinery/docs/self-hosting/architecture.md+5−2View file
@@ -3,7 +3,7 @@
33 description: How Diffinery maps onto Cloudflare products, how a git push and a workflow run flow through them, and where each kind of data is stored.
44 ---
55
6-Diffinery is one Cloudflare Worker plus the Cloudflare products it binds to. There are no servers or databases to run yourself. This page explains which product does what, how a git push and a workflow run move through the system, how the code is organized, and where each kind of data lives. Read it before you deploy or operate your own instance, or when you need to reason about consistency and failure modes.
6+Diffinery is one Cloudflare Worker plus the Cloudflare products it binds to. There are no servers or databases to run yourself. This page explains which product does what, how a git push and a workflow run move through the system, how the code is organized, and where each kind of data lives. Read it before you deploy or operate your own instance, or when you need to reason about consistency and failure modes. The same code also runs on celld, the open-source Workers runtime; [Run on celld](/docs/self-hosting/celld) maps each product to its celld equivalent.
77
88 ## Overview
99
@@ -24,6 +24,7 @@
2424 | The Git transfer of a GitHub import | Containers (`ImportContainer`, one container per transfer) | `IMPORTER` |
2525 | Scheduled workflows | Durable Object alarm, every 5 minutes (`SchedulerDO`, one instance) | `SCHEDULER` |
2626 | Joining large artifact and cache uploads | Durable Objects, one per step (`ComposeDO`) | `COMPOSE` |
27+| Request rate limits | Workers rate limiting; where it doesn't exist (`RATE_LIMITS=durable`), Durable Objects (`RateLimiterDO`, 32 shards) | `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL`; `RATE_LIMITER` |
2728 | Token expiry reminders, email log pruning, registry cleanup, expiry of draft imports and of account exports, a check that the scheduler's alarm is set, IndexNow submissions | Cron Triggers, every 5 minutes | `scheduled` handler |
2829 | Live run logs and pull request updates in the browser | Durable Object WebSockets with hibernation | Through `REPO` |
2930 | Outgoing email | Email Sending | `EMAIL` |
@@ -54,7 +55,7 @@
5455
5556 ## The Worker
5657
57-`apps/diffinery/src/index.ts` exports the Worker's `fetch`, `queue` and `scheduled` handlers, and the classes Cloudflare instantiates: `RepoDO`, `SchedulerDO`, `ComposeDO`, `RunnerContainer`, `SandboxContainer`, `RunWorkflow`, `ImportWorkflow` and `ImportContainer`.
58+`apps/diffinery/src/index.ts` exports the Worker's `fetch`, `queue` and `scheduled` handlers, and the classes Cloudflare instantiates: `RepoDO`, `SchedulerDO`, `ComposeDO`, `RateLimiterDO`, `RunnerContainer`, `SandboxContainer`, `RunWorkflow`, `ImportWorkflow` and `ImportContainer`.
5859
5960 Every request goes through one middleware before it reaches a route:
6061
@@ -215,6 +216,8 @@
215216
216217 Every request passes the rate limiting bindings before it is handled (`src/lib/rate-limit.ts`). Sign-in, invitation and security report requests count per IP address in `RL_AUTH`, other anonymous requests per IP address in `RL_ANON`, and requests with a session or token per account in `RL_ACCOUNT`. Requests that create repositories, organizations, forks, issues, pull requests, releases, comments or reviews also count in `RL_CREATE`, as do MCP tool calls that change something. Job, sandbox, runner and import credentials, health checks and avatars aren't counted. Cloudflare keeps each count in the location that serves the request, so the limits stop bursts rather than meter use exactly. Past a limit the request answers `429` with `retry-after: 60`. See [Bindings](/docs/self-hosting/configuration#bindings).
217218
219+A missing binding lets requests through, as in local development. Where the bindings don't exist at all, such as on celld, the open-source Workers runtime, set the `RATE_LIMITS` variable to `durable`: each limit without a binding is then counted by the `RateLimiterDO` Durable Object (`src/rate-limiter.ts`, binding `RATE_LIMITER`) with the same limits. Keys are spread over 32 objects by a hash of the key (`ip:<address>`, `acct:<id>` and so on), and each object counts its keys in fixed 60-second windows, in memory, without writing to storage. A request costs at most one call to one object, because the buckets a request counts against share a key. The fixed windows let up to twice a limit through around the start of a minute, and an object that restarts or moves starts its counts again. If the object fails, the request goes through, as with a failing binding.
220+
218221 ## Request flow: a git push
219222
220223 1. `git push` sends `POST /<owner>/<repo>.git/git-receive-pack` with a token in Basic authentication.
addedapps/diffinery/docs/self-hosting/celld.md+118−0View file
@@ -1,0 +1,118 @@
1+---
2+title: Run on celld
3+description: Run Diffinery outside Cloudflare on celld, the open-source Workers and Durable Objects runtime. What runs, what is left out, the gaps to know, and the commands to deploy a fleet.
4+updated: 2026-10-31
5+---
6+
7+Diffinery is built for Cloudflare, and the same code also targets [celld](https://celld.dev), the open-source (Apache-2.0) implementation of Workers and Durable Objects that the Deno team built and that is now part of Cloudflare. celld runs a Worker on your own machines, with an S3, Google Cloud Storage or Azure Blob bucket as its only outside dependency. If you ever need to leave Cloudflare, or run Diffinery where Cloudflare isn't an option, you keep the same repository, the same `wrangler.jsonc` and the same data model.
8+
9+> **Status.** celld is beta and its Containers support is experimental. On October 31, 2026, Diffinery ran on a one-node celld 0.6.3 fleet: it applied the D1 migrations and served the web UI, docs, REST, GraphQL and MCP. git push (with a 6 MB object), clone, shallow clone and fetch worked, as did issues, pull requests and squash merge, archives, profile pictures and the event queues, and pushes started workflow runs. Hosted runners and sandboxes, which need celld's containers, were not tested, and the end-to-end test suite doesn't run on celld yet. The unit tests check on every run that Diffinery stays inside what celld supports (see [How compatibility is kept](#how-compatibility-is-kept)).
10+
11+## What runs on celld
12+
13+| Diffinery uses | On Cloudflare | On celld |
14+| --- | --- | --- |
15+| The Worker: web UI, REST and GraphQL APIs, git over HTTPS, MCP server | Workers | Workers, with `nodejs_compat` |
16+| One Durable Object per repository, with SQLite, alarms and hibernating WebSockets (`REPO`, `PROJECT`, `SCHEDULER`, `COMPOSE`) | Durable Objects | Cells, distributed across the fleet |
17+| Accounts, organizations, tokens (`DB`) | D1 | D1, one cell per database, no read replicas |
18+| Git objects, LFS, logs, caches, artifacts, release assets (`BUCKET`) | R2 | R2, stored under `r2/diffinery-data/` in the fleet bucket |
19+| Webhooks, notifications and email jobs (`EVENTS`, `MAIL`) | Queues | Queues, with retries and dead-letter queues |
20+| Workflow runs, imports, account exports (`RUN_WORKFLOW`, `IMPORT_WORKFLOW`, `ACCOUNT_WORKFLOW`) | Workflows | Workflows |
21+| Housekeeping every 5 minutes | Cron Triggers | Cron Triggers, one run per occurrence across the fleet |
22+| Hosted runners, sandboxes and the import container | Containers | Containers (experimental), on Docker or Podman on each node |
23+
24+## What is left out
25+
26+`celld deploy` stops on a `wrangler.jsonc` key it doesn't know. `scripts/celld-config.mjs` writes `apps/diffinery/wrangler.celld.jsonc` from `wrangler.jsonc` without these keys, and Diffinery runs without each of them:
27+
28+| `wrangler.jsonc` key | Binding | What happens on celld |
29+| --- | --- | --- |
30+| `routes`, `workers_dev` | | celld has no managed ingress. Put a reverse proxy that terminates TLS in front of the fleet. |
31+| `send_email` | `EMAIL` | Emails are logged as skipped, not sent. **Settings → Email** (`/settings/admin/email`) shows "not configured (no EMAIL binding)". Invitation links are still shown to the person who invites, with a copy button. |
32+| `ratelimits` | `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Requests are not rate limited. Limit them in your proxy. |
33+| `version_metadata` | `CF_VERSION_METADATA` | IndexNow hashes the site's pages at every check instead of once per deployed version. |
34+| `observability`, `upload_source_maps`, `limits` | | Logs go to each node's output, and stack traces point into the bundle. |
35+
36+The script also drops the container keys celld doesn't take (`image_build_context`, `rollout_active_grace_period`, `rollout_step_percentage`); celld builds the runner image in the Dockerfile's directory, `containers/runner`, which is the same context.
37+
38+## Gaps to know
39+
40+- **The first administrator.** The first sign-in is at `/auth/access` through Cloudflare Access, or through open sign-up's emailed code. On celld there is no email, so either put the fleet behind a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) with an Access application on `/auth/access` and set `ACCESS_TEAM_DOMAIN` and `ACCESS_AUD`, or wait for a non-Cloudflare email transport. After that, the administrator invites people and sends them the link shown under "Invite created for …"; passkey sign-in needs neither Access nor email.
41+- **Client IP addresses.** Diffinery reads the client's address from the `CF-Connecting-IP` header. Cloudflare sets it; on celld your proxy must set it, and must replace any value the client sent, or a client can pick its own address.
42+- **Request location.** Requests carry no Cloudflare location, so the CLI sign-in page can't compare countries, and `Server-Timing` has no location.
43+- **`EGRESS=web`.** Limiting hosted jobs to HTTP and HTTPS needs Cloudflare Containers' outbound interception, which celld doesn't have. `scripts/celld-config.mjs` refuses `EGRESS=web`. Note that celld's own network fence blocks containers from the node, private ranges and link-local addresses.
44+- **Containers.** Each node that runs jobs needs Docker or Podman, and the `celld-fence` container that celld starts. celld doesn't enforce disk sizes, and moving a cell to another node stops its container.
45+- **Platforms.** celld runs on Linux x86-64, Linux ARM64 and Apple Silicon, not Windows.
46+
47+## Deploy a fleet
48+
49+You need the celld binary ([install](https://celld.dev)) on every node, a bucket, and Node.js 22 and pnpm 10 on the machine you deploy from. `celld deploy` bundles the Worker with esbuild, which `pnpm install` puts in `apps/diffinery/node_modules/.bin`.
50+
51+1. Build what the Worker imports (web islands and docs):
52+
53+ ```sh
54+ pnpm install
55+ pnpm -r build
56+ ```
57+
58+2. Create the Worker's secrets once and keep them. `celld deploy` has no secret store, so `scripts/celld-config.mjs` copies `MASTER_KEY`, `MASTER_KEY_PREV`, `OIDC_PRIVATE_KEY`, `MAIL_EVENTS_SECRET`, `TURNSTILE_SECRET`, `GITHUB_OAUTH_CLIENT_SECRET`, `SANDBOX_POOL_SECRET`, `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_APP_WEBHOOK_SECRET` and `SMTP_PASSWORD` from the environment into the Worker's variables. Never change `MASTER_KEY` once it is in use.
59+
60+ ```sh
61+ export MASTER_KEY="$(openssl rand -base64 32)"
62+ export OIDC_PRIVATE_KEY="$(node --input-type=module -e '
63+ const k = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
64+ const jwk = await crypto.subtle.exportKey("jwk", k.privateKey);
65+ jwk.kid = "diffinery-" + new Date().toISOString().slice(0, 10);
66+ process.stdout.write(JSON.stringify(jwk));')"
67+ ```
68+
69+3. Write the celld configuration for your hostname:
70+
71+ ```sh
72+ node scripts/celld-config.mjs --public-url https://git.example.com --var BOOTSTRAP_ADMINS=[email protected]
73+ ```
74+
75+ It writes `apps/diffinery/wrangler.celld.jsonc`, readable by you only and ignored by git, and lists what it left out. `--var NAME=VALUE` sets any [Worker variable](/docs/self-hosting/configuration#worker-variables); repeat it. Set `RUNNER_IMAGE` to an image already in a registry to skip building the runner image.
76+
77+4. Deploy, start the nodes, then apply the D1 migrations, which need a live node:
78+
79+ ```sh
80+ cd apps/diffinery
81+ PATH="$PWD/node_modules/.bin:$PATH" celld deploy wrangler.celld.jsonc --bucket s3://your-bucket
82+ celld --bucket s3://your-bucket --listen 0.0.0.0:8080 --internal-listen 10.0.0.5:8081 --advertise 10.0.0.5:8081
83+ celld d1 migrations apply diffinery wrangler.celld.jsonc --bucket s3://your-bucket
84+ ```
85+
86+ Run the second command on every node, with that node's private address. Put your proxy in front of the `--listen` ports. The deployment, including the variables, lives in the bucket, so give its credentials to fleet administrators only.
87+
88+To update, pull the repository, run steps 1, 3 and 4 again with the same secrets, and apply new migrations.
89+
90+## Try it locally
91+
92+`celld dev` serves a Worker from local storage, but the `celld d1` commands need a real bucket, so `celld dev` can't apply Diffinery's D1 migrations. To try Diffinery, run a one-node fleet on [Azurite](https://github.com/Azure/Azurite), Microsoft's Azure Blob Storage emulator, which celld supports for development. Render the `dev` environment, which has no containers and signs everyone in as `[email protected]`, with `PUBLIC_URL` set to the address you'll open:
93+
94+```sh
95+docker run -d --name azurite -p 10000:10000 mcr.microsoft.com/azure-storage/azurite azurite-blob --blobHost 0.0.0.0 --disableProductStyleUrl
96+az storage container create --name fleet --connection-string "UseDevelopmentStorage=true"
97+export AZURE_STORAGE_USE_EMULATOR=true AZURITE_BLOB_STORAGE_URL=http://127.0.0.1:10000
98+pnpm -r build
99+MASTER_KEY="$(openssl rand -base64 32)" node scripts/celld-config.mjs --env dev --var PUBLIC_URL=http://localhost:8080
100+cd apps/diffinery
101+PATH="$PWD/node_modules/.bin:$PATH" celld deploy wrangler.celld.jsonc --bucket az://fleet
102+celld --bucket az://fleet --listen 127.0.0.1:8080 --internal-listen 127.0.0.1:8081 --advertise 127.0.0.1:8081 &
103+celld d1 migrations apply diffinery-dev wrangler.celld.jsonc --bucket az://fleet
104+```
105+
106+Then open `http://localhost:8080`. The dev sign-in works only while `PUBLIC_URL` and the request are on your own machine. celld doesn't qualify Azurite for a production fleet.
107+
108+## How compatibility is kept
109+
110+`apps/diffinery/test/unit/celld.test.ts` runs with the unit tests on every pull request. It fails when:
111+
112+- `wrangler.jsonc` gets a key that `scripts/celld-config.mjs` doesn't map, so a new Cloudflare-only setting must say what happens on celld;
113+- a binding the script leaves out isn't optional in the Worker's `Env` (`CELLD_ABSENT_BINDINGS` in `src/env.ts`, checked by the typecheck);
114+- the Worker's code imports a built-in module celld doesn't provide (only `cloudflare:workers`, `cloudflare:workflows` and celld's `node:` modules), or a path with a query such as `x.wasm?module`;
115+- a Durable Object's RPC method returns a stream or a `Response` (celld: "RPC streams cannot cross isolate boundaries yet"); stream through the object's `fetch()` instead, as `RepoDO` does for `git-upload-pack`;
116+- the Worker exports a handler celld doesn't call, such as `email` or `tail`.
117+
118+If a change needs a Cloudflare feature celld lacks, make the binding optional and document what happens without it on this page.
modifiedapps/diffinery/docs/self-hosting/configuration.md+101−6View file
@@ -13,6 +13,7 @@
1313 | `apps/diffinery/wrangler.deploy.jsonc` | `wrangler.jsonc` without the `dev` environment, plus the real D1 database ID, `ACCESS_TEAM_DOMAIN`, `ACCESS_AUD`, `TURNSTILE_SITE_KEY`, and the route, `PUBLIC_URL` and `MAIL_FROM` for your hostname. Written by `scripts/render-config.mjs` on every deploy and ignored by git. | No. It is regenerated on each deploy. |
1414 | Worker secrets | `MASTER_KEY` and `OIDC_PRIVATE_KEY`, created by `scripts/ensure-secrets.sh`; `TURNSTILE_SECRET`, set by the deploy from its Turnstile widget; and optionally `GITHUB_OAUTH_CLIENT_SECRET`, which you set yourself. | Only to restore them, or to add the optional one. Never change `MASTER_KEY`. |
1515 | Repository secrets and variables | Cloudflare credentials and options for the Deploy workflow, and a token for the live test. | Yes, in your forge's repository settings. |
16+| `apps/diffinery/wrangler.celld.jsonc` | `wrangler.jsonc` as [celld](/docs/self-hosting/celld) takes it, with the Cloudflare-only keys left out and the secrets in `vars`. Written by `scripts/celld-config.mjs` and ignored by git. | No. Render it again after changing `wrangler.jsonc`. |
1617 | `apps/diffinery/.dev.vars` | Local secrets for `wrangler dev`, such as `MASTER_KEY`. Ignored by git. | Yes, for local development only. |
1718
1819 ## Worker variables
@@ -22,7 +23,8 @@
2223 | Variable | Production value in the repository | Required | What it does |
2324 | --- | --- | --- | --- |
2425 | `PUBLIC_URL` | `https://diffinery.com` | Yes | The canonical origin of the instance. See [PUBLIC_URL](#public_url). On deploy, `scripts/bootstrap.sh` replaces it with `https://$DIFFINERY_DOMAIN` (default `https://diffinery.com`), whatever `wrangler.jsonc` says. |
25-| `MAIL_FROM` | `[email protected]` | No | Sender address of every email. The display name is "Diffinery", or `<actor> (Diffinery)` for emails about someone's action. On deploy, `scripts/bootstrap.sh` replaces it with `notifications@$MAIL_DOMAIN` (default `notifications@$DIFFINERY_DOMAIN`). When empty, Diffinery sends from `notifications@<hostname of PUBLIC_URL>`. The domain must be onboarded to Email Sending. |
26+| `MAIL_FROM` | `[email protected]` | No | Sender address of every email. The display name is "Diffinery", or `<actor> (Diffinery)` for emails about someone's action. On deploy, `scripts/bootstrap.sh` replaces it with `notifications@$MAIL_DOMAIN` (default `notifications@$DIFFINERY_DOMAIN`). When empty, Diffinery sends from `notifications@<hostname of PUBLIC_URL>`. The domain must be onboarded to Email Sending, or, with `SMTP_URL`, be one your SMTP server lets you send from. |
27+| `SMTP_URL` | Not set | No | The SMTP server email goes through when the Worker has no `EMAIL` binding, such as an instance outside Cloudflare: `smtps://<user>@<host>:465` or `smtp://<user>@<host>:587`. The password goes in the `SMTP_PASSWORD` secret. See [SMTP](#smtp). |
2628 | `BOOTSTRAP_ADMINS` | Empty (set on deploy) | For the first sign-in | Emails (case-insensitive) that become site administrators. On deploy, `scripts/bootstrap.sh` sets it from the `BOOTSTRAP_ADMINS` environment variable, else keeps the deployed Worker's list. See [BOOTSTRAP_ADMINS](#bootstrap_admins). |
2729 | `ACCESS_TEAM_DOMAIN` | Empty (filled in on deploy) | For email sign-in | Your Cloudflare Zero Trust team domain, like `example.cloudflareaccess.com`. Used to fetch the Access signing keys and to check the token issuer. |
2830 | `ACCESS_AUD` | Empty (filled in on deploy) | For email sign-in | The audience tag of the Access application that guards `/auth/access`. |
@@ -35,6 +37,8 @@
3537 | `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). |
3638 | `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. |
3739 | `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). |
40+| `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. The deploy sets them from the environment (the Deploy workflow from the `DIFFINERY_GITHUB_APP_*` repository variables). See [GitHub runners](#github-runners). |
41+| `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`. |
3842 | `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)). |
3943 | `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`. |
4044 | `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. |
@@ -46,6 +50,7 @@
4650 | `MCP_REGISTRY_AUTH` | Not set | No | The proof record served at `/.well-known/mcp-registry-auth`, such as `v=MCPv1; k=ed25519; p=<public key>`, so you can publish your instance's MCP server to the official MCP registry under your domain. Not set, that path is a 404. See [List your instance in the MCP registry](/docs/agents/mcp#list-your-instance-in-the-mcp-registry). |
4751 | `INDEXNOW` | Not set | No | `off` stops telling search engines about new, changed and removed public pages through IndexNow. Not set, or anything else, it is on whenever `PUBLIC_URL` is a public `https` origin and `MASTER_KEY` is set. Turn it off for an instance search engines can't reach. See [Search engines](/docs/admin/site-administration#search-engines). |
4852 | `TERMINALS` | Not set | No | `off` switches [terminals](/docs/agents/terminal) off: nobody can open one, and open ones end at their next check, within a minute. Anything else, or not set, leaves them on. |
53+| `RATE_LIMITS` | Not set | Where the `ratelimits` bindings don't exist, such as celld, the open-source Workers runtime | `durable` counts requests in the `RATE_LIMITER` Durable Object for each rate limit whose binding (`RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL`) is missing, with the same limits. A limit that has its binding keeps using it. Anything else, or not set, lets requests through where a binding is missing. Leave it unset on Cloudflare and in local development. See [Rate limits](/docs/self-hosting/architecture#rate-limits). |
4954
5055 When either `ACCESS_TEAM_DOMAIN` or `ACCESS_AUD` is empty, email sign-in at `/auth/access` is off: the page answers "Account recovery by email is not set up on this instance. Ask an administrator for a sign-in link.", and the sign-in page doesn't offer **Recover your account by email**. Passkeys, invitations and admin sign-in links keep working, but the first administrator can't sign in, because email sign-in is how an account in `BOOTSTRAP_ADMINS` is created.
5156
@@ -160,6 +165,39 @@
160165
161166 To use a widget of your own instead, add `"TURNSTILE_SITE_KEY": "<site key>"` under `vars` in `wrangler.jsonc` and store its secret key with `printf '%s' "$TURNSTILE_SECRET" | pnpm exec wrangler secret put TURNSTILE_SECRET -c wrangler.deploy.jsonc`. The deploy then creates no widget and never replaces your secret; it only fills in a missing `TURNSTILE_SECRET` when your widget is in the same Cloudflare account. If you rotate the secret key of the deploy's widget in the dashboard, run `pnpm exec wrangler secret delete TURNSTILE_SECRET -c wrangler.deploy.jsonc` and deploy again, so the deploy stores the new one.
162167
168+### SMTP
169+
170+Without an `EMAIL` binding, Diffinery can send email through any SMTP server that speaks TLS: your mail provider's submission server, Amazon SES, Postmark, Mailgun or your own. This is how an instance outside Cloudflare, which has no Email Sending, sends sign-up codes, invitations and notifications. When the `EMAIL` binding is there, it is used and `SMTP_URL` is ignored.
171+
172+1. Add `SMTP_URL` under `vars` in `wrangler.jsonc`; the deploy keeps it.
173+ - `smtps://<user>@<host>:465` uses TLS from the start. The port defaults to 465.
174+ - `smtp://<user>@<host>:587` starts plain and upgrades with STARTTLS. The port defaults to 587. If the server doesn't offer STARTTLS, Diffinery sends nothing (`E_SMTP_REJECTED: SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS`), so the password never crosses the network in the clear.
175+ - Write an `@` in the user as `%40`: `smtps://notifications%[email protected]`.
176+ - Leave the user out (`smtps://relay.internal:465`) for a relay that needs no sign-in.
177+ - Cloudflare Workers can't open connections to port 25, so use 465 or 587.
178+2. Store the password as a secret. Never put it in `SMTP_URL`: Diffinery refuses such a URL.
179+
180+ ```sh
181+ cd apps/diffinery
182+ printf '%s' "$SMTP_PASSWORD" | pnpm exec wrangler secret put SMTP_PASSWORD -c wrangler.deploy.jsonc
183+ ```
184+
185+3. Make sure `MAIL_FROM` is an address the SMTP user may send from. It is both the `From` header and the envelope sender.
186+4. Check it: **Settings → Email** shows **Sending** as "over SMTP: smtps://...", and **Send me a test email** sends one.
187+
188+Diffinery signs in with AUTH PLAIN, or AUTH LOGIN when the server offers only that. Each email is one connection, and each reply has 30 seconds to arrive. What happens to the email depends on the server's answer:
189+
190+| Answer | Result |
191+| --- | --- |
192+| `2xx` | `sent`. **Recent emails** shows the `Message-ID` Diffinery gave the email. |
193+| `4xx`, a timeout or a dropped connection | `E_SMTP_TRANSIENT`. The queue tries again later, up to 6 times. |
194+| `5xx` to `RCPT TO` that says the address doesn't exist (enhanced status `5.1.1`, `5.1.2`, `5.1.3`, `5.1.6`, `5.1.10` or `5.2.1`, or `550`, `551` or `553` without one) | `failed` with `E_SMTP_RECIPIENT_REJECTED`, and the address goes on the [suppression list](/docs/admin/site-administration#bounces-complaints-and-the-suppression-list) as a `hard-bounce` with source `send`. |
195+| Any other `5xx`, such as `535` for a wrong password or `5.7.1` for a sender the server won't relay for | `failed` with `E_SMTP_REJECTED`. Nothing else changes. |
196+
197+Most submission servers accept every recipient and report a bounce later, by email to `MAIL_FROM`. Diffinery doesn't read that mailbox. To suppress those addresses too, have your provider post bounces and complaints to the signed intake, `POST /-/email/events` (see `MAIL_EVENTS_SECRET`).
198+
199+Diffinery never logs the password or the content of an email. Errors quote the server's reply, never the commands sent.
200+
163201 ### DEV_AUTH
164202
165203 When `DEV_AUTH` is set, `ACCESS_AUD` is empty and both `PUBLIC_URL` and the request's own address are on the local machine (`localhost`, `127.x.x.x` or `[::1]`), every request without credentials (no token, no session) acts as the account with the email in `DEV_AUTH`, with full access. That account is created on first use and is a site administrator if the email is also in `BOOTSTRAP_ADMINS`. While `DEV_AUTH` is set, the email log also keeps each whole message, and `GET /api/v3/diffinery/emails` returns it, so tests can read emails without delivering them.
@@ -176,7 +214,9 @@
176214 | `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. |
177215 | `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`. |
178216 | `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. |
217+| `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. |
179218 | `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. |
219+| `SMTP_PASSWORD` | The password of the user in `SMTP_URL` | You, optionally | Signs in to the SMTP server in `SMTP_URL`. See [SMTP](#smtp). | With a user in `SMTP_URL`, nothing is sent: every email fails with `E_SMTP_CONFIG: SMTP_URL names a user but the SMTP_PASSWORD secret is not set`. |
180220 | `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**. |
181221
182222 None of these secrets is rotated automatically, and `ensure-secrets.sh` never replaces one that exists. Keep a copy of `MASTER_KEY` somewhere safe: replacing it without keeping the old one as `MASTER_KEY_PREV` makes every stored secret undecryptable and invalidates unsubscribe links already sent, along with the runtime tokens of running jobs and cache and artifact links already handed out. To rotate it, follow [Rotating MASTER_KEY](#rotating-master_key). To rotate the OIDC key, delete `OIDC_PRIVATE_KEY` and deploy: a new key with a new `kid` (`diffinery-<date>`) is generated, and relying parties pick it up from `/.well-known/jwks`.
@@ -228,23 +268,25 @@
228268
229269 | Binding | Kind | Resource (production) | What Diffinery uses it for |
230270 | --- | --- | --- | --- |
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. |
271+| `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. |
232272 | `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. |
233273 | `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. |
234274 | `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. |
235-| `EMAIL` | `send_email` (Email Sending) | Your onboarded domain | Sending email. Optional: without it every email is logged as `skipped`. |
275+| `EMAIL` | `send_email` (Email Sending) | Your onboarded domain | Sending email. Optional: without it email goes to the SMTP server in `SMTP_URL`, and without that too every email is logged as `skipped`. |
236276 | (none) | Queue consumer | `diffinery-mail-events` | Bounces and complaints from Email Sending's event subscriptions; the deploy subscribes this queue to your sending domain's events (see [Site administration](/docs/admin/site-administration#where-bounces-and-complaints-come-from)). Consumer: batches of up to 50, waiting up to 5 seconds, 8 retries. |
237-| `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Rate limiting (`ratelimits`) | Namespaces `1001` to `1005`; 20, 300, 2,000, 60 and 600 requests per 60 seconds | [Request rate limits](/docs/reference/rest-api#rate-limits): sign-in and security reports per IP address, anonymous requests per IP address, signed-in requests per account, new content per account, and agents' model requests per paying person (`MODEL_RATE_LIMIT` in `src/lib/rate-limit.ts`). Optional: a missing binding (the `dev` environment declares none) or one that fails lets requests through. If you change a limit, change `RATE_LIMITS` (or `MODEL_RATE_LIMIT`) in `src/lib/rate-limit.ts` to match, since the 429 messages quote it. Namespace IDs are shared across your Cloudflare account, so pick others if another Worker already uses these. |
277+| `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Rate limiting (`ratelimits`) | Namespaces `1001` to `1005`; 20, 300, 2,000, 60 and 600 requests per 60 seconds | [Request rate limits](/docs/reference/rest-api#rate-limits): sign-in and security reports per IP address, anonymous requests per IP address, signed-in requests per account, new content per account, and agents' model requests per paying person (`MODEL_RATE_LIMIT` in `src/lib/rate-limit.ts`). Optional: a missing binding (the `dev` environment declares none) or one that fails lets requests through. If you change a limit, change `RATE_LIMITS` (or `MODEL_RATE_LIMIT`) in `src/lib/rate-limit.ts` to match, since the 429 messages quote it. Namespace IDs are shared across your Cloudflare account, so pick others if another Worker already uses these. Where these bindings don't exist, set `RATE_LIMITS` to `durable` to count in `RATE_LIMITER` instead. |
238278 | `REPO` | Durable Object namespace | Class `RepoDO` (SQLite) | One object per repository. |
239279 | `SCHEDULER` | Durable Object namespace | Class `SchedulerDO` (SQLite) | One object that starts scheduled workflow runs on its own alarm. |
240280 | `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. |
281+| `RATE_LIMITER` | Durable Object namespace | Class `RateLimiterDO` (SQLite) | Request rate limits when `RATE_LIMITS` is `durable` and the `ratelimits` bindings are missing, such as on celld. 32 objects, each counting a share of the keys in memory. Unused otherwise. |
282+| `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). |
283+| `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. |
242284 | `SANDBOX` | Durable Object namespace with a container | Class `SandboxContainer` (SQLite) | One container per agent sandbox. |
243285 | `RUN_WORKFLOW` | Workflow | `diffinery-run`, class `RunWorkflow` | One durable instance per workflow run. |
244286 | `IMPORTER` | Durable Object namespace with a container | Class `ImportContainer` (SQLite) | One container per Git transfer of a GitHub import. |
245287 | `IMPORT_WORKFLOW` | Workflow | `diffinery-import`, class `ImportWorkflow` | One durable instance per attempt of a GitHub import. |
246288
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.
289+The Durable Object classes are declared in eight 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`, tag `v7` for `GitHubRunnersDO`, and tag `v8` for `RateLimiterDO`. `wrangler deploy` applies a migration tag the account doesn't have yet.
248290
249291 ## Other Worker settings
250292
@@ -317,6 +359,59 @@
317359
318360 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`.
319361
362+## GitHub runners
363+
364+[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.
365+
366+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`.
367+
368+| Setting | Value |
369+| --- | --- |
370+| **GitHub App name** | Any, such as `Diffinery runners for git.example.com` |
371+| **Homepage URL** | `https://git.example.com` |
372+| **Callback URL** | `https://git.example.com/settings/github-runners/setup` |
373+| **Request user authorization (OAuth) during installation** | Off |
374+| **Setup URL** | `https://git.example.com/settings/github-runners/setup`, with **Redirect on update** on |
375+| **Webhook** | Active, URL `https://git.example.com/-/github/webhook`, and a random secret of at least 32 characters |
376+| **Repository permissions** | **Administration**: Read and write (to register and remove a repository's self-hosted runners). **Actions**: Read-only. **Metadata**: Read-only. Nothing else |
377+| **Subscribe to events** | **Workflow job** |
378+| **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 |
379+
380+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.
381+
382+Give the deploy the IDs and the slug (the last part of `https://github.com/apps/<slug>`). They aren't secrets, but they are your instance's, so the deploy takes them from the environment, like your hostname, and `scripts/render-config.mjs` writes them into the deployed config:
383+
384+| Deploy from | Set |
385+| --- | --- |
386+| The Deploy workflow | Repository variables `DIFFINERY_GITHUB_APP_ID`, `DIFFINERY_GITHUB_APP_SLUG` and `DIFFINERY_GITHUB_APP_CLIENT_ID` (and `DIFFINERY_GITHUB_APP_URL` for GitHub Enterprise Server). GitHub doesn't allow variable names that start with `GITHUB_`, so the workflow passes them on as `GITHUB_APP_ID` and the rest. |
387+| `scripts/setup.sh` | The environment variables `GITHUB_APP_ID`, `GITHUB_APP_SLUG` and `GITHUB_APP_CLIENT_ID` (and `GITHUB_APP_URL`). |
388+
389+```sh
390+gh variable set DIFFINERY_GITHUB_APP_ID --body 123456
391+gh variable set DIFFINERY_GITHUB_APP_SLUG --body diffinery-runners-for-git-example-com
392+gh variable set DIFFINERY_GITHUB_APP_CLIENT_ID --body Iv23li...
393+```
394+
395+A value of the wrong shape, such as a slug with capital letters, stops the deploy with `GITHUB_APP_SLUG must be the slug, like diffinery-runners`. You can put them under `vars` in your copy's `wrangler.jsonc` instead; the environment wins when it has them.
396+
397+Then store the secrets:
398+
399+```sh
400+cd apps/diffinery
401+printf '%s' "$CLIENT_SECRET" | pnpm exec wrangler secret put GITHUB_APP_CLIENT_SECRET -c wrangler.deploy.jsonc
402+pnpm exec wrangler secret put GITHUB_APP_PRIVATE_KEY -c wrangler.deploy.jsonc < diffinery-runners.private-key.pem
403+printf '%s' "$WEBHOOK_SECRET" | pnpm exec wrangler secret put GITHUB_APP_WEBHOOK_SECRET -c wrangler.deploy.jsonc
404+```
405+
406+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"}`.
407+
408+What to know:
409+
410+- 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).
411+- 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.
412+- 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.
413+- Containers don't run under `wrangler dev`, so locally a GitHub job's runner fails to start ("Could not start a runner: ...").
414+
320415 ## Deploy script settings
321416
322417 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)):
modifiedapps/diffinery/docs/self-hosting/deploy.md+8−3View file
@@ -68,7 +68,7 @@
6868 - `DIFFINERY_ZONE`, if the Cloudflare zone that holds your hostname is not its last two labels. For `git.example.com` the default zone is `example.com`, which is right; for `git.example.co.uk` the default would be `co.uk`, so set `DIFFINERY_ZONE` to `example.co.uk`.
6969 - `MAIL_DOMAIN`, if email should come from another domain than your hostname, for example `example.com` to send from `[email protected]`.
7070
71-The Deploy job runs on every push to `main` when your copy lives on a Diffinery instance, and whenever you start it by hand. On GitHub it doesn't run on pushes; start it by hand there (`workflow_dispatch`).
71+The Deploy job runs on every push to `main` once the CI workflow passes on that commit, on GitHub or on a Diffinery instance, and whenever you start it by hand (`workflow_dispatch`). A GitHub mirror of a repository that already deploys from Diffinery would deploy too, so keep Actions or the Cloudflare secrets off on such a mirror.
7272
7373 The workflow doesn't pass `BOOTSTRAP_ADMINS`. Set the list with a first deploy from your machine (`scripts/setup.sh`), or put it under `vars` in your copy's `wrangler.jsonc`; after that, workflow deploys keep it.
7474
@@ -110,6 +110,7 @@
110110 | `DIFFINERY_ZONE` | Variable, optional | The Cloudflare zone that holds the hostname, when it isn't the hostname's last two labels. |
111111 | `MAIL_DOMAIN` | Variable, optional | The domain email is sent from, when it isn't `DIFFINERY_DOMAIN`. |
112112 | `ACCESS_TEAM_DOMAIN` | Variable, optional | Your Zero Trust team domain, for example `example.cloudflareaccess.com`. Needed only when the token can't read it. |
113+| `DIFFINERY_GITHUB_APP_ID`, `DIFFINERY_GITHUB_APP_SLUG`, `DIFFINERY_GITHUB_APP_CLIENT_ID`, `DIFFINERY_GITHUB_APP_URL` | Variables, optional | The GitHub App of [GitHub runners](/docs/self-hosting/configuration#github-runners). The workflow passes them to render-config as `GITHUB_APP_ID` and the rest. |
113114
114115 The Deploy job runs in an environment named `production`, so you can also store the secrets as environment secrets there and add required reviewers to that environment.
115116
@@ -165,8 +166,12 @@
165166 | `--mail-from <address>` | No | Sets `MAIL_FROM`, overriding the `notifications@<hostname>` that `--public-url` sets. |
166167 | `--admins <emails>` | No | Sets `BOOTSTRAP_ADMINS` to the comma-separated emails, trimmed. An empty value sets it empty; without the flag, the value in `wrangler.jsonc` stays. An entry that isn't an email address stops the script with `--admins takes comma-separated email addresses; not an email address: ...`. |
167168
168-It also reads two environment variables: `RUNNER_IMAGE` (set by `scripts/runner-image.sh`) points every container at a prebuilt runner image and sets the `RUNNER_IMAGE` variable, and `TURNSTILE_SITE_KEY` (set by bootstrap from `scripts/turnstile.sh`) sets the `TURNSTILE_SITE_KEY` variable, unless `wrangler.jsonc` already sets one.
169+It also reads these environment variables:
169170
171+- `RUNNER_IMAGE` (set by `scripts/runner-image.sh`) points every container at a prebuilt runner image and sets the `RUNNER_IMAGE` variable.
172+- `TURNSTILE_SITE_KEY` (set by bootstrap from `scripts/turnstile.sh`) sets the `TURNSTILE_SITE_KEY` variable, unless `wrangler.jsonc` already sets one.
173+- `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID` and `GITHUB_APP_URL` set the variables of the same names, for [GitHub runners](/docs/self-hosting/configuration#github-runners). One that is empty leaves the value in `wrangler.jsonc`. A value of the wrong shape stops the script with, for example, `GITHUB_APP_ID must be the App ID, a number`; the message never shows the value.
174+
170175 Without `--public-url`, the route, `PUBLIC_URL` and `MAIL_FROM` stay as they are in `wrangler.jsonc`. Bootstrap always passes `--public-url` and `--mail-from`, so a normal deploy takes them from `DIFFINERY_DOMAIN` and `MAIL_DOMAIN`.
171176
172177 For `DIFFINERY_DOMAIN=git.example.com` and `[email protected]`, the deployed config contains:
@@ -186,7 +191,7 @@
186191
187192 ### wrangler deploy
188193
189-`pnpm exec wrangler deploy -c wrangler.deploy.jsonc` (run in `apps/diffinery`) deploys the Worker with all its bindings, and builds the runner image from `containers/runner/Dockerfile` (Ubuntu 24.04 with Node.js 22, git, git-lfs and the runner agent) for all three container classes: `RunnerContainer` (hosted jobs), `SandboxContainer` (agent sandboxes) and `ImportContainer` (the Git transfers of GitHub imports). It also applies Durable Object migrations the account doesn't have yet: tag `v1` creates `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` creates `ImportContainer`, tag `v3` creates `ProjectDO`, tag `v4` creates `SchedulerDO`, tag `v5` creates the smaller runner classes, and tag `v6` creates `ComposeDO`.
194+`pnpm exec wrangler deploy -c wrangler.deploy.jsonc` (run in `apps/diffinery`) deploys the Worker with all its bindings, and builds the runner image from `containers/runner/Dockerfile` (Ubuntu 24.04 with Node.js 22, git, git-lfs and the runner agent) for all three container classes: `RunnerContainer` (hosted jobs), `SandboxContainer` (agent sandboxes) and `ImportContainer` (the Git transfers of GitHub imports). It also applies Durable Object migrations the account doesn't have yet: tag `v1` creates `RepoDO`, `RunnerContainer` and `SandboxContainer`, tag `v2` creates `ImportContainer`, tag `v3` creates `ProjectDO`, tag `v4` creates `SchedulerDO`, tag `v5` creates the smaller runner classes, tag `v6` creates `ComposeDO`, tag `v7` creates `GitHubRunnersDO`, and tag `v8` creates `RateLimiterDO`.
190195
191196 ### scripts/ensure-secrets.sh
192197
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/api-meta.ts+1−1View file
@@ -1590,7 +1590,7 @@
15901590 description: "When your address is suppressed by a bounce or complaint, sends one email to it, past the suppression list; following its link while signed in lifts the suppression. 409 when it isn't suppressed, 403 for a suppression a site administrator added, at most 3 an hour.",
15911591 access: "account",
15921592 },
1593- "GET /diffinery/admin/email": { summary: "Email delivery status", description: "Whether sending is configured, whether the signed bounce and complaint endpoint is on (`event_intake`), and counts for the last 24 hours.", access: "site-admin" },
1593+ "GET /diffinery/admin/email": { summary: "Email delivery status", description: "Whether sending is configured and how (`transport`: Cloudflare Email Sending or SMTP, with `smtp` naming the server), whether the signed bounce and complaint endpoint is on (`event_intake`), and counts for the last 24 hours.", access: "site-admin" },
15941594 "GET /diffinery/admin/email/suppressions": { summary: "List suppressed email addresses", description: "Newest first: `email`, `reason` (`hard-bounce`, `complaint` or `manual`), `detail`, `source` (`cloudflare`, `webhook`, `send` or `admin`), `created_by` and `created_at`.", access: "site-admin" },
15951595 "PUT /diffinery/admin/email/suppressions/{email}": { summary: "Suppress an email address", description: "Diffinery sends nothing to it until it is removed. Recorded in the audit log.", access: "site-admin", body: { note: ["string", "Why, kept with the entry."] } },
15961596 "DELETE /diffinery/admin/email/suppressions/{email}": { summary: "Remove an address from the suppression list", description: "Whatever put it there. 404 when it isn't suppressed. Recorded in the audit log.", access: "site-admin", status: 204 },
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+46−1View file
@@ -2,12 +2,14 @@
22 import type { RepoDO } from "./repo/RepoDO.js";
33 import type { SchedulerDO } from "./scheduler.js";
44 import type { ComposeDO } from "./compose.js";
5+import type { RateLimiterDO } from "./rate-limiter.js";
56 import type { ImportContainer } from "./imports/container.js";
67 import type { RunnerContainer, SandboxContainer } from "./runner/containers.js";
78 import type { MailJob } from "./mail/types.js";
89 import type { ProjectDO } from "./agentic/ProjectDO.js";
910 import type { ExportJob } from "./accounts/export.js";
1011 import type { DeletionCleanup } from "./accounts/lifecycle.js";
12+import type { GitHubRunnersDO } from "./github-runners/GitHubRunnersDO.js";
1113
1214 export interface Env {
1315 DB: D1Database;
@@ -32,6 +34,8 @@
3234 RUNNER_SMALL?: DurableObjectNamespace<RunnerContainer>;
3335 RUNNER_TINY?: DurableObjectNamespace<RunnerContainer>;
3436 SANDBOX: DurableObjectNamespace<SandboxContainer>;
37+ /** GitHub jobs on Diffinery runners, one per paying account (github-runners/GitHubRunnersDO.ts). */
38+ GITHUB_RUNNERS?: DurableObjectNamespace<GitHubRunnersDO>;
3539 /** One per repository: its agent tasks (agentic/ProjectDO.ts). */
3640 PROJECT: DurableObjectNamespace<ProjectDO>;
3741 /**
@@ -47,7 +51,7 @@
4751 MODEL_UPSTREAM_OPENAI?: string;
4852 MODEL_UPSTREAM_OPENROUTER?: string;
4953 RUN_WORKFLOW: Workflow<{ repoId: string; runId: string }>;
50- /** Cloudflare Email Sending. Missing when sending isn't set up; emails are then logged as skipped. */
54+ /** Cloudflare Email Sending. Missing when sending isn't set up; emails then go over SMTP_URL, or are logged as skipped. */
5155 EMAIL?: SendEmail;
5256 /** Request rate limits (lib/rate-limit.ts); none in local development. */
5357 RL_AUTH?: RateLimit;
@@ -56,6 +60,14 @@
5660 RL_CREATE?: RateLimit;
5761 /** Model requests through the proxy, per paying person (agentic/proxy.ts). */
5862 RL_MODEL?: RateLimit;
63+ /**
64+ * "durable": count the requests of each RL_* binding that isn't configured in RATE_LIMITER instead,
65+ * for deployments without Cloudflare's rate limiting, such as celld (lib/rate-limit.ts). Unset, a
66+ * missing binding lets requests through.
67+ */
68+ RATE_LIMITS?: string;
69+ /** The rate limiter RATE_LIMITS=durable uses, one object per shard of keys (rate-limiter.ts). */
70+ RATE_LIMITER?: DurableObjectNamespace<RateLimiterDO>;
5971 /** Email jobs, sent by the queue consumer in mail/send.ts. */
6072 MAIL?: Queue<MailJob>;
6173 IMPORT_WORKFLOW: Workflow<{ importId: string }>;
@@ -80,12 +92,28 @@
8092 /** Optional GitHub OAuth app, for linking an account through the web flow instead of a gist. */
8193 GITHUB_OAUTH_CLIENT_ID?: string;
8294 GITHUB_OAUTH_CLIENT_SECRET?: string;
95+ /**
96+ * The GitHub App that lets GitHub repositories run jobs on this Diffinery's hosted runners
97+ * (github-runners/github.ts, docs/actions/github-runners.md). The feature is off until all of
98+ * GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and the secrets GITHUB_APP_CLIENT_SECRET,
99+ * GITHUB_APP_PRIVATE_KEY and GITHUB_APP_WEBHOOK_SECRET are set.
100+ */
101+ GITHUB_APP_ID?: string;
102+ GITHUB_APP_SLUG?: string;
103+ GITHUB_APP_CLIENT_ID?: string;
104+ /** A GitHub Enterprise Server origin for the app; default https://github.com. */
105+ GITHUB_APP_URL?: string;
83106
84107 /** Canonical origin, e.g. https://diffinery.com */
85108 PUBLIC_URL: string;
86109 /** Sender address for every email, e.g. [email protected]. */
87110 MAIL_FROM?: string;
88111 /**
112+ * SMTP server for email when there is no EMAIL binding (mail/smtp.ts), e.g. on celld:
113+ * `smtps://user@host:465` (TLS) or `smtp://user@host:587` (STARTTLS). The password is SMTP_PASSWORD.
114+ */
115+ SMTP_URL?: string;
116+ /**
89117 * More places security researchers can report vulnerabilities, served in /.well-known/security.txt
90118 * after the instance's own report form (/security/report): an email address or an https URL, several
91119 * separated by commas.
@@ -137,8 +165,25 @@
137165 OIDC_PRIVATE_KEY?: string;
138166 /** Secret: signs bounce and complaint events posted to /-/email/events (mail/events.ts); unset, that endpoint is off. */
139167 MAIL_EVENTS_SECRET?: string;
168+ /** Secret: the password for the user in SMTP_URL. */
169+ SMTP_PASSWORD?: string;
140170 /** Secret: Cloudflare Turnstile secret key, to check the widget on the sign-up page and the security report form (siteverify). */
141171 TURNSTILE_SECRET?: string;
172+ /** Secret: the GitHub App's client secret, to check who links an installation. */
173+ GITHUB_APP_CLIENT_SECRET?: string;
174+ /** Secret: the GitHub App's private key (PEM, as GitHub gives it). */
175+ GITHUB_APP_PRIVATE_KEY?: string;
176+ /** Secret: the GitHub App's webhook secret, which signs deliveries to /-/github/webhook. */
177+ GITHUB_APP_WEBHOOK_SECRET?: string;
142178 /** Optional GitHub Enterprise host (e.g. github.example.com) the importer may download release assets from. */
143179 IMPORT_GHE_HOST?: string;
144180 }
181+
182+type OptionalKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? K : never }[keyof T];
183+
184+/**
185+ * Bindings celld (the open-source Workers runtime, docs/self-hosting/celld.md) has no equivalent for:
186+ * scripts/celld-config.mjs leaves them out, so each must stay optional here and the Worker must run
187+ * without it. The celld unit test checks this list against what the script leaves out.
188+ */
189+export const CELLD_ABSENT_BINDINGS = ["EMAIL", "RL_AUTH", "RL_ANON", "RL_ACCOUNT", "RL_CREATE", "RL_MODEL", "CF_VERSION_METADATA"] as const satisfies ReadonlyArray<OptionalKeys<Env>>;
modifiedapps/diffinery/src/git/protocol.ts+2−0View file
@@ -2,6 +2,8 @@
22 import type { RawObject } from "../repo/objects.js";
33
44 export const AGENT = "diffinery/0.1";
5+/** The RepoDO.fetch path the Worker posts a git fetch request to (http/git.ts); the response is the streamed pack. */
6+export const UPLOAD_PACK_PATH = "/git-upload-pack";
57
68 export type RefEntry = {
79 name: string;
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); containers started before it said which don't. */
44+ async stopped(accountId: string, runnerId: string, exitCode: number | null, container?: string): Promise<void> {
45+ const r = this.runners();
46+ if (!r) return;
47+ await r.stopped(runnerId, exitCode, container);
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+255−0View file
@@ -1,0 +1,255 @@
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+ /** A job's status on GitHub (queued, in_progress, completed and others); null once GitHub no longer has it. */
197+ async jobStatus(installationId: number, repo: string, jobId: number): Promise<string | null> {
198+ try {
199+ return (await this.asInstallation<{ status: string }>(installationId, "GET", `repos/${repo}/actions/jobs/${jobId}`)).status;
200+ } catch (e) {
201+ if (e instanceof GitHubApiError && e.status === 404) return null;
202+ throw e;
203+ }
204+ }
205+
206+ /** Removes a runner that never took a job (one that did removes itself). */
207+ async removeRunner(installationId: number, repo: string, runnerId: number): Promise<void> {
208+ try {
209+ await this.asInstallation<void>(installationId, "DELETE", `repos/${repo}/actions/runners/${runnerId}`);
210+ } catch (e) {
211+ if (!(e instanceof GitHubApiError && e.status === 404)) throw e;
212+ }
213+ }
214+
215+ // ---------------------------------------------------------------- a person's GitHub sign-in, to link an installation
216+
217+ /** Where a person authorizes the app, which proves which installations they can manage. */
218+ authorizeUrl(redirectUri: string, state: string): string {
219+ const u = new URL(`${this.app.webUrl}/login/oauth/authorize`);
220+ u.searchParams.set("client_id", this.app.clientId);
221+ u.searchParams.set("redirect_uri", redirectUri);
222+ u.searchParams.set("state", state);
223+ u.searchParams.set("allow_signup", "false");
224+ return u.toString();
225+ }
226+
227+ /** Where a person installs the app; GitHub passes `state` on to the app's setup URL. */
228+ installUrl(state: string): string {
229+ return `${this.app.webUrl}/apps/${encodeURIComponent(this.app.slug)}/installations/new?state=${encodeURIComponent(state)}`;
230+ }
231+
232+ /** Trades the code GitHub sent back for the person's user token (used at once, never kept). */
233+ async userToken(code: string, redirectUri: string): Promise<string> {
234+ const res = await this.fetcher(`${this.app.webUrl}/login/oauth/access_token`, {
235+ method: "POST",
236+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "Diffinery" },
237+ body: JSON.stringify({ client_id: this.app.clientId, client_secret: this.app.clientSecret, code, redirect_uri: redirectUri }),
238+ signal: AbortSignal.timeout(30_000),
239+ });
240+ const r = (await res.json().catch(() => ({}))) as { access_token?: string; error_description?: string };
241+ if (!r.access_token) throw new GitHubApiError(422, `GitHub did not sign you in: ${r.error_description ?? "no access token"}`);
242+ return r.access_token;
243+ }
244+
245+ /** The app's installations the signed-in GitHub user can manage (at most 500). */
246+ async userInstallations(userToken: string): Promise<GitHubInstallation[]> {
247+ const out: GitHubInstallation[] = [];
248+ for (let page = 1; page <= 5; page++) {
249+ 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}`);
250+ out.push(...r.installations.map((i) => ({ id: i.id, login: i.account?.login ?? "", type: i.account?.type ?? "User" })));
251+ if (r.installations.length < 100) break;
252+ }
253+ return out;
254+ }
255+}
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+410−0View file
@@ -1,0 +1,410 @@
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, container }),
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+ await this.took(ev.installationId, ev.runnerName, ev.githubJobId);
174+ }
175+ // Cancelled before its runner started, or ran on a runner that isn't one of this account's: a runner started
176+ // for it now would only wait for IDLE_MS.
177+ if (ev.action === "completed" || ev.runnerName) {
178+ await this.db
179+ .prepare("UPDATE github_runner_jobs SET status = 'skipped', message = ?, conclusion = ?, ended_at = ? WHERE installation_id = ? AND github_job_id = ? AND status = 'queued'")
180+ .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)
181+ .run();
182+ }
183+ }
184+
185+ /**
186+ * A runner took `jobId`, which may not be the job its row was started for. When that job's own row still waits,
187+ * the two rows trade jobs: the runner's row describes the job it runs, and the other row waits for the job the
188+ * runner was started for, which still needs a runner, in that job's place in line.
189+ */
190+ private async took(installationId: number, runnerName: string, jobId: number): Promise<void> {
191+ const a = await this.db.prepare("SELECT * FROM github_runner_jobs WHERE installation_id = ? AND runner_name = ?").bind(installationId, runnerName).first<RunnerJobRow>();
192+ if (!a || a.github_job_id === jobId) return;
193+ const b = await this.db.prepare("SELECT * FROM github_runner_jobs WHERE installation_id = ? AND repo = ? AND github_job_id = ? AND status = 'queued'").bind(installationId, a.repo, jobId).first<RunnerJobRow>();
194+ if (!b) return;
195+ // (installation_id, github_job_id) is unique, so b's job id is negated (GitHub's never are) while a takes it.
196+ // The first step changes nothing unless both rows still hold the jobs they were read with, and the other two
197+ // only follow it. a keeps its size, which is its container's.
198+ const set = "github_job_id = ?, run_id = ?, workflow_name = ?, job_name = ?, html_url = ?, labels = ?, created_at = ?";
199+ const job = (r: RunnerJobRow) => [r.github_job_id, r.run_id, r.workflow_name, r.job_name, r.html_url, r.labels, r.created_at];
200+ await this.db.batch([
201+ this.db
202+ .prepare("UPDATE github_runner_jobs SET github_job_id = -github_job_id WHERE id = ? AND github_job_id = ? AND status = 'queued' AND EXISTS (SELECT 1 FROM github_runner_jobs WHERE id = ? AND github_job_id = ?)")
203+ .bind(b.id, b.github_job_id, a.id, a.github_job_id),
204+ this.db.prepare(`UPDATE github_runner_jobs SET ${set} WHERE id = ? AND EXISTS (SELECT 1 FROM github_runner_jobs WHERE id = ? AND github_job_id = ?)`).bind(...job(b), a.id, b.id, -b.github_job_id),
205+ this.db.prepare(`UPDATE github_runner_jobs SET ${set}, size = ? WHERE id = ? AND github_job_id = ?`).bind(...job(a), a.size, b.id, -b.github_job_id),
206+ ]);
207+ }
208+
209+ /**
210+ * Starts runners for the account's queued jobs, oldest first, and stops runners that took no job or ran too
211+ * long. Returns how soon to look again: null when nothing waits or runs.
212+ */
213+ async pump(accountId: string): Promise<{ next: number | null }> {
214+ await this.sweep(accountId);
215+ 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;
216+ const placements: Placement[] = [];
217+ let waiting = false;
218+ for (const row of queued) {
219+ const r = await this.admit(row);
220+ if (r === "wait") {
221+ waiting = true;
222+ break;
223+ }
224+ if (r) placements.push(r);
225+ }
226+ // A start that failed for a passing reason is tried again after a pause, not at once.
227+ if ((await Promise.all(placements.map((p) => this.place(p)))).some(Boolean)) waiting = true;
228+ return { next: await this.nextLook(accountId, waiting) };
229+ }
230+
231+ private async nextLook(accountId: string, waiting: boolean): Promise<number | null> {
232+ const counts = await this.db
233+ .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")
234+ .bind(accountId)
235+ .all<{ status: string; n: number; oldest: string | null }>();
236+ const by = new Map(counts.results.map((c) => [c.status, c]));
237+ const looks: number[] = [];
238+ if (by.has("queued")) looks.push(waiting ? WAIT_RETRY_MS : 0);
239+ const starting = by.get("starting");
240+ if (starting?.oldest) looks.push(Math.max(5_000, Date.parse(starting.oldest) + IDLE_MS - this.clock()));
241+ if (by.has("running")) looks.push(IDLE_MS);
242+ return looks.length ? Math.min(...looks) : null;
243+ }
244+
245+ private async finish(row: RunnerJobRow, status: "skipped" | "failed", message: string): Promise<void> {
246+ 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();
247+ }
248+
249+ /** Everything before a queued job's container starts: null when it doesn't start, "wait" when the account must wait for a slot. */
250+ private async admit(row: RunnerJobRow): Promise<Placement | "wait" | null> {
251+ 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 }>();
252+ if (!inst || inst.account_id !== row.account_id) {
253+ await this.finish(row, "skipped", "The GitHub installation is no longer linked to this account");
254+ return null;
255+ }
256+ if (inst.suspended_at) {
257+ await this.finish(row, "skipped", "The app's installation is suspended on GitHub");
258+ return null;
259+ }
260+ const block = blockedBy(await accountKillSwitches(this.env, row.account_id), "hosted-job");
261+ if (block) {
262+ await this.finish(row, "failed", `The runner was not started: ${block}`);
263+ return null;
264+ }
265+ const quota = await mayStart(this.env, row.account_id, "job").catch((e: unknown) => {
266+ console.error("quota check failed", e);
267+ return { ok: true } as const;
268+ });
269+ if (!quota.ok) {
270+ if (!quota.wait) {
271+ await this.finish(row, "failed", `The runner was not started: ${quota.message}`);
272+ return null;
273+ }
274+ await this.db.prepare("UPDATE github_runner_jobs SET message = ? WHERE id = ?").bind(`Waiting: ${quota.message}`, row.id).run();
275+ return "wait";
276+ }
277+ const tries = row.tries + 1;
278+ const size = this.host.has(row.size) ? row.size : "large";
279+ const name = `diffinery-${row.id}-${tries}`;
280+ let jit;
281+ try {
282+ jit = await this.gh.jitRunner(row.installation_id, row.repo, name, JSON.parse(row.labels) as string[]);
283+ } catch (e) {
284+ const message = (e as Error).message;
285+ // GitHub refusing (no permission, a repository gone) won't change by asking again.
286+ 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}`);
287+ else {
288+ 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();
289+ return "wait";
290+ }
291+ return null;
292+ }
293+ const container = githubContainerName(row.id, tries, size);
294+ const claimed = await this.db
295+ .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'")
296+ .bind(tries, name, jit.runnerId, container, size, this.at(), row.id)
297+ .run();
298+ if (!claimed.meta.changes) {
299+ // Stopped or ended meanwhile (a kill switch, the job cancelled).
300+ await this.gh.removeRunner(row.installation_id, row.repo, jit.runnerId).catch(() => {});
301+ return null;
302+ }
303+ 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));
304+ 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) };
305+ }
306+
307+ /**
308+ * Starts an admitted runner's container; one that failed for a passing reason goes back in line, up to
309+ * MAX_TRIES starts. Returns whether it went back in line.
310+ */
311+ private async place(p: Placement): Promise<boolean> {
312+ try {
313+ 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 });
314+ return false;
315+ } catch (e) {
316+ const message = (e as Error).message;
317+ const row = await this.row(p.row.id);
318+ if (!row || row.status !== "starting" || row.container !== p.container) return false;
319+ await endCompute(this.env, p.container).catch(() => {});
320+ await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id!).catch(() => {});
321+ const again = (RETRYABLE_START.test(message) || (e as { retryable?: unknown }).retryable === true) && row.tries < MAX_TRIES;
322+ await this.db
323+ .prepare("UPDATE github_runner_jobs SET status = ?, message = ?, container = NULL, ended_at = ? WHERE id = ? AND status = 'starting'")
324+ .bind(again ? "queued" : "failed", again ? `Starting a runner failed; trying again: ${message}` : `Could not start a runner: ${message}`, again ? null : this.at(), row.id)
325+ .run();
326+ return again;
327+ }
328+ }
329+
330+ /** Runners that took no job within IDLE_MS (unless GitHub says they are busy), and runners past the longest a job runs. */
331+ private async sweep(accountId: string): Promise<void> {
332+ const t = this.clock();
333+ 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;
334+ for (const row of rows) {
335+ if (Date.parse(row.started_at!) + MAX_RUN_MS.job < t) {
336+ await this.stopRunner(row, "The runner ran past the longest a job may run");
337+ continue;
338+ }
339+ if (row.status !== "starting") continue;
340+ // The in_progress webhook may be late or lost: GitHub knows whether the runner has a job.
341+ const state = await this.gh.runner(row.installation_id, row.repo, row.github_runner_id!).catch(() => undefined);
342+ if (state?.busy) {
343+ 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();
344+ continue;
345+ }
346+ if (state === undefined) continue;
347+ 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`);
348+ }
349+ }
350+
351+ /** Stops a runner's container and ends its row with `reason`. */
352+ private async stopRunner(row: RunnerJobRow, reason: string): Promise<void> {
353+ await this.db.prepare("UPDATE github_runner_jobs SET stop_reason = ? WHERE id = ?").bind(reason, row.id).run();
354+ if (row.container) await this.host.stop(row.container).catch((e: unknown) => console.error(`stopping GitHub runner ${row.id} failed`, e));
355+ await this.ended(row.id, null);
356+ }
357+
358+ /** A runner's container stopped (runner/containers.ts onStop), or Diffinery stopped it. `container` is the one that stopped, when it says. */
359+ async stopped(rowId: string, exitCode: number | null, container?: string): Promise<void> {
360+ const row = await this.row(rowId);
361+ if (!row) return;
362+ // A container the row no longer runs in: one given up on (back in line, or replaced) that stopped late.
363+ if (container && row.container !== container) return;
364+ // A runner that stopped before it took a job (nothing of the job ran) is replaced, a few times: one that crashed,
365+ // and one that stopped without crashing while GitHub still has its job queued. The containers library reports
366+ // exit code 0 for a container the platform lost, and no runner took the job then.
367+ if (row.status === "starting" && !row.stop_reason && row.tries < MAX_TRIES) {
368+ const crashed = exitCode !== 0 && exitCode !== null;
369+ if (crashed || (await this.stillQueued(row))) {
370+ if (row.container) await endCompute(this.env, row.container).catch(() => {});
371+ if (row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
372+ await this.db
373+ .prepare("UPDATE github_runner_jobs SET status = 'queued', container = NULL, message = ? WHERE id = ? AND status = 'starting'")
374+ .bind(crashed ? `The runner stopped before it took a job (exit code ${exitCode}); starting another` : "The runner's container stopped before it took a job; starting another", row.id)
375+ .run();
376+ return;
377+ }
378+ }
379+ await this.ended(rowId, exitCode);
380+ }
381+
382+ /**
383+ * Whether GitHub still has a row's job queued. When GitHub doesn't answer, it counts as queued: a job left
384+ * without a runner waits 24 hours, a runner started for nothing only IDLE_MS.
385+ */
386+ private async stillQueued(row: RunnerJobRow): Promise<boolean> {
387+ const status = await this.gh.jobStatus(row.installation_id, row.repo, row.github_job_id).catch(() => "queued");
388+ return status === "queued";
389+ }
390+
391+ private async ended(rowId: string, exitCode: number | null): Promise<void> {
392+ const row = await this.row(rowId);
393+ if (!row) return;
394+ if (row.container) await endCompute(this.env, row.container).catch((e: unknown) => console.error("compute usage failed", e));
395+ if (ENDED.has(row.status)) return;
396+ const neverPicked = row.status === "starting";
397+ // A just-in-time runner removes itself after its job; one that never took a job is removed here.
398+ if (neverPicked && row.github_runner_id) await this.gh.removeRunner(row.installation_id, row.repo, row.github_runner_id).catch(() => {});
399+ const message = row.stop_reason ?? (neverPicked && exitCode ? `The runner stopped before it took a job (exit code ${exitCode})` : null);
400+ 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();
401+ }
402+
403+ /** A kill switch: queued jobs fail and running runners stop, with `message`. Returns the runners stopped. */
404+ async stopAll(accountId: string, message: string): Promise<number> {
405+ 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();
406+ const rows = (await this.db.prepare("SELECT * FROM github_runner_jobs WHERE account_id = ? AND status IN ('starting', 'running')").bind(accountId).all<RunnerJobRow>()).results;
407+ for (const row of rows) await this.stopRunner(row, message);
408+ return rows.length;
409+ }
410+}
modifiedapps/diffinery/src/http/git.ts+4−3View file
@@ -7,7 +7,7 @@
77 import { importPushAllowed } from "../imports/service.js";
88 import { loadRepo, repoStub } from "./common.js";
99 import type { Caller } from "../repo/types.js";
10-import { resetByDeploy } from "../git/protocol.js";
10+import { resetByDeploy, UPLOAD_PACK_PATH } from "../git/protocol.js";
1111
1212 /**
1313 * Git smart HTTP (protocol v2 for fetch/clone, v0 for push) and the Git LFS
@@ -39,8 +39,9 @@
3939 git.post("/:owner/:repo/git-upload-pack", async (c) => {
4040 const { stub } = await loadRepo(c, c.req.param("owner"), c.req.param("repo"), "read", { readOnlyPost: true, follow: true });
4141 const body = await readBody(c.req.raw, MAX_UPLOAD_PACK_REQUEST, "fetch request exceeds 16 MB");
42- const out = await stub.gitUploadPack(body);
43- return new Response(out, { headers: { "content-type": "application/x-git-upload-pack-result", ...noCache } });
42+ // Through RepoDO.fetch rather than RPC, so the pack streams on celld too.
43+ const out = await stub.fetch(`https://repo${UPLOAD_PACK_PATH}`, { method: "POST", body });
44+ return new Response(out.body, { headers: { "content-type": "application/x-git-upload-pack-result", ...noCache } });
4445 });
4546
4647 git.post("/:owner/:repo/git-receive-pack", async (c) => {
modifiedapps/diffinery/src/index.ts+2−0View file
@@ -8,12 +8,14 @@
88 export { RepoDO } from "./repo/RepoDO.js";
99 export { SchedulerDO } from "./scheduler.js";
1010 export { ComposeDO } from "./compose.js";
11+export { RateLimiterDO } from "./rate-limiter.js";
1112 export { RunnerContainer, RunnerContainerMedium, RunnerContainerSmall, RunnerContainerTiny, SandboxContainer, SandboxPoolDO } from "./runner/containers.js";
1213 export { RunWorkflow } from "./runner/workflow.js";
1314 export { ImportWorkflow } from "./imports/workflow.js";
1415 export { AccountWorkflow } from "./accounts/workflow.js";
1516 export { ImportContainer } from "./imports/container.js";
1617 export { ProjectDO } from "./agentic/ProjectDO.js";
18+export { GitHubRunnersDO } from "./github-runners/GitHubRunnersDO.js";
1719 // Carries hosted containers' HTTP and HTTPS out under EGRESS=web (lib/egress.ts).
1820 export { ContainerProxy } from "@cloudflare/containers";
1921
modifiedapps/diffinery/src/lib/image.ts+6−6View file
@@ -1,7 +1,7 @@
11 /**
22 * Profile pictures: check an uploaded JPEG, PNG or WebP and turn it into small square WebPs.
33 *
4- * Everything runs in the Worker on jSquash's WASM codecs. Wrangler bundles each `*.wasm` import
4+ * Everything runs in the Worker on jSquash's WASM codecs. Wrangler (and celld) bundles each `*.wasm` import
55 * as a compiled WebAssembly.Module (its default CompiledWasm rule), and each codec gets its module
66 * through `init(module)`, so nothing is fetched at runtime.
77 *
@@ -15,12 +15,12 @@
1515 import decodeWebp, { init as initWebpDecode } from "@jsquash/webp/decode.js";
1616 import encodeWebp, { init as initWebpEncode } from "@jsquash/webp/encode.js";
1717 import resize, { initResize } from "@jsquash/resize";
18-import JPEG_DEC_WASM from "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm?module";
19-import PNG_DEC_WASM from "@jsquash/png/codec/pkg/squoosh_png_bg.wasm?module";
20-import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm?module";
18+import JPEG_DEC_WASM from "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm";
19+import PNG_DEC_WASM from "@jsquash/png/codec/pkg/squoosh_png_bg.wasm";
20+import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm";
2121 // @jsquash/webp's encoder picks its SIMD build when the runtime supports WASM SIMD, which V8 (workerd, Node) does.
22-import WEBP_ENC_WASM from "@jsquash/webp/codec/enc/webp_enc_simd.wasm?module";
23-import RESIZE_WASM from "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm?module";
22+import WEBP_ENC_WASM from "@jsquash/webp/codec/enc/webp_enc_simd.wasm";
23+import RESIZE_WASM from "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm";
2424 import { HttpError } from "./util.js";
2525
2626 /** Square sizes we store, in pixels: 2× the 20, 40 (`.av.lg`) and 96 (`.av.xl`, rounded up) CSS pixel avatars. */
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+53−6View file
@@ -6,7 +6,9 @@
66 * Request rate limits (Workers rate limiting bindings, configured in wrangler.jsonc). Each
77 * binding counts per key over 60 seconds in the Cloudflare location that serves the request, so
88 * the limits stop floods and scripted abuse rather than meter use exactly. A binding that isn't
9- * configured (local development) or that fails lets the request through.
9+ * configured (local development) or that fails lets the request through, unless RATE_LIMITS=durable:
10+ * then the RATE_LIMITER Durable Object counts that bucket instead (rate-limiter.ts), for deployments
11+ * without the bindings, such as celld. It fails open too.
1012 *
1113 * - RL_AUTH: sign-in, passkey registration, invitation and sign-in links, open sign-up, private
1214 * security reports (/security/report), early access requests and their confirmations
@@ -34,8 +36,11 @@
3436 export const RATE_LIMITS: Record<Bucket, number> = { RL_AUTH: 20, RL_ANON: 300, RL_ACCOUNT: 2000, RL_CREATE: 60 };
3537 export const RATE_PERIOD_S = 60;
3638
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\/)/;
39+/**
40+ * Paths that never count: health checks, avatars, the Actions runtime and runners (their own credentials), and
41+ * the GitHub App's signed webhook, which GitHub sends from a few addresses for every job of every installation.
42+ */
43+const EXEMPT = /^\/(?:healthz$|api\/avatars\/|twirp\/|_runtime\/|_apis\/|runner\/|-\/model\/|-\/github\/webhook$)/;
3944 const AUTH = /^\/(?:auth\/passkey\/|invite\/|signin\/|login(?:$|\/)|signup(?:$|\/)|security\/report$|early-access(?:\/confirm|\/remove(?:\/confirm)?)?$|contact(?:\/confirm)?$|-\/cli\/device$|oauth\/register$)/;
4045 const CREATE: Array<[method: string, path: RegExp]> = [
4146 ["POST", /^\/api\/v3\/(?:user|orgs\/[^/]+)\/repos$/],
@@ -67,16 +72,20 @@
6772
6873 /** The bucket that's over its limit for this request, or null. */
6974 export async function overLimit(env: Env, buckets: Array<[Bucket, string]>): Promise<Bucket | null> {
75+ const unbound: Array<[Bucket, string]> = [];
7076 for (const [b, key] of buckets) {
7177 const rl = (env as unknown as Record<string, RateLimiter | undefined>)[b];
72- if (!rl) continue;
78+ if (!rl) {
79+ unbound.push([b, key]);
80+ continue;
81+ }
7382 try {
7483 if (!(await rl.limit({ key })).success) return b;
7584 } catch (e) {
7685 console.error("rate limiter failed", b, e);
7786 }
7887 }
79- return null;
88+ return durableOverLimit(env, unbound);
8089 }
8190
8291 /**
@@ -88,7 +97,7 @@
8897
8998 /** Whether this person is over their model request rate. A missing (local) or failing binding lets it through. */
9099 export async function modelRateLimited(env: Env, personId: string): Promise<boolean> {
91- if (!env.RL_MODEL) return false;
100+ if (!env.RL_MODEL) return (await durableOverLimit(env, [["RL_MODEL", `model:${personId}`]])) !== null;
92101 try {
93102 return !(await env.RL_MODEL.limit({ key: `model:${personId}` })).success;
94103 } catch (e) {
@@ -97,6 +106,44 @@
97106 }
98107 }
99108
109+/** Limits per window for the Durable Object fallback: the same as the bindings'. */
110+const DURABLE_LIMITS: Record<Bucket | "RL_MODEL", number> = { ...RATE_LIMITS, RL_MODEL: MODEL_RATE_LIMIT };
111+
112+/**
113+ * Objects the fallback spreads keys over. A key always lands on the same one; the requests of one
114+ * key (one address, one account) can't be spread anyway, and a fixed set keeps the objects few and
115+ * warm instead of one per address.
116+ */
117+export const RATE_LIMITER_SHARDS = 32;
118+
119+/** The RATE_LIMITER object that counts `key`: FNV-1a of the key, modulo the shards. */
120+export function rateLimiterShard(key: string): string {
121+ let h = 0x811c9dc5;
122+ for (let i = 0; i < key.length; i++) h = Math.imul(h ^ key.charCodeAt(i), 0x01000193);
123+ return `shard-${(h >>> 0) % RATE_LIMITER_SHARDS}`;
124+}
125+
126+/**
127+ * Counts buckets that have no binding in the RATE_LIMITER Durable Object, when RATE_LIMITS=durable.
128+ * One call per key, so a request costs one call: its buckets share a key (an account's requests
129+ * and its new content). A failing object lets the request through, as a failing binding does.
130+ */
131+async function durableOverLimit<B extends Bucket | "RL_MODEL">(env: Env, buckets: Array<[B, string]>): Promise<B | null> {
132+ const ns = env.RATE_LIMITS === "durable" ? env.RATE_LIMITER : undefined;
133+ if (!ns || !buckets.length) return null;
134+ const byKey = new Map<string, Array<[B, number]>>();
135+ for (const [b, key] of buckets) byKey.set(key, [...(byKey.get(key) ?? []), [b, DURABLE_LIMITS[b]]]);
136+ for (const [key, limits] of byKey) {
137+ try {
138+ const over = await ns.get(ns.idFromName(rateLimiterShard(key))).hit(key, limits);
139+ if (over) return over as B;
140+ } catch (e) {
141+ console.error("rate limiter object failed", e);
142+ }
143+ }
144+ return null;
145+}
146+
100147 const WHAT: Record<Bucket, string> = {
101148 RL_AUTH: "sign-in attempts, security reports, early access requests and contact messages from your network",
102149 RL_ANON: "requests from your network without signing in",
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/mail/api.ts+14−2View file
@@ -7,7 +7,8 @@
77 import { HttpError, now } from "../lib/util.js";
88 import { MailStore, isDigestHour, isTimeZone, mergePrefs, type WatchLevel } from "./prefs.js";
99 import { sampleJobs } from "./samples.js";
10-import { deliver, senderAddress } from "./send.js";
10+import { deliver, mailTransport, senderAddress } from "./send.js";
11+import { smtpLabel } from "./smtp.js";
1112 import { Suppressions } from "./suppression.js";
1213 import { adminSuppress, adminUnsuppress, sendDigestNow, sendTest, sendVerification, suppressionJson } from "./web.js";
1314
@@ -176,7 +177,18 @@
176177 siteAdmin(c, "read");
177178 const store = new MailStore(c.env.DB);
178179 const [day, last] = await Promise.all([store.counts(new Date(Date.now() - 86400_000).toISOString()), store.recent({ limit: 1 })]);
179- return c.json({ sending: !!c.env.EMAIL, queue: !!c.env.MAIL, from: senderAddress(c.env), event_intake: !!c.env.MAIL_EVENTS_SECRET, last_24h: day, last: last[0] ? { ...last[0], dev_copy: undefined } : null });
180+ const t = mailTransport(c.env);
181+ const smtp = t?.kind === "smtp" ? ("error" in t ? { url: null, error: t.error } : { url: smtpLabel(t.config), error: null }) : null;
182+ return c.json({
183+ sending: !!t && !(t.kind === "smtp" && "error" in t),
184+ transport: t?.kind ?? null,
185+ smtp,
186+ queue: !!c.env.MAIL,
187+ from: senderAddress(c.env),
188+ event_intake: !!c.env.MAIL_EVENTS_SECRET,
189+ last_24h: day,
190+ last: last[0] ? { ...last[0], dev_copy: undefined } : null,
191+ });
180192 });
181193
182194 /**
modifiedapps/diffinery/src/mail/send.ts+27−9View file
@@ -4,6 +4,7 @@
44 import { MailStore, wantsEmail } from "./prefs.js";
55 import { compose, toHtml, toText, type RenderCtx } from "./templates.js";
66 import { categoryOf, isMandatory, type MailJob } from "./types.js";
7+import { SmtpError, sendSmtp, smtpConfig, type SmtpConfig } from "./smtp.js";
78 import { REASON_TEXT, Suppressions, sendSuppression } from "./suppression.js";
89 import { unsubUrl } from "./unsubscribe.js";
910
@@ -11,8 +12,9 @@
1112 * Sending: jobs go on the `diffinery-mail` queue (so a slow or failing send
1213 * never holds up a request, and failures retry with backoff), and the queue
1314 * consumer checks the recipient's settings, renders and sends each one through
14- * Cloudflare Email Sending. Nothing goes to an address on the suppression list
15- * (suppression.ts), and an address Email Sending refuses for good goes on it.
15+ * Cloudflare Email Sending, or over SMTP (smtp.ts) where there is no EMAIL binding.
16+ * Nothing goes to an address on the suppression list (suppression.ts), and an
17+ * address Email Sending or the SMTP server refuses for good goes on it.
1618 */
1719
1820 /**
@@ -74,10 +76,23 @@
7476 }
7577 }
7678
77-const RETRYABLE = new Set(["E_RATE_LIMIT_EXCEEDED", "E_INTERNAL_SERVER_ERROR", "E_DELIVERY_FAILED"]);
79+const RETRYABLE = new Set(["E_RATE_LIMIT_EXCEEDED", "E_INTERNAL_SERVER_ERROR", "E_DELIVERY_FAILED", "E_SMTP_TRANSIENT"]);
7880
7981 export class RetryableMailError extends Error {}
8082
83+/**
84+ * How this instance sends email: Cloudflare Email Sending when the EMAIL binding is there, else
85+ * the SMTP server in SMTP_URL (with what is wrong with it, if anything); null when neither is set.
86+ */
87+export type MailTransport = { kind: "email-sending"; binding: SendEmail } | { kind: "smtp"; config: SmtpConfig } | { kind: "smtp"; error: string };
88+
89+export function mailTransport(env: Pick<Env, "EMAIL" | "SMTP_URL" | "SMTP_PASSWORD">): MailTransport | null {
90+ if (env.EMAIL) return { kind: "email-sending", binding: env.EMAIL };
91+ const smtp = smtpConfig(env);
92+ if (!smtp) return null;
93+ return "error" in smtp ? { kind: "smtp", error: smtp.error } : { kind: "smtp", config: smtp };
94+}
95+
8196 /** The address every email is sent from: MAIL_FROM, or notifications@ the public host. */
8297 export const senderAddress = (env: Pick<Env, "MAIL_FROM" | "PUBLIC_URL">): string => env.MAIL_FROM || `notifications@${new URL(env.PUBLIC_URL).hostname}`;
8398
@@ -205,18 +220,21 @@
205220 const msg = await buildMessage(env, job, to);
206221 const devCopy = devAuth(env) ? JSON.stringify(msg) : null;
207222 const base = { account_id: to.accountId ?? null, to_addr: to.email, kind: job.kind, subject: msg.subject, dev_copy: devCopy };
208- if (!env.EMAIL) {
209- await store.log({ ...base, status: "skipped", detail: "email sending is not configured (no EMAIL binding)", message_id: null });
210- return { status: "skipped", detail: "no EMAIL binding" };
223+ const transport = mailTransport(env);
224+ if (!transport) {
225+ await store.log({ ...base, status: "skipped", detail: "email sending is not configured (no EMAIL binding or SMTP_URL)", message_id: null });
226+ return { status: "skipped", detail: "no EMAIL binding or SMTP_URL" };
211227 }
212228 let res: { messageId?: string };
213229 try {
214- res = await env.EMAIL.send(msg);
230+ if (transport.kind === "email-sending") res = await transport.binding.send(msg);
231+ else if ("error" in transport) throw new SmtpError("E_SMTP_CONFIG", transport.error);
232+ else res = await sendSmtp(transport.config, msg, { ehlo: new URL(env.PUBLIC_URL).hostname });
215233 } catch (e) {
216234 const code = (e as { code?: string }).code ?? "";
217235 const detail = `${code ? `${code}: ` : ""}${(e as Error).message ?? String(e)}`;
218236 if (RETRYABLE.has(code)) throw new RetryableMailError(detail);
219- // A permanent failure for this recipient (it's on Cloudflare's suppression list) puts it on ours.
237+ // A permanent failure for this recipient (it's on Cloudflare's suppression list, or the SMTP server has no such mailbox) puts it on ours.
220238 const s = sendSuppression(to.email, { error: e });
221239 if (s) await suppressFromSend(env, s);
222240 await store.log({ ...base, status: "failed", detail, message_id: null });
@@ -234,7 +252,7 @@
234252 return { status: "sent", messageId: res.messageId };
235253 }
236254
237-/** Suppress an address Email Sending refused for good (source `send`), audited like any other addition. Never throws. */
255+/** Suppress an address Email Sending or the SMTP server refused for good (source `send`), audited like any other addition. Never throws. */
238256 async function suppressFromSend(env: Env, s: NonNullable<ReturnType<typeof sendSuppression>>): Promise<void> {
239257 try {
240258 await new Suppressions(env.DB).add({ ...s, source: "send" });
addedapps/diffinery/src/mail/smtp.ts+316−0View file
@@ -1,0 +1,316 @@
1+import { connect } from "cloudflare:sockets";
2+import type { Env } from "../env.js";
3+import type { Outgoing } from "./send.js";
4+
5+/**
6+ * Sending over SMTP, for an instance without Cloudflare Email Sending (the EMAIL binding), such as
7+ * one on celld. SMTP_URL names the server and the user and SMTP_PASSWORD (a secret) the password:
8+ * `smtps://user@host:465` is TLS from the first byte, and `smtp://user@host:587` upgrades with
9+ * STARTTLS and refuses to go on without it, so the password never crosses the network in the clear.
10+ * Each email is one TCP connection (`cloudflare:sockets`, which celld provides too). Nothing of the
11+ * conversation is logged; errors carry the server's replies, never the commands sent.
12+ */
13+
14+export interface SmtpConfig {
15+ host: string;
16+ port: number;
17+ /** `implicit`: TLS from the start (smtps://). `starttls`: plain until STARTTLS, which is required (smtp://). */
18+ tls: "implicit" | "starttls";
19+ user: string | null;
20+ password: string | null;
21+}
22+
23+/**
24+ * E_SMTP_TRANSIENT (a 4xx reply, a timeout or a dropped connection) is retried. E_SMTP_RECIPIENT_REJECTED
25+ * (the server refused the recipient for good) suppresses the address. E_SMTP_REJECTED (any other 5xx,
26+ * such as a wrong password) and E_SMTP_CONFIG fail the email and change nothing else.
27+ */
28+export type SmtpErrorCode = "E_SMTP_CONFIG" | "E_SMTP_TRANSIENT" | "E_SMTP_REJECTED" | "E_SMTP_RECIPIENT_REJECTED";
29+
30+export class SmtpError extends Error {
31+ constructor(
32+ readonly code: SmtpErrorCode,
33+ message: string,
34+ ) {
35+ super(message);
36+ this.name = "SmtpError";
37+ }
38+}
39+
40+/** The SMTP settings, null when SMTP_URL is unset, or what is wrong with them. */
41+export function smtpConfig(env: Pick<Env, "SMTP_URL" | "SMTP_PASSWORD">): SmtpConfig | { error: string } | null {
42+ const raw = env.SMTP_URL?.trim();
43+ if (!raw) return null;
44+ let u: URL;
45+ try {
46+ u = new URL(raw);
47+ } catch {
48+ return { error: "SMTP_URL is not a URL" };
49+ }
50+ const tls = u.protocol === "smtps:" ? "implicit" : u.protocol === "smtp:" ? "starttls" : null;
51+ if (!tls) return { error: "SMTP_URL must start with smtps:// or smtp://" };
52+ if (u.password) return { error: "the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" };
53+ const host = u.hostname.replace(/^\[(.*)\]$/, "$1");
54+ if (!host) return { error: "SMTP_URL has no host" };
55+ if ((u.pathname && u.pathname !== "/") || u.search || u.hash) return { error: "SMTP_URL takes no path or query" };
56+ let user: string | null;
57+ try {
58+ user = u.username ? decodeURIComponent(u.username) : null;
59+ } catch {
60+ return { error: "SMTP_URL has a badly escaped user" };
61+ }
62+ const password = env.SMTP_PASSWORD || null;
63+ if (user && !password) return { error: "SMTP_URL names a user but the SMTP_PASSWORD secret is not set" };
64+ if (password && !user) return { error: "SMTP_PASSWORD is set but SMTP_URL names no user" };
65+ return { host, port: u.port ? Number(u.port) : tls === "implicit" ? 465 : 587, tls, user, password };
66+}
67+
68+/** SMTP_URL as an administrator may see it: scheme, user, host and port. */
69+export const smtpLabel = (c: SmtpConfig): string =>
70+ `${c.tls === "implicit" ? "smtps" : "smtp"}://${c.user ? `${encodeURIComponent(c.user)}@` : ""}${c.host.includes(":") ? `[${c.host}]` : c.host}:${c.port}${c.tls === "starttls" ? " (STARTTLS)" : ""}`;
71+
72+/** How long to wait for each reply, and for each write. */
73+export const SMTP_TIMEOUT_MS = 30_000;
74+
75+const enc = new TextEncoder();
76+
77+function b64(s: string): string {
78+ let bin = "";
79+ for (const b of enc.encode(s)) bin += String.fromCharCode(b);
80+ return btoa(bin);
81+}
82+
83+/** Base64 in lines of 76 characters (RFC 2045). */
84+const b64Lines = (s: string): string => b64(s).replace(/.{76}/g, "$&\r\n");
85+
86+const ASCII = /^[\x20-\x7e]*$/;
87+
88+/** A header value with non-ASCII text as RFC 2047 encoded words of at most 39 bytes of UTF-8 each, so a folded line stays under 78 characters. */
89+function encodeWords(s: string): string {
90+ if (ASCII.test(s)) return s;
91+ const words: string[] = [];
92+ let cur = "";
93+ for (const ch of s) {
94+ if (cur && enc.encode(cur + ch).length > 39) {
95+ words.push(cur);
96+ cur = "";
97+ }
98+ cur += ch;
99+ }
100+ if (cur) words.push(cur);
101+ return words.map((w) => `=?UTF-8?B?${b64(w)}?=`).join("\r\n ");
102+}
103+
104+const oneLine = (s: string): string => s.replace(/[\r\n]+/g, " ");
105+
106+function mailbox(m: { name: string; email: string } | string): string {
107+ if (typeof m === "string") return oneLine(m);
108+ const name = oneLine(m.name).trim();
109+ if (!name) return oneLine(m.email);
110+ return `${ASCII.test(name) ? `"${name.replace(/[\\"]/g, "\\$&")}"` : encodeWords(name)} <${oneLine(m.email)}>`;
111+}
112+
113+/** Headers formatMessage writes itself; the same names in Outgoing.headers are left out. */
114+const OWN_HEADERS = new Set(["from", "to", "cc", "bcc", "reply-to", "subject", "date", "message-id", "mime-version", "content-type", "content-transfer-encoding"]);
115+
116+/** The email as RFC 5322 text with CRLF line ends: text and HTML as multipart/alternative, each in base64. */
117+export function formatMessage(msg: Outgoing, o: { messageId: string; date: Date; boundary?: string }): string {
118+ const boundary = o.boundary ?? `=_diffinery_${crypto.randomUUID().replace(/-/g, "")}`;
119+ const headers: Array<[string, string]> = [
120+ ["From", mailbox(msg.from)],
121+ ["To", mailbox(msg.to)],
122+ ...(msg.replyTo ? [["Reply-To", mailbox(msg.replyTo)] as [string, string]] : []),
123+ ["Subject", encodeWords(oneLine(msg.subject))],
124+ ["Date", o.date.toUTCString().replace(/GMT$/, "+0000")],
125+ ["Message-ID", o.messageId],
126+ ["MIME-Version", "1.0"],
127+ ...Object.entries(msg.headers)
128+ .filter(([k]) => /^[A-Za-z0-9-]+$/.test(k) && !OWN_HEADERS.has(k.toLowerCase()))
129+ .map(([k, v]) => [k, encodeWords(oneLine(v))] as [string, string]),
130+ ["Content-Type", `multipart/alternative; boundary="${boundary}"`],
131+ ];
132+ const part = (type: string, body: string) => `--${boundary}\r\nContent-Type: ${type}; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Lines(body)}\r\n`;
133+ return `${headers.map(([k, v]) => `${k}: ${v}\r\n`).join("")}\r\n${part("text/plain", msg.text)}${part("text/html", msg.html)}--${boundary}--\r\n`;
134+}
135+
136+/** Enhanced status codes (RFC 3463) that mean the recipient's address is bad for good: no such mailbox or domain, or a disabled mailbox. */
137+const BAD_RECIPIENT = new Set(["5.1.1", "5.1.2", "5.1.3", "5.1.6", "5.1.10", "5.2.1"]);
138+
139+interface Reply {
140+ code: number;
141+ text: string;
142+}
143+
144+/** Whether a 5xx reply to RCPT TO is about the address rather than the sender, the relay or the message. */
145+function recipientGone(r: Reply): boolean {
146+ const enhanced = /^5\.\d{1,3}\.\d{1,3}\b/.exec(r.text)?.[0];
147+ return enhanced ? BAD_RECIPIENT.has(enhanced) : r.code === 550 || r.code === 551 || r.code === 553;
148+}
149+
150+function failure(stage: string, r: Reply): SmtpError {
151+ const detail = `SMTP ${stage}: ${r.code} ${r.text}`.slice(0, 300);
152+ if (r.code >= 400 && r.code < 500) return new SmtpError("E_SMTP_TRANSIENT", detail);
153+ if (r.code >= 500) return new SmtpError(stage === "RCPT TO" && recipientGone(r) ? "E_SMTP_RECIPIENT_REJECTED" : "E_SMTP_REJECTED", detail);
154+ return new SmtpError("E_SMTP_TRANSIENT", `${detail} (unexpected reply)`);
155+}
156+
157+/** One SMTP connection: reads replies line by line and writes commands, each within the timeout. */
158+class Session {
159+ private reader!: ReadableStreamDefaultReader<Uint8Array>;
160+ private writer!: WritableStreamDefaultWriter<Uint8Array>;
161+ private decoder = new TextDecoder();
162+ private buf = "";
163+
164+ constructor(
165+ private socket: Socket,
166+ private timeoutMs: number,
167+ ) {
168+ this.attach(socket);
169+ }
170+
171+ private attach(socket: Socket): void {
172+ this.socket = socket;
173+ // A connection that fails shows up in the next read; these would otherwise be unhandled rejections.
174+ socket.opened.catch(() => {});
175+ socket.closed.catch(() => {});
176+ this.reader = socket.readable.getReader();
177+ this.writer = socket.writable.getWriter();
178+ this.decoder = new TextDecoder();
179+ this.buf = "";
180+ }
181+
182+ private async within<T>(p: Promise<T>, what: string): Promise<T> {
183+ let timer: ReturnType<typeof setTimeout> | null = null;
184+ const timeout = new Promise<never>((_, reject) => {
185+ timer = setTimeout(() => reject(new SmtpError("E_SMTP_TRANSIENT", `SMTP ${what}: no answer from the server in ${this.timeoutMs / 1000} seconds`)), this.timeoutMs);
186+ });
187+ try {
188+ return await Promise.race([p, timeout]);
189+ } finally {
190+ clearTimeout(timer);
191+ }
192+ }
193+
194+ private async line(stage: string): Promise<string> {
195+ for (;;) {
196+ const nl = this.buf.indexOf("\n");
197+ if (nl >= 0) {
198+ const l = this.buf.slice(0, nl).replace(/\r$/, "");
199+ this.buf = this.buf.slice(nl + 1);
200+ return l;
201+ }
202+ if (this.buf.length > 64_000) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: reply line too long`);
203+ const { value, done } = await this.within(this.reader.read(), stage);
204+ if (done) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: the server closed the connection`);
205+ this.buf += this.decoder.decode(value, { stream: true });
206+ }
207+ }
208+
209+ /** One reply, all lines of a multiline one (`250-...` up to `250 ...`) joined. */
210+ async reply(stage: string): Promise<Reply> {
211+ const lines: string[] = [];
212+ for (;;) {
213+ const l = await this.line(stage);
214+ const m = /^(\d{3})([ -]|$)(.*)$/.exec(l);
215+ if (!m) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: not an SMTP reply`);
216+ lines.push(m[3]!);
217+ if (m[2] !== "-") return { code: Number(m[1]), text: lines.join("\n") };
218+ }
219+ }
220+
221+ async write(data: string, stage: string): Promise<void> {
222+ await this.within(this.writer.write(enc.encode(data)), stage);
223+ }
224+
225+ /** Send a command and expect one of the codes. `stage` names it in errors, so a command with a password in it never shows up. */
226+ async command(line: string, ok: number[], stage: string): Promise<Reply> {
227+ await this.write(`${line}\r\n`, stage);
228+ return this.expect(ok, stage);
229+ }
230+
231+ async expect(ok: number[], stage: string): Promise<Reply> {
232+ const r = await this.reply(stage);
233+ if (!ok.includes(r.code)) throw failure(stage, r);
234+ return r;
235+ }
236+
237+ /** EHLO, and the extensions the server lists (keyword → parameters). */
238+ async ehlo(name: string): Promise<Map<string, string>> {
239+ const r = await this.command(`EHLO ${name}`, [250], "EHLO");
240+ const caps = new Map<string, string>();
241+ for (const l of r.text.split("\n").slice(1)) {
242+ const [k, ...rest] = l.trim().split(/\s+/);
243+ if (k) caps.set(k.toUpperCase(), rest.join(" ").toUpperCase());
244+ }
245+ return caps;
246+ }
247+
248+ /** Switch to TLS after the server's 220 to STARTTLS. Anything it sent before is dropped, so it can't be injected into the TLS session. */
249+ startTls(): void {
250+ this.reader.releaseLock();
251+ this.writer.releaseLock();
252+ this.attach(this.socket.startTls());
253+ }
254+
255+ async close(): Promise<void> {
256+ await this.socket.close().catch(() => {});
257+ }
258+}
259+
260+const ADDRESS = /^[^\s<>()[\],;:"\\@]+@[^\s<>()[\],;:"\\@]+$/;
261+
262+/**
263+ * Send one email over SMTP. Resolves with the Message-ID it gave the email; throws SmtpError.
264+ * `ehlo` is the name Diffinery greets the server with (its own hostname).
265+ */
266+export async function sendSmtp(cfg: SmtpConfig, msg: Outgoing, opts: { ehlo: string; timeoutMs?: number; now?: Date }): Promise<{ messageId: string }> {
267+ const from = msg.from.email;
268+ const to = typeof msg.to === "string" ? msg.to : msg.to.email;
269+ for (const a of [from, to]) if (!ADDRESS.test(a)) throw new SmtpError("E_SMTP_REJECTED", `not an address SMTP can send to: ${oneLine(a).slice(0, 100)}`);
270+ const messageId = `<${crypto.randomUUID()}@${from.slice(from.lastIndexOf("@") + 1)}>`;
271+ const data = formatMessage(msg, { messageId, date: opts.now ?? new Date() });
272+
273+ let session: Session;
274+ try {
275+ session = new Session(connect({ hostname: cfg.host, port: cfg.port }, { secureTransport: cfg.tls === "implicit" ? "on" : "starttls", allowHalfOpen: false }), opts.timeoutMs ?? SMTP_TIMEOUT_MS);
276+ } catch (e) {
277+ throw new SmtpError("E_SMTP_TRANSIENT", `SMTP connect: ${(e as Error).message ?? String(e)}`);
278+ }
279+ try {
280+ await session.expect([220], "greeting");
281+ let caps = await session.ehlo(opts.ehlo);
282+ if (cfg.tls === "starttls") {
283+ if (!caps.has("STARTTLS")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS");
284+ await session.command("STARTTLS", [220], "STARTTLS");
285+ session.startTls();
286+ caps = await session.ehlo(opts.ehlo);
287+ }
288+ if (cfg.user && cfg.password) {
289+ const mechanisms = (caps.get("AUTH") ?? "").split(" ");
290+ if (mechanisms.includes("PLAIN")) {
291+ await session.command(`AUTH PLAIN ${b64(`\0${cfg.user}\0${cfg.password}`)}`, [235], "AUTH");
292+ } else if (mechanisms.includes("LOGIN")) {
293+ await session.command("AUTH LOGIN", [334], "AUTH");
294+ await session.command(b64(cfg.user), [334], "AUTH");
295+ await session.command(b64(cfg.password), [235], "AUTH");
296+ } else {
297+ throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server offers neither AUTH PLAIN nor AUTH LOGIN");
298+ }
299+ }
300+ const utf8 = !ASCII.test(from + to);
301+ if (utf8 && !caps.has("SMTPUTF8")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the address isn't ASCII and the server doesn't offer SMTPUTF8");
302+ await session.command(`MAIL FROM:<${from}>${utf8 ? " SMTPUTF8" : ""}`, [250], "MAIL FROM");
303+ await session.command(`RCPT TO:<${to}>`, [250, 251], "RCPT TO");
304+ await session.command("DATA", [354], "DATA");
305+ // A line that starts with a dot gets another (RFC 5321 4.5.2); a dot alone ends the message.
306+ await session.write(`${data.replace(/^\./gm, "..")}.\r\n`, "DATA");
307+ await session.expect([250], "DATA");
308+ await session.write("QUIT\r\n", "QUIT").catch(() => {});
309+ return { messageId };
310+ } catch (e) {
311+ if (e instanceof SmtpError) throw e;
312+ throw new SmtpError("E_SMTP_TRANSIENT", `SMTP: ${(e as Error).message ?? String(e)}`);
313+ } finally {
314+ await session.close();
315+ }
316+}
modifiedapps/diffinery/src/mail/suppression.ts+7−5View file
@@ -12,7 +12,7 @@
1212 *
1313 * Bounces and complaints come from Cloudflare Email Sending's Event Subscriptions (a queue,
1414 * mail/events.ts), from a signed POST to /-/email/events for anything else, and from Email
15- * Sending's own answer to a send that it refuses for good (sendSuppression, used by deliver()).
15+ * Sending's or the SMTP server's own answer to a send it refuses for good (sendSuppression, used by deliver()).
1616 */
1717
1818 export type SuppressionReason = "hard-bounce" | "complaint" | "manual";
@@ -103,11 +103,13 @@
103103 /**
104104 * Error codes with which Email Sending's send() refuses a recipient for good: it is on Cloudflare's
105105 * own suppression list (after a bounce or complaint there), so every later send fails the same way.
106- * Everything else (rate limits, the daily limit, delivery and internal errors, a bad message or
107- * sender) is about the send, not the address, and changes nothing.
106+ * Over SMTP (smtp.ts), E_SMTP_RECIPIENT_REJECTED: the server answered RCPT TO with a permanent
107+ * "no such mailbox or domain". Everything else (rate limits, the daily limit, delivery and internal
108+ * errors, a bad message or sender, a wrong SMTP password) is about the send, not the address, and
109+ * changes nothing.
108110 * https://developers.cloudflare.com/email-service/api/send-emails/workers-api/
109111 */
110-export const PERMANENT_SEND_CODES: ReadonlySet<string> = new Set(["E_RECIPIENT_SUPPRESSED"]);
112+export const PERMANENT_SEND_CODES: ReadonlySet<string> = new Set(["E_RECIPIENT_SUPPRESSED", "E_SMTP_RECIPIENT_REJECTED"]);
111113
112114 /**
113115 * What Email Sending's answer to one send means for the list: a permanent failure for the
@@ -122,7 +124,7 @@
122124 const e = answer.error as { code?: unknown; message?: unknown };
123125 const code = typeof e.code === "string" ? e.code : "";
124126 if (!PERMANENT_SEND_CODES.has(code)) return null;
125- return { email, reason: "hard-bounce", detail: clip(`Email Sending refused it: ${code}${typeof e.message === "string" && e.message ? `: ${e.message}` : ""}`) };
127+ return { email, reason: "hard-bounce", detail: clip(`${code.startsWith("E_SMTP_") ? "The SMTP server" : "Email Sending"} refused it: ${code}${typeof e.message === "string" && e.message ? `: ${e.message}` : ""}`) };
126128 }
127129 const r = answer.result && typeof answer.result === "object" ? (answer.result as { permanent_bounces?: unknown }) : null;
128130 const bounced = Array.isArray(r?.permanent_bounces) ? r.permanent_bounces : [];
modifiedapps/diffinery/src/mail/web.tsx+12−2View file
@@ -12,7 +12,8 @@
1212 import { Form, Time, WATCH_OPTIONS, act, flash, post, prm, render, repoUrl, type WebApp } from "../web/ui.js";
1313 import { MailStore, WATCH_LEVELS, type EmailLogRow, type NotificationPrefs, type WatchLevel } from "./prefs.js";
1414 import { sampleJobs } from "./samples.js";
15-import { buildMessage, deliver, enqueueMail, senderAddress } from "./send.js";
15+import { buildMessage, deliver, enqueueMail, mailTransport, senderAddress } from "./send.js";
16+import { smtpLabel } from "./smtp.js";
1617 import type { Category, MailJob } from "./types.js";
1718 import { readUnsubToken, type UnsubScope, type UnsubToken } from "./unsubscribe.js";
1819 import { normalEmail } from "../auth/signup.js";
@@ -60,6 +61,15 @@
6061 return me;
6162 };
6263
64+/** The Sending line on Settings → Email: which transport sends, or why nothing does. */
65+function sendingStatus(env: AppContext["env"]): Child {
66+ const t = mailTransport(env);
67+ if (!t) return <span class="bad">not configured (no EMAIL binding or SMTP_URL): emails are logged, not sent</span>;
68+ if (t.kind === "email-sending") return <span class="ok">Cloudflare Email Sending is bound</span>;
69+ if ("error" in t) return <span class="bad">SMTP_URL is set but can't be used: {t.error}</span>;
70+ return <span class="ok">over SMTP: {smtpLabel(t.config)}</span>;
71+}
72+
6373 /** One-line description of what an unsubscribe link changes. */
6474 function scopeText(s: UnsubScope): string {
6575 if (s.t === "thread") return `Mute ${s.repo}#${s.number}`;
@@ -631,7 +641,7 @@
631641 <div class="body">
632642 <dl class="kv m0">
633643 <dt>Sending</dt>
634- <dd>{c.env.EMAIL ? <span class="ok">Cloudflare Email Sending is bound</span> : <span class="bad">not configured (no EMAIL binding): emails are logged, not sent</span>}</dd>
644+ <dd>{sendingStatus(c.env)}</dd>
635645 <dt>Queue</dt>
636646 <dd>{c.env.MAIL ? "diffinery-mail" : <span class="bad">not bound: emails are dropped</span>}</dd>
637647 <dt>From</dt>
addedapps/diffinery/src/rate-limiter.ts+36−0View file
@@ -1,0 +1,36 @@
1+import { DurableObject } from "cloudflare:workers";
2+import type { Env } from "./env.js";
3+import { RATE_PERIOD_S } from "./lib/rate-limit.js";
4+
5+/**
6+ * Request rate limits for deployments without Cloudflare's rate limiting bindings, such as celld
7+ * (RATE_LIMITS=durable, lib/rate-limit.ts). Each object counts the keys of one shard in fixed
8+ * windows of RATE_PERIOD_S, in memory only: nothing is written to storage, so counting costs no
9+ * write per request, and an object that is evicted or moved starts its window again. Like the
10+ * bindings, the limits stop floods and scripted abuse rather than meter use exactly.
11+ */
12+export class RateLimiterDO extends DurableObject<Env> {
13+ private window = 0;
14+ /** `<bucket>\n<key>` → requests in the current window. Cleared when the window rolls over, so it holds one window's keys. */
15+ private counts = new Map<string, number>();
16+
17+ /**
18+ * Counts one request for `key` against each bucket in turn ([name, limit per window]), and
19+ * returns the first bucket over its limit, or null. Buckets after that one aren't counted, as
20+ * with the bindings.
21+ */
22+ hit(key: string, limits: Array<[bucket: string, limit: number]>): string | null {
23+ const w = Math.floor(Date.now() / 1000 / RATE_PERIOD_S);
24+ if (w !== this.window) {
25+ this.window = w;
26+ this.counts.clear();
27+ }
28+ for (const [bucket, limit] of limits) {
29+ const k = `${bucket}\n${key}`;
30+ const n = (this.counts.get(k) ?? 0) + 1;
31+ this.counts.set(k, n);
32+ if (n > limit) return bucket;
33+ }
34+ return null;
35+ }
36+}
modifiedapps/diffinery/src/repo/RepoDO.ts+5−1View file
@@ -47,6 +47,7 @@
4747 type ReceiveRequest,
4848 resetByDeploy,
4949 unpackFailure,
50+ UPLOAD_PACK_PATH,
5051 type RefEntry,
5152 type RefResult,
5253 } from "../git/protocol.js";
@@ -623,7 +624,7 @@
623624 }
624625
625626 /** The response streams: the pack is read and sent one object at a time, as the client takes it. */
626- async gitUploadPack(body: Uint8Array): Promise<ReadableStream<Uint8Array>> {
627+ private async gitUploadPack(body: Uint8Array): Promise<ReadableStream<Uint8Array>> {
627628 const { readable, writable } = new IdentityTransformStream();
628629 const writer = writable.getWriter();
629630 let started = false;
@@ -2161,6 +2162,9 @@
21612162 // ---------------------------------------------------------------- live updates (WebSockets with hibernation)
21622163
21632164 override async fetch(request: Request): Promise<Response> {
2165+ // The pack streams back through fetch, not RPC: celld can't return a stream from an RPC call
2166+ // ("RPC streams cannot cross isolate boundaries yet"), and a fetch body streams on both runtimes.
2167+ if (request.method === "POST" && new URL(request.url).pathname === UPLOAD_PACK_PATH) return new Response(await this.gitUploadPack(new Uint8Array(await request.arrayBuffer())));
21642168 if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 });
21652169 const topics = (new URL(request.url).searchParams.get("topics") ?? "repo").split(",").filter((t) => /^[a-z]+(:[A-Za-z0-9_-]+)?$/.test(t)).slice(0, 10);
21662170 const pair = new WebSocketPair();
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+51−19View 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; container?: 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;
@@ -51,31 +53,49 @@
5153 export class RunnerContainer extends HostedContainer {
5254 // Jobs make no inbound requests, so activity-based sleep must not stop them.
5355 override sleepAfter = "6h";
56+ /** True while start() runs (startRunner). */
57+ private starting = false;
5458
5559 async startJob(input: { repoId: string; jobId: string; container?: string; token: string; apiUrl: string; egress?: Egress; vcpu?: number }): Promise<void> {
5660 await this.ctx.storage.put("job", { repoId: input.repoId, jobId: input.jobId, container: input.container });
57- const egressEnv = await this.useEgress(input.egress ?? "open");
58- 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- },
69- // The library gives up after 8 s and reports "no container instance", but a container on a host
70- // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
71- // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
72- // The runner listens on no port: the library's own fallback port (33) answers "not listening" once it is up.
73- // Each check can itself take up to 5 s, so the signal bounds the whole wait.
74- { portToCheck: 33, waitInterval: START_POLL_MS, retries: Math.ceil(START_WAIT_MS / START_POLL_MS), signal: AbortSignal.timeout(START_WAIT_MS + 60_000) },
75- );
61+ await this.startRunner({
62+ DIFFINERY_API_URL: input.apiUrl,
63+ DIFFINERY_JOB_ID: input.jobId,
64+ DIFFINERY_JOB_TOKEN: input.token,
65+ // The runner's share of CPU, which the agent measures the job's use against (runner/sizes.ts).
66+ ...(input.vcpu ? { DIFFINERY_RUNNER_VCPU: String(input.vcpu) } : {}),
67+ ...(await this.useEgress(input.egress ?? "open")),
68+ });
7669 }
7770
7871 /**
72+ * A GitHub job's runner (github-runners/service.ts): the agent runs GitHub's runner with the just-in-time
73+ * configuration GitHub made for it, which holds the runner's credentials, so it is only ever in the
74+ * container's environment.
75+ */
76+ async startGitHubRunner(input: { accountId: string; runnerId: string; container?: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void> {
77+ await this.ctx.storage.put("github", { accountId: input.accountId, runnerId: input.runnerId, container: input.container } satisfies GitHubRunner);
78+ await this.startRunner({ DIFFINERY_GITHUB_JIT_CONFIG: input.jitConfig, DIFFINERY_RUNNER_VCPU: String(input.vcpu), ...(await this.useEgress(input.egress)) });
79+ }
80+
81+ private async startRunner(envVars: Record<string, string>): Promise<void> {
82+ this.starting = true;
83+ try {
84+ await this.start(
85+ { envVars },
86+ // The library gives up after 8 s and reports "no container instance", but a container on a host
87+ // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
88+ // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
89+ // The runner listens on no port: the library's own fallback port (33) answers "not listening" once it is up.
90+ // Each check can itself take up to 5 s, so the signal bounds the whole wait.
91+ { portToCheck: 33, waitInterval: START_POLL_MS, retries: Math.ceil(START_WAIT_MS / START_POLL_MS), signal: AbortSignal.timeout(START_WAIT_MS + 60_000) },
92+ );
93+ } finally {
94+ this.starting = false;
95+ }
96+ }
97+
98+ /**
7999 * Diffinery ended the job (a timeout, fail-fast, a newer run in its concurrency group): the container
80100 * goes at once. `graceful` (someone cancelled the run) sends SIGINT instead: the runner stops the step
81101 * under way, runs the steps that run after a cancel and reports. The agent reads SIGTERM as a platform
@@ -91,6 +111,18 @@
91111 }
92112
93113 override async onStop(params: StopParams): Promise<void> {
114+ const gh = await this.ctx.storage.get<GitHubRunner>("github");
115+ if (gh) {
116+ // While a start the platform had no machine for is tried again, the library's alarm reports the container
117+ // stopped with exit code 0, though nothing ran and the start goes on. Told so, Diffinery removed the runner
118+ // from GitHub and its job waited 24 hours for another (2 or 3 jobs of 10 started at once). The start ends in
119+ // a running runner, or in an error that github-runners/service.ts place() handles.
120+ if (this.starting) return;
121+ const ns = this.env.GITHUB_RUNNERS;
122+ if (ns) await ns.get(ns.idFromName(gh.accountId)).stopped(gh.accountId, gh.runnerId, params.exitCode ?? null, gh.container);
123+ await this.ctx.storage.delete("github");
124+ return;
125+ }
94126 const job = await this.ctx.storage.get<RunnerJob>("job");
95127 if (!job) return;
96128 const repo = this.env.REPO.get(this.env.REPO.idFromName(job.repoId));
modifiedapps/diffinery/src/text-modules.d.ts+14−2View file
@@ -4,8 +4,9 @@
44 export default text;
55 }
66
7-// Compiled WebAssembly modules (wrangler's default CompiledWasm rule; the wasm plugin in vitest.config.ts under tests).
8-declare module "*.wasm?module" {
7+// Compiled WebAssembly modules (wrangler's default CompiledWasm rule, and celld's for every .wasm import; the wasm
8+// plugin in vitest.config.ts under tests). A plain .wasm path: celld documents .wasm?module only for unbundled Workers.
9+declare module "*.wasm" {
910 const module: WebAssembly.Module;
1011 export default module;
1112 }
@@ -15,3 +16,14 @@
1516 const data: ArrayBuffer;
1617 export default data;
1718 }
19+
20+// These two packages ship wasm-bindgen typings beside the file (`*.wasm.d.ts`, the module's exports), which
21+// would win over the pattern above; an exact name wins over both.
22+declare module "@jsquash/png/codec/pkg/squoosh_png_bg.wasm" {
23+ const module: WebAssembly.Module;
24+ export default module;
25+}
26+declare module "@jsquash/resize/lib/resize/pkg/squoosh_resize_bg.wasm" {
27+ const module: WebAssembly.Module;
28+ export default module;
29+}
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);
modifiedapps/diffinery/test/e2e/entry.ts+1−0View file
@@ -7,6 +7,7 @@
77 export { RepoDO } from "../../src/repo/RepoDO.js";
88 export { SchedulerDO } from "../../src/scheduler.js";
99 export { ComposeDO } from "../../src/compose.js";
10+export { RateLimiterDO } from "../../src/rate-limiter.js";
1011 export { RunnerContainer, RunnerContainerMedium, RunnerContainerSmall, RunnerContainerTiny, SandboxContainer } from "../../src/runner/containers.js";
1112 export { RunWorkflow } from "../../src/runner/workflow.js";
1213 export { ImportWorkflow } from "../../src/imports/workflow.js";
addedapps/diffinery/test/unit/celld.test.ts+103−0View file
@@ -1,0 +1,103 @@
1+import { readdirSync, readFileSync, statSync } from "node:fs";
2+import { join } from "node:path";
3+import { fileURLToPath } from "node:url";
4+import { describe, expect, it } from "vitest";
5+import { CELLD_ABSENT_BINDINGS } from "../../src/env.js";
6+import { CELLD_KEYS, SECRETS, celldConfig } from "../../../../scripts/celld-config.mjs";
7+import { parseJsonc } from "../../../../scripts/jsonc.mjs";
8+
9+/**
10+ * Diffinery runs on Cloudflare and on celld, the open-source Workers runtime (docs/self-hosting/celld.md).
11+ * These checks keep it that way: wrangler.jsonc renders to a config celld accepts, the bindings celld
12+ * lacks are optional in Env, and the Worker's own code uses only modules and handlers celld provides.
13+ */
14+
15+const repo = fileURLToPath(new URL("../../../../", import.meta.url));
16+const wrangler = parseJsonc(readFileSync(join(repo, "apps/diffinery/wrangler.jsonc"), "utf8"));
17+
18+describe("wrangler.jsonc for celld", () => {
19+ it("renders with only keys celld accepts", () => {
20+ for (const env of [undefined, "dev"]) {
21+ const { config } = celldConfig(wrangler, { env });
22+ for (const key of Object.keys(config)) expect(CELLD_KEYS.has(key), `${env ?? "production"}: ${key}`).toBe(true);
23+ for (const c of config.containers ?? []) expect(Object.keys(c).every((k) => ["class_name", "image", "name", "instance_type", "max_instances", "runtime"].includes(k))).toBe(true);
24+ expect(config.rules).toEqual(expect.arrayContaining([{ type: "Text", globs: ["**/*.txt"] }, { type: "Data", globs: ["**/*.bin"] }]));
25+ }
26+ expect(celldConfig(wrangler, { env: "dev" }).config.name).toBe("diffinery-dev");
27+ });
28+
29+ it("leaves out exactly the bindings the Worker runs without", () => {
30+ // CELLD_ABSENT_BINDINGS is type-checked to be optional in Env; this ties it to what the script drops.
31+ const { absent } = celldConfig(wrangler);
32+ expect(new Set(absent)).toEqual(new Set(CELLD_ABSENT_BINDINGS));
33+ });
34+
35+ it("stops on a key it doesn't know, a nested key celld refuses, and EGRESS=web", () => {
36+ expect(() => celldConfig({ ...wrangler, tail_consumers: [{ service: "x" }] })).toThrow(/"tail_consumers" is not supported by celld/);
37+ expect(() => celldConfig({ ...wrangler, r2_buckets: [{ binding: "BUCKET", bucket_name: "b", jurisdiction: "eu" }] })).toThrow(/r2_buckets: celld doesn't support jurisdiction/);
38+ expect(() => celldConfig({ ...wrangler, migrations: [{ tag: "v9", renamed_classes: [] }] })).toThrow(/renamed_classes/);
39+ expect(() => celldConfig(wrangler, { vars: { EGRESS: "web" } })).toThrow(/EGRESS=web/);
40+ });
41+
42+ it("takes secrets and variables into vars, and a registry image for every container", () => {
43+ const { config } = celldConfig(wrangler, { vars: { SIGNUP: "open" }, secrets: { MASTER_KEY: "k" }, runnerImage: "registry.example.com/runner:1" });
44+ expect(config.vars).toMatchObject({ SIGNUP: "open", MASTER_KEY: "k", PUBLIC_URL: wrangler.vars.PUBLIC_URL });
45+ expect(config.containers.every((c: { image: string }) => c.image === "registry.example.com/runner:1")).toBe(true);
46+ expect(SECRETS).toContain("OIDC_PRIVATE_KEY");
47+ });
48+
49+ it("copies every secret the Worker reads", () => {
50+ // celld deploy has no secret store: a secret missing from SECRETS never reaches the Worker. Env marks them "Secret".
51+ const env = readFileSync(join(repo, "apps/diffinery/src/env.ts"), "utf8");
52+ const secrets = [...env.matchAll(/\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*([A-Z][A-Z0-9_]*)\??:/g)].filter(([, doc]) => /^Secret\b/.test(doc.replace(/^[\s*]+/, ""))).map(([, , name]) => name);
53+ expect(secrets.length).toBeGreaterThan(5);
54+ expect(secrets.filter((s) => !SECRETS.includes(s))).toEqual([]);
55+ });
56+});
57+
58+/** Built-in modules celld implements (its docs/cloudflare-compat.md); node:crypto and node:zlib only in part. */
59+const CELLD_MODULES = new Set(["cloudflare:workers", "cloudflare:workflows", "cloudflare:sockets", ...["assert", "async_hooks", "buffer", "crypto", "diagnostics_channel", "events", "fs", "os", "path", "stream", "timers/promises", "util", "zlib"].map((m) => `node:${m}`)]);
60+
61+function sources(dir: string): string[] {
62+ return readdirSync(dir).flatMap((f) => {
63+ const p = join(dir, f);
64+ if (statSync(p).isDirectory()) return sources(p);
65+ return /\.tsx?$/.test(f) && !f.endsWith(".d.ts") ? [p] : [];
66+ });
67+}
68+
69+describe("Worker code celld runs", () => {
70+ const files = ["apps/diffinery/src", "packages/git-core/src", "packages/shared/src", "packages/workflow-yaml/src"].flatMap((d) => sources(join(repo, d)));
71+
72+ it("imports only runtime modules celld provides, and no query-suffixed paths", () => {
73+ const bad: string[] = [];
74+ for (const file of files) {
75+ // Static imports and re-exports (`from "x"`, `import "x"`) and dynamic `import("x")`.
76+ for (const [, a, b] of readFileSync(file, "utf8").matchAll(/^\s*(?:import|export)\b[^;]*?(?:\bfrom\s*|import\s+)"([^"\n]+)"|\bimport\(\s*"([^"\n]+)"\s*\)/gm)) {
77+ const spec = a ?? b;
78+ const builtin = /^(?:node|cloudflare):/.test(spec);
79+ // `x.wasm?module` and the like: celld's esbuild picks a loader by extension only.
80+ if ((builtin && !CELLD_MODULES.has(spec)) || spec.includes("?")) bad.push(`${file.slice(repo.length)}: ${spec}`);
81+ }
82+ }
83+ expect(bad).toEqual([]);
84+ });
85+
86+ it("returns no stream from a Durable Object's RPC methods", () => {
87+ // celld: "RPC streams cannot cross isolate boundaries yet". A streamed answer goes through the object's
88+ // fetch() instead, as git-upload-pack does (RepoDO.fetch).
89+ const bad: string[] = [];
90+ for (const file of files.filter((f) => /extends (?:DurableObject|Container)\b/.test(readFileSync(f, "utf8")))) {
91+ for (const [m] of readFileSync(file, "utf8").matchAll(/^ {2}(?!private |protected |static |override async fetch\b|async fetch\b)(?:override )?(?:async )?\w+\([^)]*\)\s*:\s*Promise<(?:ReadableStream|Response|R2ObjectBody)\b[^\n]*/gm)) bad.push(`${file.slice(repo.length)}: ${m.trim()}`);
92+ }
93+ expect(bad).toEqual([]);
94+ });
95+
96+ it("exports only the handlers celld calls", () => {
97+ // celld has no email or tail handlers.
98+ const handlers = readFileSync(join(repo, "apps/diffinery/src/index.ts"), "utf8").match(/export default \{([^}]*)\}/)?.[1];
99+ const names = (handlers ?? "").split(",").map((h) => h.split(":")[0].trim()).filter(Boolean);
100+ expect(names.length).toBeGreaterThan(0);
101+ for (const n of names) expect(["fetch", "queue", "scheduled", "alarm"]).toContain(n);
102+ });
103+});
addedapps/diffinery/test/unit/deploy-github-app.test.ts+75−0View file
@@ -1,0 +1,75 @@
1+import { spawnSync } from "node:child_process";
2+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { afterEach, describe, expect, it } from "vitest";
6+
7+/**
8+ * The GitHub App of GitHub runners on deploy: render-config.mjs takes its IDs from the environment
9+ * (the Deploy workflow maps the DIFFINERY_GITHUB_APP_* repository variables to them), so the
10+ * repository's wrangler.jsonc names no instance's app.
11+ */
12+
13+const repo = new URL("../../../../", import.meta.url).pathname;
14+const APP = { GITHUB_APP_ID: "1234567", GITHUB_APP_SLUG: "diffinery-runners", GITHUB_APP_CLIENT_ID: "Iv23liAbCdEf", GITHUB_APP_URL: "https://ghe.example.com" };
15+
16+let dir = "";
17+afterEach(() => {
18+ if (dir) rmSync(dir, { recursive: true, force: true });
19+ dir = "";
20+});
21+
22+function tree(wranglerVars: Record<string, string> = {}): void {
23+ dir = mkdtempSync(join(tmpdir(), "github-app-"));
24+ for (const d of ["scripts", "apps/diffinery"]) mkdirSync(join(dir, d), { recursive: true });
25+ for (const f of ["jsonc.mjs", "render-config.mjs"]) copyFileSync(join(repo, "scripts", f), join(dir, "scripts", f));
26+ const cfg = readFileSync(join(repo, "apps/diffinery/wrangler.jsonc"), "utf8");
27+ const vars = Object.entries(wranglerVars).map(([k, v]) => `\n ${JSON.stringify(k)}: ${JSON.stringify(v)},`).join("");
28+ writeFileSync(join(dir, "apps/diffinery/wrangler.jsonc"), cfg.replace(/"vars": \{/, `"vars": {${vars}`));
29+}
30+
31+function render(env: Record<string, string> = {}) {
32+ const r = spawnSync("node", [join(dir, "scripts/render-config.mjs"), "--d1", "db-id", "--public-url", "https://git.example.com"], {
33+ cwd: dir,
34+ encoding: "utf8",
35+ env: { PATH: process.env.PATH, HOME: dir, ...env },
36+ });
37+ const cfg = r.status === 0 ? (JSON.parse(readFileSync(join(dir, "apps/diffinery/wrangler.deploy.jsonc"), "utf8").split("\n").slice(1).join("\n")) as { vars: Record<string, string> }) : null;
38+ return { status: r.status, stderr: r.stderr, vars: cfg?.vars ?? null };
39+}
40+
41+describe("scripts/render-config.mjs and the GitHub App", () => {
42+ it("sets the app's IDs from the environment, trimmed", () => {
43+ tree();
44+ const { vars } = render({ ...APP, GITHUB_APP_SLUG: " diffinery-runners\n" });
45+ expect(vars).toMatchObject(APP);
46+ });
47+
48+ it("leaves them out without the environment: the repository's wrangler.jsonc has none, so the feature is off", () => {
49+ tree();
50+ const { vars } = render({ GITHUB_APP_ID: "", GITHUB_APP_SLUG: "" });
51+ for (const key of Object.keys(APP)) expect(vars).not.toHaveProperty(key);
52+ });
53+
54+ it("keeps a copy's own wrangler.jsonc values when the environment has none, and the environment wins over them", () => {
55+ tree({ GITHUB_APP_ID: "42", GITHUB_APP_SLUG: "own-app" });
56+ expect(render().vars).toMatchObject({ GITHUB_APP_ID: "42", GITHUB_APP_SLUG: "own-app" });
57+ expect(render({ GITHUB_APP_ID: "7" }).vars).toMatchObject({ GITHUB_APP_ID: "7", GITHUB_APP_SLUG: "own-app" });
58+ });
59+
60+ it("refuses a value of the wrong shape without printing it", () => {
61+ tree();
62+ const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEsecret\n-----END RSA PRIVATE KEY-----";
63+ for (const [key, value, message] of [
64+ ["GITHUB_APP_ID", pem, "GITHUB_APP_ID must be the App ID, a number"],
65+ ["GITHUB_APP_SLUG", "Diffinery Runners", "GITHUB_APP_SLUG must be the slug"],
66+ ["GITHUB_APP_CLIENT_ID", "Iv23li with space", "GITHUB_APP_CLIENT_ID must be the Client ID"],
67+ ["GITHUB_APP_URL", "https://ghe.example.com/api/v3", "GITHUB_APP_URL must be an https origin"],
68+ ] as const) {
69+ const r = render({ [key]: value });
70+ expect(r.status).not.toBe(0);
71+ expect(r.stderr).toContain(message);
72+ expect(r.stderr).not.toContain(value);
73+ }
74+ });
75+});
addedapps/diffinery/test/unit/github-runners.test.ts+555−0View file
@@ -1,0 +1,555 @@
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+ jobState: "queued" as string | Error | null,
45+ async jitRunner(installationId: number, repo: string, name: string, labels: string[]) {
46+ calls.push({ op: "jit", args: [installationId, repo, name, labels] });
47+ if (gh.fail) throw gh.fail;
48+ return { runnerId: ++next, encodedJitConfig: `jit-${next}` };
49+ },
50+ async runner(installationId: number, repo: string, runnerId: number) {
51+ calls.push({ op: "runner", args: [installationId, repo, runnerId] });
52+ return gh.busy === null ? null : { busy: gh.busy, status: "online" };
53+ },
54+ async removeRunner(installationId: number, repo: string, runnerId: number) {
55+ calls.push({ op: "remove", args: [installationId, repo, runnerId] });
56+ },
57+ async jobStatus(installationId: number, repo: string, jobId: number) {
58+ calls.push({ op: "job", args: [installationId, repo, jobId] });
59+ if (gh.jobState instanceof Error) throw gh.jobState;
60+ return gh.jobState;
61+ },
62+ };
63+ return { gh, calls, client: gh as unknown as GitHubAppClient };
64+}
65+
66+function fakeHost(sizes: string[] = ["large", "medium", "small", "tiny"]) {
67+ const started: Array<{ container: string; input: Parameters<RunnerHost["start"]>[1] }> = [];
68+ const stopped: string[] = [];
69+ const host = {
70+ fail: null as Error | null,
71+ async start(container: string, input: Parameters<RunnerHost["start"]>[1]) {
72+ if (host.fail) throw host.fail;
73+ started.push({ container, input });
74+ },
75+ async stop(container: string) {
76+ stopped.push(container);
77+ },
78+ has: (size: string) => sizes.includes(size),
79+ };
80+ return { host: host as RunnerHost & { fail: Error | null }, started, stopped };
81+}
82+
83+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 });
84+
85+function world(vars: Record<string, unknown> = {}, sizes?: string[]) {
86+ const s = setup(vars);
87+ const g = fakeGitHub();
88+ const h = fakeHost(sizes);
89+ let t = Date.parse("2026-10-30T12:00:00.000Z");
90+ const clock = { now: () => t, advance: (ms: number) => (t += ms) };
91+ const svc = new GitHubRunners(s.env, g.client, h.host, clock.now);
92+ const rows = () => s.DB.sqlite.prepare("SELECT * FROM github_runner_jobs ORDER BY created_at, github_job_id").all() as unknown as RunnerJobRow[];
93+ const compute = () => s.DB.sqlite.prepare("SELECT * FROM compute_usage").all() as Array<{ id: string; repo_id: string; ended_at: string | null }>;
94+ return { ...s, ...g, ...h, svc, clock, rows, compute };
95+}
96+
97+describe("the GitHub App", () => {
98+ it("is off until every setting is there", () => {
99+ expect(githubApp({ ...APP_VARS } as unknown as Env)).toMatchObject({ appId: "123", webUrl: "https://github.com", apiUrl: "https://api.github.com" });
100+ 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" });
101+ expect(githubApp({ ...APP_VARS, GITHUB_APP_WEBHOOK_SECRET: "" } as unknown as Env)).toBeNull();
102+ });
103+
104+ it("signs its JWT with the PKCS#1 key GitHub gives, also pasted on one line", async () => {
105+ for (const key of [PKCS1, PKCS1.replace(/\n/g, "\\n")]) {
106+ const jwt = await appJwt({ appId: "123", privateKey: key }, 1_800_000_000);
107+ const [h, p, sig] = jwt.split(".");
108+ expect(JSON.parse(Buffer.from(p!, "base64url").toString())).toEqual({ iat: 1_799_999_940, exp: 1_800_000_540, iss: "123" });
109+ expect(createVerify("RSA-SHA256").update(`${h}.${p}`).verify(SPKI, Buffer.from(sig!, "base64url"))).toBe(true);
110+ }
111+ const { privateKey: pkcs8 } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs8", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
112+ expect(pkcs8FromPem(pkcs8)[0]).toBe(0x30);
113+ expect(() => pkcs8FromPem("not a key")).toThrow(/not a PEM private key/);
114+ });
115+
116+ it("takes only webhooks GitHub signed with the app's secret", async () => {
117+ const body = '{"action":"queued"}';
118+ const sig = `sha256=${createHmac("sha256", "hook-secret").update(body).digest("hex")}`;
119+ expect(await webhookSigned("hook-secret", sig, body)).toBe(true);
120+ expect(await webhookSigned("hook-secret", sig, body + " ")).toBe(false);
121+ expect(await webhookSigned("other", sig, body)).toBe(false);
122+ expect(await webhookSigned("hook-secret", undefined, body)).toBe(false);
123+ });
124+});
125+
126+describe("runs-on labels", () => {
127+ it("are for Diffinery with diffinery or a size, and only labels a Diffinery runner has", () => {
128+ expect(runnerFor(["diffinery"])).toBe("large");
129+ expect(runnerFor(["Diffinery-Medium"])).toBe("medium");
130+ expect(runnerFor(["self-hosted", "linux", "x64", "diffinery-tiny"])).toBe("tiny");
131+ expect(runnerFor(["diffinery-small", "diffinery-medium"])).toBe("medium");
132+ expect(runnerFor(["ubuntu-latest"])).toBeNull();
133+ expect(runnerFor(["self-hosted"])).toBeNull();
134+ expect(runnerFor(["diffinery", "gpu"])).toBeNull();
135+ expect(runnerFor(["diffinery", "arm64"])).toBeNull();
136+ expect(runnerFor([])).toBeNull();
137+ });
138+});
139+
140+describe("GitHub jobs on Diffinery runners", () => {
141+ it("start a runner for a queued job, follow it through its job and end when its container stops", async () => {
142+ const w = world();
143+ expect(await w.svc.queued("ann", job(1001, ["self-hosted", "diffinery-small"]), "small")).toBe(true);
144+ // GitHub delivers a webhook again after a timeout: the same job doesn't get a second runner.
145+ expect(await w.svc.queued("ann", job(1001, ["self-hosted", "diffinery-small"]), "small")).toBe(false);
146+ expect((await w.svc.pump("ann")).next).toBe(IDLE_MS);
147+ const [row] = w.rows();
148+ 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` });
149+ expect(w.calls[0]).toEqual({ op: "jit", args: [11, "ann-gh/app", `diffinery-${row!.id}-1`, ["self-hosted", "diffinery-small"]] });
150+ expect(w.started).toEqual([{ container: `gh-${row!.id}-1.small`, input: { accountId: "ann", runnerId: row!.id, jitConfig: "jit-501", egress: "open", vcpu: 0.5 } }]);
151+ // It counts as one of ann's hosted jobs, under no Diffinery repository.
152+ expect(w.compute()).toEqual([expect.objectContaining({ id: `gh-${row!.id}-1.small`, repo_id: "github:11", ended_at: null })]);
153+
154+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1001, action: "in_progress", runnerName: `diffinery-${row!.id}-1`, jobName: "test 1001", conclusion: null });
155+ expect(w.rows()[0]).toMatchObject({ status: "running", ran_job_id: 1001 });
156+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1001, action: "completed", runnerName: `diffinery-${row!.id}-1`, jobName: "test 1001", conclusion: "success" });
157+ await w.svc.stopped(row!.id, 0);
158+ expect(w.rows()[0]).toMatchObject({ status: "completed", conclusion: "success", exit_code: 0, message: null });
159+ expect(w.compute()[0]!.ended_at).not.toBeNull();
160+ // A runner that ran its job removes itself from GitHub.
161+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([]);
162+ expect((await w.svc.pump("ann")).next).toBeNull();
163+ });
164+
165+ it("wait while the account runs as many hosted jobs as it may, and start once one ends", async () => {
166+ const w = world({ QUOTA_HOSTED_JOBS: "1" });
167+ 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());
168+ await w.svc.queued("ann", job(1), "large");
169+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
170+ expect(w.rows()[0]).toMatchObject({ status: "queued", message: expect.stringMatching(/^Waiting: waiting for one of this account's 1 hosted jobs/) });
171+ expect(w.started).toEqual([]);
172+ w.DB.sqlite.prepare("UPDATE compute_usage SET ended_at = ? WHERE id = 'other'").run(new Date().toISOString());
173+ await w.svc.pump("ann");
174+ expect(w.rows()[0]!.status).toBe("starting");
175+ });
176+
177+ it("don't start while the account's Actions are suspended or hosted compute is paused", async () => {
178+ const w = world();
179+ w.DB.sqlite.prepare("UPDATE accounts SET actions_suspended_at = ?, actions_suspended_reason = 'mining' WHERE id = 'ann'").run(at);
180+ await w.svc.queued("ann", job(1), "large");
181+ await w.svc.pump("ann");
182+ 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" });
183+ w.DB.sqlite.prepare("UPDATE accounts SET actions_suspended_at = NULL WHERE id = 'ann'").run();
184+ w.DB.sqlite.prepare("INSERT INTO site_flags (key, value, updated_at, updated_by) VALUES ('hosted_compute_paused', 'maintenance', ?, 'root')").run(at);
185+ await w.svc.queued("ann", job(2), "large");
186+ await w.svc.pump("ann");
187+ expect(w.rows()[1]!.message).toMatch(/^The runner was not started: Hosted runners are paused on this instance by a site administrator: maintenance/);
188+ expect(w.started).toEqual([]);
189+ });
190+
191+ it("skip jobs that end before their runner starts, and jobs of an installation no longer linked or suspended", async () => {
192+ const w = world({ QUOTA_HOSTED_JOBS: "0" });
193+ await w.svc.queued("ann", job(1), "large");
194+ await w.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "completed", runnerName: null, jobName: "test 1", conclusion: "cancelled" });
195+ expect(w.rows()[0]).toMatchObject({ status: "skipped", conclusion: "cancelled", message: "The job ended before a runner started for it" });
196+ // A Diffinery runner this account didn't start (another instance's, say) took it.
197+ await w.svc.queued("ann", job(2), "large");
198+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: "diffinery-other-1", jobName: "test 2", conclusion: null });
199+ expect(w.rows()[1]).toMatchObject({ status: "skipped", message: "The job ran on diffinery-other-1 before a runner started for it" });
200+
201+ const v = world();
202+ v.DB.sqlite.prepare("UPDATE github_installations SET suspended_at = ?").run(at);
203+ await v.svc.queued("ann", job(1), "large");
204+ await v.svc.pump("ann");
205+ expect(v.rows()[0]).toMatchObject({ status: "skipped", message: "The app's installation is suspended on GitHub" });
206+ v.DB.sqlite.prepare("DELETE FROM github_installations").run();
207+ await v.svc.queued("ann", job(2), "large");
208+ await v.svc.pump("ann");
209+ expect(v.rows()[1]).toMatchObject({ status: "skipped", message: "The GitHub installation is no longer linked to this account" });
210+ });
211+
212+ it("still start a runner for a job when the runner started for it took another queued job", async () => {
213+ const w = world();
214+ const byJob = (id: number) => w.rows().find((r) => r.github_job_id === id)!;
215+ await w.svc.queued("ann", job(1, ["diffinery-small", "diffinery-medium"]), "medium");
216+ await w.svc.pump("ann");
217+ const first = w.rows()[0]!;
218+ // Job 2 is queued after job 1, and GitHub hands it to job 1's runner before a runner starts for it.
219+ w.clock.advance(1000);
220+ await w.svc.queued("ann", job(2, ["diffinery-small"]), "small");
221+ const queued2 = byJob(2).created_at;
222+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: first.runner_name, jobName: "test 2", conclusion: null });
223+ // The rows trade jobs: the runner's row shows the job it runs, the other waits for job 1 in job 1's place in line.
224+ expect(byJob(2)).toMatchObject({ id: first.id, status: "running", job_name: "test 2", html_url: job(2).htmlUrl, labels: '["diffinery-small"]', size: "medium", created_at: queued2, ran_job_id: 2, container: first.container });
225+ expect(byJob(1)).toMatchObject({ status: "queued", job_name: "test 1", html_url: job(1).htmlUrl, labels: '["diffinery-small","diffinery-medium"]', size: "medium", created_at: first.created_at, runner_name: null, ran_job_id: null });
226+ const waiting = byJob(1);
227+
228+ await w.svc.pump("ann");
229+ expect(byJob(1)).toMatchObject({ id: waiting.id, status: "starting", runner_name: `diffinery-${waiting.id}-1`, container: `gh-${waiting.id}-1.medium` });
230+ expect(w.calls.filter((c) => c.op === "jit").map((c) => c.args[3])).toEqual([
231+ ["diffinery-small", "diffinery-medium"],
232+ ["diffinery-small", "diffinery-medium"],
233+ ]);
234+ expect(w.compute().map((c) => [c.id, c.ended_at])).toEqual([
235+ [first.container, null],
236+ [`gh-${waiting.id}-1.medium`, null],
237+ ]);
238+ // Each runner's row ends with its own container.
239+ await w.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "completed", runnerName: first.runner_name, jobName: "test 2", conclusion: "success" });
240+ await w.svc.stopped(first.id, 0);
241+ expect(byJob(2)).toMatchObject({ status: "completed", conclusion: "success", exit_code: 0 });
242+ expect(byJob(1)).toMatchObject({ status: "starting" });
243+ expect(w.compute().map((c) => c.ended_at === null)).toEqual([false, true]);
244+
245+ // Job 1 cancelled while its row waits: the row is skipped and no runner starts for it.
246+ const v = world();
247+ await v.svc.queued("ann", job(1), "large");
248+ await v.svc.pump("ann");
249+ const runner = v.rows()[0]!.runner_name;
250+ await v.svc.queued("ann", job(2), "large");
251+ await v.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: runner, jobName: "test 2", conclusion: null });
252+ await v.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "completed", runnerName: null, jobName: "test 1", conclusion: "cancelled" });
253+ expect(v.rows().map((r) => [r.github_job_id, r.status, r.message])).toEqual([
254+ [1, "skipped", "The job ended before a runner started for it"],
255+ [2, "running", null],
256+ ]);
257+ await v.svc.pump("ann");
258+ expect(v.started).toHaveLength(1);
259+
260+ // A job whose own runner already started keeps it: GitHub hands that runner the job the other was started for.
261+ const u = world();
262+ await u.svc.queued("ann", job(1), "large");
263+ await u.svc.queued("ann", job(2), "large");
264+ await u.svc.pump("ann");
265+ const [r1, r2] = u.rows();
266+ await u.svc.jobEvent({ installationId: 11, githubJobId: 2, action: "in_progress", runnerName: r1!.runner_name, jobName: "test 2", conclusion: null });
267+ await u.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "in_progress", runnerName: r2!.runner_name, jobName: "test 1", conclusion: null });
268+ expect(u.rows().map((r) => [r.id, r.github_job_id, r.status, r.ran_job_id])).toEqual([
269+ [r1!.id, 1, "running", 2],
270+ [r2!.id, 2, "running", 1],
271+ ]);
272+ });
273+
274+ it("run a size this Diffinery doesn't have on a large runner", async () => {
275+ const w = world({}, ["large"]);
276+ await w.svc.queued("ann", job(1, ["diffinery-tiny"]), "tiny");
277+ await w.svc.pump("ann");
278+ expect(w.rows()[0]).toMatchObject({ size: "large" });
279+ expect(w.started[0]!.container).not.toContain(".");
280+ expect(w.started[0]!.input.vcpu).toBe(4);
281+ });
282+
283+ it("give up when GitHub refuses the runner, and try again later when GitHub is down", async () => {
284+ const w = world();
285+ w.gh.fail = new GitHubApiError(403, "GitHub answered 403 to POST repos/ann-gh/app/actions/runners/generate-jitconfig: Resource not accessible by integration");
286+ await w.svc.queued("ann", job(1), "large");
287+ await w.svc.pump("ann");
288+ expect(w.rows()[0]).toMatchObject({ status: "failed", message: expect.stringMatching(/^Could not register a runner on GitHub: .*Resource not accessible/) });
289+
290+ w.gh.fail = new GitHubApiError(502, "bad gateway");
291+ await w.svc.queued("ann", job(2), "large");
292+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
293+ expect(w.rows()[1]).toMatchObject({ status: "queued", tries: 1 });
294+ w.gh.fail = null;
295+ await w.svc.pump("ann");
296+ expect(w.rows()[1]).toMatchObject({ status: "starting", tries: 2 });
297+ });
298+
299+ it("put a runner whose container got no machine back in line, and fail one whose start can't work", async () => {
300+ const w = world();
301+ w.host.fail = new Error("there is no container instance that can be provided to this durable object");
302+ await w.svc.queued("ann", job(1), "large");
303+ expect((await w.svc.pump("ann")).next).toBe(WAIT_RETRY_MS);
304+ const row = w.rows()[0]!;
305+ expect(row).toMatchObject({ status: "queued", container: null, message: expect.stringMatching(/^Starting a runner failed; trying again/) });
306+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([{ op: "remove", args: [11, "ann-gh/app", 501] }]);
307+ expect(w.compute()[0]!.ended_at).not.toBeNull();
308+ w.host.fail = new Error("image not found");
309+ await w.svc.pump("ann");
310+ expect(w.rows()[0]).toMatchObject({ status: "failed", message: "Could not start a runner: image not found" });
311+ });
312+
313+ it("replace a runner that crashed before it took a job, a few times", async () => {
314+ const w = world();
315+ await w.svc.queued("ann", job(1), "large");
316+ for (let i = 1; i < MAX_TRIES; i++) {
317+ await w.svc.pump("ann");
318+ await w.svc.stopped(w.rows()[0]!.id, 1);
319+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: i, message: "The runner stopped before it took a job (exit code 1); starting another" });
320+ }
321+ await w.svc.pump("ann");
322+ await w.svc.stopped(w.rows()[0]!.id, 1);
323+ expect(w.rows()[0]).toMatchObject({ status: "completed", tries: MAX_TRIES, message: "The runner stopped before it took a job (exit code 1)" });
324+ expect(w.compute().every((c) => c.ended_at)).toBe(true);
325+ expect(w.started.map((s) => s.container)).toEqual([1, 2, 3].map((n) => `gh-${w.rows()[0]!.id}-${n}`));
326+ });
327+
328+ it("replace a runner whose container stopped before it took a job while GitHub still has the job queued", async () => {
329+ const w = world();
330+ await w.svc.queued("ann", job(1), "large");
331+ await w.svc.pump("ann");
332+ const first = w.rows()[0]!;
333+ // The library reports exit code 0 for a container the platform lost: the job still waits on GitHub.
334+ await w.svc.stopped(first.id, 0, first.container!);
335+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 1, container: null, message: "The runner's container stopped before it took a job; starting another" });
336+ expect(w.calls.filter((c) => c.op === "job" || c.op === "remove")).toEqual([
337+ { op: "job", args: [11, "ann-gh/app", 1] },
338+ { op: "remove", args: [11, "ann-gh/app", 501] },
339+ ]);
340+ expect(w.compute()[0]!.ended_at).not.toBeNull();
341+ // The lost container's stop again, late: the row no longer runs in it.
342+ await w.svc.stopped(first.id, 0, first.container!);
343+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 1 });
344+
345+ // GitHub doesn't answer: the job counts as queued. Without an exit code it is the same.
346+ await w.svc.pump("ann");
347+ w.gh.jobState = new GitHubApiError(502, "bad gateway");
348+ await w.svc.stopped(first.id, null, w.rows()[0]!.container!);
349+ expect(w.rows()[0]).toMatchObject({ status: "queued", tries: 2 });
350+
351+ // The job ran on another runner or was cancelled meanwhile: the row ends.
352+ await w.svc.pump("ann");
353+ w.gh.jobState = "completed";
354+ await w.svc.stopped(first.id, 0, w.rows()[0]!.container!);
355+ expect(w.rows()[0]).toMatchObject({ status: "completed", tries: 3, exit_code: 0, message: null });
356+ expect(w.started.map((s) => s.container)).toEqual([1, 2, 3].map((n) => `gh-${first.id}-${n}`));
357+
358+ // A runner that took its job and stopped isn't asked about.
359+ const v = world();
360+ await v.svc.queued("ann", job(1), "large");
361+ await v.svc.pump("ann");
362+ const row = v.rows()[0]!;
363+ await v.svc.jobEvent({ installationId: 11, githubJobId: 1, action: "in_progress", runnerName: row.runner_name, jobName: "test 1", conclusion: null });
364+ await v.svc.stopped(row.id, 0, row.container!);
365+ expect(v.rows()[0]).toMatchObject({ status: "completed", exit_code: 0 });
366+ expect(v.calls.filter((c) => c.op === "job")).toEqual([]);
367+ });
368+
369+ it("stop a runner no job took within the idle time, unless GitHub says it is busy", async () => {
370+ const w = world();
371+ await w.svc.queued("ann", job(1), "large");
372+ await w.svc.queued("ann", job(2), "large");
373+ await w.svc.pump("ann");
374+ w.clock.advance(IDLE_MS + 1000);
375+ // The first runner's in_progress webhook never came, but it has a job; the second has none.
376+ let n = 0;
377+ const runner = w.gh.runner.bind(w.gh);
378+ w.gh.runner = async (...a) => ((w.gh.busy = n++ === 0), runner(...a));
379+ await w.svc.pump("ann");
380+ const [a, b] = w.rows();
381+ expect(a).toMatchObject({ status: "running" });
382+ expect(b).toMatchObject({ status: "completed", message: expect.stringMatching(/^No job took this runner within 10 minutes/) });
383+ expect(w.stopped).toEqual([b!.container]);
384+ expect(w.calls.filter((c) => c.op === "remove")).toEqual([{ op: "remove", args: [11, "ann-gh/app", b!.github_runner_id] }]);
385+ // Its container's stop arrives afterwards and changes nothing.
386+ await w.svc.stopped(b!.id, 137);
387+ expect(w.rows()[1]).toMatchObject({ status: "completed", exit_code: null });
388+ });
389+
390+ it("stop everything for a kill switch", async () => {
391+ const w = world({ QUOTA_HOSTED_JOBS: "1" });
392+ await w.svc.queued("ann", job(1), "large");
393+ await w.svc.queued("ann", job(2), "large");
394+ await w.svc.pump("ann");
395+ expect(await w.svc.stopAll("ann", "paused")).toBe(1);
396+ expect(w.rows().map((r) => [r.status, r.message])).toEqual([
397+ ["completed", "paused"],
398+ ["failed", "paused"],
399+ ]);
400+ expect(w.stopped).toHaveLength(1);
401+ });
402+});
403+
404+// ---------------------------------------------------------------- the webhook
405+
406+function hookEnv(DB: D1Database, vars: Record<string, unknown> = APP_VARS) {
407+ const calls: Array<{ op: string; name: string; args: unknown[] }> = [];
408+ const stub = (name: string) => ({
409+ queued: async (...args: unknown[]) => void calls.push({ op: "queued", name, args }),
410+ jobEvent: async (...args: unknown[]) => void calls.push({ op: "jobEvent", name, args }),
411+ });
412+ const GITHUB_RUNNERS = { idFromName: (n: string) => n, get: (n: string) => stub(n) };
413+ return { env: { DB, GITHUB_RUNNERS, ...vars } as unknown as Env, calls };
414+}
415+
416+async function deliver(env: Env, event: string, payload: unknown, secret = "hook-secret") {
417+ const body = JSON.stringify(payload);
418+ 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);
419+}
420+
421+const queuedPayload = (labels: string[], installation = 11, action = "queued", runner_name: string | null = null) => ({
422+ action,
423+ 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" },
424+ repository: { full_name: "ann-gh/app" },
425+ installation: { id: installation },
426+});
427+
428+describe("the GitHub App's webhook", () => {
429+ it("is off without the app and refuses unsigned deliveries", async () => {
430+ const { DB } = setup();
431+ expect((await deliver(hookEnv(DB, { PUBLIC_URL: "https://diffinery.test" }).env, "ping", {})).status).toBe(404);
432+ const { env } = hookEnv(DB);
433+ expect((await deliver(env, "ping", {}, "wrong")).status).toBe(401);
434+ expect((await deliver(env, "ping", {})).status).toBe(200);
435+ });
436+
437+ it("hands queued jobs for Diffinery to the linked account, and nothing else", async () => {
438+ const { DB } = setup();
439+ const { env, calls } = hookEnv(DB);
440+ expect(await (await deliver(env, "workflow_job", queuedPayload(["diffinery-medium"]))).json()).toEqual({ queued: true, size: "medium" });
441+ expect(calls).toEqual([{ op: "queued", name: "ann", args: ["ann", expect.objectContaining({ installationId: 11, repo: "ann-gh/app", githubJobId: 99, labels: ["diffinery-medium"] }), "medium"] }]);
442+ expect(await (await deliver(env, "workflow_job", queuedPayload(["ubuntu-latest"]))).json()).toEqual({ ignored: "not for a Diffinery runner" });
443+ expect(await (await deliver(env, "workflow_job", queuedPayload(["diffinery"], 12))).json()).toEqual({ ignored: "this installation isn't linked to a Diffinery account" });
444+ await deliver(env, "workflow_job", queuedPayload(["diffinery"], 11, "in_progress", "diffinery-abc-1"));
445+ 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 }] });
446+ // Another provider's runner doesn't count as Diffinery's.
447+ await deliver(env, "workflow_job", queuedPayload(["diffinery"], 11, "completed", "hosted-runner-7"));
448+ expect(calls[2]!.args[1]).toMatchObject({ action: "completed", runnerName: null });
449+ expect(calls).toHaveLength(3);
450+ });
451+
452+ it("follows the installation: suspended, renamed, uninstalled", async () => {
453+ const { DB } = setup();
454+ const { env } = hookEnv(DB);
455+ const inst = () => DB.sqlite.prepare("SELECT * FROM github_installations WHERE id = 11").get() as { suspended_at: string | null; github_login: string } | undefined;
456+ await deliver(env, "installation", { action: "suspend", installation: { id: 11 } });
457+ expect(inst()!.suspended_at).not.toBeNull();
458+ await deliver(env, "installation", { action: "unsuspend", installation: { id: 11 } });
459+ expect(inst()!.suspended_at).toBeNull();
460+ await deliver(env, "installation_target", { action: "renamed", installation: { id: 11, account: { login: "ann-new" } } });
461+ expect(inst()!.github_login).toBe("ann-new");
462+ await deliver(env, "installation", { action: "deleted", installation: { id: 11 } });
463+ expect(inst()).toBeUndefined();
464+ });
465+});
466+
467+// ---------------------------------------------------------------- linking an installation
468+
469+function linking(installations: Array<{ id: number; account: { login: string; type: string } }>) {
470+ const s = setup({ ...APP_VARS, GITHUB_RUNNERS: {} });
471+ const audits: Array<{ action: string; target?: string; detail?: unknown }> = [];
472+ const accounts = { ann: { id: "ann", login: "ann", kind: "user" }, bob: { id: "bob", login: "bob", kind: "user" } } as const;
473+ const dir = {
474+ orgsFor: async (id: string) => (id === "ann" ? [{ id: "acme", login: "acme", kind: "org", role: "owner" }] : []),
475+ audit: async (e: { action: string; target?: string; detail?: unknown }) => void audits.push(e),
476+ } as unknown as Directory;
477+ const requests: string[] = [];
478+ const fetcher = (async (input: string, init?: RequestInit) => {
479+ requests.push(`${init?.method ?? "GET"} ${input}`);
480+ if (input === "https://github.com/login/oauth/access_token") {
481+ const code = (JSON.parse(String(init!.body)) as { code: string }).code;
482+ return Response.json(code === "good" ? { access_token: "ghu_x" } : { error_description: "bad code" });
483+ }
484+ if (input.startsWith("https://api.github.com/user/installations")) return Response.json({ installations });
485+ return new Response("not found", { status: 404 });
486+ }) as typeof fetch;
487+ const links = new GitHubRunnerLinks(s.env, dir, fetcher);
488+ const stateOf = (url: string) => new URL(url).searchParams.get("state")!;
489+ const linked = () => s.DB.sqlite.prepare("SELECT id, account_id, github_login FROM github_installations ORDER BY id").all();
490+ return { ...s, links, audits, requests, stateOf, linked, ann: accounts.ann as never, bob: accounts.bob as never };
491+}
492+
493+describe("linking an installation", () => {
494+ it("installs on GitHub for an account the person manages, and links what GitHub says they can manage", async () => {
495+ const l = linking([{ id: 42, account: { login: "acme-gh", type: "Organization" } }]);
496+ const install = await l.links.installUrl(l.ann, "acme");
497+ expect(install).toMatch(/^https:\/\/github\.com\/apps\/diffinery-runners\/installations\/new\?state=/);
498+ // No code (user authorization during installation is off): authorize the app first.
499+ const r1 = await l.links.setup(l.ann, { installationId: 42, code: null, state: l.stateOf(install) });
500+ if (!("redirect" in r1)) throw new Error("expected a redirect");
501+ 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/);
502+ const r2 = await l.links.setup(l.ann, { installationId: null, code: "good", state: l.stateOf(r1.redirect) });
503+ expect(r2).toMatchObject({ linked: { id: 42, account_id: "acme", github_login: "acme-gh", github_type: "Organization", linked_by: "ann" } });
504+ expect(l.audits).toEqual([{ actorId: "ann", actorLogin: "ann", action: "github_runners.link", target: "acme", detail: { installation: 42, github: "acme-gh" } }]);
505+ });
506+
507+ it("refuses an installation the person can't manage on GitHub, an account they don't manage, and someone else's state", async () => {
508+ const l = linking([{ id: 42, account: { login: "acme-gh", type: "Organization" } }]);
509+ const state = l.stateOf(await l.links.installUrl(l.ann, "ann"));
510+ await expect(l.links.setup(l.ann, { installationId: 43, code: "good", state })).rejects.toThrow(/can't manage that installation/);
511+ await expect(l.links.installUrl(l.bob, "acme")).rejects.toThrow(/only to your own account or an organization you own or administer/);
512+ await expect(l.links.setup(l.bob, { installationId: 42, code: "good", state })).rejects.toThrow(/made for someone else/);
513+ await expect(l.links.setup(l.ann, { installationId: 42, code: "good", state: state.slice(0, -2) + "xx" })).rejects.toThrow(/not valid/);
514+ await expect(l.links.setup(l.ann, { installationId: 42, code: "bad", state })).rejects.toThrow(/did not sign you in: bad code/);
515+ expect(l.linked()).toEqual([{ id: 11, account_id: "ann", github_login: "ann-gh" }]);
516+ });
517+
518+ it("never uses a code that came without the person's own state, and links a picked installation to the account they pick", async () => {
519+ const l = linking([
520+ { id: 11, account: { login: "ann-gh", type: "User" } },
521+ { id: 42, account: { login: "acme-gh", type: "Organization" } },
522+ ]);
523+ // A code without a state may be another GitHub user's: authorize again with the person's own.
524+ const r1 = await l.links.setup(l.ann, { installationId: 42, code: "someone-elses", state: null });
525+ if (!("redirect" in r1)) throw new Error("expected a redirect");
526+ expect(l.requests).toEqual([]);
527+ const r2 = await l.links.setup(l.ann, { installationId: null, code: "good", state: l.stateOf(r1.redirect) });
528+ if (!("choose" in r2)) throw new Error("expected a choice");
529+ expect(r2.choose.map((i) => [i.id, i.login, i.linkedTo])).toEqual([
530+ [11, "ann-gh", "ann"],
531+ [42, "acme-gh", null],
532+ ]);
533+ expect(l.linked()).toHaveLength(1);
534+ const proof = r2.choose[1]!.proof;
535+ await expect(l.links.linkWithProof(l.bob, proof, "bob")).rejects.toThrow(/made for someone else/);
536+ await expect(l.links.linkWithProof(l.ann, proof, "bob")).rejects.toThrow(/only to your own account/);
537+ await l.links.linkWithProof(l.ann, proof, "acme");
538+ expect(l.linked()).toEqual([
539+ { id: 11, account_id: "ann", github_login: "ann-gh" },
540+ { id: 42, account_id: "acme", github_login: "acme-gh" },
541+ ]);
542+ });
543+
544+ it("unlinks: jobs waiting for a runner get none", async () => {
545+ const l = linking([]);
546+ l.DB.sqlite
547+ .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', ?)")
548+ .run(at);
549+ await expect(l.links.unlink(l.bob, 11)).rejects.toThrow(/only to your own account/);
550+ await l.links.unlink(l.ann, 11);
551+ expect(l.linked()).toEqual([]);
552+ expect(l.DB.sqlite.prepare("SELECT status, message FROM github_runner_jobs").get()).toEqual({ status: "skipped", message: "The GitHub installation was unlinked" });
553+ expect(l.audits.at(-1)).toMatchObject({ action: "github_runners.unlink", target: "ann", detail: { installation: 11, github: "ann-gh" } });
554+ });
555+});
modifiedapps/diffinery/test/unit/image.test.ts+2−2View file
@@ -3,8 +3,8 @@
33 import encodeJpeg, { init as initJpegEncode } from "@jsquash/jpeg/encode.js";
44 import decodeWebpWasm, { init as initWebpDecode } from "@jsquash/webp/decode.js";
55 import encodeWebp from "@jsquash/webp/encode.js";
6-import JPEG_ENC_WASM from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm?module";
7-import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm?module";
6+import JPEG_ENC_WASM from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm";
7+import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm";
88 import { AVATAR_SIZES, MAX_AVATAR_BYTES, cropAndShrink, imageSize, jpegOrientation, makeAvatarImages, orientSquare, shrinkFactor, sniffImage, squareCrop, type Pixels } from "../../src/lib/image.js";
99 import { HttpError } from "../../src/lib/util.js";
1010
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/rate-limit.test.ts+93−2View file
@@ -1,8 +1,9 @@
11 import { readFileSync } from "node:fs";
2-import { describe, expect, it } from "vitest";
2+import { afterEach, describe, expect, it, vi } from "vitest";
33 import type { Env } from "../../src/env.js";
44 import type { Principal } from "../../src/auth/principal.js";
5-import { bucketsFor, MODEL_RATE_LIMIT, modelRateLimited, overLimit, RATE_LIMITS, RATE_PERIOD_S, type RateLimiter } from "../../src/lib/rate-limit.js";
5+import { bucketsFor, MODEL_RATE_LIMIT, modelRateLimited, overLimit, RATE_LIMITER_SHARDS, rateLimiterShard, RATE_LIMITS, RATE_PERIOD_S, type RateLimiter } from "../../src/lib/rate-limit.js";
6+import { RateLimiterDO } from "../../src/rate-limiter.js";
67
78 const anon: Principal = { type: "anonymous" };
89 const person = { type: "account", account: { id: "u1" }, via: "token", scopes: ["write"], repoIds: null } as unknown as Principal;
@@ -140,3 +141,93 @@
140141 expect(bucketsFor("POST", "/-/model/anthropic/v1/messages", person, "203.0.113.9")).toEqual([]);
141142 });
142143 });
144+
145+/** A RATE_LIMITER namespace of real RateLimiterDO objects, recording which object each call reached. */
146+function limiterObjects(fail = false) {
147+ const objects = new Map<string, RateLimiterDO>();
148+ const calls: string[] = [];
149+ const ns = {
150+ idFromName: (name: string) => name,
151+ get: (name: string) => ({
152+ hit: async (key: string, limits: Array<[string, number]>) => {
153+ calls.push(name);
154+ if (fail) throw new Error("object unreachable");
155+ if (!objects.has(name)) objects.set(name, new RateLimiterDO({} as DurableObjectState, {} as Env));
156+ return objects.get(name)!.hit(key, limits);
157+ },
158+ }),
159+ };
160+ return { ns, calls };
161+}
162+
163+describe("the Durable Object fallback (RATE_LIMITS=durable)", () => {
164+ afterEach(() => vi.useRealTimers());
165+
166+ it("counts buckets without a binding at the production limits, one object call per request", async () => {
167+ const { ns, calls } = limiterObjects();
168+ const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env;
169+ const sign = bucketsFor("POST", "/signup", anon, "203.0.113.9");
170+ for (let i = 0; i < RATE_LIMITS.RL_AUTH; i++) expect(await overLimit(env, sign)).toBeNull();
171+ expect(await overLimit(env, sign)).toBe("RL_AUTH");
172+ expect(await overLimit(env, bucketsFor("POST", "/signup", anon, "203.0.113.10"))).toBeNull();
173+ // An account's request and its new content share a key: one call counts both buckets.
174+ calls.length = 0;
175+ const create = bucketsFor("POST", "/api/v3/repos/acme/app/issues", person, "x");
176+ for (let i = 0; i < RATE_LIMITS.RL_CREATE; i++) expect(await overLimit(env, create)).toBeNull();
177+ expect(await overLimit(env, create)).toBe("RL_CREATE");
178+ expect(calls).toHaveLength(RATE_LIMITS.RL_CREATE + 1);
179+ expect(new Set(calls)).toEqual(new Set([rateLimiterShard("acct:u1")]));
180+ });
181+
182+ it("starts a new count every window", async () => {
183+ vi.useFakeTimers({ toFake: ["Date"] });
184+ vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, 0));
185+ const { ns } = limiterObjects();
186+ const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env;
187+ const b = bucketsFor("POST", "/signup", anon, "203.0.113.9");
188+ for (let i = 0; i < RATE_LIMITS.RL_AUTH; i++) await overLimit(env, b);
189+ expect(await overLimit(env, b)).toBe("RL_AUTH");
190+ vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, RATE_PERIOD_S - 1));
191+ expect(await overLimit(env, b)).toBe("RL_AUTH");
192+ vi.setSystemTime(Date.UTC(2026, 9, 30, 12, 0, RATE_PERIOD_S));
193+ expect(await overLimit(env, b)).toBeNull();
194+ });
195+
196+ it("limits model requests per paying person", async () => {
197+ const { ns } = limiterObjects();
198+ const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env;
199+ for (let i = 0; i < MODEL_RATE_LIMIT; i++) expect(await modelRateLimited(env, "p1")).toBe(false);
200+ expect(await modelRateLimited(env, "p1")).toBe(true);
201+ expect(await modelRateLimited(env, "p2")).toBe(false);
202+ });
203+
204+ it("uses a binding where there is one, and is off unless RATE_LIMITS is durable", async () => {
205+ const { ns, calls } = limiterObjects();
206+ const bound = { RATE_LIMITS: "durable", RATE_LIMITER: ns, RL_ANON: limiter(1) } as unknown as Env;
207+ expect(await overLimit(bound, [["RL_ANON", "ip:x"]])).toBeNull();
208+ expect(await overLimit(bound, [["RL_ANON", "ip:x"]])).toBe("RL_ANON");
209+ expect(await modelRateLimited({ RATE_LIMITER: ns } as unknown as Env, "p1")).toBe(false);
210+ expect(await overLimit({ RATE_LIMITER: ns } as unknown as Env, [["RL_AUTH", "ip:x"]])).toBeNull();
211+ expect(calls).toEqual([]);
212+ });
213+
214+ it("lets requests through when the object fails", async () => {
215+ const { ns, calls } = limiterObjects(true);
216+ const env = { RATE_LIMITS: "durable", RATE_LIMITER: ns } as unknown as Env;
217+ expect(await overLimit(env, [["RL_AUTH", "ip:x"]])).toBeNull();
218+ expect(await modelRateLimited(env, "p1")).toBe(false);
219+ expect(calls).toHaveLength(2);
220+ });
221+
222+ it("spreads keys over a fixed set of objects", () => {
223+ const shards = new Set(Array.from({ length: 2000 }, (_, i) => rateLimiterShard(`ip:198.51.${i >> 8}.${i & 255}`)));
224+ expect(shards.size).toBe(RATE_LIMITER_SHARDS);
225+ expect(rateLimiterShard("acct:u1")).toBe(rateLimiterShard("acct:u1"));
226+ });
227+
228+ it("is bound in wrangler.jsonc, for production and local development", () => {
229+ const text = readFileSync(new URL("../../wrangler.jsonc", import.meta.url), "utf8");
230+ expect(text.match(/\{ "name": "RATE_LIMITER", "class_name": "RateLimiterDO" \}/g)).toHaveLength(2);
231+ expect(text).toMatch(/"new_sqlite_classes": \["RateLimiterDO"\]/);
232+ });
233+});
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"]);
addedapps/diffinery/test/unit/runner-containers.test.ts+60−0View file
@@ -1,0 +1,60 @@
1+import { describe, expect, it, vi } from "vitest";
2+import type { Env } from "../../src/env.js";
3+
4+// The containers library's Container, with a start() each test gives: the real one needs the Workers runtime.
5+const lib = vi.hoisted(() => ({ start: async (_self: { onStop(p: { exitCode?: number; reason: string }): Promise<void> }): Promise<void> => {} }));
6+vi.mock("@cloudflare/containers", () => ({
7+ Container: class {
8+ constructor(
9+ protected ctx: unknown,
10+ protected env: unknown,
11+ ) {}
12+ async start(): Promise<void> {
13+ await lib.start(this as never);
14+ }
15+ async setAllowedHosts(): Promise<void> {}
16+ },
17+}));
18+
19+const { RunnerContainer } = await import("../../src/runner/containers.js");
20+
21+function runner() {
22+ const kept = new Map<string, unknown>();
23+ const ctx = {
24+ storage: {
25+ kv: { get: () => undefined, put: () => {} },
26+ put: async (k: string, v: unknown) => void kept.set(k, v),
27+ get: async (k: string) => kept.get(k),
28+ delete: async (k: string) => kept.delete(k),
29+ },
30+ };
31+ const stops: unknown[][] = [];
32+ const env = { GITHUB_RUNNERS: { idFromName: (n: string) => n, get: () => ({ stopped: async (...a: unknown[]) => void stops.push(a) }) } };
33+ return { c: new RunnerContainer(ctx as never, env as unknown as Env), stops, kept };
34+}
35+
36+const input = { accountId: "ann", runnerId: "row1", container: "gh-row1-1", jitConfig: "jit", egress: "open" as const, vcpu: 4 };
37+
38+describe("a GitHub runner's container", () => {
39+ it("isn't reported stopped while its start is still under way", async () => {
40+ const { c, stops } = runner();
41+ // The platform had no machine for the first try: the library's alarm reports the container stopped with
42+ // exit code 0 while start() tries again, and the second try starts it.
43+ lib.start = async (self) => self.onStop({ exitCode: 0, reason: "exit" });
44+ await c.startGitHubRunner(input);
45+ expect(stops).toEqual([]);
46+ // Its real stop, after the job, with the container that stopped.
47+ await c.onStop({ exitCode: 0, reason: "exit" });
48+ expect(stops).toEqual([["ann", "row1", 0, "gh-row1-1"]]);
49+ });
50+
51+ it("is reported stopped after a start that failed", async () => {
52+ const { c, stops } = runner();
53+ lib.start = async () => {
54+ throw new Error("there is no container instance that can be provided to this durable object");
55+ };
56+ await expect(c.startGitHubRunner(input)).rejects.toThrow(/no container instance/);
57+ await c.onStop({ exitCode: 1, reason: "exit" });
58+ expect(stops).toEqual([["ann", "row1", 1, "gh-row1-1"]]);
59+ });
60+});
addedapps/diffinery/test/unit/smtp.test.ts+367−0View file
@@ -1,0 +1,367 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import type { Env } from "../../src/env.js";
3+import { deliver, mailTransport, RetryableMailError, type Outgoing } from "../../src/mail/send.js";
4+import { formatMessage, sendSmtp, SmtpError, smtpConfig, smtpLabel, type SmtpConfig } from "../../src/mail/smtp.js";
5+import { Suppressions } from "../../src/mail/suppression.js";
6+import type { MailJob } from "../../src/mail/types.js";
7+import { setConnect } from "./stubs/cloudflare-sockets.js";
8+import { testD1 } from "./stubs/d1.js";
9+
10+const enc = new TextEncoder();
11+const PASSWORD = "hunter2-very-secret";
12+const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
13+
14+type Verb = "STARTTLS" | "AUTH" | "MAIL" | "RCPT" | "DATA" | "END";
15+
16+/**
17+ * A fake SMTP server behind a fake socket: it answers each command as a submission server would,
18+ * or with the reply a test sets for that step ("CLOSE" hangs up instead), and records the commands
19+ * and the message. Replies go out as soon as a command is written, so nothing here waits on time.
20+ */
21+class FakeSmtp {
22+ commands: string[] = [];
23+ data = "";
24+ connects: Array<{ address: unknown; options: unknown }> = [];
25+ upgrades = 0;
26+ private out: (s: string) => void = () => {};
27+ private hangUp: () => void = () => {};
28+ private buf = "";
29+ private inData = false;
30+ private loginStep = 0;
31+ private tls = false;
32+
33+ constructor(
34+ private s: {
35+ silent?: boolean;
36+ /** Extensions after TLS (default PIPELINING, AUTH PLAIN LOGIN, ENHANCEDSTATUSCODES) and before it (default STARTTLS). */
37+ ehlo?: string[];
38+ ehloPlain?: string[];
39+ reply?: Partial<Record<Verb, string>>;
40+ } = {},
41+ ) {}
42+
43+ connect = (address: unknown, options?: { secureTransport?: string }): Socket => {
44+ this.connects.push({ address, options });
45+ this.tls = options?.secureTransport === "on";
46+ const socket = this.socket();
47+ if (!this.s.silent) this.send("220 smtp.example ESMTP");
48+ return socket;
49+ };
50+
51+ private socket(): Socket {
52+ const dec = new TextDecoder();
53+ let ctrl!: ReadableStreamDefaultController<Uint8Array>;
54+ const readable = new ReadableStream<Uint8Array>({ start: (c) => void (ctrl = c) });
55+ this.out = (s) => ctrl.enqueue(enc.encode(s));
56+ this.hangUp = () => {
57+ try {
58+ ctrl.close();
59+ } catch {
60+ // already closed
61+ }
62+ };
63+ const writable = new WritableStream<Uint8Array>({ write: (chunk) => this.receive(dec.decode(chunk, { stream: true })) });
64+ const startTls = () => {
65+ this.upgrades++;
66+ this.tls = true;
67+ return this.socket();
68+ };
69+ return { readable, writable, opened: Promise.resolve({}), closed: Promise.resolve(), close: async () => this.hangUp(), startTls } as unknown as Socket;
70+ }
71+
72+ private send(s: string): void {
73+ if (s === "CLOSE") this.hangUp();
74+ else this.out(`${s}\r\n`);
75+ }
76+
77+ private receive(text: string): void {
78+ this.buf += text;
79+ for (let i = this.buf.indexOf("\r\n"); i >= 0; i = this.buf.indexOf("\r\n")) {
80+ const line = this.buf.slice(0, i);
81+ this.buf = this.buf.slice(i + 2);
82+ if (this.inData) {
83+ if (line === ".") {
84+ this.inData = false;
85+ this.send(this.s.reply?.END ?? "250 2.0.0 Ok: queued as ABC123");
86+ } else this.data += `${line.startsWith(".") ? line.slice(1) : line}\r\n`;
87+ } else this.command(line);
88+ }
89+ }
90+
91+ private command(line: string): void {
92+ this.commands.push(line);
93+ const r = this.s.reply ?? {};
94+ if (this.loginStep === 1) {
95+ this.loginStep = 2;
96+ return this.send("334 UGFzc3dvcmQ6");
97+ }
98+ if (this.loginStep === 2) {
99+ this.loginStep = 0;
100+ return this.send(r.AUTH ?? "235 2.7.0 Authentication successful");
101+ }
102+ const verb = line.split(" ")[0]!.toUpperCase();
103+ if (verb === "EHLO") {
104+ const ext = this.tls ? (this.s.ehlo ?? ["PIPELINING", "AUTH PLAIN LOGIN", "ENHANCEDSTATUSCODES"]) : (this.s.ehloPlain ?? ["STARTTLS", "ENHANCEDSTATUSCODES"]);
105+ const lines = ["smtp.example Hello", ...ext];
106+ return this.send(lines.map((l, i) => `250${i === lines.length - 1 ? " " : "-"}${l}`).join("\r\n"));
107+ }
108+ if (verb === "STARTTLS") return this.send(r.STARTTLS ?? "220 2.0.0 Ready to start TLS");
109+ if (line === "AUTH LOGIN") {
110+ this.loginStep = 1;
111+ return this.send("334 VXNlcm5hbWU6");
112+ }
113+ if (verb === "AUTH") return this.send(r.AUTH ?? "235 2.7.0 Authentication successful");
114+ if (verb === "MAIL") return this.send(r.MAIL ?? "250 2.1.0 Ok");
115+ if (verb === "RCPT") return this.send(r.RCPT ?? "250 2.1.5 Ok");
116+ if (verb === "DATA") {
117+ const reply = r.DATA ?? "354 End data with <CR><LF>.<CR><LF>";
118+ this.inData = reply.startsWith("354");
119+ return this.send(reply);
120+ }
121+ if (verb === "QUIT") return this.send("221 2.0.0 Bye");
122+ this.send("500 5.5.2 Unknown command");
123+ }
124+
125+ /** The decoded text/plain or text/html part of the message the server received. */
126+ part(type: "plain" | "html"): string {
127+ const m = new RegExp(`Content-Type: text/${type}; charset=utf-8\\r\\nContent-Transfer-Encoding: base64\\r\\n\\r\\n([\\s\\S]*?)\\r\\n--`).exec(this.data);
128+ return Buffer.from(m![1]!.replace(/\r\n/g, ""), "base64").toString("utf8");
129+ }
130+}
131+
132+const msg = (over: Partial<Outgoing> = {}): Outgoing => ({
133+ from: { name: "Ann (Diffinery)", email: "[email protected]" },
134+ to: { name: "Bob", email: "[email protected]" },
135+ subject: "Your test email",
136+ html: "<p>Hello <b>Bob</b></p>",
137+ text: "Hello Bob\n.a line that starts with a dot",
138+ headers: { "X-Diffinery-Reason": "account", "List-Unsubscribe": "<https://diffinery.example/u/x>" },
139+ ...over,
140+});
141+
142+const implicit: SmtpConfig = { host: "smtp.example", port: 465, tls: "implicit", user: "[email protected]", password: PASSWORD };
143+const starttls: SmtpConfig = { ...implicit, port: 587, tls: "starttls" };
144+
145+function server(s: ConstructorParameters<typeof FakeSmtp>[0] = {}): FakeSmtp {
146+ const f = new FakeSmtp(s);
147+ setConnect(f.connect);
148+ return f;
149+}
150+
151+afterEach(() => {
152+ setConnect(null);
153+ vi.restoreAllMocks();
154+});
155+
156+describe("SMTP settings", () => {
157+ it("reads SMTP_URL and SMTP_PASSWORD", () => {
158+ expect(smtpConfig({})).toBeNull();
159+ expect(smtpConfig({ SMTP_URL: "smtps://ann%[email protected]", SMTP_PASSWORD: PASSWORD })).toEqual(implicit);
160+ expect(smtpConfig({ SMTP_URL: "smtp://ann%[email protected]", SMTP_PASSWORD: PASSWORD })).toEqual(starttls);
161+ expect(smtpConfig({ SMTP_URL: "smtps://relay.example:2465" })).toEqual({ host: "relay.example", port: 2465, tls: "implicit", user: null, password: null });
162+ expect(smtpConfig({ SMTP_URL: "smtp://[::1]:1587" })).toMatchObject({ host: "::1", port: 1587 });
163+ });
164+
165+ it("says what is wrong, and never takes a password from the URL", () => {
166+ expect(smtpConfig({ SMTP_URL: "smtps://ann:[email protected]" })).toEqual({ error: "the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" });
167+ expect(smtpConfig({ SMTP_URL: "https://smtp.example" })).toEqual({ error: "SMTP_URL must start with smtps:// or smtp://" });
168+ expect(smtpConfig({ SMTP_URL: "smtps://[email protected]" })).toEqual({ error: "SMTP_URL names a user but the SMTP_PASSWORD secret is not set" });
169+ expect(smtpConfig({ SMTP_URL: "smtps://smtp.example", SMTP_PASSWORD: PASSWORD })).toEqual({ error: "SMTP_PASSWORD is set but SMTP_URL names no user" });
170+ expect(smtpConfig({ SMTP_URL: "smtps://smtp.example/x?y" })).toEqual({ error: "SMTP_URL takes no path or query" });
171+ });
172+
173+ it("shows administrators the server but not the password", () => {
174+ expect(smtpLabel(implicit)).toBe("smtps://ann%[email protected]:465");
175+ expect(smtpLabel(starttls)).toBe("smtp://ann%[email protected]:587 (STARTTLS)");
176+ });
177+
178+ it("prefers the EMAIL binding when both are there", () => {
179+ const EMAIL = { send: async () => ({ messageId: "x" }) } as unknown as SendEmail;
180+ expect(mailTransport({ EMAIL, SMTP_URL: "smtps://smtp.example" })?.kind).toBe("email-sending");
181+ expect(mailTransport({ SMTP_URL: "smtps://smtp.example" })?.kind).toBe("smtp");
182+ expect(mailTransport({})).toBeNull();
183+ });
184+});
185+
186+describe("the MIME message", () => {
187+ const date = new Date("2026-10-30T12:00:00Z");
188+
189+ it("has the headers, and the text and HTML parts in base64, with CRLF line ends", () => {
190+ const m = formatMessage(msg({ replyTo: "[email protected]" }), { messageId: "<[email protected]>", date, boundary: "b" });
191+ expect(m.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/);
192+ const [head] = m.split("\r\n\r\n");
193+ expect(head!.split("\r\n")).toEqual([
194+ 'From: "Ann (Diffinery)" <[email protected]>',
195+ 'To: "Bob" <[email protected]>',
196+ "Reply-To: [email protected]",
197+ "Subject: Your test email",
198+ "Date: Fri, 30 Oct 2026 12:00:00 +0000",
199+ "Message-ID: <[email protected]>",
200+ "MIME-Version: 1.0",
201+ "X-Diffinery-Reason: account",
202+ "List-Unsubscribe: <https://diffinery.example/u/x>",
203+ 'Content-Type: multipart/alternative; boundary="b"',
204+ ]);
205+ expect(m).toContain(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64(msg().text)}\r\n--b\r\n`);
206+ expect(m).toContain(`Content-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64(msg().html)}\r\n--b--\r\n`);
207+ });
208+
209+ it("encodes non-ASCII names and subjects, and keeps out injected headers", () => {
210+ const m = formatMessage(
211+ msg({ subject: "Ünal commented on acme/website#12 — a long subject that needs more than one encoded word", to: { name: "Bob Ünal", email: "[email protected]" }, headers: { "X-Evil\r\nBcc": "x", "X-Ok": "a\r\nBcc: [email protected]", Subject: "twice" } }),
212+ { messageId: "<id@x>", date },
213+ );
214+ const head = m.split("\r\n\r\n")[0]!;
215+ const decode = (s: string) => s.replace(/\r\n /g, "").replace(/=\?UTF-8\?B\?([^?]*)\?=/g, (_, w: string) => Buffer.from(w, "base64").toString("utf8"));
216+ expect(decode(/^Subject: (.*(?:\r\n .*)*)/m.exec(head)![1]!)).toBe("Ünal commented on acme/website#12 — a long subject that needs more than one encoded word");
217+ expect(/^Subject: .*(?:\r\n .*)*/m.exec(head)![0].split("\r\n").every((l) => l.length <= 78)).toBe(true);
218+ expect(decode(/^To: (.*)/m.exec(head)![1]!)).toBe("Bob Ünal <[email protected]>");
219+ expect(head).toContain("X-Ok: a Bcc: [email protected]");
220+ expect(head).not.toMatch(/^Bcc/m);
221+ expect(head.match(/^Subject:/gm)).toHaveLength(1);
222+ });
223+});
224+
225+describe("sending over SMTP", () => {
226+ it("sends over implicit TLS with AUTH PLAIN", async () => {
227+ const f = server();
228+ const r = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" });
229+ expect(f.connects).toEqual([{ address: { hostname: "smtp.example", port: 465 }, options: { secureTransport: "on", allowHalfOpen: false } }]);
230+ expect(f.commands).toEqual(["EHLO diffinery.example", `AUTH PLAIN ${b64(`\[email protected]\0${PASSWORD}`)}`, "MAIL FROM:<[email protected]>", "RCPT TO:<[email protected]>", "DATA", "QUIT"]);
231+ expect(r.messageId).toMatch(/^<[0-9a-f-]{36}@diffinery\.example>$/);
232+ expect(f.data).toContain(`Message-ID: ${r.messageId}\r\n`);
233+ expect(f.part("plain")).toBe(msg().text);
234+ expect(f.part("html")).toBe(msg().html);
235+ });
236+
237+ it("upgrades with STARTTLS before anything else, and falls back to AUTH LOGIN", async () => {
238+ const f = server({ ehlo: ["AUTH LOGIN"] });
239+ await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" });
240+ expect(f.connects[0]).toEqual({ address: { hostname: "smtp.example", port: 587 }, options: { secureTransport: "starttls", allowHalfOpen: false } });
241+ expect(f.upgrades).toBe(1);
242+ expect(f.commands.slice(0, 6)).toEqual(["EHLO diffinery.example", "STARTTLS", "EHLO diffinery.example", "AUTH LOGIN", b64("[email protected]"), b64(PASSWORD)]);
243+ });
244+
245+ it("won't send the password without TLS", async () => {
246+ const f = server({ ehloPlain: ["AUTH PLAIN LOGIN"] });
247+ const err = await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" }).catch((e: SmtpError) => e);
248+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED", message: "SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS" });
249+ expect(f.commands).toEqual(["EHLO diffinery.example"]);
250+ });
251+
252+ it("ignores anything the server sent before TLS started", async () => {
253+ // A man in the middle appends a reply to the 220; read after the upgrade, it would answer the second EHLO.
254+ const f = server({ reply: { STARTTLS: "220 2.0.0 go ahead\r\n250 injected" } });
255+ await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" });
256+ expect(f.commands.slice(2, 4)).toEqual(["EHLO diffinery.example", `AUTH PLAIN ${b64(`\[email protected]\0${PASSWORD}`)}`]);
257+ });
258+
259+ it("sends without AUTH when SMTP_URL names no user", async () => {
260+ const f = server();
261+ await sendSmtp({ ...implicit, user: null, password: null }, msg(), { ehlo: "diffinery.example" });
262+ expect(f.commands[1]).toBe("MAIL FROM:<[email protected]>");
263+ });
264+
265+ it.each([
266+ ["RCPT", "550 5.1.1 <[email protected]>: Recipient address rejected: User unknown", "E_SMTP_RECIPIENT_REJECTED"],
267+ ["RCPT", "550 Mailbox not found", "E_SMTP_RECIPIENT_REJECTED"],
268+ ["RCPT", "550 5.7.1 Relaying denied", "E_SMTP_REJECTED"],
269+ ["RCPT", "552 5.2.2 Mailbox full", "E_SMTP_REJECTED"],
270+ ["RCPT", "451 4.3.0 Try again later", "E_SMTP_TRANSIENT"],
271+ ["MAIL", "550 5.1.8 Sender address rejected", "E_SMTP_REJECTED"],
272+ ["MAIL", "421 4.7.0 Too many connections", "E_SMTP_TRANSIENT"],
273+ ["END", "554 5.6.0 Message rejected", "E_SMTP_REJECTED"],
274+ ["DATA", "CLOSE", "E_SMTP_TRANSIENT"],
275+ ] as const)("maps %s %s to %s", async (verb, reply, code) => {
276+ server({ reply: { [verb]: reply } });
277+ const err = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e);
278+ expect(err).toBeInstanceOf(SmtpError);
279+ expect((err as SmtpError).code).toBe(code);
280+ });
281+
282+ it("never puts the password in an error", async () => {
283+ server({ reply: { AUTH: "535 5.7.8 Authentication credentials invalid" } });
284+ const err = (await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e)) as SmtpError;
285+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED", message: "SMTP AUTH: 535 5.7.8 Authentication credentials invalid" });
286+ const login = server({ ehlo: ["AUTH LOGIN"], reply: { AUTH: "535 5.7.8 nope" } });
287+ const err2 = (await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e)) as SmtpError;
288+ expect(login.commands).toContain(b64(PASSWORD));
289+ for (const e of [err, err2]) for (const secret of [PASSWORD, b64(PASSWORD), b64(`\[email protected]\0${PASSWORD}`)]) expect(`${e.message} ${e.stack}`).not.toContain(secret);
290+ });
291+
292+ it("gives up on a server that doesn't answer", async () => {
293+ server({ silent: true });
294+ const err = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example", timeoutMs: 5 }).catch((e: unknown) => e);
295+ expect(err).toMatchObject({ code: "E_SMTP_TRANSIENT", message: "SMTP greeting: no answer from the server in 0.005 seconds" });
296+ });
297+
298+ it("refuses an address that would break the command", async () => {
299+ const f = server();
300+ const err = await sendSmtp(implicit, msg({ to: "[email protected]>\r\nRCPT TO:<[email protected]" }), { ehlo: "diffinery.example" }).catch((e: unknown) => e);
301+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED" });
302+ expect(f.connects).toEqual([]);
303+ });
304+});
305+
306+describe("deliver() over SMTP", () => {
307+ const at = "2026-10-01T00:00:00.000Z";
308+ const job: MailJob = { kind: "test", data: { by: "ann" }, to: { accountId: "ann" }, reason: "account", at } as MailJob;
309+
310+ function setup(vars: Partial<Env> = { SMTP_URL: "smtps://ann%[email protected]", SMTP_PASSWORD: PASSWORD }) {
311+ const DB = testD1();
312+ DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, email, status, created_at) VALUES ('ann', 'ann', 'user', '[email protected]', 'active', ?)").run(at);
313+ const env = { DB, PUBLIC_URL: "https://diffinery.example", MASTER_KEY: "test-master-key", MAIL_FROM: "[email protected]", ...vars } as unknown as Env;
314+ const log = () => DB.sqlite.prepare("SELECT to_addr, status, detail, message_id FROM email_log ORDER BY rowid").all() as Array<{ to_addr: string; status: string; detail: string | null; message_id: string | null }>;
315+ return { env, log };
316+ }
317+
318+ it("sends through SMTP_URL when there is no EMAIL binding", async () => {
319+ const f = server();
320+ const { env, log } = setup();
321+ const r = await deliver(env, job);
322+ expect(r.status).toBe("sent");
323+ expect(f.commands).toContain("RCPT TO:<[email protected]>");
324+ expect(log()).toEqual([{ to_addr: "[email protected]", status: "sent", detail: null, message_id: r.messageId }]);
325+ });
326+
327+ it("suppresses an address the server says doesn't exist", async () => {
328+ server({ reply: { RCPT: "550 5.1.1 User unknown" } });
329+ const { env, log } = setup();
330+ expect(await deliver(env, job)).toEqual({ status: "failed", detail: "E_SMTP_RECIPIENT_REJECTED: SMTP RCPT TO: 550 5.1.1 User unknown" });
331+ expect(await new Suppressions(env.DB).get("[email protected]")).toMatchObject({ reason: "hard-bounce", source: "send", detail: "The SMTP server refused it: E_SMTP_RECIPIENT_REJECTED: SMTP RCPT TO: 550 5.1.1 User unknown" });
332+ expect(log()[0]).toMatchObject({ status: "failed" });
333+ });
334+
335+ it("retries a temporary failure, and suppresses nothing", async () => {
336+ server({ reply: { MAIL: "421 4.7.0 Try again later" } });
337+ const { env, log } = setup();
338+ await expect(deliver(env, job)).rejects.toBeInstanceOf(RetryableMailError);
339+ expect(await new Suppressions(env.DB).get("[email protected]")).toBeNull();
340+ expect(log()).toEqual([]);
341+ });
342+
343+ it("fails a wrong password without suppressing the recipient or logging the password", async () => {
344+ server({ reply: { AUTH: "535 5.7.8 Authentication credentials invalid" } });
345+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
346+ const { env, log } = setup();
347+ expect((await deliver(env, job)).status).toBe("failed");
348+ expect(await new Suppressions(env.DB).get("[email protected]")).toBeNull();
349+ const logged = JSON.stringify([errors.mock.calls, log()]);
350+ expect(logged).toContain("535 5.7.8");
351+ for (const secret of [PASSWORD, b64(PASSWORD), b64(`\[email protected]\0${PASSWORD}`)]) expect(logged).not.toContain(secret);
352+ });
353+
354+ it("fails without connecting when SMTP_URL can't be used", async () => {
355+ const f = server();
356+ vi.spyOn(console, "error").mockImplementation(() => {});
357+ const { env } = setup({ SMTP_URL: "smtps://ann:[email protected]" });
358+ expect(await deliver(env, job)).toEqual({ status: "failed", detail: "E_SMTP_CONFIG: the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" });
359+ expect(f.connects).toEqual([]);
360+ });
361+
362+ it("skips when neither EMAIL nor SMTP_URL is set", async () => {
363+ const { env, log } = setup({});
364+ expect(await deliver(env, job)).toEqual({ status: "skipped", detail: "no EMAIL binding or SMTP_URL" });
365+ expect(log()[0]).toMatchObject({ status: "skipped", detail: "email sending is not configured (no EMAIL binding or SMTP_URL)" });
366+ });
367+});
addedapps/diffinery/test/unit/stubs/cloudflare-sockets.ts+13−0View file
@@ -1,0 +1,13 @@
1+/** Stand-in for the Workers runtime's `cloudflare:sockets` module: a unit test sets what connect() returns with setConnect. */
2+type Connect = (address: { hostname: string; port: number } | string, options?: { secureTransport?: string; allowHalfOpen: boolean }) => Socket;
3+
4+let fake: Connect | null = null;
5+
6+export function setConnect(fn: Connect | null): void {
7+ fake = fn;
8+}
9+
10+export const connect: Connect = (address, options) => {
11+ if (!fake) throw new Error("this test set no fake connect()");
12+ return fake(address, options);
13+};
modifiedapps/diffinery/vitest.config.ts+4−3View file
@@ -11,6 +11,7 @@
1111 alias: {
1212 "cloudflare:workflows": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workflows.ts", import.meta.url)),
1313 "cloudflare:workers": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workers.ts", import.meta.url)),
14+ "cloudflare:sockets": fileURLToPath(new URL("./test/unit/stubs/cloudflare-sockets.ts", import.meta.url)),
1415 },
1516 },
1617 plugins: [
@@ -26,12 +27,12 @@
2627 },
2728 },
2829 {
29- // `import mod from "x.wasm?module"` gives a compiled WebAssembly.Module, like wrangler's CompiledWasm rule in the Worker.
30+ // `import mod from "x.wasm"` gives a compiled WebAssembly.Module, like wrangler's CompiledWasm rule in the Worker.
3031 name: "diffinery:wasm-module",
3132 enforce: "pre",
3233 async resolveId(source, importer) {
33- if (!source.endsWith(".wasm?module")) return null;
34- const file = await this.resolve(source.slice(0, -"?module".length), importer, { skipSelf: true });
34+ if (!source.endsWith(".wasm")) return null;
35+ const file = await this.resolve(source, importer, { skipSelf: true });
3536 return file ? PREFIX + Buffer.from(file.id).toString("base64url") : null;
3637 },
3738 load(id) {
modifiedapps/diffinery/wrangler.jsonc+15−4View file
@@ -49,7 +49,8 @@
4949 // domain is onboarded under Compute > Email Service > Email Sending (see scripts/email-sending.sh).
5050 "send_email": [{ "name": "EMAIL" }],
5151 // Request rate limits per minute (src/lib/rate-limit.ts; RATE_LIMITS there must match). Local
52- // development declares none, so nothing is limited there.
52+ // development declares none, so nothing is limited there. Where these bindings don't exist (celld),
53+ // the RATE_LIMITER Durable Object counts instead when the RATE_LIMITS var is "durable".
5354 "ratelimits": [
5455 { "name": "RL_AUTH", "namespace_id": "1001", "simple": { "limit": 20, "period": 60 } },
5556 { "name": "RL_ANON", "namespace_id": "1002", "simple": { "limit": 300, "period": 60 } },
@@ -63,6 +64,8 @@
6364 { "name": "REPO", "class_name": "RepoDO" },
6465 { "name": "SCHEDULER", "class_name": "SchedulerDO" },
6566 { "name": "COMPOSE", "class_name": "ComposeDO" },
67+ // Request rate limits without the ratelimits bindings (RATE_LIMITS=durable, src/rate-limiter.ts).
68+ { "name": "RATE_LIMITER", "class_name": "RateLimiterDO" },
6669 { "name": "RUNNER", "class_name": "RunnerContainer" },
6770 // Smaller hosted runners (src/runner/sizes.ts), the same runner on smaller instance types.
6871 { "name": "RUNNER_MEDIUM", "class_name": "RunnerContainerMedium" },
@@ -70,7 +73,9 @@
7073 { "name": "RUNNER_TINY", "class_name": "RunnerContainerTiny" },
7174 { "name": "SANDBOX", "class_name": "SandboxContainer" },
7275 { "name": "IMPORTER", "class_name": "ImportContainer" },
73- { "name": "PROJECT", "class_name": "ProjectDO" }
76+ { "name": "PROJECT", "class_name": "ProjectDO" },
77+ // GitHub jobs on Diffinery runners, one per paying account (src/github-runners/GitHubRunnersDO.ts).
78+ { "name": "GITHUB_RUNNERS", "class_name": "GitHubRunnersDO" }
7479 ]
7580 },
7681 "migrations": [
@@ -83,7 +88,11 @@
8388 // Smaller hosted runner sizes (src/runner/sizes.ts).
8489 { "tag": "v5", "new_sqlite_classes": ["RunnerContainerMedium", "RunnerContainerSmall", "RunnerContainerTiny"] },
8590 // Joining large uploads' blocks, a step per object (compose.ts).
86- { "tag": "v6", "new_sqlite_classes": ["ComposeDO"] }
91+ { "tag": "v6", "new_sqlite_classes": ["ComposeDO"] },
92+ // GitHub jobs on Diffinery runners (src/github-runners/GitHubRunnersDO.ts).
93+ { "tag": "v7", "new_sqlite_classes": ["GitHubRunnersDO"] },
94+ // Request rate limits without the ratelimits bindings (rate-limiter.ts).
95+ { "tag": "v8", "new_sqlite_classes": ["RateLimiterDO"] }
8796 ],
8897 "workflows": [
8998 { "name": "diffinery-run", "binding": "RUN_WORKFLOW", "class_name": "RunWorkflow" },
@@ -156,6 +165,7 @@
156165 { "name": "REPO", "class_name": "RepoDO" },
157166 { "name": "SCHEDULER", "class_name": "SchedulerDO" },
158167 { "name": "COMPOSE", "class_name": "ComposeDO" },
168+ { "name": "RATE_LIMITER", "class_name": "RateLimiterDO" },
159169 { "name": "RUNNER", "class_name": "RunnerContainer" },
160170 { "name": "RUNNER_MEDIUM", "class_name": "RunnerContainerMedium" },
161171 { "name": "RUNNER_SMALL", "class_name": "RunnerContainerSmall" },
@@ -163,7 +173,8 @@
163173 // Sandboxes run in an `agent.mjs --sandbox-pool` process (SANDBOX_POOL_URL), not containers.
164174 { "name": "SANDBOX", "class_name": "SandboxPoolDO" },
165175 { "name": "IMPORTER", "class_name": "ImportContainer" },
166- { "name": "PROJECT", "class_name": "ProjectDO" }
176+ { "name": "PROJECT", "class_name": "ProjectDO" },
177+ { "name": "GITHUB_RUNNERS", "class_name": "GitHubRunnersDO" }
167178 ]
168179 },
169180 "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+});
modifiedcontainers/runner/test/job.test.ts+2−1View file
@@ -954,7 +954,8 @@
954954 expect(api.logText()).toContain("Runner: image diffinery-runner:abc123, in fra06, EEUR, container d0");
955955 // A hosted runner also names its host's processor and, at the end, the share of its vCPUs' time the host took.
956956 if (existsSync("/proc/cpuinfo")) {
957- expect(api.logText()).toContain(`Host: ${runner.cpu}`);
957+ // The clock speed is read again for the log line, and it moves between reads on a busy host.
958+ expect(api.logText()).toContain(`Host: ${String(runner.cpu).replace(/, \d+ MHz$/, "")}`);
958959 expect(api.logText()).toMatch(/Host: \d+% of the vCPUs' time went to other work on the host \(steal\)/);
959960 }
960961 expect(api.completion).toMatchObject({ conclusion: "failure", failure: { step: 0 } });
addedscripts/celld-config.mjs+136−0View file
@@ -1,0 +1,136 @@
1+#!/usr/bin/env node
2+// Render apps/diffinery/wrangler.celld.jsonc from wrangler.jsonc, for celld (https://celld.dev), the
3+// open-source Workers and Durable Objects runtime. wrangler.jsonc stays the one source of truth: this
4+// keeps what celld runs and drops the Cloudflare-network features, whose bindings the Worker treats as
5+// optional (CELLD_ABSENT_BINDINGS in src/env.ts). celld stops on a key it doesn't know, so a new
6+// key in wrangler.jsonc fails here until it is listed below (docs/self-hosting/celld.md).
7+//
8+// node scripts/celld-config.mjs [--env dev] [--public-url https://git.example.com] [--var NAME=VALUE ...] [--out <file>]
9+//
10+// --env applies one of wrangler.jsonc's environments, as `wrangler -e` does (`--env dev` for `celld dev`).
11+// --var sets a Worker variable; repeat it. `celld deploy` takes no secrets of its own, so the secrets
12+// named in SECRETS are copied from this process's environment into `vars` when set: the rendered file
13+// then holds them, is written readable by its owner only and is ignored by git. celld keeps the
14+// deployment in the fleet bucket, whose credentials are the fleet's administrator access anyway.
15+// From the environment it also takes RUNNER_IMAGE, an image already in a registry (scripts/runner-image.sh).
16+import { chmodSync, readFileSync, writeFileSync } from "node:fs";
17+import { dirname, join, resolve } from "node:path";
18+import { fileURLToPath, pathToFileURL } from "node:url";
19+import { parseArgs } from "node:util";
20+import { parseJsonc } from "./jsonc.mjs";
21+
22+/** Top-level keys `celld deploy` accepts (celld's docs/cloudflare-compat.md); any other stops the deploy. */
23+export const CELLD_KEYS = new Set(["$schema", "name", "main", "no_bundle", "compatibility_date", "compatibility_flags", "durable_objects", "migrations", "assets", "services", "triggers", "vars", "d1_databases", "kv_namespaces", "queues", "workflows", "r2_buckets", "worker_loaders", "containers", "define", "rules"]);
24+
25+/** Keys celld accepts inside a list entry; any other stops the deploy. */
26+const NESTED = {
27+ migrations: ["tag", "new_sqlite_classes"],
28+ workflows: ["name", "binding", "class_name", "script_name"],
29+ producers: ["binding", "queue", "delivery_delay"],
30+ consumers: ["queue", "max_batch_size", "max_batch_timeout", "max_retries", "dead_letter_queue", "max_concurrency", "retry_delay"],
31+ d1_databases: ["binding", "database_name", "database_id", "migrations_dir", "migrations_table"],
32+ r2_buckets: ["binding", "bucket_name"],
33+};
34+
35+/**
36+ * wrangler.jsonc keys celld has no equivalent for, and what the instance does without each. A key
37+ * that holds bindings names them, so the guard test can check the Worker runs without them.
38+ */
39+export const DROPPED = {
40+ routes: { why: "celld has no managed ingress: put a TLS-terminating proxy in front of the fleet" },
41+ workers_dev: { why: "a workers.dev subdomain only exists on Cloudflare" },
42+ observability: { why: "logs go to each celld node's output" },
43+ upload_source_maps: { why: "stack traces point into the bundle" },
44+ limits: { why: "celld has no per-request CPU limit to raise" },
45+ version_metadata: { why: "IndexNow hashes the site's pages at every check instead of once per deployed version", bindings: (v) => [v.binding] },
46+ ratelimits: { why: "requests are not rate limited: limit them in the proxy in front of the fleet", bindings: (v) => v.map((r) => r.name) },
47+ send_email: { why: "emails are logged as skipped, not sent", bindings: (v) => v.map((e) => e.name) },
48+};
49+
50+/** Container keys celld accepts. The image build context is the Dockerfile's directory, as image_build_context says here. */
51+const CONTAINER_KEYS = ["class_name", "image", "name", "instance_type", "max_instances", "runtime"];
52+
53+/** Secrets (`wrangler secret put` on Cloudflare) copied from the environment into `vars`. */
54+export const SECRETS = ["MASTER_KEY", "MASTER_KEY_PREV", "OIDC_PRIVATE_KEY", "MAIL_EVENTS_SECRET", "TURNSTILE_SECRET", "GITHUB_OAUTH_CLIENT_SECRET", "SANDBOX_POOL_SECRET", "GITHUB_APP_CLIENT_SECRET", "GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_WEBHOOK_SECRET", "SMTP_PASSWORD"];
55+
56+/**
57+ * wrangler.jsonc as celld takes it. Returns the config and the bindings left out (`absent`), which
58+ * must all be optional in the Worker's Env. Throws on anything celld would refuse or run differently.
59+ */
60+export function celldConfig(wrangler, { env, vars = {}, secrets = {}, runnerImage } = {}) {
61+ let cfg = structuredClone(wrangler);
62+ if (env) {
63+ const block = cfg.env?.[env];
64+ if (!block) throw new Error(`wrangler.jsonc has no environment "${env}"`);
65+ cfg = { ...cfg, ...structuredClone(block), name: `${cfg.name}-${env}` };
66+ }
67+ delete cfg.env;
68+
69+ const absent = [];
70+ const dropped = [];
71+ for (const key of Object.keys(cfg)) {
72+ if (CELLD_KEYS.has(key)) continue;
73+ const d = DROPPED[key];
74+ if (!d) throw new Error(`wrangler.jsonc key "${key}" is not supported by celld; handle it in scripts/celld-config.mjs (DROPPED) and docs/self-hosting/celld.md`);
75+ absent.push(...(d.bindings?.(cfg[key]) ?? []));
76+ dropped.push({ key, why: d.why });
77+ delete cfg[key];
78+ }
79+
80+ for (const m of cfg.migrations ?? []) only("migrations", m, NESTED.migrations);
81+ for (const w of cfg.workflows ?? []) only("workflows", w, NESTED.workflows);
82+ for (const p of cfg.queues?.producers ?? []) only("queues.producers", p, NESTED.producers);
83+ for (const c of cfg.queues?.consumers ?? []) only("queues.consumers", c, NESTED.consumers);
84+ for (const d of cfg.d1_databases ?? []) only("d1_databases", d, NESTED.d1_databases);
85+ for (const r of cfg.r2_buckets ?? []) only("r2_buckets", r, NESTED.r2_buckets);
86+ // celld schedules containers itself: no rollout settings, and the build context is the Dockerfile's directory.
87+ cfg.containers = (cfg.containers ?? []).map((c) => {
88+ if (c.image_build_context && resolve(c.image_build_context) !== dirname(resolve(c.image))) throw new Error(`container ${c.class_name}: celld builds in the Dockerfile's directory, not ${c.image_build_context}`);
89+ const out = Object.fromEntries(Object.entries(c).filter(([k]) => CONTAINER_KEYS.includes(k)));
90+ if (runnerImage) out.image = runnerImage;
91+ return out;
92+ });
93+ if (!cfg.containers.length) delete cfg.containers;
94+
95+ // Wrangler's default module rules, which the Worker relies on (src/text-modules.d.ts), stated for celld's esbuild.
96+ const rules = cfg.rules ?? [];
97+ for (const [type, glob] of [["Text", "**/*.txt"], ["Data", "**/*.bin"]]) if (!rules.some((r) => r.globs?.includes(glob))) rules.push({ type, globs: [glob] });
98+ cfg.rules = rules;
99+
100+ cfg.vars = { ...cfg.vars, ...vars, ...secrets };
101+ for (const [k, v] of Object.entries(cfg.vars)) if (typeof v !== "string") throw new Error(`var ${k} must be a string for celld`);
102+ // EGRESS=web starts containers without internet and intercepts their HTTPS (lib/egress.ts), which celld refuses.
103+ if (cfg.vars.EGRESS === "web") throw new Error("EGRESS=web needs Cloudflare Containers' outbound interception, which celld doesn't have; leave EGRESS unset");
104+ return { config: cfg, absent, dropped };
105+}
106+
107+function only(where, entry, keys) {
108+ const extra = Object.keys(entry).filter((k) => !keys.includes(k));
109+ if (extra.length) throw new Error(`${where}: celld doesn't support ${extra.join(", ")}`);
110+}
111+
112+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
113+ const { values } = parseArgs({ options: { env: { type: "string" }, "public-url": { type: "string" }, var: { type: "string", multiple: true }, out: { type: "string" } } });
114+ const appDir = join(dirname(fileURLToPath(import.meta.url)), "..", "apps", "diffinery");
115+ const vars = {};
116+ for (const v of values.var ?? []) {
117+ const i = v.indexOf("=");
118+ if (i < 1) throw new Error(`--var takes NAME=VALUE, not ${JSON.stringify(v)}`);
119+ vars[v.slice(0, i)] = v.slice(i + 1);
120+ }
121+ if (values["public-url"]) {
122+ const url = new URL(values["public-url"]);
123+ if (url.pathname !== "/") throw new Error("--public-url must be an origin, like https://git.example.com");
124+ vars.PUBLIC_URL = url.origin;
125+ vars.MAIL_FROM ??= `notifications@${url.hostname}`;
126+ }
127+ const secrets = Object.fromEntries(SECRETS.filter((s) => process.env[s]).map((s) => [s, process.env[s]]));
128+ const wrangler = parseJsonc(readFileSync(join(appDir, "wrangler.jsonc"), "utf8"));
129+ const { config, dropped } = celldConfig(wrangler, { env: values.env, vars, secrets, runnerImage: process.env.RUNNER_IMAGE });
130+ const out = values.out ? resolve(values.out) : join(appDir, "wrangler.celld.jsonc");
131+ writeFileSync(out, `// Generated by scripts/celld-config.mjs from wrangler.jsonc; do not edit.\n${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
132+ chmodSync(out, 0o600);
133+ for (const d of dropped) console.error(`left out ${d.key}: ${d.why}`);
134+ if (Object.keys(secrets).length) console.error(`copied ${Object.keys(secrets).join(", ")} into vars; keep ${out} private`);
135+ console.log(`wrote ${out}`);
136+}
modifiedscripts/render-config.mjs+19−2View file
@@ -10,8 +10,9 @@
1010 // the host's last two labels) and sends email from notifications@<host>.
1111 // --admins sets BOOTSTRAP_ADMINS (comma-separated emails; bootstrap.sh passes what
1212 // scripts/bootstrap-admins.sh found). Without it, wrangler.jsonc's value stays.
13-// From the environment it takes RUNNER_IMAGE (scripts/runner-image.sh) and
14-// TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap).
13+// From the environment it takes RUNNER_IMAGE (scripts/runner-image.sh),
14+// TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap) and the GitHub App of GitHub
15+// runners: GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and GITHUB_APP_URL.
1516 import { readFileSync, writeFileSync } from "node:fs";
1617 import { dirname, join } from "node:path";
1718 import { fileURLToPath } from "node:url";
@@ -57,5 +58,21 @@
5758 // The site key of the Turnstile widget scripts/turnstile.sh set up for this hostname (not a
5859 // secret). One set in wrangler.jsonc is the operator's own and wins; turnstile.sh then leaves it alone.
5960 if (process.env.TURNSTILE_SITE_KEY && !cfg.vars.TURNSTILE_SITE_KEY) cfg.vars.TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY;
61+// The GitHub App's IDs (docs/self-hosting/configuration.md#github-runners) aren't secrets, but they are
62+// the instance's own, so they come from the environment like the hostname rather than from
63+// wrangler.jsonc; one that is empty there leaves wrangler.jsonc's value. Its secrets are Worker secrets.
64+const githubApp = [
65+ ["GITHUB_APP_ID", /^\d+$/, "the App ID, a number"],
66+ ["GITHUB_APP_SLUG", /^[a-z0-9][a-z0-9-]*$/, "the slug, like diffinery-runners"],
67+ ["GITHUB_APP_CLIENT_ID", /^\S+$/, "the Client ID, like Iv23li..."],
68+ ["GITHUB_APP_URL", /^https:\/\/[^/\s]+$/, "an https origin, like https://ghe.example.com"],
69+];
70+for (const [key, shape, want] of githubApp) {
71+ const value = process.env[key]?.trim();
72+ if (!value) continue;
73+ // Not the value itself: a secret set in the wrong variable would end up in the deploy log.
74+ if (!shape.test(value)) throw new Error(`${key} must be ${want}`);
75+ cfg.vars[key] = value;
76+}
6077 writeFileSync(join(appDir, "wrangler.deploy.jsonc"), `// Generated by scripts/render-config.mjs; do not edit.\n${JSON.stringify(cfg, null, 2)}\n`);
6178 console.log(`wrote ${join(appDir, "wrangler.deploy.jsonc")}`);
modifiedscripts/setup.sh+2−0View file
@@ -16,6 +16,8 @@
1616 # DIFFINERY_ZONE the Cloudflare zone holding DIFFINERY_DOMAIN (default: its last two labels)
1717 # MAIL_DOMAIN send email from notifications@<MAIL_DOMAIN> (default DIFFINERY_DOMAIN)
1818 # ACCESS_TEAM_DOMAIN your Zero Trust team domain, e.g. example.cloudflareaccess.com, when the token can't read it
19+# GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID, GITHUB_APP_URL
20+# the GitHub App of GitHub runners (docs/self-hosting/configuration.md#github-runners)
1921 # ROLLOUT_WAIT_MINUTES how long to wait for the container rollout (default 10)
2022 #
2123 # Every step is idempotent: it creates only what is missing and keeps your data and secrets, so run