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.

diffinery/scripts/bootstrap.sh
263 lines · 17.1 KB · executableRaw History
1#!/usr/bin/env bash
2# Idempotent production setup for Diffinery on a Cloudflare account.
3#
4# Creates (only when missing): the D1 database, R2 bucket, event and mail queues, the
5# subscription that sends Email Sending's bounces and complaints to the diffinery-mail-events
6# queue, the Email Sending setup for the domain (scripts/email-sending.sh), the Turnstile
7# widget for the security report form (scripts/turnstile.sh) and the
8# Cloudflare Access application for /auth/access, the email-based account
9# recovery path. Everyday sign-in uses passkeys; git, the API, MCP and runners
10# use Diffinery tokens.
11# Then renders apps/diffinery/wrangler.deploy.jsonc and applies D1 migrations.
12#
13# Requires: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, node, jq, curl.
14# Optional: DIFFINERY_DOMAIN (default diffinery.com; the Worker's route, PUBLIC_URL
15# and sender follow it), DIFFINERY_ZONE (the Cloudflare zone holding that host,
16# default its last two labels), MAIL_DOMAIN (default DIFFINERY_DOMAIN),
17# ACCESS_TEAM_DOMAIN (e.g. example.cloudflareaccess.com) when the token cannot read it,
18# BOOTSTRAP_ADMINS (comma-separated emails that become site administrators on first sign-in;
19# when unset, the deployed Worker keeps the list it has: see scripts/bootstrap-admins.sh).
20set -euo pipefail
21
22: "${CLOUDFLARE_API_TOKEN:?set CLOUDFLARE_API_TOKEN}"
23: "${CLOUDFLARE_ACCOUNT_ID:?set CLOUDFLARE_ACCOUNT_ID}"
24DOMAIN="${DIFFINERY_DOMAIN:-diffinery.com}"
25ROOT="$(cd "$(dirname "$0")/.." && pwd)"
26APP="$ROOT/apps/diffinery"
27WRANGLER=(pnpm --dir "$APP" exec wrangler)
28CF_API="${CLOUDFLARE_API_BASE_URL:-https://api.cloudflare.com/client/v4}"
29API="$CF_API/accounts/$CLOUDFLARE_ACCOUNT_ID"
30# 0 on another Cloudflare-compatible API (Homeflare): the steps that need Cloudflare itself are skipped.
31ON_CLOUDFLARE=1
32[[ "$CF_API" == https://api.cloudflare.com/* ]] || ON_CLOUDFLARE=0
33
34cf() { # cf METHOD PATH [JSON]
35 local method="$1" path="$2" body="${3:-}"
36 if [[ -n "$body" ]]; then
37 curl -sS -X "$method" "$API$path" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" --data "$body"
38 else
39 curl -sS -X "$method" "$API$path" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
40 fi
41}
42log() { echo "::group::$*"; }
43endlog() { echo "::endgroup::"; }
44warn() { echo "::warning::$*" >&2; }
45
46# ------------------------------------------------------------------ D1
47log "D1 database"
48D1_ID="$(cf GET "/d1/database?name=diffinery&per_page=100" | jq -r '.result[]? | select(.name=="diffinery") | .uuid' | head -n1)"
49if [[ -z "$D1_ID" ]]; then
50 D1_ID="$(cf POST /d1/database '{"name":"diffinery"}' | jq -r '.result.uuid // empty')"
51 [[ -n "$D1_ID" ]] || { echo "could not create D1 database (does the token have D1: Edit?)" >&2; exit 1; }
52 echo "created D1 database $D1_ID"
53else
54 echo "D1 database exists: $D1_ID"
55fi
56echo "read replication: $(cf GET "/d1/database/$D1_ID" | jq -r '.result.read_replication.mode // "unknown"') (turn it on with the 'D1 read replication' workflow)"
57endlog
58
59# ------------------------------------------------------------------ R2
60log "R2 bucket"
61if cf GET "/r2/buckets/diffinery-data" | jq -e '.success' >/dev/null; then
62 echo "R2 bucket exists"
63else
64 cf POST /r2/buckets '{"name":"diffinery-data"}' | jq -e '.success' >/dev/null || { echo "could not create R2 bucket (R2 enabled? token has R2: Edit?)" >&2; exit 1; }
65 echo "created R2 bucket diffinery-data"
66fi
67# Lifecycle rules (layout: apps/diffinery/src/lib/storage-keys.ts). Only transient prefixes
68# age out; repos/ (git objects, LFS, release assets), registry/ and actions-cache/ (evicted
69# by Diffinery) have no age rule. Multipart uploads left unfinished are aborted after a day.
70LIFECYCLE='{"rules":[
71 {"id":"abort-multipart-1d","enabled":true,"conditions":{"prefix":""},"abortMultipartUploadsTransition":{"condition":{"type":"Age","maxAge":86400}}},
72 {"id":"artifacts-90d","enabled":true,"conditions":{"prefix":"artifacts/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":7776000}}},
73 {"id":"logs-90d","enabled":true,"conditions":{"prefix":"logs/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":7776000}}},
74 {"id":"actions-staging-1d","enabled":true,"conditions":{"prefix":"actions-staging/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":86400}}},
75 {"id":"archives-30d","enabled":true,"conditions":{"prefix":"archives/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":2592000}}},
76 {"id":"exports-8d","enabled":true,"conditions":{"prefix":"exports/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":691200}}},
77 {"id":"events-400d","enabled":true,"conditions":{"prefix":"events/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":34560000}}},
78 {"id":"action-mirror-30d","enabled":true,"conditions":{"prefix":"action-mirror/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":2592000}}}
79]}'
80# Applied on every deploy; a failure stops it, since a wrong rule can delete data.
81if ((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."
83else
84RESULT="$(cf PUT "/r2/buckets/diffinery-data/lifecycle" "$LIFECYCLE")"
85if ! jq -e '.success' >/dev/null <<<"$RESULT"; then
86 echo "could not set the R2 lifecycle rules (token has R2: Edit?): $(jq -c '.errors // .' <<<"$RESULT" 2>/dev/null || echo "$RESULT")" >&2
87 exit 1
88fi
89CURRENT="$(cf GET "/r2/buckets/diffinery-data/lifecycle")"
90if jq -e '[.result.rules[]? | select(.deleteObjectsTransition != null and ((.conditions.prefix // "") | startswith("repos/") or . == ""))] | length > 0' >/dev/null <<<"$CURRENT"; then
91 echo "an R2 lifecycle rule still deletes objects under repos/ (git objects, LFS); refusing to continue" >&2
92 exit 1
93fi
94echo "R2 lifecycle rules set"
95fi
96endlog
97
98# ------------------------------------------------------------------ Queues
99log "Queues"
100EXISTING_QUEUES="$(cf GET "/queues?per_page=100" | jq -r '.result[]?.queue_name')"
101for q in diffinery-events diffinery-events-dlq diffinery-mail diffinery-mail-dlq diffinery-mail-events; do
102 if grep -qx "$q" <<<"$EXISTING_QUEUES"; then
103 echo "queue $q exists"
104 else
105 cf POST /queues "{\"queue_name\":\"$q\"}" | jq -e '.success' >/dev/null || { echo "could not create queue $q (token has Queues: Edit?)" >&2; exit 1; }
106 echo "created queue $q"
107 fi
108done
109endlog
110
111# ------------------------------------------------------------------ Email Sending events
112# Bounces and complaints reach the Worker through a Queues event subscription: source email.sending
113# (one per sending domain), events message.bounced and message.complained, destination the
114# diffinery-mail-events queue. Created only when missing; one that lacks an event gets it added.
115# Create: POST /accounts/{account_id}/event_subscriptions/subscriptions
116# https://developers.cloudflare.com/api/resources/queues/subresources/subscriptions/methods/create/
117# List: GET /accounts/{account_id}/event_subscriptions/subscriptions?queue_id=...
118# Update: PATCH /accounts/{account_id}/event_subscriptions/subscriptions/{id}
119# Source and event names: https://developers.cloudflare.com/queues/event-subscriptions/events-schemas/
120# and https://developers.cloudflare.com/email-service/platform/event-subscriptions/. The email.sending
121# source takes zone_id and domain, as `wrangler queues subscription create --source email.sending
122# --zone-id ... --domain ...` sends them (https://developers.cloudflare.com/workers/wrangler/commands/queues/).
123# The token needs Account → Queues → Edit (the API reference's "Queues Write") for this, and
124# Zone → Zone → Read on the sending domain to find its zone. Without them this warns and the deploy
125# goes on: bounces and complaints then don't reach the suppression list until someone subscribes the
126# queue in the dashboard (docs/admin/site-administration.md).
127log "Email Sending event subscription"
128SEND_DOMAIN="${MAIL_DOMAIN:-$DOMAIN}"
129SUB_EVENTS='["message.bounced","message.complained"]'
130SUB_PERMISSION="Account → Queues → Edit (\"Queues Write\" in the API reference)"
131api_errors() { jq -r '[.errors[]? | "\(.code): \(.message)"] | join("; ")' <<<"$1" 2>/dev/null || echo "$1"; }
132subscribe_mail_events() {
133 local qid zone="" name="$SEND_DOMAIN" list existing id body res
134 qid="$(cf GET "/queues?per_page=100" | jq -r '.result[]? | select(.queue_name=="diffinery-mail-events") | .queue_id' | head -n1 || true)"
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
136 # The zone that holds the sending domain (the domain itself or a parent), as scripts/email-sending.sh finds it.
137 while [[ "$name" == *.* ]]; do
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)"
139 [[ -n "$zone" ]] && break
140 name="${name#*.}"
141 done
142 if [[ -z "$zone" ]]; then warn "Could not find the Cloudflare zone for $SEND_DOMAIN (the token needs Zone → Zone → Read on it), so diffinery-mail-events isn't subscribed to Email Sending's bounce and complaint events. Subscribe it in the dashboard: see Site administration → Email in the docs."; return; fi
143 list="$(cf GET "/event_subscriptions/subscriptions?queue_id=$qid&per_page=100" || true)"
144 if ! jq -e '.success' >/dev/null 2>&1 <<<"$list"; then
145 warn "Could not read the queue's event subscriptions, so diffinery-mail-events may not get bounces and complaints. The token needs $SUB_PERMISSION. Cloudflare said: $(api_errors "$list")"
146 return
147 fi
148 existing="$(jq -c --arg d "$SEND_DOMAIN" --arg q "$qid" '[.result[]? | select(.source.type == "email.sending" and .source.domain == $d and (.destination.queue_id // $q) == $q)][0] // empty' <<<"$list")"
149 if [[ -n "$existing" ]]; then
150 id="$(jq -r '.id' <<<"$existing")"
151 if jq -e --argjson want "$SUB_EVENTS" '.enabled != false and ((.events // []) as $have | all($want[]; . as $e | $have | index($e)))' >/dev/null <<<"$existing"; then
152 echo "event subscription $id sends $SEND_DOMAIN's bounces and complaints to diffinery-mail-events"
153 return
154 fi
155 body="$(jq -c --argjson want "$SUB_EVENTS" '{events: ((.events // []) + $want | unique), enabled: true}' <<<"$existing")"
156 res="$(cf PATCH "/event_subscriptions/subscriptions/$id" "$body" || true)"
157 if jq -e '.success' >/dev/null 2>&1 <<<"$res"; then echo "event subscription $id now includes bounced and complained events"; else warn "Could not update event subscription $id. The token needs $SUB_PERMISSION. Cloudflare said: $(api_errors "$res")"; fi
158 return
159 fi
160 body="$(jq -nc --arg d "$SEND_DOMAIN" --arg z "$zone" --arg q "$qid" --argjson events "$SUB_EVENTS" '{
161 name: ("diffinery-mail-events " + $d), enabled: true,
162 source: {type: "email.sending", zone_id: $z, domain: $d},
163 destination: {type: "queues.queue", queue_id: $q},
164 events: $events
165 }')"
166 res="$(cf POST /event_subscriptions/subscriptions "$body" || true)"
167 if jq -e '.success' >/dev/null 2>&1 <<<"$res"; then
168 echo "created event subscription $(jq -r '.result.id' <<<"$res"): $SEND_DOMAIN's bounces and complaints go to diffinery-mail-events"
169 else
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")"
171 fi
172}
173if ((ON_CLOUDFLARE)); then subscribe_mail_events; else echo "skipped on $CF_API: bounces and complaints don't reach the suppression list by themselves"; fi
174endlog
175
176# ------------------------------------------------------------------ Email Sending
177# notifications@<MAIL_DOMAIN or DIFFINERY_DOMAIN>; warns (and email is skipped) until the domain is onboarded.
178if ((ON_CLOUDFLARE)); then
179 DIFFINERY_DOMAIN="$DOMAIN" "$ROOT/scripts/email-sending.sh" || warn "Email Sending check failed; email may not be delivered."
180else
181 echo "Email Sending setup skipped on $CF_API: the sending domain is set up wherever that API sends from."
182fi
183
184# ------------------------------------------------------------------ Turnstile
185# The widget "diffinery <DIFFINERY_DOMAIN>", created when missing, so people who aren't signed in can
186# send security reports (security.txt points researchers at the form). Its site key is deployed as the
187# TURNSTILE_SITE_KEY var (render-config below); ensure-secrets.sh sets TURNSTILE_SECRET when it's missing,
188# and turnstile.sh replaces it here, before the deploy, when it goes with another widget. Needs
189# Account → Turnstile → Edit; without it turnstile.sh warns, naming it, and the deploy goes on with
190# anonymous reports refused. Sign-up stays as SIGNUP says: keys alone don't open it.
191log "Turnstile"
192if ((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=""; }
194else
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."
198fi
199echo "site key: ${TURNSTILE_SITE_KEY:-none}"
200endlog
201
202# ------------------------------------------------------------------ Access
203log "Cloudflare Access"
204TEAM="${ACCESS_TEAM_DOMAIN:-}"
205if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then
206 TEAM="$(cf GET /access/organizations | jq -r '.result.auth_domain // empty' || true)"
207fi
208AUD=""
209APPS='{}'
210((ON_CLOUDFLARE == 0)) || APPS="$(cf GET "/access/apps?per_page=100" || echo '{}')"
211if ((ON_CLOUDFLARE == 0)); then
212 echo "Access skipped on $CF_API: passkeys work; email recovery and the /auth/access first sign-in stay off."
213elif ! jq -e '.success' >/dev/null <<<"$APPS"; then
214 warn "Could not read Access applications (token needs Access: Apps and Policies Edit). Passkeys work; email recovery stays off."
215else
216 # People sign in with passkeys. Access guards only /auth/access, the email-based
217 # recovery path, so everything else (web, git, API, MCP, runners) reaches the Worker directly.
218 WEB_BODY="$(jq -nc --arg d "$DOMAIN" '{
219 name: "Diffinery account recovery", type: "self_hosted", domain: ($d + "/auth/access"),
220 destinations: [{type: "public", uri: ($d + "/auth/access")}],
221 session_duration: "15m", app_launcher_visible: false, http_only_cookie_attribute: true, same_site_cookie_attribute: "lax"
222 }')"
223 POLICY='[{"name": "Anyone who proves their email (Diffinery decides access)", "decision": "allow", "include": [{"everyone": {}}], "precedence": 1}]'
224 WEB_ID="$(jq -r '.result[] | select(.name=="Diffinery account recovery" or .name=="Diffinery") | .id' <<<"$APPS" | head -n1)"
225 if [[ -z "$WEB_ID" ]]; then
226 WEB_APP="$(cf POST /access/apps "$(jq -c --argjson p "$POLICY" '. + {policies: $p}' <<<"$WEB_BODY")" | jq -c '.result // empty')"
227 [[ -n "$WEB_APP" ]] && echo "created Access app for $DOMAIN/auth/access" || warn "Could not create the Access application; email recovery stays off."
228 else
229 WEB_APP="$(cf PUT "/access/apps/$WEB_ID" "$WEB_BODY" | jq -c '.result // empty')"
230 [[ -n "$WEB_APP" ]] && echo "Access app covers $DOMAIN/auth/access" || warn "Could not update the Access application."
231 fi
232 AUD="$(jq -r '.aud // empty' <<<"${WEB_APP:-null}")"
233
234 # Earlier versions put Access in front of the whole site and needed a bypass app; remove it.
235 BYPASS_ID="$(jq -r '.result[] | select(.name=="Diffinery machine endpoints") | .id' <<<"$APPS" | head -n1)"
236 if [[ -n "$BYPASS_ID" ]]; then
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."
238 fi
239fi
240if [[ -z "$TEAM" ]] && ((ON_CLOUDFLARE)); then
241 # Fall back to the sign-in redirect, which names the team domain.
242 TEAM="$(curl -sS -o /dev/null -w '%{redirect_url}' "https://$DOMAIN/auth/access" | sed -nE 's#^https://([^/]+\.cloudflareaccess\.com)/.*#\1#p' || true)"
243fi
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)."
245echo "team=${TEAM:-?} aud=${AUD:+set}"
246endlog
247
248# ------------------------------------------------------------------ Site administrators
249# BOOTSTRAP_ADMINS from the environment, else wrangler.jsonc, else what the deployed Worker has; it
250# stops the deploy if the Worker's list can't be read, rather than deploy an empty one in its place.
251log "Bootstrap administrators"
252ADMINS="$("$ROOT/scripts/bootstrap-admins.sh")"
253endlog
254
255# ------------------------------------------------------------------ config + migrations
256log "Render config and migrate D1"
257TURNSTILE_SITE_KEY="$TURNSTILE_SITE_KEY" node "$ROOT/scripts/render-config.mjs" --d1 "$D1_ID" ${TEAM:+--team "$TEAM"} ${AUD:+--aud "$AUD"} --public-url "https://$DOMAIN" ${DIFFINERY_ZONE:+--zone "$DIFFINERY_ZONE"} --mail-from "notifications@${MAIL_DOMAIN:-$DOMAIN}" --admins "$ADMINS"
258"${WRANGLER[@]}" d1 migrations apply diffinery --remote -c wrangler.deploy.jsonc
259endlog
260
261if [[ -n "${GITHUB_OUTPUT:-}" ]]; then
262 { echo "d1_id=$D1_ID"; echo "access_team=$TEAM"; echo "access_aud_set=${AUD:+true}"; } >>"$GITHUB_OUTPUT"
263fi