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.

276 lines · 15.8 KB · executableRaw History
1#!/usr/bin/env bash
2# Deploy Diffinery to your own Cloudflare account and domain from your own machine: the first
3# deploy and every update after it. It runs the same steps as .github/workflows/deploy.yml.
4#
5# scripts/setup.sh # asks for whatever isn't in the environment, then deploys
6# scripts/setup.sh --dry-run # checks everything and builds the Worker, but changes nothing
7# pnpm setup:cloudflare # the same as scripts/setup.sh
8#
9# Settings, from the environment or asked for (in a terminal):
10# CLOUDFLARE_API_TOKEN API token with the permissions in docs/self-hosting/deploy.md (asked without echo)
11# CLOUDFLARE_ACCOUNT_ID the Cloudflare account to deploy to
12# DIFFINERY_DOMAIN your instance's hostname, e.g. git.example.com
13# BOOTSTRAP_ADMINS comma-separated emails that become site administrators on first sign-in;
14# empty keeps the list the deployed Worker has (scripts/bootstrap-admins.sh)
15# Optional, from the environment only:
16# DIFFINERY_ZONE the Cloudflare zone holding DIFFINERY_DOMAIN (default: its last two labels)
17# MAIL_DOMAIN send email from notifications@<MAIL_DOMAIN> (default DIFFINERY_DOMAIN)
18# ACCESS_TEAM_DOMAIN your Zero Trust team domain, e.g. example.cloudflareaccess.com, when the token can't read it
19# GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID, GITHUB_APP_URL
20# the GitHub App of GitHub runners (docs/self-hosting/configuration.md#github-runners)
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
28#
29# Every step is idempotent: it creates only what is missing and keeps your data and secrets, so run
30# it again to update. Secrets are never printed. Needs Node.js 22+, pnpm, jq, curl, openssl and Docker.
31set -euo pipefail
32
33ROOT="$(cd "$(dirname "$0")/.." && pwd)"
34APP="$ROOT/apps/diffinery"
35CF_API="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}"
36PLACEHOLDER_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.
39ON_CLOUDFLARE=1
40[[ "$CF_API" == https://api.cloudflare.com/* ]] || ON_CLOUDFLARE=0
41export ON_CLOUDFLARE
42DRY_RUN=0
43ASK=1
44
45usage() {
46 cat <<'EOF'
47Usage: scripts/setup.sh [--dry-run] [--yes] [--help]
48
49Deploys Diffinery to your Cloudflare account and domain, or updates a deployment: checks the
50tools and your API token, then builds, creates any missing Cloudflare resources (scripts/bootstrap.sh),
51deploys the Worker and runner image, sets the Worker's secrets and checks the live site.
52
53 --dry-run Check the tools, the token and the zone (read-only, when a token is given), build,
54 render apps/diffinery/wrangler.deploy.jsonc with a placeholder D1 id and run
55 `wrangler deploy --dry-run` on it. Creates, changes and deploys nothing.
56 --yes, -y Don't ask: take every setting from the environment and fail if one is missing.
57 --help, -h Show this help.
58
59Settings (environment variables; asked for in a terminal when missing):
60 CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, DIFFINERY_DOMAIN (e.g. git.example.com),
61 BOOTSTRAP_ADMINS (comma-separated emails of the first site administrators; empty keeps the
62 deployed Worker's list). Optional: DIFFINERY_ZONE, MAIL_DOMAIN, ACCESS_TEAM_DOMAIN.
63
64Docs: apps/diffinery/docs/self-hosting/deploy.md (served at /docs/self-hosting/deploy).
65EOF
66}
67
68for arg in "$@"; do
69 case "$arg" in
70 --dry-run) DRY_RUN=1 ;;
71 --yes | -y) ASK=0 ;;
72 --help | -h) usage; exit 0 ;;
73 *) echo "unknown option: $arg (see scripts/setup.sh --help)" >&2; exit 2 ;;
74 esac
75done
76[[ -t 0 ]] || ASK=0
77
78step() { printf '\n==> %s\n' "$*"; }
79info() { printf ' %s\n' "$*"; }
80warn() { printf 'warning: %s\n' "$*" >&2; }
81die() { printf 'error: %s\n' "$*" >&2; exit 1; }
82
83# ------------------------------------------------------------------ prerequisites
84step "Checking tools"
85missing=()
86for tool in node pnpm jq curl openssl; do command -v "$tool" >/dev/null 2>&1 || missing+=("$tool"); done
87((${#missing[@]} == 0)) || die "missing: ${missing[*]}. Install Node.js 22+, pnpm 10, jq, curl, openssl and Docker (see the deploy docs)."
88node_major="$(node -p 'process.versions.node.split(".")[0]')"
89((node_major >= 22)) || die "Node.js 22 or later is needed (this is $(node --version))"
90info "node $(node --version), pnpm $(pnpm --version), $(jq --version), curl, openssl"
91if ! command -v docker >/dev/null 2>&1; then
92 ((DRY_RUN)) || die "docker is missing: the runner container image is built with Docker. Install it and start the daemon."
93 warn "docker is missing; a real deploy needs it to build the runner image"
94elif ! docker info >/dev/null 2>&1; then
95 ((DRY_RUN)) || die "docker is installed but its daemon isn't running (docker info failed). Start it and run this again."
96 warn "the Docker daemon isn't running; a real deploy needs it to build the runner image"
97else
98 info "docker $(docker version --format '{{.Server.Version}}' 2>/dev/null || echo '(running)')"
99fi
100
101# ------------------------------------------------------------------ settings
102# ask VAR "Prompt" [secret]: keeps a value from the environment, else asks (in a terminal).
103ask() {
104 local var="$1" prompt="$2" secret="${3:-}" value
105 value="${!var:-}"
106 if [[ -z "$value" && $ASK == 1 ]]; then
107 if [[ -n "$secret" ]]; then
108 read -rsp "$prompt: " value; echo
109 else
110 read -rp "$prompt: " value
111 fi
112 fi
113 printf -v "$var" '%s' "$value"
114 export "${var?}"
115}
116
117step "Settings"
118ask CLOUDFLARE_API_TOKEN "Cloudflare API token (input hidden)" secret
119ask CLOUDFLARE_ACCOUNT_ID "Cloudflare account ID"
120ask DIFFINERY_DOMAIN "Hostname for your instance (e.g. git.example.com)"
121if [[ -z "${BOOTSTRAP_ADMINS:-}" && $ASK == 1 ]]; then
122 read -rp "Emails of the first site administrators, comma-separated (empty keeps the deployed list): " BOOTSTRAP_ADMINS
123fi
124export BOOTSTRAP_ADMINS="${BOOTSTRAP_ADMINS:-}"
125
126DIFFINERY_DOMAIN="$(tr '[:upper:]' '[:lower:]' <<<"$DIFFINERY_DOMAIN")"
127[[ -n "$DIFFINERY_DOMAIN" ]] || die "set DIFFINERY_DOMAIN to your instance's hostname, for example git.example.com"
128[[ "$DIFFINERY_DOMAIN" =~ ^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$ ]] || die "DIFFINERY_DOMAIN must be a bare hostname such as git.example.com, without https:// or a path (got \"$DIFFINERY_DOMAIN\")"
129ZONE="${DIFFINERY_ZONE:-$(awk -F. '{print $(NF-1)"."$NF}' <<<"$DIFFINERY_DOMAIN")}"
130[[ "$DIFFINERY_DOMAIN" == "$ZONE" || "$DIFFINERY_DOMAIN" == *".$ZONE" ]] || die "DIFFINERY_ZONE ($ZONE) doesn't hold $DIFFINERY_DOMAIN"
131MAIL_FROM="notifications@${MAIL_DOMAIN:-$DIFFINERY_DOMAIN}"
132if [[ -n "$BOOTSTRAP_ADMINS" ]]; then
133 IFS=, read -ra entries <<<"$BOOTSTRAP_ADMINS"
134 for e in "${entries[@]}"; do
135 e="$(sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<<"$e")"
136 [[ -z "$e" || "$e" =~ ^[^[:space:]@]+@[^[:space:]@]+$ ]] || die "BOOTSTRAP_ADMINS takes comma-separated email addresses; \"$e\" isn't one"
137 done
138fi
139export DIFFINERY_DOMAIN
140[[ -z "${DIFFINERY_ZONE:-}" ]] || export DIFFINERY_ZONE
141info "hostname: https://$DIFFINERY_DOMAIN (route $DIFFINERY_DOMAIN/* in zone $ZONE)"
142info "email: $MAIL_FROM"
143info "admins: $(if [[ -n "$BOOTSTRAP_ADMINS" ]]; then tr ',' '\n' <<<"$BOOTSTRAP_ADMINS" | grep -c '[^[:space:]]' | sed 's/$/ address(es) from BOOTSTRAP_ADMINS/'; else echo "keep the deployed Worker's list (none on a new instance)"; fi)"
144if ((DRY_RUN)); then info "mode: dry run (changes nothing)"; else info "mode: deploy"; fi
145
146# ------------------------------------------------------------------ token and zone
147cf_get() { curl -sS --retry 3 --retry-delay 2 "$CF_API$1" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"; }
148errors_of() { jq -r '[.errors[]? | "\(.code): \(.message)"] | join("; ")' <<<"$1" 2>/dev/null || echo "no answer"; }
149
150if [[ -z "$CLOUDFLARE_API_TOKEN" || -z "$CLOUDFLARE_ACCOUNT_ID" ]]; then
151 ((DRY_RUN)) || die "set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID (Step 2 of the deploy docs says which permissions the token needs)"
152 step "Cloudflare token"
153 warn "no CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID: the dry run skips the token and zone checks"
154else
155 [[ "$CLOUDFLARE_ACCOUNT_ID" =~ ^[0-9a-f]{32}$ ]] || die "CLOUDFLARE_ACCOUNT_ID should be 32 hex characters (the dashboard's Account ID), not \"$CLOUDFLARE_ACCOUNT_ID\""
156 step "Cloudflare token"
157 # User tokens verify at /user/tokens/verify, account-owned tokens at /accounts/{id}/tokens/verify.
158 verify="$(cf_get /user/tokens/verify || true)"
159 if ! jq -e '.success == true and .result.status == "active"' >/dev/null 2>&1 <<<"$verify"; then
160 verify="$(cf_get "/accounts/$CLOUDFLARE_ACCOUNT_ID/tokens/verify" || true)"
161 fi
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")"
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
167 zones="$(cf_get "/zones?name=$ZONE&account.id=$CLOUDFLARE_ACCOUNT_ID" || true)"
168 jq -e '.success == true' >/dev/null 2>&1 <<<"$zones" || die "couldn't look up the zone $ZONE: $(errors_of "$zones")"
169 zone_status="$(jq -r '.result[0].status // empty' <<<"$zones")"
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."
171 [[ "$zone_status" == active ]] || warn "the zone $ZONE is $zone_status, not active: the route serves nothing until its nameservers point at Cloudflare"
172 info "zone $ZONE is in the account ($zone_status)"
173 fi
174fi
175
176cd "$ROOT"
177
178# ------------------------------------------------------------------ build
179step "Installing and building"
180pnpm install --frozen-lockfile
181pnpm -r --if-present build
182
183if ((DRY_RUN)); then
184 # ---------------------------------------------------------------- dry run
185 step "Bootstrap administrators"
186 # Reads the deployed Worker's list when there are credentials (a read, never a write).
187 ADMINS="$("$ROOT/scripts/bootstrap-admins.sh")"
188
189 step "Rendering the deploy config (placeholder D1 id) and bundling the Worker"
190 # A placeholder runner image: the dry run builds no container image (that needs Docker and the registry).
191 RUNNER_IMAGE="${CLOUDFLARE_CONTAINER_REGISTRY:-registry.cloudflare.com}/${CLOUDFLARE_ACCOUNT_ID:-00000000000000000000000000000000}/diffinery-runner:dry-run" \
192 node "$ROOT/scripts/render-config.mjs" --d1 "$PLACEHOLDER_D1" ${ACCESS_TEAM_DOMAIN:+--team "$ACCESS_TEAM_DOMAIN"} \
193 --public-url "https://$DIFFINERY_DOMAIN" ${DIFFINERY_ZONE:+--zone "$DIFFINERY_ZONE"} --mail-from "$MAIL_FROM" --admins "$ADMINS"
194 OUT="$(mktemp -d "${TMPDIR:-/tmp}/diffinery-dry-run.XXXXXX")"
195 (cd "$APP" && pnpm exec wrangler deploy --dry-run -c wrangler.deploy.jsonc --outdir "$OUT")
196
197 CFG="$(tail -n +2 "$APP/wrangler.deploy.jsonc")"
198 step "Dry run summary"
199 info "route: $(jq -r '.routes | map("\(.pattern) (zone \(.zone_name))") | join(", ")' <<<"$CFG")"
200 info "PUBLIC_URL: $(jq -r .vars.PUBLIC_URL <<<"$CFG")"
201 info "MAIL_FROM: $(jq -r .vars.MAIL_FROM <<<"$CFG")"
202 info "BOOTSTRAP_ADMINS: $(jq -r '.vars.BOOTSTRAP_ADMINS | split(",") | map(select(length > 0)) | length' <<<"$CFG") address(es)"
203 info "bundle: $OUT"
204 if [[ "$DIFFINERY_DOMAIN" != diffinery.com ]] && grep -q 'diffinery\.com' <<<"$CFG"; then
205 warn "the rendered config still mentions diffinery.com: $(grep -o '"[^"]*diffinery\.com[^"]*"' <<<"$CFG" | sort -u | tr '\n' ' ')"
206 fi
207 echo
208 echo "Dry run passed: apps/diffinery/wrangler.deploy.jsonc is valid and the Worker bundles. Nothing was"
209 echo "created or deployed. Run scripts/setup.sh without --dry-run to deploy to https://$DIFFINERY_DOMAIN."
210 exit 0
211fi
212
213# ------------------------------------------------------------------ deploy
214wrangler() { (cd "$APP" && pnpm exec wrangler "$@"); }
215OUTPUTS="$(mktemp "${TMPDIR:-/tmp}/diffinery-setup.XXXXXX")"
216trap 'rm -f "$OUTPUTS"' EXIT
217
218step "Runner image (built only when the runner changed)"
219image_log="$(mktemp "${TMPDIR:-/tmp}/diffinery-image.XXXXXX")"
220env -u GITHUB_ENV "$ROOT/scripts/runner-image.sh" | tee "$image_log"
221RUNNER_IMAGE="$(tail -n 1 "$image_log")"
222rm -f "$image_log"
223[[ "$RUNNER_IMAGE" == ${CLOUDFLARE_CONTAINER_REGISTRY:-registry.cloudflare.com}/* ]] || die "scripts/runner-image.sh didn't print the runner image"
224export RUNNER_IMAGE
225
226step "Creating or updating Cloudflare resources (scripts/bootstrap.sh)"
227GITHUB_OUTPUT="$OUTPUTS" "$ROOT/scripts/bootstrap.sh"
228ACCESS_TEAM="$(sed -n 's/^access_team=//p' "$OUTPUTS" | tail -n 1)"
229
230step "Deploying the Worker and runner image"
231wrangler deploy -c wrangler.deploy.jsonc
232
233step "Waiting for new containers to get the new image"
234"$ROOT/scripts/wait-container-rollout.sh"
235
236step "Worker secrets (generated on the first deploy; never printed)"
237"$ROOT/scripts/ensure-secrets.sh"
238
239if [[ -z "$ACCESS_TEAM" ]] && ((ON_CLOUDFLARE)); then
240 step "Finishing the Access setup (first deploy)"
241 : >"$OUTPUTS"
242 GITHUB_OUTPUT="$OUTPUTS" "$ROOT/scripts/bootstrap.sh"
243 wrangler deploy -c wrangler.deploy.jsonc --containers-rollout none
244 ACCESS_TEAM="$(sed -n 's/^access_team=//p' "$OUTPUTS" | tail -n 1)"
245fi
246
247# ------------------------------------------------------------------ checks
248step "Checking https://$DIFFINERY_DOMAIN"
249code=""
250for _ in $(seq 1 30); do
251 code="$(curl -s -o /dev/null -w '%{http_code}' "https://$DIFFINERY_DOMAIN/healthz" || true)"
252 [[ "$code" == 200 ]] && break
253 sleep 10
254done
255if ((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."
257else
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."
259fi
260info "/healthz -> 200"
261curl -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"
262info "/login serves the passkey sign-in page"
263loc="$(curl -sS -o /dev/null -w '%{http_code} %{redirect_url}' "https://$DIFFINERY_DOMAIN/auth/access" || true)"
264if ((ON_CLOUDFLARE == 0)); then
265 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"
266elif [[ "$loc" == 302\ https://*.cloudflareaccess.com/* ]]; then
267 info "/auth/access is behind Cloudflare Access"
268else
269 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."
270fi
271
272echo
273echo "Diffinery is live at https://$DIFFINERY_DOMAIN."
274echo "Sign in as the first administrator at https://$DIFFINERY_DOMAIN/auth/access with an email in BOOTSTRAP_ADMINS,"
275echo "then add a passkey. Run scripts/setup.sh again at any time to update."
276[[ -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"