name: Self-host deploy # Reusable CD for every app on bitbaum. Call it from an app repo with a 12-line # shim (see docs/infrastructure/self-host-cd.md); all the logic lives here so # there is exactly ONE deploy pipeline to fix, audit, or improve. # # What it does, in order: # 1. wait for the pushed commit's own CI to go green (ci-gate.sh — a red blocks) # 2. pull the app's runtime .env FROM THE BOX (the box stays the env SSOT; # no prod secrets are duplicated into GitHub) # 3. build + rsync + atomic symlink swap + health check + auto-rollback # (scripts/hetzner/deploy.sh — the same script laptop deploys use) # 4. verify the PUBLIC url returns 2xx/3xx before calling the deploy done # # The only secret an app repo needs is HETZNER_SSH_PRIVATE_KEY (ubuntu@bitbaum). on: workflow_call: inputs: app: description: "Key in scripts/hetzner/apps.conf — SSOT for port, domain, app dir and database" required: true type: string git-ref: description: "Exact app commit to deploy (for workflow_run callers)" required: false type: string default: "" node-version: # The FALLBACK when a repo commits no .nvmrc. It must track the box # runtime (Node 24 since 2026-08-31) and the fleet's CI default — # 2026-09-02: aoz-begleitung's deploy npm-ci'd with npm 10 (Node 20) # against a lockfile written by npm 11 (Node 24 CI) and failed on # "Missing: esbuild from lock file", stranding two merged commits. # A stale fallback here recreates that npm-major split for every # .nvmrc-less repo in the fleet. description: "Node version to build with" required: false type: string default: "24" install-flags: description: "Extra flags for the install command (e.g. --legacy-peer-deps)" required: false type: string default: "" package-manager: description: "Override lockfile detection: npm | pnpm | yarn" required: false type: string default: "" secrets: HETZNER_SSH_PRIVATE_KEY: required: true jobs: deploy: name: ${{ inputs.app }} → bitbaum runs-on: ubuntu-latest timeout-minutes: 45 # Never cancel a deploy in flight: the swap is atomic but a half-finished # rsync leaves a junk release dir. Queue instead. concurrency: group: selfhost-deploy-${{ inputs.app }} cancel-in-progress: false steps: # A missing secret must FAIL, not skip. A deploy job that silently does # nothing and reports green is the exact failure mode this pipeline exists # to remove — prod would drift from main with no signal anywhere. - name: Require deploy key env: SSH_KEY: ${{ secrets.HETZNER_SSH_PRIVATE_KEY }} run: | if [ -z "$SSH_KEY" ]; then echo "::error::HETZNER_SSH_PRIVATE_KEY is not set on this repository — ${{ inputs.app }} cannot deploy." exit 1 fi echo "deploy key present" - name: Checkout app uses: actions/checkout@v7 with: ref: ${{ inputs.git-ref || github.sha }} # Cloned rather than checked out: actions/checkout can only write inside # the workspace, and a second repo there would end up inside the app's own # build/lint globs. - name: Fetch fleet tooling run: | git clone --quiet --depth 1 https://github.com/bitbaum/loki.git "$RUNNER_TEMP/fleet-tooling" echo "tooling at $(git -C "$RUNNER_TEMP/fleet-tooling" rev-parse --short HEAD)" - name: Setup SSH env: SSH_KEY: ${{ secrets.HETZNER_SSH_PRIVATE_KEY }} # The box address is the org-level Actions variable HETZNER_IP, not a # literal. This workflow is REUSED by ~20 repos, so a literal here is # twenty edits on the day the box moves — and the DNS hint below # quoted the same number a second time, in prose nobody greps. IP: ${{ vars.HETZNER_IP }} run: | set -euo pipefail if [ -z "$IP" ]; then echo "::error::org variable HETZNER_IP is unset — a deploy cannot guess where the box is." echo "::error::Set it under the bitbaum org: Settings -> Secrets and variables -> Actions -> Variables." exit 1 fi mkdir -p ~/.ssh && chmod 700 ~/.ssh printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 ssh-keyscan -H "$IP" >> ~/.ssh/known_hosts 2>/dev/null ssh -o BatchMode=yes "ubuntu@$IP" 'echo "ssh to $(hostname) ok"' - name: Resolve app from manifest id: app run: | set -euo pipefail TOOLING="$RUNNER_TEMP/fleet-tooling/scripts/hetzner" # lib.sh sets NAME PORT DOMAINS REPO APP_DIR DB, and exits non-zero on # an unknown app — a typo in the caller shim fails here, not in prod. source "$TOOLING/lib.sh" APP="${{ inputs.app }}" [[ "$APP" =~ ^[a-z0-9][a-z0-9-]*$ ]] || exit 1 if ! app_lookup "$APP"; then # Registration writes the durable canonical register. A new site # must not wait for an unrelated Loki source deployment. ssh -o BatchMode=yes "ubuntu@$HETZNER_IP" 'cat /home/ubuntu/dev/loki/scripts/hetzner/apps.conf' > "$RUNNER_TEMP/registered-apps.conf" export MANIFEST="$RUNNER_TEMP/registered-apps.conf" app_lookup "$APP" # Prove the registered checkout belongs to this caller repository. registered_repo=$(ssh -o BatchMode=yes "ubuntu@$HETZNER_IP" "git -C '$REPO' remote get-url origin") registered_repo=$(printf '%s' "$registered_repo" | sed -E 's#^https://github.com/##; s#^git@github.com:##; s#\.git$##') [ "$registered_repo" = "$GITHUB_REPOSITORY" ] || { echo "::error::registered repository does not match caller"; exit 1; } echo "MANIFEST=$MANIFEST" >> "$GITHUB_ENV" fi { echo "name=$NAME" echo "port=$PORT" echo "app_dir=$APP_DIR" echo "domain=${DOMAINS%%,*}" echo "ip=$HETZNER_IP" echo "tooling=$TOOLING" } >> "$GITHUB_OUTPUT" echo "resolved $NAME → port $PORT, dir '$APP_DIR', domain ${DOMAINS%%,*}, db $DB" # The box holds the authoritative runtime env (NEXT_PUBLIC_* is baked in at # build time, so the builder needs it too). Pulling it keeps ONE copy of # every prod secret instead of forking it into N GitHub secret stores. - name: Pull runtime env from the box env: NAME: ${{ steps.app.outputs.name }} APP_DIR: ${{ steps.app.outputs.app_dir }} IP: ${{ steps.app.outputs.ip }} run: | set -euo pipefail src="" for cand in "/opt/$NAME/shared/.env" "/opt/$NAME/app/.env"; do if ssh -o BatchMode=yes "ubuntu@$IP" "test -f '$cand'"; then src="$cand"; break; fi done if [ -z "$src" ]; then echo "::error::no runtime .env found on the box for $NAME (looked in shared/ and app/)" exit 1 fi dest="$GITHUB_WORKSPACE/$APP_DIR/.env.selfhost.local" scp -q -o BatchMode=yes "ubuntu@$IP:$src" "$dest" chmod 600 "$dest" # Count, never a bare "ok": an empty file would otherwise sail through # and produce a build with every env var silently undefined. vars=$(grep -cE '^[A-Za-z_][A-Za-z0-9_]*=' "$dest" || true) [ "${vars:-0}" -gt 0 ] || { echo "::error::$src has no variables"; exit 1; } echo "pulled $src → $APP_DIR/.env.selfhost.local ($vars variables)" # The fleet is mixed: eight apps are npm, four are pnpm. Detect from the # lockfile rather than asking every caller to declare it — the lockfile is # already the source of truth for which manager can install this tree. - name: Detect package manager id: pm env: OVERRIDE: ${{ inputs.package-manager }} run: | set -euo pipefail if [ -n "$OVERRIDE" ]; then mgr="$OVERRIDE" elif [ -f pnpm-lock.yaml ]; then mgr=pnpm elif [ -f yarn.lock ]; then mgr=yarn elif [ -f package-lock.json ]; then mgr=npm else echo "::error::no lockfile at the repo root — cannot install reproducibly" exit 1 fi echo "manager=$mgr" >> "$GITHUB_OUTPUT" echo "package manager: $mgr" # Must precede setup-node: its pnpm/yarn cache lookup needs the binary. - name: Enable corepack if: steps.pm.outputs.manager != 'npm' env: MGR: ${{ steps.pm.outputs.manager }} run: | set -euo pipefail corepack enable # The repo's own packageManager field is the source of truth for its # toolchain. Guessing a version from lockfileVersion does not work — # pnpm 9, 10 and 11 all write lockfileVersion 9.0, and pinning 9 # against a pnpm-10-style pnpm-workspace.yaml breaks the install. if node -p "require('./package.json').packageManager||''" 2>/dev/null | grep -q .; then echo "using declared toolchain: $(node -p "require('./package.json').packageManager")" else echo "::warning::$GITHUB_REPOSITORY does not declare packageManager in package.json — falling back to $MGR@latest, which can change under you. Declare it." corepack prepare "$MGR@latest" --activate fi # A dependency cache is an optimisation. Probing it first means a broken # cache lookup degrades to a slower deploy instead of failing one — the # pnpm store probe reads pnpm-workspace.yaml and errors on configs it # does not understand, which took vitareba's first deploy down. - name: Probe dependency cache id: cache env: MGR: ${{ steps.pm.outputs.manager }} run: | set +e case "$MGR" in npm) ok=0 ;; pnpm) pnpm store path >/dev/null 2>&1; ok=$? ;; yarn) yarn config get cacheFolder >/dev/null 2>&1; ok=$? ;; esac if [ "$ok" -eq 0 ]; then echo "use=$MGR" >> "$GITHUB_OUTPUT" echo "dependency cache: $MGR" else echo "use=" >> "$GITHUB_OUTPUT" echo "::warning::$MGR cache unavailable — deploying without it (slower, not broken)" fi # The build must run on the SAME Node the repo's CI verified with. npm 10 # and 11 disagree about optional platform deps, so a lockfile npm 11 wrote # reads as "out of sync" to npm 10 — that is how hirnli's CI passed on # Node 24 while its deploy failed `npm ci` on Node 20. A committed .nvmrc # is the one declaration both sides read; the input is the fallback. - name: Resolve Node version id: node env: FALLBACK: ${{ inputs.node-version }} run: | set -euo pipefail for f in .nvmrc .node-version; do if [ -f "$f" ]; then echo "file=$f" >> "$GITHUB_OUTPUT" echo "Node version from $f: $(tr -d 'v \n' < "$f")" exit 0 fi done echo "file=" >> "$GITHUB_OUTPUT" echo "version=$FALLBACK" >> "$GITHUB_OUTPUT" echo "::notice::no .nvmrc — building on Node $FALLBACK. If this repo's CI uses a different major, commit a .nvmrc both can read." - uses: actions/setup-node@v7 with: node-version: ${{ steps.node.outputs.version }} node-version-file: ${{ steps.node.outputs.file }} cache: ${{ steps.cache.outputs.use }} - name: Install dependencies env: APP_DIR: ${{ steps.app.outputs.app_dir }} MGR: ${{ steps.pm.outputs.manager }} INSTALL_FLAGS: ${{ inputs.install-flags }} # Deploys build from a lockfile CI already verified; a drifted lockfile # should fail in CI, not be silently papered over here. NPM_CONFIG_FUND: "false" NPM_CONFIG_AUDIT: "false" run: | set -euo pipefail case "$MGR" in npm) install="npm ci" ;; pnpm) install="pnpm install --frozen-lockfile" ;; yarn) install="yarn install --immutable" ;; esac # Always install at the repo root (workspaces live there). Then install # again inside the app dir only when it carries its OWN lockfile — a # nested standalone project, as in sbb-lost-found and datacat. echo "→ $install in ./" $install $INSTALL_FLAGS if [ "$APP_DIR" != "." ] && [ -f "$APP_DIR/package-lock.json" -o -f "$APP_DIR/pnpm-lock.yaml" -o -f "$APP_DIR/yarn.lock" ]; then echo "→ $install in ./$APP_DIR (nested project with its own lockfile)" ( cd "$APP_DIR" && $install $INSTALL_FLAGS ) fi # Prod only ever receives code CI has verified. Exit 3 = this commit was # superseded by a newer push, whose own deploy will ship — skip quietly. # Next keeps its compiler output in .next/cache. Deploys here run a full # `npm run build` (deploy.sh) on the runner, and without this the build is # COLD every single time — for every repo that calls this workflow. # # Measured 2026-09-07 across the fleet: nobody's deploy cached this, and # only one repo's CI did. Deploy medians ran 2.9m (loki) to 12.7m # (evig) against CI medians of 1.9m to 10.7m for the same commits, because # the same compile happens twice from scratch. # # Scoped by app so two apps in one repo cannot evict each other, and keyed # on the lockfile so a dependency change invalidates it. The bare # restore-key is last on purpose: a stale cache is still far cheaper than # no cache, and Next validates entries itself rather than trusting them. - name: Cache Next.js build uses: actions/cache@v6 with: path: ${{ steps.app.outputs.app_dir }}/.next/cache key: nextjs-${{ runner.os }}-${{ inputs.app }}-${{ hashFiles('**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock') }}-${{ github.sha }} restore-keys: | nextjs-${{ runner.os }}-${{ inputs.app }}-${{ hashFiles('**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock') }}- nextjs-${{ runner.os }}-${{ inputs.app }}- - name: Wait for CI to pass on this commit id: gate env: GH_TOKEN: ${{ github.token }} TOOLING: ${{ steps.app.outputs.tooling }} run: | # +e on purpose: exit 3 ("superseded") is a normal outcome to branch on, # and the default `bash -e` shell would abort the step before we read it. set +e # Exclude this deploy workflow from what counts as CI — every run of # it. It is a workflow run on the same SHA, so without this the gate # waits on itself, and a retry after a failed deploy reads that # earlier failure as a red CI and can never succeed. # GITHUB_WORKFLOW_REF is owner/repo/.github/workflows/x.yml@refs/... wf="${GITHUB_WORKFLOW_REF#*/*/}"; wf="${wf%%@*}" echo "not counting $wf as CI" CI_GATE_EXCLUDE_PATH="$wf" bash "$TOOLING/ci-gate.sh" "$GITHUB_REPOSITORY" "${{ inputs.git-ref || github.sha }}" rc=$? case "$rc" in 0) echo "proceed=true" >> "$GITHUB_OUTPUT" ;; 3) echo "proceed=false" >> "$GITHUB_OUTPUT" echo "::notice::commit superseded — a newer push will deploy" ;; *) echo "::error::CI is not green for ${{ inputs.git-ref || github.sha }} — deploy blocked"; exit 1 ;; esac - name: Deploy if: steps.gate.outputs.proceed == 'true' env: BUILD_PACKAGE_MANAGER: ${{ steps.pm.outputs.manager }} REPO_OVERRIDE: ${{ github.workspace }} TOOLING: ${{ steps.app.outputs.tooling }} run: bash "$TOOLING/deploy.sh" "${{ inputs.app }}" # deploy.sh already health-checks localhost and auto-rolls-back. This # checks what a USER actually hits — through Caddy, TLS and DNS — because # "the service is up" and "the site works" are different claims. - name: Verify public URL if: steps.gate.outputs.proceed == 'true' env: DOMAIN: ${{ steps.app.outputs.domain }} run: | set -uo pipefail if [ "$DOMAIN" = "-" ]; then echo "::notice::${{ inputs.app }} is internal-only — no public URL to check" exit 0 fi # Resolve BEFORE curling. A hostname with no DNS record and an app # that is genuinely down both make curl print 000, so reporting only # the status code sends you to read service logs for a box that is # perfectly healthy. solon burned this: every deploy since 2026-08-03 # failed here, the app was running the whole time, and the actual # cause was that solon.orangecat.ch was never created at the # registrar. Retrying an NXDOMAIN 10 times cannot help either — DNS # is not going to appear during the sleep. if ! getent hosts "$DOMAIN" >/dev/null 2>&1; then echo "::error::$DOMAIN does not resolve — this is a DNS gap, NOT a broken deploy." echo "::error::The app was deployed and Caddy is configured for it; the hostname simply does not exist." echo "::error::Fix: create an A record $DOMAIN → $IP at the DNS provider (orangecat.ch is on Infomaniak), then re-run this workflow." exit 1 fi for attempt in $(seq 1 10); do code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "https://$DOMAIN/" || echo 000) if [ "$code" -ge 200 ] 2>/dev/null && [ "$code" -lt 400 ]; then echo "https://$DOMAIN → $code (attempt $attempt)" exit 0 fi sleep 6 done if [ "$code" = "000" ]; then echo "::error::$DOMAIN resolves but nothing answered on https — check Caddy (TLS cert issuance) and the app service on the box." else echo "::error::https://$DOMAIN returned $code after the deploy" fi exit 1