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 #9 from alankernel67/claude/diffinery-celld-workers-compat-ce6323

Run on celld, the open-source Workers runtime, as well as Cloudflare
altugank authored · GitHub committed 2 parents c969fbbca9673fcommit 754895ad466927d843a1137527215a136e230c81Browse files
19 files changed+423−19
Files (19)
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` 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/nav.json+1−0View file
@@ -133,6 +133,7 @@
133133 "self-hosting/deploy",
134134 "self-hosting/configuration",
135135 "self-hosting/architecture",
136+ "self-hosting/celld",
136137 "self-hosting/status-page"
137138 ]
138139 },
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+1−1View 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
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` and `GITHUB_APP_WEBHOOK_SECRET` 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+1−0View 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
modifiedapps/diffinery/src/env.ts+9−0View file
@@ -178,3 +178,12 @@
178178 /** Optional GitHub Enterprise host (e.g. github.example.com) the importer may download release assets from. */
179179 IMPORT_GHE_HOST?: string;
180180 }
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;
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/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/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/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+}
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", ...["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+});
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/vitest.config.ts+3−3View file
@@ -27,12 +27,12 @@
2727 },
2828 },
2929 {
30- // `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.
3131 name: "diffinery:wasm-module",
3232 enforce: "pre",
3333 async resolveId(source, importer) {
34- if (!source.endsWith(".wasm?module")) return null;
35- 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 });
3636 return file ? PREFIX + Buffer.from(file.id).toString("base64url") : null;
3737 },
3838 load(id) {
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"];
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+}