Diffinery

codician/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.

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