Compare changes
Choose two branches to see what changed or to start a new pull request.
5 commits
19 files changed+330−111
Files (19)
- CHANGELOG.md+7−0
- HOMEFLARE.md+84−0
- apps/diffinery/.gitignore+1−0
- apps/diffinery/docs/self-hosting/architecture.md+2−0
- apps/diffinery/docs/self-hosting/configuration.md+1−1
- apps/diffinery/package.json+2−2
- apps/diffinery/scripts/build-docs.mjs+38−10
- apps/diffinery/scripts/build-grammars.mjs+58−0
- apps/diffinery/src/web/highlight.ts+19−72
- apps/diffinery/test/unit/main-module-size.test.ts+27−0
- scripts/bootstrap-admins.sh+1−1
- scripts/bootstrap.sh+31−10
- scripts/email-sending.sh+1−1
- scripts/ensure-secrets.sh+5−1
- scripts/render-config.mjs+18−2
- scripts/runner-image.sh+1−1
- scripts/setup.sh+32−8
- scripts/turnstile.sh+1−1
- scripts/wait-container-rollout.sh+1−1
modifiedCHANGELOG.md+7−0View file
| @@ -6,6 +6,13 @@ | ||
| 6 | 6 | |
| 7 | 7 | ## [Unreleased] |
| 8 | 8 | |
| 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 | + | |
| 9 | 16 | ## [0.2.0] - 2026-10-31 |
| 10 | 17 | |
| 11 | 18 | 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 @@ | ||
| 1 | 1 | build/ |
| 2 | 2 | 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 @@ | ||
| 68 | 68 | |
| 69 | 69 | 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. |
| 70 | 70 | |
| 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 | + | |
| 71 | 73 | 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. |
| 72 | 74 | |
| 73 | 75 | 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 @@ | ||
| 300 | 300 | | `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. | |
| 301 | 301 | | `observability` | Enabled, `head_sampling_rate: 1` | Every request is logged to Workers Logs. | |
| 302 | 302 | | `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`. | | |
| 304 | 304 | | `limits.cpu_ms` | `300000` | Up to 5 minutes of CPU time per request (large pushes, diffs and merges). | |
| 305 | 305 | | `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. | |
| 306 | 306 | | `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 @@ | ||
| 12 | 12 | "cf-typegen": "wrangler types", |
| 13 | 13 | "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", |
| 14 | 14 | "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", | |
| 17 | 17 | "build:docs": "node scripts/build-docs.mjs" |
| 18 | 18 | }, |
| 19 | 19 | "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). | |
| 2 | 4 | // - every Markdown page under docs/ (with its frontmatter), in the order of docs/nav.json |
| 3 | 5 | // - the public site's pages under site/ (the product, comparison and company pages around the |
| 4 | 6 | // home page), in the order of site/nav.json |
| @@ -39,6 +41,7 @@ | ||
| 39 | 41 | /** The Claude Code plugins Diffinery serves for upload to claude.ai, by name. */ |
| 40 | 42 | const CLAUDE_PLUGIN_NAMES = new Set(["diffinery", "diffinery-ci"]); |
| 41 | 43 | const out = path.join(app, "src/docs/content.generated.ts"); |
| 44 | +const dataOut = path.join(app, "build/docs/content.txt"); | |
| 42 | 45 | |
| 43 | 46 | /** Pages produced in code rather than from a Markdown file. */ |
| 44 | 47 | const RUNTIME_PAGES = new Set(["api", "reference/mcp-tools"]); |
| @@ -315,38 +318,63 @@ | ||
| 315 | 318 | } |
| 316 | 319 | |
| 317 | 320 | 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 | +}; | |
| 318 | 331 | const src = `// Generated by scripts/build-docs.mjs from docs/, site/, claude-plugins/, apps/cli, apps/vscode and apps/jetbrains/dist. Do not edit. |
| 319 | 332 | /* eslint-disable */ |
| 333 | +import DATA from "../../build/docs/content.txt"; | |
| 334 | + | |
| 320 | 335 | export interface DocPage { title: string; description: string; markdown: string; updated?: string } |
| 321 | 336 | 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. */ | |
| 325 | 337 | export interface SitePage { title: string; description: string; markdown: string; updated: string; seoTitle: string | null; published?: string } |
| 326 | 338 | 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; | |
| 327 | 352 | /** The public site's pages (site/), by URL path, and their sections in reading order. The home page is code (web/site.tsx). */ |
| 328 | 353 | 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; | |
| 331 | 357 | 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; | |
| 333 | 359 | export const EDITOR_EXTENSION_VERSION = ${JSON.stringify(editor.version)}; |
| 334 | 360 | 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; | |
| 336 | 362 | export const EDITOR_INSTALL_SH = ${JSON.stringify(await readFile(path.join(editorInstall, "install.sh"), "utf8"))}; |
| 337 | 363 | export const EDITOR_INSTALL_PS1 = ${JSON.stringify(await readFile(path.join(editorInstall, "install.ps1"), "utf8"))}; |
| 338 | 364 | export const JETBRAINS_PLUGIN_VERSION = ${JSON.stringify(jetbrains.version)}; |
| 339 | 365 | export const JETBRAINS_PLUGIN_SINCE_BUILD = ${JSON.stringify(jetbrains.sinceBuild)}; |
| 340 | 366 | export const JETBRAINS_PLUGIN_DESCRIPTION = ${JSON.stringify(jetbrains.description)}; |
| 341 | 367 | 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; | |
| 343 | 369 | /** 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; | |
| 345 | 371 | export const CLI_INSTALL_SH = ${JSON.stringify(await readFile(path.join(cliInstall, "install.sh"), "utf8"))}; |
| 346 | 372 | export const CLI_INSTALL_PS1 = ${JSON.stringify(await readFile(path.join(cliInstall, "install.ps1"), "utf8"))}; |
| 347 | 373 | export const CLI_SHA256 = ${JSON.stringify(createHash("sha256").update(cli.bin).digest("hex"))}; |
| 348 | 374 | export const AGENT_SETUP_SH = ${JSON.stringify(await readFile(path.join(cliInstall, "agent-setup.sh"), "utf8"))}; |
| 349 | 375 | `; |
| 350 | 376 | await mkdir(path.dirname(out), { recursive: true }); |
| 377 | +await mkdir(path.dirname(dataOut), { recursive: true }); | |
| 378 | +await writeFile(dataOut, JSON.stringify(data)); | |
| 351 | 379 | await writeFile(out, src); |
| 352 | 380 | 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 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * 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. | |
| 6 | 7 | */ |
| 7 | 8 | import { createHighlighterCore, type HighlighterCore, type LanguageRegistration, type ThemedToken, type ThemeRegistration } from "shiki/core"; |
| 8 | 9 | import { createJavaScriptRegexEngine } from "shiki/engine/javascript"; |
| 10 | +import { GRAMMAR_LANGS, GRAMMAR_ORDER, GRAMMAR_TEXT } from "./grammars.generated.js"; | |
| 9 | 11 | import { escapeHtml } from "./markdown.js"; |
| 10 | 12 | |
| 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); | |
| 12 | 16 | |
| 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>(); | |
| 77 | 18 | |
| 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 | +} | |
| 80 | 27 | |
| 81 | 28 | const EXT: Record<string, Lang> = { |
| 82 | 29 | ts: "typescript", mts: "typescript", cts: "typescript", tsx: "tsx", |
| @@ -137,7 +84,7 @@ | ||
| 137 | 84 | /** Shiki language for a Markdown fence info string ("ts", "yaml", "c++" …), or null. */ |
| 138 | 85 | export function langForFence(info: string): Lang | null { |
| 139 | 86 | 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); | |
| 141 | 88 | } |
| 142 | 89 | |
| 143 | 90 | // ---------------------------------------------------------------- highlighter |
| @@ -207,7 +154,7 @@ | ||
| 207 | 154 | let p = loading.get(l); |
| 208 | 155 | if (!p) { |
| 209 | 156 | p = hl |
| 210 | - .loadLanguage(GRAMMARS[l]()) | |
| 157 | + .loadLanguage(...grammar(l)) | |
| 211 | 158 | // Compile the grammar's top-level rules now: on a cold Worker that alone can outlast the |
| 212 | 159 | // per-line time limit, which would leave the first line of a file unhighlighted. |
| 213 | 160 | .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 @@ | ||
| 59 | 59 | if [[ -z "${CLOUDFLARE_API_TOKEN:-}" || -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]]; then |
| 60 | 60 | 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" |
| 61 | 61 | 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)" | |
| 63 | 63 | if jq -e '.success == true' >/dev/null 2>&1 <<<"$SETTINGS"; then |
| 64 | 64 | LIVE="$(jq -r '[.result.bindings[]? | select(.type == "plain_text" and .name == "BOOTSTRAP_ADMINS") | .text][0] // empty' <<<"$SETTINGS")" |
| 65 | 65 | LIVE="$(trimmed "$LIVE")" |
modifiedscripts/bootstrap.sh+31−10View file
| @@ -25,7 +25,11 @@ | ||
| 25 | 25 | ROOT="$(cd "$(dirname "$0")/.." && pwd)" |
| 26 | 26 | APP="$ROOT/apps/diffinery" |
| 27 | 27 | 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 | |
| 29 | 33 | |
| 30 | 34 | cf() { # cf METHOD PATH [JSON] |
| 31 | 35 | local method="$1" path="$2" body="${3:-}" |
| @@ -74,6 +78,9 @@ | ||
| 74 | 78 | {"id":"action-mirror-30d","enabled":true,"conditions":{"prefix":"action-mirror/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":2592000}}} |
| 75 | 79 | ]}' |
| 76 | 80 | # 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 | |
| 77 | 84 | RESULT="$(cf PUT "/r2/buckets/diffinery-data/lifecycle" "$LIFECYCLE")" |
| 78 | 85 | if ! jq -e '.success' >/dev/null <<<"$RESULT"; then |
| 79 | 86 | 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 @@ | ||
| 85 | 92 | exit 1 |
| 86 | 93 | fi |
| 87 | 94 | echo "R2 lifecycle rules set" |
| 95 | +fi | |
| 88 | 96 | endlog |
| 89 | 97 | |
| 90 | 98 | # ------------------------------------------------------------------ Queues |
| @@ -127,7 +135,7 @@ | ||
| 127 | 135 | 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 |
| 128 | 136 | # The zone that holds the sending domain (the domain itself or a parent), as scripts/email-sending.sh finds it. |
| 129 | 137 | 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)" | |
| 131 | 139 | [[ -n "$zone" ]] && break |
| 132 | 140 | name="${name#*.}" |
| 133 | 141 | done |
| @@ -162,12 +170,16 @@ | ||
| 162 | 170 | 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")" |
| 163 | 171 | fi |
| 164 | 172 | } |
| 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 | |
| 166 | 174 | endlog |
| 167 | 175 | |
| 168 | 176 | # ------------------------------------------------------------------ Email Sending |
| 169 | 177 | # 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 | |
| 171 | 183 | |
| 172 | 184 | # ------------------------------------------------------------------ Turnstile |
| 173 | 185 | # The widget "diffinery <DIFFINERY_DOMAIN>", created when missing, so people who aren't signed in can |
| @@ -177,19 +189,28 @@ | ||
| 177 | 189 | # Account → Turnstile → Edit; without it turnstile.sh warns, naming it, and the deploy goes on with |
| 178 | 190 | # anonymous reports refused. Sign-up stays as SIGNUP says: keys alone don't open it. |
| 179 | 191 | 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 | |
| 181 | 199 | echo "site key: ${TURNSTILE_SITE_KEY:-none}" |
| 182 | 200 | endlog |
| 183 | 201 | |
| 184 | 202 | # ------------------------------------------------------------------ Access |
| 185 | 203 | log "Cloudflare Access" |
| 186 | 204 | TEAM="${ACCESS_TEAM_DOMAIN:-}" |
| 187 | -if [[ -z "$TEAM" ]]; then | |
| 205 | +if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then | |
| 188 | 206 | TEAM="$(cf GET /access/organizations | jq -r '.result.auth_domain // empty' || true)" |
| 189 | 207 | fi |
| 190 | -APPS="$(cf GET "/access/apps?per_page=100" || echo '{}')" | |
| 191 | 208 | 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 | |
| 193 | 214 | warn "Could not read Access applications (token needs Access: Apps and Policies Edit). Passkeys work; email recovery stays off." |
| 194 | 215 | else |
| 195 | 216 | # People sign in with passkeys. Access guards only /auth/access, the email-based |
| @@ -216,11 +237,11 @@ | ||
| 216 | 237 | 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." |
| 217 | 238 | fi |
| 218 | 239 | fi |
| 219 | -if [[ -z "$TEAM" ]]; then | |
| 240 | +if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then | |
| 220 | 241 | # Fall back to the sign-in redirect, which names the team domain. |
| 221 | 242 | TEAM="$(curl -sS -o /dev/null -w '%{redirect_url}' "https://$DOMAIN/auth/access" | sed -nE 's#^https://([^/]+\.cloudflareaccess\.com)/.*#\1#p' || true)" |
| 222 | 243 | 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)." | |
| 224 | 245 | echo "team=${TEAM:-?} aud=${AUD:+set}" |
| 225 | 246 | endlog |
| 226 | 247 |
modifiedscripts/email-sending.sh+1−1View file
| @@ -12,7 +12,7 @@ | ||
| 12 | 12 | |
| 13 | 13 | : "${CLOUDFLARE_API_TOKEN:?set CLOUDFLARE_API_TOKEN}" |
| 14 | 14 | 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}" | |
| 16 | 16 | |
| 17 | 17 | cf() { curl -sS "$CF$1" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"; } |
| 18 | 18 | warn() { echo "::warning::$*" >&2; } |
modifiedscripts/ensure-secrets.sh+5−1View file
| @@ -36,7 +36,11 @@ | ||
| 36 | 36 | # Without the Turnstile permission this warns (scripts/turnstile.sh names it) and the deploy goes on: |
| 37 | 37 | # people who aren't signed in can't send security reports until it's set. |
| 38 | 38 | 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 | |
| 40 | 44 | if "$ROOT/scripts/turnstile.sh" secret "$SITE_KEY" -c wrangler.deploy.jsonc; then |
| 41 | 45 | echo "set TURNSTILE_SECRET" |
| 42 | 46 | else |
modifiedscripts/render-config.mjs+18−2View file
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | // the host's last two labels) and sends email from notifications@<host>. |
| 11 | 11 | // --admins sets BOOTSTRAP_ADMINS (comma-separated emails; bootstrap.sh passes what |
| 12 | 12 | // 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, | |
| 14 | 14 | // TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap) and the GitHub App of GitHub |
| 15 | 15 | // runners: GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and GITHUB_APP_URL. |
| 16 | 16 | import { readFileSync, writeFileSync } from "node:fs"; |
| @@ -34,7 +34,9 @@ | ||
| 34 | 34 | if (url.protocol !== "https:" || url.pathname !== "/") throw new Error("--public-url must be an https origin, like https://git.example.com"); |
| 35 | 35 | cfg.vars.PUBLIC_URL = url.origin; |
| 36 | 36 | 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 }]; | |
| 38 | 40 | cfg.vars.MAIL_FROM = `notifications@${url.hostname}`; |
| 39 | 41 | } |
| 40 | 42 | if (values["mail-from"]) cfg.vars.MAIL_FROM = values["mail-from"]; |
| @@ -55,6 +57,20 @@ | ||
| 55 | 57 | delete c.image_build_context; |
| 56 | 58 | } |
| 57 | 59 | } |
| 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 | +} | |
| 58 | 74 | // The site key of the Turnstile widget scripts/turnstile.sh set up for this hostname (not a |
| 59 | 75 | // secret). One set in wrangler.jsonc is the operator's own and wins; turnstile.sh then leaves it alone. |
| 60 | 76 | 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 @@ | ||
| 20 | 20 | } | sha256sum | cut -c1-24 |
| 21 | 21 | ) |
| 22 | 22 | : "${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" | |
| 24 | 24 | wrangler() { (cd apps/diffinery && pnpm exec wrangler "$@"); } |
| 25 | 25 | |
| 26 | 26 | if ! listed=$(wrangler containers images list --json --filter "(^|/)$name\$" 2>&1); then |
modifiedscripts/setup.sh+32−8View file
| @@ -19,6 +19,12 @@ | ||
| 19 | 19 | # GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID, GITHUB_APP_URL |
| 20 | 20 | # the GitHub App of GitHub runners (docs/self-hosting/configuration.md#github-runners) |
| 21 | 21 | # 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 | |
| 22 | 28 | # |
| 23 | 29 | # Every step is idempotent: it creates only what is missing and keeps your data and secrets, so run |
| 24 | 30 | # it again to update. Secrets are never printed. Needs Node.js 22+, pnpm, jq, curl, openssl and Docker. |
| @@ -26,8 +32,13 @@ | ||
| 26 | 32 | |
| 27 | 33 | ROOT="$(cd "$(dirname "$0")/.." && pwd)" |
| 28 | 34 | 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}" | |
| 30 | 36 | 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 | |
| 31 | 42 | DRY_RUN=0 |
| 32 | 43 | ASK=1 |
| 33 | 44 | |
| @@ -150,12 +161,16 @@ | ||
| 150 | 161 | fi |
| 151 | 162 | jq -e '.success == true and .result.status == "active"' >/dev/null 2>&1 <<<"$verify" || die "Cloudflare doesn't accept the API token: $(errors_of "$verify")" |
| 152 | 163 | 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 | |
| 153 | 167 | zones="$(cf_get "/zones?name=$ZONE&account.id=$CLOUDFLARE_ACCOUNT_ID" || true)" |
| 154 | 168 | jq -e '.success == true' >/dev/null 2>&1 <<<"$zones" || die "couldn't look up the zone $ZONE: $(errors_of "$zones")" |
| 155 | 169 | zone_status="$(jq -r '.result[0].status // empty' <<<"$zones")" |
| 156 | 170 | [[ -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." |
| 157 | 171 | [[ "$zone_status" == active ]] || warn "the zone $ZONE is $zone_status, not active: the route serves nothing until its nameservers point at Cloudflare" |
| 158 | 172 | info "zone $ZONE is in the account ($zone_status)" |
| 173 | + fi | |
| 159 | 174 | fi |
| 160 | 175 | |
| 161 | 176 | cd "$ROOT" |
| @@ -173,7 +188,7 @@ | ||
| 173 | 188 | |
| 174 | 189 | step "Rendering the deploy config (placeholder D1 id) and bundling the Worker" |
| 175 | 190 | # 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" \ | |
| 177 | 192 | node "$ROOT/scripts/render-config.mjs" --d1 "$PLACEHOLDER_D1" ${ACCESS_TEAM_DOMAIN:+--team "$ACCESS_TEAM_DOMAIN"} \ |
| 178 | 193 | --public-url "https://$DIFFINERY_DOMAIN" ${DIFFINERY_ZONE:+--zone "$DIFFINERY_ZONE"} --mail-from "$MAIL_FROM" --admins "$ADMINS" |
| 179 | 194 | OUT="$(mktemp -d "${TMPDIR:-/tmp}/diffinery-dry-run.XXXXXX")" |
| @@ -205,7 +220,7 @@ | ||
| 205 | 220 | env -u GITHUB_ENV "$ROOT/scripts/runner-image.sh" | tee "$image_log" |
| 206 | 221 | RUNNER_IMAGE="$(tail -n 1 "$image_log")" |
| 207 | 222 | 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" | |
| 209 | 224 | export RUNNER_IMAGE |
| 210 | 225 | |
| 211 | 226 | step "Creating or updating Cloudflare resources (scripts/bootstrap.sh)" |
| @@ -221,7 +236,7 @@ | ||
| 221 | 236 | step "Worker secrets (generated on the first deploy; never printed)" |
| 222 | 237 | "$ROOT/scripts/ensure-secrets.sh" |
| 223 | 238 | |
| 224 | -if [[ -z "$ACCESS_TEAM" ]]; then | |
| 239 | +if [[ -z "$ACCESS_TEAM" ]] && ((ON_CLOUDFLARE)); then | |
| 225 | 240 | step "Finishing the Access setup (first deploy)" |
| 226 | 241 | : >"$OUTPUTS" |
| 227 | 242 | GITHUB_OUTPUT="$OUTPUTS" "$ROOT/scripts/bootstrap.sh" |
| @@ -237,12 +252,21 @@ | ||
| 237 | 252 | [[ "$code" == 200 ]] && break |
| 238 | 253 | sleep 10 |
| 239 | 254 | 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 | |
| 241 | 260 | 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" | |
| 243 | 265 | info "/login serves the passkey sign-in page" |
| 244 | 266 | 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 | |
| 246 | 270 | info "/auth/access is behind Cloudflare Access" |
| 247 | 271 | else |
| 248 | 272 | 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 @@ | ||
| 252 | 276 | echo "Diffinery is live at https://$DIFFINERY_DOMAIN." |
| 253 | 277 | echo "Sign in as the first administrator at https://$DIFFINERY_DOMAIN/auth/access with an email in BOOTSTRAP_ADMINS," |
| 254 | 278 | 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 @@ | ||
| 43 | 43 | APP="$ROOT/apps/diffinery" |
| 44 | 44 | WRANGLER=(pnpm --dir "$APP" exec wrangler) |
| 45 | 45 | 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" | |
| 47 | 47 | WIDGET_NAME="diffinery $DOMAIN" |
| 48 | 48 | PERMISSION="Account → Turnstile → Edit (\"Turnstile Sites Write\" in the API reference)" |
| 49 | 49 |
modifiedscripts/wait-container-rollout.sh+1−1View file
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | # ROLLOUT_WAIT_MINUTES (default 10) rather than failing the deploy. |
| 11 | 11 | set -euo pipefail |
| 12 | 12 | : "${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"; } | |
| 14 | 14 | deadline=$(( $(date +%s) + ${ROLLOUT_WAIT_MINUTES:-10} * 60 )) |
| 15 | 15 | last="" |
| 16 | 16 | while :; do |