| 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 queues and the |
| 5 | # Cloudflare Access application for /auth/access, the email-based account |
| 6 | # recovery path. Everyday sign-in uses passkeys; git, the API, MCP and runners |
| 7 | # use Diffinery tokens. |
| 8 | # Then renders apps/diffinery/wrangler.deploy.jsonc and applies D1 migrations. |
| 9 | # |
| 10 | # Requires: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID, node, jq, curl. |
| 11 | # Optional: DIFFINERY_DOMAIN (default diffinery.com), ACCESS_TEAM_DOMAIN |
| 12 | # (e.g. codician.cloudflareaccess.com) when the token cannot read it. |
| 13 | set -euo pipefail |
| 14 | |
| 15 | : "${CLOUDFLARE_API_TOKEN:?set CLOUDFLARE_API_TOKEN}" |
| 16 | : "${CLOUDFLARE_ACCOUNT_ID:?set CLOUDFLARE_ACCOUNT_ID}" |
| 17 | DOMAIN="${DIFFINERY_DOMAIN:-diffinery.com}" |
| 18 | ROOT="$(cd "$(dirname "$0")/.." && pwd)" |
| 19 | APP="$ROOT/apps/diffinery" |
| 20 | WRANGLER=(pnpm --dir "$APP" exec wrangler) |
| 21 | API="https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID" |
| 22 | |
| 23 | cf() { # cf METHOD PATH [JSON] |
| 24 | local method="$1" path="$2" body="${3:-}" |
| 25 | if [[ -n "$body" ]]; then |
| 26 | curl -sS -X "$method" "$API$path" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" --data "$body" |
| 27 | else |
| 28 | curl -sS -X "$method" "$API$path" -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" |
| 29 | fi |
| 30 | } |
| 31 | log() { echo "::group::$*"; } |
| 32 | endlog() { echo "::endgroup::"; } |
| 33 | warn() { echo "::warning::$*" >&2; } |
| 34 | |
| 35 | # ------------------------------------------------------------------ D1 |
| 36 | log "D1 database" |
| 37 | D1_ID="$(cf GET "/d1/database?name=diffinery&per_page=100" | jq -r '.result[]? | select(.name=="diffinery") | .uuid' | head -n1)" |
| 38 | if [[ -z "$D1_ID" ]]; then |
| 39 | D1_ID="$(cf POST /d1/database '{"name":"diffinery"}' | jq -r '.result.uuid // empty')" |
| 40 | [[ -n "$D1_ID" ]] || { echo "could not create D1 database (does the token have D1: Edit?)" >&2; exit 1; } |
| 41 | echo "created D1 database $D1_ID" |
| 42 | else |
| 43 | echo "D1 database exists: $D1_ID" |
| 44 | fi |
| 45 | echo "read replication: $(cf GET "/d1/database/$D1_ID" | jq -r '.result.read_replication.mode // "unknown"') (turn it on with the 'D1 read replication' workflow)" |
| 46 | endlog |
| 47 | |
| 48 | # ------------------------------------------------------------------ R2 |
| 49 | log "R2 bucket" |
| 50 | if cf GET "/r2/buckets/diffinery-data" | jq -e '.success' >/dev/null; then |
| 51 | echo "R2 bucket exists" |
| 52 | else |
| 53 | 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; } |
| 54 | echo "created R2 bucket diffinery-data" |
| 55 | fi |
| 56 | # Expire transient data: run logs/caches are rewritten on use, artifacts and event archives age out. |
| 57 | cf PUT "/r2/buckets/diffinery-data/lifecycle" '{"rules":[ |
| 58 | {"id":"artifacts-90d","enabled":true,"conditions":{"prefix":"repos/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":7776000}},"abortMultipartUploadsTransition":{"condition":{"type":"Age","maxAge":86400}}}, |
| 59 | {"id":"events-400d","enabled":true,"conditions":{"prefix":"events/"},"deleteObjectsTransition":{"condition":{"type":"Age","maxAge":34560000}}} |
| 60 | ]}' >/dev/null || true |
| 61 | endlog |
| 62 | |
| 63 | # ------------------------------------------------------------------ Queues |
| 64 | log "Queues" |
| 65 | EXISTING_QUEUES="$(cf GET "/queues?per_page=100" | jq -r '.result[]?.queue_name')" |
| 66 | for q in diffinery-events diffinery-events-dlq; do |
| 67 | if grep -qx "$q" <<<"$EXISTING_QUEUES"; then |
| 68 | echo "queue $q exists" |
| 69 | else |
| 70 | cf POST /queues "{\"queue_name\":\"$q\"}" | jq -e '.success' >/dev/null || { echo "could not create queue $q (token has Queues: Edit?)" >&2; exit 1; } |
| 71 | echo "created queue $q" |
| 72 | fi |
| 73 | done |
| 74 | endlog |
| 75 | |
| 76 | # ------------------------------------------------------------------ Access |
| 77 | log "Cloudflare Access" |
| 78 | TEAM="${ACCESS_TEAM_DOMAIN:-}" |
| 79 | if [[ -z "$TEAM" ]]; then |
| 80 | TEAM="$(cf GET /access/organizations | jq -r '.result.auth_domain // empty' || true)" |
| 81 | fi |
| 82 | APPS="$(cf GET "/access/apps?per_page=100" || echo '{}')" |
| 83 | AUD="" |
| 84 | if ! jq -e '.success' >/dev/null <<<"$APPS"; then |
| 85 | warn "Could not read Access applications (token needs Access: Apps and Policies Edit). Passkeys work; email recovery stays off." |
| 86 | else |
| 87 | # People sign in with passkeys. Access guards only /auth/access, the email-based |
| 88 | # recovery path, so everything else (web, git, API, MCP, runners) reaches the Worker directly. |
| 89 | WEB_BODY="$(jq -nc --arg d "$DOMAIN" '{ |
| 90 | name: "Diffinery account recovery", type: "self_hosted", domain: ($d + "/auth/access"), |
| 91 | destinations: [{type: "public", uri: ($d + "/auth/access")}], |
| 92 | session_duration: "15m", app_launcher_visible: false, http_only_cookie_attribute: true, same_site_cookie_attribute: "lax" |
| 93 | }')" |
| 94 | POLICY='[{"name": "Anyone who proves their email (Diffinery decides access)", "decision": "allow", "include": [{"everyone": {}}], "precedence": 1}]' |
| 95 | WEB_ID="$(jq -r '.result[] | select(.name=="Diffinery account recovery" or .name=="Diffinery") | .id' <<<"$APPS" | head -n1)" |
| 96 | if [[ -z "$WEB_ID" ]]; then |
| 97 | WEB_APP="$(cf POST /access/apps "$(jq -c --argjson p "$POLICY" '. + {policies: $p}' <<<"$WEB_BODY")" | jq -c '.result // empty')" |
| 98 | [[ -n "$WEB_APP" ]] && echo "created Access app for $DOMAIN/auth/access" || warn "Could not create the Access application; email recovery stays off." |
| 99 | else |
| 100 | WEB_APP="$(cf PUT "/access/apps/$WEB_ID" "$WEB_BODY" | jq -c '.result // empty')" |
| 101 | [[ -n "$WEB_APP" ]] && echo "Access app covers $DOMAIN/auth/access" || warn "Could not update the Access application." |
| 102 | fi |
| 103 | AUD="$(jq -r '.aud // empty' <<<"${WEB_APP:-null}")" |
| 104 | |
| 105 | # Earlier versions put Access in front of the whole site and needed a bypass app; remove it. |
| 106 | BYPASS_ID="$(jq -r '.result[] | select(.name=="Diffinery machine endpoints") | .id' <<<"$APPS" | head -n1)" |
| 107 | if [[ -n "$BYPASS_ID" ]]; then |
| 108 | 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." |
| 109 | fi |
| 110 | fi |
| 111 | if [[ -z "$TEAM" ]]; then |
| 112 | # Fall back to the sign-in redirect, which names the team domain. |
| 113 | TEAM="$(curl -sS -o /dev/null -w '%{redirect_url}' "https://$DOMAIN/auth/access" | sed -nE 's#^https://([^/]+\.cloudflareaccess\.com)/.*#\1#p' || true)" |
| 114 | fi |
| 115 | [[ -n "$TEAM" ]] || warn "Access team domain unknown; set the ACCESS_TEAM_DOMAIN repository variable (Zero Trust → Settings → Custom pages shows it)." |
| 116 | echo "team=${TEAM:-?} aud=${AUD:+set}" |
| 117 | endlog |
| 118 | |
| 119 | # ------------------------------------------------------------------ config + migrations |
| 120 | log "Render config and migrate D1" |
| 121 | node "$ROOT/scripts/render-config.mjs" --d1 "$D1_ID" ${TEAM:+--team "$TEAM"} ${AUD:+--aud "$AUD"} --public-url "https://$DOMAIN" |
| 122 | "${WRANGLER[@]}" d1 migrations apply diffinery --remote -c wrangler.deploy.jsonc |
| 123 | endlog |
| 124 | |
| 125 | if [[ -n "${GITHUB_OUTPUT:-}" ]]; then |
| 126 | { echo "d1_id=$D1_ID"; echo "access_team=$TEAM"; echo "access_aud_set=${AUD:+true}"; } >>"$GITHUB_OUTPUT" |
| 127 | fi |