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.

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