Nix binary cache index for GHCR with isolated PR overlays, closure-safe GC, and keyless GitHub Actions OIDC uploads.
Firn stores only store path metadata and signatures; compressed NAR blobs are stored in GHCR and transfer directly via 302 redirects.
- Cache & Dashboard: cache.so1ve.dev
- CI Integration: so1ve/nur-packages
# Run once
nix run github:so1ve/firn -- --help
# Or use nix shell
nix shell github:so1ve/firnIn a NixOS or Home Manager flake, add inputs.firn.url = "github:so1ve/firn"
and include inputs.firn.packages.${system}.default in environment.systemPackages.
Keep wrangler.jsonc unmodified so upstream binding and routing
updates merge cleanly. Instance-specific values (database_id, custom domains,
PUBLIC_BASE_URL, OWNERS_JSON) live in GitHub repository variables,
Cloudflare dashboard variables (preserved via keep_vars: true), or a
gitignored wrangler.local.jsonc.
- Fork this repository on GitHub and create a D1 database (
firn) in your Cloudflare account. - Add Repository Secrets in your fork:
CLOUDFLARE_API_TOKEN(Workers Scripts, D1, and Account Settings edit permissions) andCLOUDFLARE_ACCOUNT_ID. - Add Repository Variables in your fork:
FIRN_DEPLOY=trueFIRN_D1_DATABASE_ID=<your-d1-database-id>- Optional:
FIRN_CUSTOM_DOMAIN(e.g.cache.example.com),FIRN_PUBLIC_BASE_URL,FIRN_OWNERS_JSON,FIRN_GITHUB_APP_ID,FIRN_GC_PR_TTL_DAYS,FIRN_GC_MAIN_LRU_DAYS,FIRN_GC_MAX_SUBREQUESTS,FIRN_WORKER_NAME,FIRN_D1_DATABASE_NAME
- Run the Deploy Worker workflow once (or push to
main). - Configure the secrets below in the Cloudflare dashboard or via
wrangler secret put.
To stay up to date in a fork or one-click clone, use Sync fork on GitHub or
run the Sync Upstream workflow (choosing latest-release or main).
Cloudflare automatically provisions the D1 database (DB) and deploys the
Worker. After the first deploy, set the variables and secrets below in the
Cloudflare dashboard and set the Workers Builds deploy command to
pnpm run deploy so future builds apply migrations/ automatically.
Generate two Ed25519 key pairs: one for the main cache and one for pull request overlays.
firn keygen cache.example.com-1 -s main.key -p main.pub
firn keygen cache.example.com-pr-1 -s pr.key -p pr.pubpnpm exec wrangler d1 create firnCreate a gitignored wrangler.local.jsonc containing only your instance
overrides:
Environment variables (vars):
PUBLIC_BASE_URL: public HTTPS URL of the cache (also used as the OIDC audience).GC_PR_TTL_DAYS/GC_MAIN_LRU_DAYS: PR expiry (default3) and closure-safe main LRU (default15).GC_MAX_SUBREQUESTS: max GitHub API subrequests per GC invocation (default40for Cloudflare Workers Free plan; increase on Workers Paid plans, e.g.800).GITHUB_APP_ID: numeric GitHub App ID (optional; required for local manual pushes and private GHCR package pull fallback).OWNERS_JSON: JSON array of allowed GitHub users/orgs, for example:
[
{
"name": "so1ve",
"owner_type": "user",
"github_owner_id": 58381667,
"github_installation_id": 98765432,
"package_template": "{repo}-cache",
"repo_packages": {
"nix-config": "nixos-cache"
},
"manual_push_package": "manual-cache",
"main_refs": ["refs/heads/main"],
"allowed_repos": []
}
]repo_packages is optional and overrides package_template for specific
repositories (when allowed_repos is non-empty, every key in repo_packages
must also be listed in allowed_repos).
For GHCR GC deletion, set
GITHUB_PACKAGES_TOKENto a GitHub classic PAT withread:packagesanddelete:packagesscopes (GitHub Packages REST API rejects custom GitHub App installation tokens on package deletion). If you also set up a GitHub App for webhooks and local push, grant Packages: Read & write and Pull requests: Read-only, subscribe toPull requestevents, and point the webhook URL tohttps://cache.example.com/api/v1/webhooks/github.
See .dev.vars.example for local development. In production,
set secrets via Wrangler and deploy (pnpm run deploy applies D1 migrations and
deploys the Worker):
pnpm exec wrangler secret put MAIN_SIGNING_KEY < main.key
pnpm exec wrangler secret put PR_SIGNING_KEY < pr.key
pnpm exec wrangler secret put GITHUB_PACKAGES_TOKEN
pnpm exec wrangler secret put GITHUB_APP_PRIVATE_KEY < github-app.pem
pnpm exec wrangler secret put GITHUB_WEBHOOK_SECRET
pnpm exec wrangler secret put MANUAL_TOKENS_JSON
pnpm exec wrangler secret put ADMIN_TOKEN
pnpm run deployHigh-concurrency CI tip: Enable Read Replication on the D1 database in the Cloudflare dashboard. Firn automatically routes read-only cache lookups through D1
first-unconstrainedread sessions, edge-caches200.narinfohits incaches.default(never caching404misses), and returns429withRetry-Afterif D1 temporarily hits its resource limit so Nix backs off cleanly.
Self-hosted Firn uses Node 24's built-in node:sqlite (zero native builds),
applies migrations automatically on startup, schedules periodic GC in-process
(with no 50-subrequest Worker cap), and supports *_FILE variants for all
secret environment variables (MAIN_SIGNING_KEY_FILE, PR_SIGNING_KEY_FILE,
GITHUB_PACKAGES_TOKEN_FILE, GITHUB_APP_PRIVATE_KEY_FILE,
GITHUB_WEBHOOK_SECRET_FILE, MANUAL_TOKENS_JSON_FILE, ADMIN_TOKEN_FILE,
LIBSQL_AUTH_TOKEN_FILE).
export PUBLIC_BASE_URL=https://cache.example.com
export OWNERS_JSON='[{"name":"so1ve","owner_type":"user","github_owner_id":58381667}]'
export MAIN_SIGNING_KEY_FILE=/path/to/main.key
export PR_SIGNING_KEY_FILE=/path/to/pr.key
firn serve --host 0.0.0.0 --port 8787 --db /var/lib/firn/firn.dbPass --libsql-url (or set LIBSQL_URL + LIBSQL_AUTH_TOKEN) to store index
state in Turso/libSQL instead of a local SQLite file. Set --gc-interval 0 (or
GC_INTERVAL_MINUTES=0) to disable built-in periodic GC.
Prebuilt multi-arch (linux/amd64, linux/arm64) images are published to
ghcr.io/so1ve/firn:
docker run -d --name firn -p 8787:8787 -v firn-data:/data \
-e PUBLIC_BASE_URL=https://cache.example.com \
-e OWNERS_JSON='[...]' \
-e MAIN_SIGNING_KEY="$(cat main.key)" \
-e PR_SIGNING_KEY="$(cat pr.key)" \
ghcr.io/so1ve/firn:latestThe flake exports nixosModules.default with hardened systemd DynamicUser
and LoadCredential secret wiring:
{
imports = [ inputs.firn.nixosModules.default ];
services.firn = {
enable = true;
publicBaseUrl = "https://cache.example.com";
mainSigningKeyFile = config.age.secrets.firn-main-key.path;
prSigningKeyFile = config.age.secrets.firn-pr-key.path;
adminTokenFile = config.age.secrets.firn-admin-token.path;
owners = [
{
name = "so1ve";
owner_type = "user";
github_owner_id = 58381667;
}
];
};
}src/entry/web.ts exports a standard Web Fetch handler
(default.fetch and createWebApp) backed by Turso/libSQL over Hrana HTTP
(LIBSQL_URL and LIBSQL_AUTH_TOKEN), with zero native dependencies and zero
filesystem access at runtime. Before deploying (or after adding migrations),
apply migrations/*.sql once with:
LIBSQL_URL=libsql://... LIBSQL_AUTH_TOKEN=... firn migrateThen serve public/ as static assets, point Vercel, Deno Deploy, Bun, or
Netlify Edge at src/entry/web.ts, and trigger periodic GC via your platform's
cron calling POST /api/v1/admin/gc (or createWebApp().runScheduledGc()).
Opening the cache root URL (GET /) in a browser serves a server-rendered
dashboard showing:
- Cache summary (main/PR path counts, blob totals, priority, GC policy)
- Copyable
nix.conf, GitHub Actions, and PR Overlay configuration snippets - Live-filterable store paths table with direct
.narinfolinks - Active PR overlays with remaining TTL and GitHub links
- Per-owner GHCR storage breakdown and
gc-blockedpackage notices - Optional Admin unlock (using
ADMIN_TOKEN, stored insessionStorage) to run dry-run/full GC or remove PR overlays directly from the browser
Uses OIDC (id-token: write) with no repository secrets. Public keys are
fetched automatically from /api/v1/public-keys, and the action runs directly
on Node 24 with zero dependency installation or binary downloads.
permissions:
contents: read
id-token: write
packages: write
steps:
- uses: actions/checkout@v7
- uses: cachix/install-nix-action@v32
- uses: so1ve/firn@v1
with:
server: https://cache.example.com
- run: nix build .#default --print-out-paths >> "$FIRN_PATHS_FILE"- Explicit runtime closure (recommended): append build outputs to the
automatically exported
$FIRN_PATHS_FILE(or passpaths/paths-file) so Firn uploads only the runtime closure of final outputs, skipping build-time crates, patches, and vendored sources. - Zero-config fallback: if no explicit paths are recorded, Firn diffs
/nix/storeand automatically drops unreferenced fixed-output derivations (FODs) and store-copied source files. - Refs listed in
main_refs(defaultrefs/heads/main) push to the main cache. Pushes from other branches skip cache upload gracefully. - Internal
pull_requestjobs pull from and push to/pr/<owner>/<repo>/<number>. Fork PRs only pull from the main cache.
Add the cache and main public key to nix.conf (or flake.nix nixConfig):
extra-substituters = https://cache.example.com
extra-trusted-public-keys = cache.example.com-1:<MAIN_PUBLIC_KEY>
To push store paths from a local machine, configure MANUAL_TOKENS_JSON (for
example {"so1ve":["<random-token>"]}) and a GitHub App installation for the
owner. Firn exchanges a short-lived scoped GHCR upload token on demand.
export FIRN_SERVER=https://cache.example.com
export FIRN_TOKEN=<manual-token>
firn push ./result
# Or pipe paths from stdin (already-signed cache.nixos.org paths are skipped):
nix build .#default --print-out-paths | firn push --stdinUse --owner <name> only if the same token is shared across multiple owners,
--jobs <n> to control upload concurrency (default 4), and
--include-upstream to upload paths already signed by cache.nixos.org-1:.
When ADMIN_TOKEN is configured on the server, the local CLI can inspect and
manage the remote cache from any machine (pass --server / --token or set
FIRN_SERVER / FIRN_ADMIN_TOKEN; add --json to any read/GC command for
machine-readable output):
export FIRN_SERVER=https://cache.example.com
export FIRN_ADMIN_TOKEN=<admin-token>
# Overview: public keys, GC policy, store path counts, per-owner blob usage & gc-blocked list
firn status
# List recently accessed store paths (optional: -q <text>, --owner <name>, --scope <scope>)
firn ls --limit 50
firn ls -q firefox --owner so1ve
# List active PR overlays and remaining TTL
firn pr ls
# Remove a PR overlay immediately (unreferenced blobs are cleaned on next GC)
firn pr rm so1ve latchshot 7
# Trigger GC on demand (add --dry-run to preview without mutating D1 or GHCR)
firn gc --dry-run
firn gc
{ "d1_databases": [{ "binding": "DB", "database_id": "<your-d1-database-id>" }], "routes": [{ "pattern": "cache.example.com", "custom_domain": true }], "vars": { "PUBLIC_BASE_URL": "https://cache.example.com", "OWNERS_JSON": "[...]", }, }