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.

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