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.

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