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.

Compare changes

Choose two branches to see what changed or to start a new pull request.

base:←compare:5 commits ahead, 0 behind v0.2.0
19 files changed+330−111
Files (19)
modifiedCHANGELOG.md+7−0View file
@@ -6,6 +6,13 @@
66
77 ## [Unreleased]
88
9+### Self-hosting
10+
11+- The Worker's main module is about 7 MB instead of 14 MB: the docs, the downloads and the
12+ syntax highlighting grammars upload as separate text modules, none larger than about
13+ 4.5 MB. Hosts that cap each part of an upload, like open-compute (8 MiB), take it, and
14+ a cold start parses less JavaScript.
15+
916 ## [0.2.0] - 2026-10-31
1017
1118 Development moved to [GitHub](https://github.com/codician-team/diffinery). GitHub
addedHOMEFLARE.md+84−0View file
@@ -1,0 +1,84 @@
1+# Diffinery on Homeflare
2+
3+A fork of [codician-team/diffinery](https://github.com/codician-team/diffinery)
4+whose deploy scripts also work against Homeflare. `main` is upstream's `main`
5+plus a few commits, each one droppable or fit to send upstream on its own:
6+
7+- `CLOUDFLARE_API_BASE_URL` and `CLOUDFLARE_CONTAINER_REGISTRY` in the scripts,
8+ with Cloudflare's API and registry as the defaults.
9+- The Homeflare deploy described below, skipping the steps that need Cloudflare
10+ itself.
11+- `scripts/setup.sh` reading the `/login` page before matching it: `curl | grep -q`
12+ fails under `pipefail` when grep stops early.
13+- `CONTAINER_MAX_INSTANCE_TYPE` in `scripts/render-config.mjs`, for a machine smaller than Cloudflare's
14+ ([Container sizes](#container-sizes)).
15+
16+Rebase onto upstream when it moves:
17+
18+```sh
19+git remote add upstream https://github.com/codician-team/diffinery.git
20+git fetch upstream && git rebase upstream/main
21+```
22+
23+## How it works
24+
25+[Homeflare](https://github.com/jason-s13r/homeflare) runs Workers on your own machines (celld) behind a
26+Cloudflare-compatible API. These scripts deploy to it when `CLOUDFLARE_API_BASE_URL` points at that API,
27+which `homeflare-wrangler run` sets, along with `CLOUDFLARE_CONTAINER_REGISTRY` (Homeflare's registry) and a
28+`docker` command on your Podman.
29+
30+On another API than Cloudflare's, `scripts/setup.sh` and `scripts/bootstrap.sh` skip what needs Cloudflare
31+itself:
32+
33+| Skipped | What it means |
34+| --- | --- |
35+| Zone check | The hostname is a Homeflare custom domain, not a route in a Cloudflare zone. |
36+| R2 lifecycle rules | Logs, artifacts, archives and exports don't age out by themselves. |
37+| Email Sending setup and its event subscription | Onboard the sending domain in Cloudflare yourself (Homeflare relays email through it with `HOMEFLARE_EMAIL=cloudflare`). Bounces and complaints don't reach the suppression list. |
38+| Turnstile widget | Make one in the Cloudflare dashboard and pass its keys: `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET`. Without them open sign-up and anonymous security reports stay off. |
39+| Cloudflare Access | Email recovery and the `/auth/access` first sign-in stay off. Passkeys work. |
40+
41+## Deploy
42+
43+Put the settings in a file outside the repository (it holds the Turnstile secret), for example
44+`~/.config/homeflare/diffinery.env`, readable by you only:
45+
46+```sh
47+CLOUDFLARE_ACCOUNT_ID=<Homeflare's account id>
48+DIFFINERY_DOMAIN=git.homeflare.example.com
49+MAIL_DOMAIN=example.com
50+[email protected]
51+TURNSTILE_SITE_KEY=0x4AAA...
52+TURNSTILE_SECRET=0x4AAA...
53+```
54+
55+`MAIL_DOMAIN` is a domain onboarded to Email Sending in your Cloudflare account. Homeflare's account id is
56+in the Dashboard, or from `GET /client/v4/accounts`. Then, from the repository:
57+
58+```sh
59+homeflare-wrangler --env-file ~/.config/homeflare/diffinery.env run scripts/setup.sh --yes
60+```
61+
62+`homeflare-wrangler` reads the Homeflare API token from `~/.config/homeflare/wrangler.env` and sets
63+`CLOUDFLARE_API_BASE_URL` itself. Run it again to update.
64+
65+### Container sizes
66+
67+celld reserves each running container's whole instance type: a large runner (`standard-4`) books 12 GiB
68+and 4 vCPUs, so a few at once fill a home machine. celld starts a container only while the running ones'
69+reservations fit its container budget (`CELLD_CONTAINER_MEMORY_MB` in Homeflare's `homeflare.env`; 80% of
70+the machine's memory by default); past it, a job waits for one to finish. For more jobs at once, raise that
71+budget (reservations are caps, rarely all used), or make the containers smaller:
72+
73+```sh
74+CONTAINER_MAX_INSTANCE_TYPE=standard-3 # in diffinery.env: no container above 2 vCPUs / 8 GiB
75+```
76+
77+Every container class above it (large and medium runners, imports) then runs on it, with its vCPUs too:
78+`standard-2` is 1 vCPU and 6 GiB, so builds slow down. Unset, each class keeps `wrangler.jsonc`'s type.
79+
80+## The first administrator
81+
82+Without Access, the first account comes from open sign-up, which needs Turnstile and email. Deploy once with
83+`"SIGNUP": "open"` under `vars` in `apps/diffinery/wrangler.jsonc`, sign up at `https://<host>/signup` with an
84+address in `BOOTSTRAP_ADMINS`, add a passkey, then remove `SIGNUP` and deploy again.
modifiedapps/diffinery/.gitignore+1−0View file
@@ -1,2 +1,3 @@
11 build/
22 src/docs/content.generated.ts
3+src/web/grammars.generated.ts
modifiedapps/diffinery/docs/self-hosting/architecture.md+2−0View file
@@ -68,6 +68,8 @@
6868
6969 Some work happens in the Worker itself: profile pictures are checked, cropped and resized to small WebP files with WebAssembly image codecs, and code in the web UI and the docs is syntax highlighted with Shiki on the server.
7070
71+The Worker uploads as one JavaScript module of about 7 MB plus separate modules for the bulky content: the public docs, the downloads and the syntax highlighting grammars as text modules, which `pnpm build` writes to `apps/diffinery/build/` (`scripts/build-docs.mjs`, `scripts/build-grammars.mjs`), and the image codecs as WebAssembly. No module is larger than about 4.5 MB, so the Worker also deploys to hosts that cap each part of an upload, like open-compute's 8 MiB. The source map is larger than that: on such a host, set `upload_source_maps` to `false`.
72+
7173 The Worker holds no state of its own. It authenticates, checks the caller's role on the repository against D1, and then calls the repository's Durable Object over RPC.
7274
7375 Before it calls the object, the Worker also decides whether the request is a read or a write. `GET` and `HEAD` are reads, and so are the two `POST` requests that only fetch data: git's `git-upload-pack` (clone and fetch) and a Git LFS batch request for `download`. MCP tools marked read-only count as reads too. Every other request is a write:
modifiedapps/diffinery/docs/self-hosting/configuration.md+1−1View file
@@ -300,7 +300,7 @@
300300 | `routes` | `[{ "pattern": "diffinery.com/*", "zone_name": "diffinery.com" }]` | A zone route, not a Custom Domain. The hostname's DNS record must be proxied. On deploy, `scripts/render-config.mjs` replaces it with one route, `<DIFFINERY_DOMAIN>/*` in the zone `DIFFINERY_ZONE` (by default the hostname's last two labels), so you don't edit it by hand. |
301301 | `observability` | Enabled, `head_sampling_rate: 1` | Every request is logged to Workers Logs. |
302302 | `version_metadata` | Binding `CF_VERSION_METADATA` | The deployed version's id and time. [IndexNow](/docs/admin/site-administration#search-engines) checks the site's pages once for each new version and ignores older versions still running during a rollout. Optional: without it, it checks whenever the pages' content differs from what it last submitted. |
303-| `upload_source_maps` | `true` | Readable stack traces in the logs. |
303+| `upload_source_maps` | `true` | Readable stack traces in the logs. The source map is uploaded as one part of about 12 MB: on a host that caps each part (open-compute's limit is 8 MiB), set it to `false`. |
304304 | `limits.cpu_ms` | `300000` | Up to 5 minutes of CPU time per request (large pushes, diffs and merges). |
305305 | `containers` | `RunnerContainer`: `standard-4`, `max_instances: 100`; `RunnerContainerMedium`, `RunnerContainerSmall`, `RunnerContainerTiny`: `standard-3`, `standard-1`, `basic`, `max_instances: 100` each (smaller hosted runners; remove them and their `RUNNER_*` bindings to run every job on `standard-4`); `SandboxContainer`: `standard-1`, `max_instances: 50`; `ImportContainer`: `standard-4`, `max_instances: 20`; `rollout_active_grace_period`: 23400 for runners and 25200 for imports (longer than a job or transfer can run, so a deploy never replaces a running one), 3600 for sandboxes; `rollout_step_percentage: 100`, so containers started after a deploy get the new image | All three build `containers/runner/Dockerfile` with `containers/runner` as context. Raise `max_instances` for more concurrent jobs, sandboxes or import transfers. |
306306 | `triggers.crons` | `["*/5 * * * *"]` | Token expiry reminders, email log pruning, registry cleanup, cancelling draft imports older than 7 days, and setting the workflow scheduler's alarm if it isn't set. Scheduled workflows run from that alarm, not from the cron trigger. |
modifiedapps/diffinery/package.json+2−2View file
@@ -12,8 +12,8 @@
1212 "cf-typegen": "wrangler types",
1313 "e2e": "node --test --test-concurrency=1 --test-timeout=600000 test/e2e/e2e.test.mjs test/e2e/passkeys.test.mjs test/e2e/accounts.test.mjs test/e2e/registry.test.mjs test/e2e/email.test.mjs test/e2e/security-txt.test.mjs test/e2e/security.test.mjs test/e2e/security-limits.test.mjs test/e2e/agentic.test.mjs test/e2e/tasks.test.mjs test/e2e/terminals.test.mjs test/e2e/review.test.mjs",
1414 "db:migrate:local": "wrangler d1 migrations apply diffinery-dev --local -e dev",
15- "build": "node islands/build.mjs && node scripts/build-docs.mjs",
16- "predev": "node islands/build.mjs && node scripts/build-docs.mjs",
15+ "build": "node islands/build.mjs && node scripts/build-docs.mjs && node scripts/build-grammars.mjs",
16+ "predev": "node islands/build.mjs && node scripts/build-docs.mjs && node scripts/build-grammars.mjs",
1717 "build:docs": "node scripts/build-docs.mjs"
1818 },
1919 "dependencies": {
modifiedapps/diffinery/scripts/build-docs.mjs+38−10View file
@@ -1,4 +1,6 @@
1-// Builds the public documentation into src/docs/content.generated.ts:
1+// Builds the public documentation into src/docs/content.generated.ts, with the bulky values (pages, images and
2+// the downloads) in build/docs/content.txt, which the Worker imports as a separate text module and parses once:
3+// that keeps the Worker's main module small (hosts that cap each uploaded part, like open-compute's 8 MiB, take it).
24 // - every Markdown page under docs/ (with its frontmatter), in the order of docs/nav.json
35 // - the public site's pages under site/ (the product, comparison and company pages around the
46 // home page), in the order of site/nav.json
@@ -39,6 +41,7 @@
3941 /** The Claude Code plugins Diffinery serves for upload to claude.ai, by name. */
4042 const CLAUDE_PLUGIN_NAMES = new Set(["diffinery", "diffinery-ci"]);
4143 const out = path.join(app, "src/docs/content.generated.ts");
44+const dataOut = path.join(app, "build/docs/content.txt");
4245
4346 /** Pages produced in code rather than from a Markdown file. */
4447 const RUNTIME_PAGES = new Set(["api", "reference/mcp-tools"]);
@@ -315,38 +318,63 @@
315318 }
316319
317320 const ordered = Object.fromEntries(navSlugs.filter((s) => pages[s]).map((s) => [s, pages[s]]));
321+/** The bulky values, in build/docs/content.txt (JSON). */
322+const data = {
323+ DOCS_PAGES: ordered,
324+ SITE_PAGES: Object.fromEntries(sitePaths.filter((u) => site[u]).map((u) => [u, site[u]])),
325+ DOCS_IMAGES: images,
326+ CLI_BUNDLE: cli.bin,
327+ EDITOR_EXTENSION_VSIX_B64: editor.vsix.toString("base64"),
328+ JETBRAINS_PLUGIN_ZIP_B64: jetbrains.zip.toString("base64"),
329+ CLAUDE_PLUGINS: claudePlugins,
330+};
318331 const src = `// Generated by scripts/build-docs.mjs from docs/, site/, claude-plugins/, apps/cli, apps/vscode and apps/jetbrains/dist. Do not edit.
319332 /* eslint-disable */
333+import DATA from "../../build/docs/content.txt";
334+
320335 export interface DocPage { title: string; description: string; markdown: string; updated?: string }
321336 export interface DocSection { title: string; pages: string[] }
322-export const DOCS_NAV: DocSection[] = ${JSON.stringify(nav)};
323-export const DOCS_PAGES: Record<string, DocPage> = ${JSON.stringify(ordered)};
324-/** docs/images/: content type and base64 bytes by file name. */
325337 export interface SitePage { title: string; description: string; markdown: string; updated: string; seoTitle: string | null; published?: string }
326338 export interface SiteSection { title: string; pages: string[] }
339+
340+const data = JSON.parse(DATA) as {
341+ DOCS_PAGES: Record<string, DocPage>;
342+ SITE_PAGES: Record<string, SitePage>;
343+ DOCS_IMAGES: Record<string, { type: string; data: string }>;
344+ CLI_BUNDLE: string;
345+ EDITOR_EXTENSION_VSIX_B64: string;
346+ JETBRAINS_PLUGIN_ZIP_B64: string;
347+ CLAUDE_PLUGINS: Record<string, { version: string; sha256: string; zip: string }>;
348+};
349+
350+export const DOCS_NAV: DocSection[] = ${JSON.stringify(nav)};
351+export const DOCS_PAGES = data.DOCS_PAGES;
327352 /** The public site's pages (site/), by URL path, and their sections in reading order. The home page is code (web/site.tsx). */
328353 export const SITE_NAV: SiteSection[] = ${JSON.stringify(siteNav)};
329-export const SITE_PAGES: Record<string, SitePage> = ${JSON.stringify(Object.fromEntries(sitePaths.filter((u) => site[u]).map((u) => [u, site[u]])))};
330-export const DOCS_IMAGES: Record<string, { type: string; data: string }> = ${JSON.stringify(images)};
354+export const SITE_PAGES = data.SITE_PAGES;
355+/** docs/images/: content type and base64 bytes by file name. */
356+export const DOCS_IMAGES = data.DOCS_IMAGES;
331357 export const CLI_VERSION = ${JSON.stringify(cli.VERSION)};
332-export const CLI_BUNDLE = ${JSON.stringify(cli.bin)};
358+export const CLI_BUNDLE = data.CLI_BUNDLE;
333359 export const EDITOR_EXTENSION_VERSION = ${JSON.stringify(editor.version)};
334360 export const EDITOR_EXTENSION_SHA256 = ${JSON.stringify(createHash("sha256").update(editor.vsix).digest("hex"))};
335-export const EDITOR_EXTENSION_VSIX_B64 = ${JSON.stringify(editor.vsix.toString("base64"))};
361+export const EDITOR_EXTENSION_VSIX_B64 = data.EDITOR_EXTENSION_VSIX_B64;
336362 export const EDITOR_INSTALL_SH = ${JSON.stringify(await readFile(path.join(editorInstall, "install.sh"), "utf8"))};
337363 export const EDITOR_INSTALL_PS1 = ${JSON.stringify(await readFile(path.join(editorInstall, "install.ps1"), "utf8"))};
338364 export const JETBRAINS_PLUGIN_VERSION = ${JSON.stringify(jetbrains.version)};
339365 export const JETBRAINS_PLUGIN_SINCE_BUILD = ${JSON.stringify(jetbrains.sinceBuild)};
340366 export const JETBRAINS_PLUGIN_DESCRIPTION = ${JSON.stringify(jetbrains.description)};
341367 export const JETBRAINS_PLUGIN_SHA256 = ${JSON.stringify(createHash("sha256").update(jetbrains.zip).digest("hex"))};
342-export const JETBRAINS_PLUGIN_ZIP_B64 = ${JSON.stringify(jetbrains.zip.toString("base64"))};
368+export const JETBRAINS_PLUGIN_ZIP_B64 = data.JETBRAINS_PLUGIN_ZIP_B64;
343369 /** claude-plugins/: the Claude Code plugins served at /-/claude/<name>.zip, base64. */
344-export const CLAUDE_PLUGINS: Record<string, { version: string; sha256: string; zip: string }> = ${JSON.stringify(claudePlugins)};
370+export const CLAUDE_PLUGINS = data.CLAUDE_PLUGINS;
345371 export const CLI_INSTALL_SH = ${JSON.stringify(await readFile(path.join(cliInstall, "install.sh"), "utf8"))};
346372 export const CLI_INSTALL_PS1 = ${JSON.stringify(await readFile(path.join(cliInstall, "install.ps1"), "utf8"))};
347373 export const CLI_SHA256 = ${JSON.stringify(createHash("sha256").update(cli.bin).digest("hex"))};
348374 export const AGENT_SETUP_SH = ${JSON.stringify(await readFile(path.join(cliInstall, "agent-setup.sh"), "utf8"))};
349375 `;
350376 await mkdir(path.dirname(out), { recursive: true });
377+await mkdir(path.dirname(dataOut), { recursive: true });
378+await writeFile(dataOut, JSON.stringify(data));
351379 await writeFile(out, src);
352380 console.log(`docs: ${Object.keys(ordered).length} pages (+${RUNTIME_PAGES.size} generated at runtime), ${Object.keys(site).length} site pages, ${Object.keys(images).length} images, CLI ${cli.VERSION} (${Math.round(cli.bin.length / 1024)} KiB), editor extension ${editor.version} (${Math.round(editor.vsix.length / 1024)} KiB), JetBrains plugin ${jetbrains.version} (${Math.round(jetbrains.zip.length / 1024)} KiB), Claude Code plugins ${Object.entries(claudePlugins).map(([n, p]) => `${n} ${p.version}`).join(", ")}`);
addedapps/diffinery/scripts/build-grammars.mjs+58−0View file
@@ -1,0 +1,58 @@
1+// Builds the Shiki grammars the Worker highlights code with into text modules in build/grammars/, one JSON file
2+// per grammar (a grammar embedded by several languages, like JavaScript, is there once), and writes
3+// src/web/grammars.generated.ts, which imports them. As JavaScript the grammars would add about 3 MB to the Worker's
4+// main module; as text modules they are separate parts of the upload, parsed only when a file in that language is
5+// shown. That keeps the main module small (hosts that cap each uploaded part, like
6+// open-compute's 8 MiB, take it).
7+//
8+// Run by `pnpm build` and `pnpm dev`. A language added to LANGS needs no other change: src/web/highlight.ts
9+// takes its list from the generated file.
10+import { mkdir, rm, writeFile } from "node:fs/promises";
11+import path from "node:path";
12+import { fileURLToPath } from "node:url";
13+
14+const app = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
15+const dir = path.join(app, "build/grammars");
16+const out = path.join(app, "src/web/grammars.generated.ts");
17+
18+/** Shiki's names for the languages Diffinery highlights (src/web/highlight.ts maps file names and fences to them). */
19+const LANGS = ["astro", "bat", "c", "clojure", "cmake", "cpp", "csharp", "css", "dart", "diff", "docker", "dotenv", "elixir", "erlang", "fish", "fsharp", "go", "graphql", "groovy", "haskell", "hcl", "html", "ini", "java", "javascript", "json", "json5", "jsonc", "jsx", "julia", "kotlin", "less", "lua", "make", "markdown", "nginx", "nix", "objective-c", "ocaml", "perl", "php", "powershell", "proto", "python", "r", "ruby", "rust", "sass", "scala", "scss", "shellscript", "sql", "svelte", "swift", "terraform", "toml", "tsx", "typescript", "vue", "xml", "yaml", "zig"];
20+
21+/** Each grammar's JSON by name, and each language's grammars in registration order (the ones it embeds, then its own). */
22+const grammars = new Map();
23+const order = {};
24+for (const lang of LANGS) {
25+ const { default: regs } = await import(`shiki/langs/${lang}.mjs`);
26+ order[lang] = [];
27+ for (const reg of regs) {
28+ const json = JSON.stringify(reg);
29+ if (grammars.has(reg.name) && grammars.get(reg.name) !== json) throw new Error(`grammars: two different grammars are named "${reg.name}"`);
30+ grammars.set(reg.name, json);
31+ if (!order[lang].includes(reg.name)) order[lang].push(reg.name);
32+ }
33+}
34+
35+await rm(dir, { recursive: true, force: true });
36+await mkdir(dir, { recursive: true });
37+for (const [name, json] of grammars) await writeFile(path.join(dir, `${name}.txt`), json);
38+
39+const names = [...grammars.keys()].sort();
40+const imports = names.map((n, i) => `import g${i} from "../../build/grammars/${n}.txt";`);
41+const texts = names.map((n, i) => ` ${JSON.stringify(n)}: g${i},`);
42+await writeFile(
43+ out,
44+ `// Generated by scripts/build-grammars.mjs from Shiki's grammars. Do not edit.
45+/* eslint-disable */
46+${imports.join("\n")}
47+
48+export const GRAMMAR_LANGS = ${JSON.stringify(LANGS)} as const;
49+/** Each language's grammars in registration order: the ones it embeds, then its own. */
50+export const GRAMMAR_ORDER: Record<(typeof GRAMMAR_LANGS)[number], string[]> = ${JSON.stringify(order)};
51+/** Each grammar's JSON, by name. */
52+export const GRAMMAR_TEXT: Record<string, string> = {
53+${texts.join("\n")}
54+};
55+`,
56+);
57+const bytes = [...grammars.values()].reduce((n, j) => n + j.length, 0);
58+console.log(`grammars: ${LANGS.length} languages, ${grammars.size} grammars (${Math.round(bytes / 1024)} KiB)`);
modifiedapps/diffinery/src/web/highlight.ts+19−72View file
@@ -1,82 +1,29 @@
11 /**
22 * Syntax highlighting with Shiki (JavaScript regex engine, fine-grained grammars
3- * loaded on first use). Tokens carry both GitHub themes as CSS variables
4- * (--shiki-light / --shiki-dark); the site stylesheet picks one. Everything here
5- * fails soft: an unknown language, an oversized input or an error means plain text.
3+ * parsed on first use from the text modules scripts/build-grammars.mjs writes).
4+ * Tokens carry both GitHub themes as CSS variables (--shiki-light / --shiki-dark);
5+ * the site stylesheet picks one. Everything here fails soft: an unknown language,
6+ * an oversized input or an error means plain text.
67 */
78 import { createHighlighterCore, type HighlighterCore, type LanguageRegistration, type ThemedToken, type ThemeRegistration } from "shiki/core";
89 import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
10+import { GRAMMAR_LANGS, GRAMMAR_ORDER, GRAMMAR_TEXT } from "./grammars.generated.js";
911 import { escapeHtml } from "./markdown.js";
1012
11-type Grammar = () => Promise<{ default: LanguageRegistration[] }>;
13+export type Lang = (typeof GRAMMAR_LANGS)[number];
14+export const LANGS: Lang[] = [...GRAMMAR_LANGS];
15+const KNOWN = new Set<string>(GRAMMAR_LANGS);
1216
13-const GRAMMARS = {
14- astro: () => import("shiki/langs/astro.mjs"),
15- bat: () => import("shiki/langs/bat.mjs"),
16- c: () => import("shiki/langs/c.mjs"),
17- clojure: () => import("shiki/langs/clojure.mjs"),
18- cmake: () => import("shiki/langs/cmake.mjs"),
19- cpp: () => import("shiki/langs/cpp.mjs"),
20- csharp: () => import("shiki/langs/csharp.mjs"),
21- css: () => import("shiki/langs/css.mjs"),
22- dart: () => import("shiki/langs/dart.mjs"),
23- diff: () => import("shiki/langs/diff.mjs"),
24- docker: () => import("shiki/langs/docker.mjs"),
25- dotenv: () => import("shiki/langs/dotenv.mjs"),
26- elixir: () => import("shiki/langs/elixir.mjs"),
27- erlang: () => import("shiki/langs/erlang.mjs"),
28- fish: () => import("shiki/langs/fish.mjs"),
29- fsharp: () => import("shiki/langs/fsharp.mjs"),
30- go: () => import("shiki/langs/go.mjs"),
31- graphql: () => import("shiki/langs/graphql.mjs"),
32- groovy: () => import("shiki/langs/groovy.mjs"),
33- haskell: () => import("shiki/langs/haskell.mjs"),
34- hcl: () => import("shiki/langs/hcl.mjs"),
35- html: () => import("shiki/langs/html.mjs"),
36- ini: () => import("shiki/langs/ini.mjs"),
37- java: () => import("shiki/langs/java.mjs"),
38- javascript: () => import("shiki/langs/javascript.mjs"),
39- json: () => import("shiki/langs/json.mjs"),
40- json5: () => import("shiki/langs/json5.mjs"),
41- jsonc: () => import("shiki/langs/jsonc.mjs"),
42- jsx: () => import("shiki/langs/jsx.mjs"),
43- julia: () => import("shiki/langs/julia.mjs"),
44- kotlin: () => import("shiki/langs/kotlin.mjs"),
45- less: () => import("shiki/langs/less.mjs"),
46- lua: () => import("shiki/langs/lua.mjs"),
47- make: () => import("shiki/langs/make.mjs"),
48- markdown: () => import("shiki/langs/markdown.mjs"),
49- nginx: () => import("shiki/langs/nginx.mjs"),
50- nix: () => import("shiki/langs/nix.mjs"),
51- "objective-c": () => import("shiki/langs/objective-c.mjs"),
52- ocaml: () => import("shiki/langs/ocaml.mjs"),
53- perl: () => import("shiki/langs/perl.mjs"),
54- php: () => import("shiki/langs/php.mjs"),
55- powershell: () => import("shiki/langs/powershell.mjs"),
56- proto: () => import("shiki/langs/proto.mjs"),
57- python: () => import("shiki/langs/python.mjs"),
58- r: () => import("shiki/langs/r.mjs"),
59- ruby: () => import("shiki/langs/ruby.mjs"),
60- rust: () => import("shiki/langs/rust.mjs"),
61- sass: () => import("shiki/langs/sass.mjs"),
62- scala: () => import("shiki/langs/scala.mjs"),
63- scss: () => import("shiki/langs/scss.mjs"),
64- shellscript: () => import("shiki/langs/shellscript.mjs"),
65- sql: () => import("shiki/langs/sql.mjs"),
66- svelte: () => import("shiki/langs/svelte.mjs"),
67- swift: () => import("shiki/langs/swift.mjs"),
68- terraform: () => import("shiki/langs/terraform.mjs"),
69- toml: () => import("shiki/langs/toml.mjs"),
70- tsx: () => import("shiki/langs/tsx.mjs"),
71- typescript: () => import("shiki/langs/typescript.mjs"),
72- vue: () => import("shiki/langs/vue.mjs"),
73- xml: () => import("shiki/langs/xml.mjs"),
74- yaml: () => import("shiki/langs/yaml.mjs"),
75- zig: () => import("shiki/langs/zig.mjs"),
76-} satisfies Record<string, Grammar>;
17+const parsed = new Map<string, LanguageRegistration>();
7718
78-export type Lang = keyof typeof GRAMMARS;
79-export const LANGS = Object.keys(GRAMMARS) as Lang[];
19+/** A language's grammars (the ones it embeds, then its own), each parsed from its text module once. */
20+function grammar(lang: Lang): LanguageRegistration[] {
21+ return GRAMMAR_ORDER[lang].map((name) => {
22+ let g = parsed.get(name);
23+ if (!g) parsed.set(name, (g = JSON.parse(GRAMMAR_TEXT[name]!) as LanguageRegistration));
24+ return g;
25+ });
26+}
8027
8128 const EXT: Record<string, Lang> = {
8229 ts: "typescript", mts: "typescript", cts: "typescript", tsx: "tsx",
@@ -137,7 +84,7 @@
13784 /** Shiki language for a Markdown fence info string ("ts", "yaml", "c++" …), or null. */
13885 export function langForFence(info: string): Lang | null {
13986 const name = info.trim().toLowerCase().replace(/^\{?\.?/, "").replace(/\}$/, "");
140- return name in GRAMMARS ? (name as Lang) : (ALIASES[name] ?? null);
87+ return KNOWN.has(name) ? (name as Lang) : (ALIASES[name] ?? null);
14188 }
14289
14390 // ---------------------------------------------------------------- highlighter
@@ -207,7 +154,7 @@
207154 let p = loading.get(l);
208155 if (!p) {
209156 p = hl
210- .loadLanguage(GRAMMARS[l]())
157+ .loadLanguage(...grammar(l))
211158 // Compile the grammar's top-level rules now: on a cold Worker that alone can outlast the
212159 // per-line time limit, which would leave the first line of a file unhighlighted.
213160 .then(() => void hl.codeToTokens("x", { lang: l, theme: PAIR }))
addedapps/diffinery/test/unit/main-module-size.test.ts+27−0View file
@@ -1,0 +1,27 @@
1+/**
2+ * The bulky generated content stays out of the Worker's main module, in text modules that upload as parts of their
3+ * own (scripts/build-docs.mjs, scripts/build-grammars.mjs). With it inlined the main module was 14 MB, which hosts
4+ * that cap each uploaded part refuse (open-compute: 8 MiB). Needs `pnpm build`.
5+ */
6+import { statSync } from "node:fs";
7+import { describe, expect, it } from "vitest";
8+import { DOCS_PAGES } from "../../src/docs/content.generated.js";
9+import { GRAMMAR_LANGS, GRAMMAR_ORDER, GRAMMAR_TEXT } from "../../src/web/grammars.generated.js";
10+
11+const size = (rel: string) => statSync(new URL(rel, import.meta.url)).size;
12+
13+describe("main module size", () => {
14+ it("keeps the docs' pages, images and downloads in a text module", () => {
15+ expect(size("../../src/docs/content.generated.ts")).toBeLessThan(64 * 1024);
16+ expect(size("../../build/docs/content.txt")).toBeGreaterThan(1024 * 1024);
17+ expect(DOCS_PAGES.quickstart?.title).toBeTruthy();
18+ });
19+
20+ it("keeps the highlighting grammars in text modules, each grammar once", () => {
21+ expect(size("../../src/web/grammars.generated.ts")).toBeLessThan(32 * 1024);
22+ for (const lang of GRAMMAR_LANGS) {
23+ expect(GRAMMAR_ORDER[lang].length).toBeGreaterThan(0);
24+ for (const name of GRAMMAR_ORDER[lang]) expect(JSON.parse(GRAMMAR_TEXT[name]!).name).toBe(name);
25+ }
26+ });
27+});
modifiedscripts/bootstrap-admins.sh+1−1View file
@@ -59,7 +59,7 @@
5959 if [[ -z "${CLOUDFLARE_API_TOKEN:-}" || -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]]; then
6060 none "it isn't in the environment or wrangler.jsonc, and without CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID the deployed Worker's list can't be read"
6161 fi
62-SETTINGS="$(curl -sS --retry 4 --retry-all-errors --retry-delay 3 "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$WORKER/settings" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" || true)"
62+SETTINGS="$(curl -sS --retry 4 --retry-all-errors --retry-delay 3 "${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/$WORKER/settings" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" || true)"
6363 if jq -e '.success == true' >/dev/null 2>&1 <<<"$SETTINGS"; then
6464 LIVE="$(jq -r '[.result.bindings[]? | select(.type == "plain_text" and .name == "BOOTSTRAP_ADMINS") | .text][0] // empty' <<<"$SETTINGS")"
6565 LIVE="$(trimmed "$LIVE")"
modifiedscripts/bootstrap.sh+31−10View file
@@ -25,7 +25,11 @@
2525 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
2626 APP="$ROOT/apps/diffinery"
2727 WRANGLER=(pnpm --dir "$APP" exec wrangler)
28-API="https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID"
28+CF_API="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}"
29+API="$CF_API/accounts/$CLOUDFLARE_ACCOUNT_ID"
30+# 0 on another Cloudflare-compatible API (Homeflare): the steps that need Cloudflare itself are skipped.
31+ON_CLOUDFLARE=1
32+[[ "$CF_API" == https://api.cloudflare.com/* ]] || ON_CLOUDFLARE=0
2933
3034 cf() { # cf METHOD PATH [JSON]
3135 local method="$1" path="$2" body="${3:-}"
@@ -74,6 +78,9 @@
7478 {"id":"action-mirror-30d","enabled":true,"conditions":{"prefix":"action-mirror/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":2592000}}}
7579 ]}'
7680 # Applied on every deploy; a failure stops it, since a wrong rule can delete data.
81+if ((ON_CLOUDFLARE == 0)); then
82+ warn "R2 lifecycle rules are skipped on $CF_API: transient objects (logs, artifacts, archives, exports) don't age out by themselves."
83+else
7784 RESULT="$(cf PUT "/r2/buckets/diffinery-data/lifecycle" "$LIFECYCLE")"
7885 if ! jq -e '.success' >/dev/null <<<"$RESULT"; then
7986 echo "could not set the R2 lifecycle rules (token has R2: Edit?): $(jq -c '.errors // .' <<<"$RESULT" 2>/dev/null || echo "$RESULT")" >&2
@@ -85,6 +92,7 @@
8592 exit 1
8693 fi
8794 echo "R2 lifecycle rules set"
95+fi
8896 endlog
8997
9098 # ------------------------------------------------------------------ Queues
@@ -127,7 +135,7 @@
127135 if [[ -z "$qid" ]]; then warn "Could not find the diffinery-mail-events queue, so it isn't subscribed to Email Sending's bounce and complaint events."; return; fi
128136 # The zone that holds the sending domain (the domain itself or a parent), as scripts/email-sending.sh finds it.
129137 while [[ "$name" == *.* ]]; do
130- zone="$(curl -sS "https://api.cloudflare.com/client/v4/zones?name=$name" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id // empty' || true)"
138+ zone="$(curl -sS "${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}/zones?name=$name" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id // empty' || true)"
131139 [[ -n "$zone" ]] && break
132140 name="${name#*.}"
133141 done
@@ -162,12 +170,16 @@
162170 warn "Could not subscribe diffinery-mail-events to Email Sending's bounce and complaint events for $SEND_DOMAIN. The token needs $SUB_PERMISSION (and $SEND_DOMAIN onboarded to Email Sending). Cloudflare said: $(api_errors "$res")"
163171 fi
164172 }
165-subscribe_mail_events
173+if ((ON_CLOUDFLARE)); then subscribe_mail_events; else echo "skipped on $CF_API: bounces and complaints don't reach the suppression list by themselves"; fi
166174 endlog
167175
168176 # ------------------------------------------------------------------ Email Sending
169177 # notifications@<MAIL_DOMAIN or DIFFINERY_DOMAIN>; warns (and email is skipped) until the domain is onboarded.
170-DIFFINERY_DOMAIN="$DOMAIN" "$ROOT/scripts/email-sending.sh" || warn "Email Sending check failed; email may not be delivered."
178+if ((ON_CLOUDFLARE)); then
179+ DIFFINERY_DOMAIN="$DOMAIN" "$ROOT/scripts/email-sending.sh" || warn "Email Sending check failed; email may not be delivered."
180+else
181+ echo "Email Sending setup skipped on $CF_API: the sending domain is set up wherever that API sends from."
182+fi
171183
172184 # ------------------------------------------------------------------ Turnstile
173185 # The widget "diffinery <DIFFINERY_DOMAIN>", created when missing, so people who aren't signed in can
@@ -177,19 +189,28 @@
177189 # Account → Turnstile → Edit; without it turnstile.sh warns, naming it, and the deploy goes on with
178190 # anonymous reports refused. Sign-up stays as SIGNUP says: keys alone don't open it.
179191 log "Turnstile"
180-TURNSTILE_SITE_KEY="$(DIFFINERY_DOMAIN="$DOMAIN" "$ROOT/scripts/turnstile.sh")" || { warn "scripts/turnstile.sh failed; anonymous security reports stay refused."; TURNSTILE_SITE_KEY=""; }
192+if ((ON_CLOUDFLARE)); then
193+ TURNSTILE_SITE_KEY="$(DIFFINERY_DOMAIN="$DOMAIN" "$ROOT/scripts/turnstile.sh")" || { warn "scripts/turnstile.sh failed; anonymous security reports stay refused."; TURNSTILE_SITE_KEY=""; }
194+else
195+ # No Turnstile API here: a widget made in the Cloudflare dashboard, its keys in the environment.
196+ TURNSTILE_SITE_KEY="${TURNSTILE_SITE_KEY:-}"
197+ [[ -n "$TURNSTILE_SITE_KEY" ]] || warn "No TURNSTILE_SITE_KEY: open sign-up and anonymous security reports stay off."
198+fi
181199 echo "site key: ${TURNSTILE_SITE_KEY:-none}"
182200 endlog
183201
184202 # ------------------------------------------------------------------ Access
185203 log "Cloudflare Access"
186204 TEAM="${ACCESS_TEAM_DOMAIN:-}"
187-if [[ -z "$TEAM" ]]; then
205+if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then
188206 TEAM="$(cf GET /access/organizations | jq -r '.result.auth_domain // empty' || true)"
189207 fi
190-APPS="$(cf GET "/access/apps?per_page=100" || echo '{}')"
191208 AUD=""
192-if ! jq -e '.success' >/dev/null <<<"$APPS"; then
209+APPS='{}'
210+((ON_CLOUDFLARE == 0)) || APPS="$(cf GET "/access/apps?per_page=100" || echo '{}')"
211+if ((ON_CLOUDFLARE == 0)); then
212+ echo "Access skipped on $CF_API: passkeys work; email recovery and the /auth/access first sign-in stay off."
213+elif ! jq -e '.success' >/dev/null <<<"$APPS"; then
193214 warn "Could not read Access applications (token needs Access: Apps and Policies Edit). Passkeys work; email recovery stays off."
194215 else
195216 # People sign in with passkeys. Access guards only /auth/access, the email-based
@@ -216,11 +237,11 @@
216237 cf DELETE "/access/apps/$BYPASS_ID" | jq -e '.success' >/dev/null && echo "removed the old Access bypass app" || warn "Could not remove the old Access bypass application."
217238 fi
218239 fi
219-if [[ -z "$TEAM" ]]; then
240+if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then
220241 # Fall back to the sign-in redirect, which names the team domain.
221242 TEAM="$(curl -sS -o /dev/null -w '%{redirect_url}' "https://$DOMAIN/auth/access" | sed -nE 's#^https://([^/]+\.cloudflareaccess\.com)/.*#\1#p' || true)"
222243 fi
223-[[ -n "$TEAM" ]] || warn "Access team domain unknown; set the ACCESS_TEAM_DOMAIN repository variable (Zero Trust → Settings → Custom pages shows it)."
244+[[ -n "$TEAM" ]] || ((ON_CLOUDFLARE == 0)) || warn "Access team domain unknown; set the ACCESS_TEAM_DOMAIN repository variable (Zero Trust → Settings → Custom pages shows it)."
224245 echo "team=${TEAM:-?} aud=${AUD:+set}"
225246 endlog
226247
modifiedscripts/email-sending.sh+1−1View file
@@ -12,7 +12,7 @@
1212
1313 : "${CLOUDFLARE_API_TOKEN:?set CLOUDFLARE_API_TOKEN}"
1414 DOMAIN="${MAIL_DOMAIN:-${DIFFINERY_DOMAIN:-diffinery.com}}"
15-CF="https://api.cloudflare.com/client/v4"
15+CF="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}"
1616
1717 cf() { curl -sS "$CF$1" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"; }
1818 warn() { echo "::warning::$*" >&2; }
modifiedscripts/ensure-secrets.sh+5−1View file
@@ -36,7 +36,11 @@
3636 # Without the Turnstile permission this warns (scripts/turnstile.sh names it) and the deploy goes on:
3737 # people who aren't signed in can't send security reports until it's set.
3838 SITE_KEY="$(tail -n +2 "$APP/wrangler.deploy.jsonc" | jq -r '.vars.TURNSTILE_SITE_KEY // empty')"
39-if [[ -n "$SITE_KEY" ]] && ! grep -qx TURNSTILE_SECRET <<<"$EXISTING"; then
39+if [[ -n "$SITE_KEY" && -n "${TURNSTILE_SECRET:-}" ]] && ! grep -qx TURNSTILE_SECRET <<<"$EXISTING"; then
40+ # A widget's secret from the environment (an API without Turnstile, such as Homeflare's).
41+ printf '%s' "$TURNSTILE_SECRET" | "${WRANGLER[@]}" secret put TURNSTILE_SECRET -c wrangler.deploy.jsonc >/dev/null
42+ echo "set TURNSTILE_SECRET"
43+elif [[ -n "$SITE_KEY" ]] && ! grep -qx TURNSTILE_SECRET <<<"$EXISTING"; then
4044 if "$ROOT/scripts/turnstile.sh" secret "$SITE_KEY" -c wrangler.deploy.jsonc; then
4145 echo "set TURNSTILE_SECRET"
4246 else
modifiedscripts/render-config.mjs+18−2View file
@@ -10,7 +10,7 @@
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),
13+// From the environment it takes RUNNER_IMAGE (scripts/runner-image.sh), CONTAINER_MAX_INSTANCE_TYPE,
1414 // TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap) and the GitHub App of GitHub
1515 // runners: GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and GITHUB_APP_URL.
1616 import { readFileSync, writeFileSync } from "node:fs";
@@ -34,7 +34,9 @@
3434 if (url.protocol !== "https:" || url.pathname !== "/") throw new Error("--public-url must be an https origin, like https://git.example.com");
3535 cfg.vars.PUBLIC_URL = url.origin;
3636 const zone = values.zone ?? url.hostname.split(".").slice(-2).join(".");
37- cfg.routes = [{ pattern: `${url.hostname}/*`, zone_name: zone }];
37+ // On another Cloudflare-compatible API (Homeflare), a custom domain: the zone isn't Cloudflare's.
38+ const onCloudflare = (process.env.CLOUDFLARE_API_BASE_URL ?? "https://api.cloudflare.com/").startsWith("https://api.cloudflare.com/");
39+ cfg.routes = onCloudflare ? [{ pattern: `${url.hostname}/*`, zone_name: zone }] : [{ pattern: url.hostname, custom_domain: true }];
3840 cfg.vars.MAIL_FROM = `notifications@${url.hostname}`;
3941 }
4042 if (values["mail-from"]) cfg.vars.MAIL_FROM = values["mail-from"];
@@ -55,6 +57,20 @@
5557 delete c.image_build_context;
5658 }
5759 }
60+// The largest instance type a container may have, for a machine smaller than Cloudflare's fleet
61+// (Homeflare): a class above it (runners, imports, sandboxes) runs on it instead. celld reserves a running container's whole
62+// instance type, so four 12 GiB large runners fill a 60 GiB machine. The capped class has the smaller
63+// type's vCPU and memory, though src/runner/sizes.ts still names the larger. Unset, nothing changes.
64+const INSTANCE_TYPES = ["lite", "basic", "standard-1", "standard-2", "standard-3", "standard-4"];
65+const typeRank = (t) => INSTANCE_TYPES.indexOf({ dev: "lite", standard: "standard-1" }[t] ?? t);
66+const maxType = process.env.CONTAINER_MAX_INSTANCE_TYPE?.trim();
67+if (maxType) {
68+ if (typeRank(maxType) < 0) throw new Error(`CONTAINER_MAX_INSTANCE_TYPE must be one of ${INSTANCE_TYPES.join(", ")}`);
69+ for (const c of cfg.containers) {
70+ // A custom instance type (an object) is the operator's own choice; leave it.
71+ if (typeof c.instance_type === "string" && typeRank(c.instance_type) > typeRank(maxType)) c.instance_type = maxType;
72+ }
73+}
5874 // The site key of the Turnstile widget scripts/turnstile.sh set up for this hostname (not a
5975 // secret). One set in wrangler.jsonc is the operator's own and wins; turnstile.sh then leaves it alone.
6076 if (process.env.TURNSTILE_SITE_KEY && !cfg.vars.TURNSTILE_SITE_KEY) cfg.vars.TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY;
modifiedscripts/runner-image.sh+1−1View file
@@ -20,7 +20,7 @@
2020 } | sha256sum | cut -c1-24
2121 )
2222 : "${CLOUDFLARE_ACCOUNT_ID:?CLOUDFLARE_ACCOUNT_ID is required}"
23-image="registry.cloudflare.com/$CLOUDFLARE_ACCOUNT_ID/$name:$tag"
23+image="${CLOUDFLARE_CONTAINER_REGISTRY:-registry.cloudflare.com}/$CLOUDFLARE_ACCOUNT_ID/$name:$tag"
2424 wrangler() { (cd apps/diffinery && pnpm exec wrangler "$@"); }
2525
2626 if ! listed=$(wrangler containers images list --json --filter "(^|/)$name\$" 2>&1); then
modifiedscripts/setup.sh+32−8View file
@@ -19,6 +19,12 @@
1919 # GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID, GITHUB_APP_URL
2020 # the GitHub App of GitHub runners (docs/self-hosting/configuration.md#github-runners)
2121 # ROLLOUT_WAIT_MINUTES how long to wait for the container rollout (default 10)
22+# CLOUDFLARE_API_BASE_URL another Cloudflare-compatible API, such as Homeflare's (default Cloudflare's).
23+# Steps that need Cloudflare itself (the zone check, R2 lifecycle rules, Email
24+# Sending setup and events, Turnstile and Access) are skipped there; see
25+# HOMEFLARE.md.
26+# CLOUDFLARE_CONTAINER_REGISTRY the registry runner images go to (default registry.cloudflare.com)
27+# TURNSTILE_SITE_KEY, TURNSTILE_SECRET a Turnstile widget's keys, for an API without Turnstile
2228 #
2329 # Every step is idempotent: it creates only what is missing and keeps your data and secrets, so run
2430 # it again to update. Secrets are never printed. Needs Node.js 22+, pnpm, jq, curl, openssl and Docker.
@@ -26,8 +32,13 @@
2632
2733 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
2834 APP="$ROOT/apps/diffinery"
29-CF_API="https://api.cloudflare.com/client/v4"
35+CF_API="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}"
3036 PLACEHOLDER_D1="00000000-0000-0000-0000-000000000000"
37+# 1 on Cloudflare's own API; 0 on another Cloudflare-compatible one (Homeflare), which skips the
38+# steps that need Cloudflare itself.
39+ON_CLOUDFLARE=1
40+[[ "$CF_API" == https://api.cloudflare.com/* ]] || ON_CLOUDFLARE=0
41+export ON_CLOUDFLARE
3142 DRY_RUN=0
3243 ASK=1
3344
@@ -150,12 +161,16 @@
150161 fi
151162 jq -e '.success == true and .result.status == "active"' >/dev/null 2>&1 <<<"$verify" || die "Cloudflare doesn't accept the API token: $(errors_of "$verify")"
152163 info "the token is valid and active"
164+ if ((ON_CLOUDFLARE == 0)); then
165+ info "API: $CF_API (not Cloudflare's: the zone check, R2 lifecycle rules, Email Sending setup, Turnstile and Access are skipped)"
166+ else
153167 zones="$(cf_get "/zones?name=$ZONE&account.id=$CLOUDFLARE_ACCOUNT_ID" || true)"
154168 jq -e '.success == true' >/dev/null 2>&1 <<<"$zones" || die "couldn't look up the zone $ZONE: $(errors_of "$zones")"
155169 zone_status="$(jq -r '.result[0].status // empty' <<<"$zones")"
156170 [[ -n "$zone_status" ]] || die "the zone $ZONE isn't in account $CLOUDFLARE_ACCOUNT_ID, or the token can't see it. Add the domain to the account, give the token Zone → Zone → Read on it, or set DIFFINERY_ZONE if the zone that holds $DIFFINERY_DOMAIN is another one."
157171 [[ "$zone_status" == active ]] || warn "the zone $ZONE is $zone_status, not active: the route serves nothing until its nameservers point at Cloudflare"
158172 info "zone $ZONE is in the account ($zone_status)"
173+ fi
159174 fi
160175
161176 cd "$ROOT"
@@ -173,7 +188,7 @@
173188
174189 step "Rendering the deploy config (placeholder D1 id) and bundling the Worker"
175190 # A placeholder runner image: the dry run builds no container image (that needs Docker and the registry).
176- RUNNER_IMAGE="registry.cloudflare.com/${CLOUDFLARE_ACCOUNT_ID:-00000000000000000000000000000000}/diffinery-runner:dry-run" \
191+ RUNNER_IMAGE="${CLOUDFLARE_CONTAINER_REGISTRY:-registry.cloudflare.com}/${CLOUDFLARE_ACCOUNT_ID:-00000000000000000000000000000000}/diffinery-runner:dry-run" \
177192 node "$ROOT/scripts/render-config.mjs" --d1 "$PLACEHOLDER_D1" ${ACCESS_TEAM_DOMAIN:+--team "$ACCESS_TEAM_DOMAIN"} \
178193 --public-url "https://$DIFFINERY_DOMAIN" ${DIFFINERY_ZONE:+--zone "$DIFFINERY_ZONE"} --mail-from "$MAIL_FROM" --admins "$ADMINS"
179194 OUT="$(mktemp -d "${TMPDIR:-/tmp}/diffinery-dry-run.XXXXXX")"
@@ -205,7 +220,7 @@
205220 env -u GITHUB_ENV "$ROOT/scripts/runner-image.sh" | tee "$image_log"
206221 RUNNER_IMAGE="$(tail -n 1 "$image_log")"
207222 rm -f "$image_log"
208-[[ "$RUNNER_IMAGE" == registry.cloudflare.com/* ]] || die "scripts/runner-image.sh didn't print the runner image"
223+[[ "$RUNNER_IMAGE" == ${CLOUDFLARE_CONTAINER_REGISTRY:-registry.cloudflare.com}/* ]] || die "scripts/runner-image.sh didn't print the runner image"
209224 export RUNNER_IMAGE
210225
211226 step "Creating or updating Cloudflare resources (scripts/bootstrap.sh)"
@@ -221,7 +236,7 @@
221236 step "Worker secrets (generated on the first deploy; never printed)"
222237 "$ROOT/scripts/ensure-secrets.sh"
223238
224-if [[ -z "$ACCESS_TEAM" ]]; then
239+if [[ -z "$ACCESS_TEAM" ]] && ((ON_CLOUDFLARE)); then
225240 step "Finishing the Access setup (first deploy)"
226241 : >"$OUTPUTS"
227242 GITHUB_OUTPUT="$OUTPUTS" "$ROOT/scripts/bootstrap.sh"
@@ -237,12 +252,21 @@
237252 [[ "$code" == 200 ]] && break
238253 sleep 10
239254 done
240-[[ "$code" == 200 ]] || die "https://$DIFFINERY_DOMAIN/healthz did not return 200 (last: ${code:-no answer}). Check that the $DIFFINERY_DOMAIN DNS record is proxied (orange cloud); a new certificate can take a few minutes, so run this again."
255+if ((ON_CLOUDFLARE)); then
256+ [[ "$code" == 200 ]] || die "https://$DIFFINERY_DOMAIN/healthz did not return 200 (last: ${code:-no answer}). Check that the $DIFFINERY_DOMAIN DNS record is proxied (orange cloud); a new certificate can take a few minutes, so run this again."
257+else
258+ [[ "$code" == 200 ]] || die "https://$DIFFINERY_DOMAIN/healthz did not return 200 (last: ${code:-no answer}). Check that $DIFFINERY_DOMAIN resolves to the host serving $CF_API and that the Worker started."
259+fi
241260 info "/healthz -> 200"
242-curl -sS "https://$DIFFINERY_DOMAIN/login" | grep -q "Sign in with a passkey" || die "/login is not the Diffinery sign-in page: check DIFFINERY_DOMAIN, DIFFINERY_ZONE and the route in apps/diffinery/wrangler.deploy.jsonc"
261+# Read the whole page before matching: `curl | grep -q` fails under pipefail when grep stops
262+# early and curl can't finish writing (curl: (23) Failed writing body).
263+LOGIN_PAGE="$(curl -sS "https://$DIFFINERY_DOMAIN/login" || true)"
264+grep -q "Sign in with a passkey" <<<"$LOGIN_PAGE" || die "/login is not the Diffinery sign-in page: check DIFFINERY_DOMAIN, DIFFINERY_ZONE and the route in apps/diffinery/wrangler.deploy.jsonc"
243265 info "/login serves the passkey sign-in page"
244266 loc="$(curl -sS -o /dev/null -w '%{http_code} %{redirect_url}' "https://$DIFFINERY_DOMAIN/auth/access" || true)"
245-if [[ "$loc" == 302\ https://*.cloudflareaccess.com/* ]]; then
267+if ((ON_CLOUDFLARE == 0)); then
268+ info "no Cloudflare Access here: the first administrator signs up with SIGNUP=open (needs TURNSTILE_SITE_KEY and TURNSTILE_SECRET and email), see HOMEFLARE.md"
269+elif [[ "$loc" == 302\ https://*.cloudflareaccess.com/* ]]; then
246270 info "/auth/access is behind Cloudflare Access"
247271 else
248272 warn "/auth/access is not behind Cloudflare Access yet ($loc), so email recovery and the first admin sign-in won't work. Set ACCESS_TEAM_DOMAIN and run this again."
@@ -252,4 +276,4 @@
252276 echo "Diffinery is live at https://$DIFFINERY_DOMAIN."
253277 echo "Sign in as the first administrator at https://$DIFFINERY_DOMAIN/auth/access with an email in BOOTSTRAP_ADMINS,"
254278 echo "then add a passkey. Run scripts/setup.sh again at any time to update."
255-[[ -n "$ACCESS_TEAM" ]] || warn "the Access team domain is still unknown; set ACCESS_TEAM_DOMAIN (Zero Trust → Settings → Custom pages shows it) and run this again"
279+[[ -n "$ACCESS_TEAM" ]] || ((ON_CLOUDFLARE == 0)) || warn "the Access team domain is still unknown; set ACCESS_TEAM_DOMAIN (Zero Trust → Settings → Custom pages shows it) and run this again"
modifiedscripts/turnstile.sh+1−1View file
@@ -43,7 +43,7 @@
4343 APP="$ROOT/apps/diffinery"
4444 WRANGLER=(pnpm --dir "$APP" exec wrangler)
4545 WORKER=diffinery
46-API="https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID"
46+API="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}/accounts/$CLOUDFLARE_ACCOUNT_ID"
4747 WIDGET_NAME="diffinery $DOMAIN"
4848 PERMISSION="Account → Turnstile → Edit (\"Turnstile Sites Write\" in the API reference)"
4949
modifiedscripts/wait-container-rollout.sh+1−1View file
@@ -10,7 +10,7 @@
1010 # ROLLOUT_WAIT_MINUTES (default 10) rather than failing the deploy.
1111 set -euo pipefail
1212 : "${CLOUDFLARE_API_TOKEN:?}" "${CLOUDFLARE_ACCOUNT_ID:?}" "${RUNNER_IMAGE:?RUNNER_IMAGE is required (scripts/runner-image.sh)}"
13-api() { curl -fsS --retry 4 --retry-all-errors --retry-delay 3 "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/containers$1" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"; }
13+api() { curl -fsS --retry 4 --retry-all-errors --retry-delay 3 "${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}/accounts/$CLOUDFLARE_ACCOUNT_ID/containers$1" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"; }
1414 deadline=$(( $(date +%s) + ${ROLLOUT_WAIT_MINUTES:-10} * 60 ))
1515 last=""
1616 while :; do