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.

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