Files
orangecat/.github/workflows/cd.yml

365 lines
17 KiB
YAML

# Continuous Deployment — OrangeCat → bitbaum (self-hosted Hetzner).
#
# Receives one explicit handoff from successful main CI, builds/deploys only
# from the SHA and artifact it verifies, then ships via the atomic-swap+rollback
# deploy verb (scripts/deploy-selfhost.sh). A scheduled reconciler can dispatch
# this workflow as recovery if the handoff is missed or a deploy fails.
#
# DISABLED until secrets are configured: every deploy step is gated on
# `steps.guard.outputs.ok`, which is false unless SELFHOST_SSH_KEY exists. So
# merging this file is a safe no-op; CD activates the moment the key is added.
#
# Required repo secrets (Settings → Secrets and variables → Actions):
# SELFHOST_SSH_KEY private SSH key whose public half is in the box's
# authorized_keys for the OC_BOX user (default root). Treat
# as a deploy credential; rotate if leaked.
# SELFHOST_KNOWN_HOSTS output of `ssh-keyscan <box host>` (pins the host).
# NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY /
# NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY real self-host values, baked at build.
# Required variables (vars.*) — the deploy target, configuration not source:
# OC_BOX full `user@host` SSH target; or
# HETZNER_IP the box address, used as `root@<HETZNER_IP>` when OC_BOX is unset.
# There is deliberately NO literal fallback here. A baked-in address means the
# variable is never exercised, so nobody notices when it is missing or wrong —
# the "deploy target configured?" guard below fails the run instead.
#
# Note: OrangeCat's build does not require live-DB access (no blocking SSG DB
# queries), so unlike loki/scripts/hetzner/deploy.sh this needs no tunnel.
name: CD
on:
workflow_dispatch:
inputs:
ci_run_id:
description: Successful CI run to reuse (set by the CI handoff)
required: false
type: string
ci_sha:
description: Commit verified by that CI run
required: false
type: string
concurrency:
group: cd-selfhost
cancel-in-progress: false # never interrupt a deploy mid-swap
permissions:
contents: read
# Needed by the "was this commit verified?" guard, which asks the Actions API
# whether a sibling CI run for the same commit passed.
actions: read
jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 25
env:
NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: ${{ secrets.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY }}
# OrangeCat's public donation addresses, baked into the client bundle for
# the /support founding-supporter page. Repo *variables* (not secrets) —
# these are public receiving addresses, meant to be shown. Unset → the
# page shows its graceful "opens shortly" state. (NEXT_PUBLIC_* must be set
# HERE at build time; the box's runtime .env can't reach the client bundle.)
NEXT_PUBLIC_LIGHTNING_ADDRESS: ${{ vars.NEXT_PUBLIC_LIGHTNING_ADDRESS }}
NEXT_PUBLIC_BITCOIN_ADDRESS: ${{ vars.NEXT_PUBLIC_BITCOIN_ADDRESS }}
# Flips the Cat Credits UI from "Activating" to "Live" (build-time, client
# bundle). Set the repo variable to true only once PLATFORM_NWC_URI exists
# in the box's runtime .env — the UI must never claim Live before the
# server can actually receive. Server-side receive is gated independently
# on PLATFORM_NWC_URI (runtime), so this flag is display-only.
NEXT_PUBLIC_CAT_CREDITS_LIVE: ${{ vars.NEXT_PUBLIC_CAT_CREDITS_LIVE }}
# Voice input on create forms and onboarding. This was missing here for
# its whole life, which meant the flag could never be true in production:
# NEXT_PUBLIC_* is compiled into the client bundle, so setting it in the
# box's runtime .env does nothing. The mic on every create form was
# unreachable dead code — off by omission, not by decision.
NEXT_PUBLIC_FEATURE_VOICE_INPUT: ${{ vars.NEXT_PUBLIC_FEATURE_VOICE_INPUT }}
# Loki feedback widget token — must match ci.yml's build env so a
# cd-side rebuild bakes the same embed into prerendered pages. Public by
# design (ships in page source): repo variable, not a secret.
LOKI_FEEDBACK_TOKEN: ${{ vars.LOKI_FEEDBACK_TOKEN }}
# The SSH target comes from configuration only — see the header note on
# why there is no literal fallback.
OC_BOX: ${{ vars.OC_BOX || (vars.HETZNER_IP && format('root@{0}', vars.HETZNER_IP)) }}
steps:
- name: Verify the successful main CI handoff
id: ci
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
CI_RUN_ID: ${{ inputs.ci_run_id }}
CI_SHA: ${{ inputs.ci_sha }}
run: |
# A transient GitHub Actions API 5xx must not strand a verified
# release before deploy. Retry only temporary HTTP/network failures;
# invalid IDs and authorization errors still fail immediately.
gh_api() {
local attempt=1 output status
while :; do
if output=$(gh api "$@" 2>&1); then
printf '%s\n' "$output"
return 0
else
status=$?
fi
case "$output" in
*'HTTP 429'*|*'HTTP 500'*|*'HTTP 502'*|*'HTTP 503'*|*'HTTP 504'*|*'Server Error'*|*'timed out'*|*'connection reset'*)
if [ "$attempt" -ge 5 ]; then
printf '%s\n' "$output" >&2
return "$status"
fi
echo "GitHub API transient failure (attempt $attempt/5); retrying in $((attempt * 2))s: $output" >&2
sleep $((attempt * 2))
attempt=$((attempt + 1))
;;
*)
printf '%s\n' "$output" >&2
return "$status"
;;
esac
done
}
if [ -n "$CI_RUN_ID" ] || [ -n "$CI_SHA" ]; then
if [ -z "$CI_RUN_ID" ] || [ -z "$CI_SHA" ]; then
echo '::error::ci_run_id and ci_sha must be supplied together'
exit 1
fi
run=$(gh_api "repos/$REPO/actions/runs/$CI_RUN_ID" \
--jq '[.head_sha, .head_branch, .status] | @tsv')
IFS=$'\t' read -r run_sha branch status <<< "$run"
gates=$(gh_api "repos/$REPO/actions/runs/$CI_RUN_ID/jobs?per_page=100" \
--jq '[.jobs[] | select(.name == "build-and-smoke" or .name == "security") | .name + "=" + .conclusion] | join(" ")')
if [ "$run_sha" != "$CI_SHA" ] || [ "$branch" != 'main' ] \
|| { [ "$status" != 'in_progress' ] && [ "$status" != 'completed' ]; } \
|| [[ "$gates" != *'build-and-smoke=success'* ]] \
|| [[ "$gates" != *'security=success'* ]]; then
echo '::error::CD requires successful build-and-smoke and security jobs for the supplied main SHA'
exit 1
fi
run_id="$CI_RUN_ID"
sha="$CI_SHA"
else
# Scheduled reconciliation/manual recovery uses the latest verified
# main SHA. Re-use its CI artifact when available instead of rebuilding.
#
# Ask for a successful run OF THE TIP, not for "the newest successful
# run" and then compare. Every merge gets two CI runs for one commit
# and one of them is cancelled; the newest-run question also depends
# on the order the run list happens to come back in. Asked that way,
# this refused a tip that had a green run (2026-10-07, four times in
# one evening), leaving a red CD run behind each merge.
main_sha=$(gh_api "repos/$REPO/commits/main" --jq '.sha')
run=$(gh_api \
"repos/$REPO/actions/workflows/ci.yml/runs?branch=main&head_sha=$main_sha&status=success&per_page=1" \
--jq '.workflow_runs[0] | [.head_sha, .head_branch, .conclusion, (.id | tostring)] | @tsv')
IFS=$'\t' read -r sha branch conclusion run_id <<< "$run"
if [ -z "$main_sha" ] || [ "$sha" != "$main_sha" ] || [ "$branch" != 'main' ] \
|| [ "$conclusion" != 'success' ]; then
echo "::error::No successful CI run verifies the current main SHA (${main_sha:-unknown}); refusing to deploy"
exit 1
fi
# Reconciliation is the recovery path, so an expired/missing
# artifact must fall back to a verified local build. Normal CI
# handoffs still require their exact artifact and fail closed.
artifact_count=$(gh_api \
"repos/$REPO/actions/runs/$run_id/artifacts?per_page=100" \
--jq "[.artifacts[] | select(.name == \"standalone-$sha\" and .expired == false)] | length")
if [ "$artifact_count" -eq 0 ]; then
echo "::notice::No retained standalone artifact for $sha; recovery will rebuild from the verified main commit."
run_id=''
fi
fi
echo "sha=$sha" >> "$GITHUB_OUTPUT"
echo "run_id=$run_id" >> "$GITHUB_OUTPUT"
- name: Guard — is the deploy key configured?
id: guard
env:
KEY: ${{ secrets.SELFHOST_SSH_KEY }}
CI_OK: ${{ steps.ci.outputs.sha != '' && 'true' || 'false' }}
run: |
if [ -z "$KEY" ]; then
echo "ok=false" >> "$GITHUB_OUTPUT"
echo "::notice::SELFHOST_SSH_KEY not set — CD is dormant. Add it to enable deploys."
elif [ "$CI_OK" != "true" ]; then
echo "ok=false" >> "$GITHUB_OUTPUT"
else
echo "ok=true" >> "$GITHUB_OUTPUT"
fi
- name: Guard — is the deploy target configured?
# Fail loudly rather than deploying to a guessed address. This runs only
# once the key guard passed, so a dormant CD stays a no-op.
if: steps.guard.outputs.ok == 'true'
run: |
if [ -z "$OC_BOX" ]; then
echo "::error::OC_BOX is empty — set the OC_BOX (user@host) or HETZNER_IP variable."
exit 1
fi
echo "deploy target: $OC_BOX"
- name: Configure SSH
if: steps.guard.outputs.ok == 'true'
run: |
BOX_HOST="${OC_BOX##*@}"
mkdir -p ~/.ssh
echo "${{ secrets.SELFHOST_SSH_KEY }}" > ~/.ssh/id_deploy
chmod 600 ~/.ssh/id_deploy
if [ -n "${{ secrets.SELFHOST_KNOWN_HOSTS }}" ]; then
echo "${{ secrets.SELFHOST_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
else
ssh-keyscan -H "$BOX_HOST" >> ~/.ssh/known_hosts 2>/dev/null
fi
cat > ~/.ssh/config <<EOF
Host bitbaum
HostName $BOX_HOST
IdentityFile ~/.ssh/id_deploy
IdentitiesOnly yes
EOF
- name: Skip commit already live
id: live
if: steps.guard.outputs.ok == 'true'
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
EXPECTED_SHA: ${{ steps.ci.outputs.sha }}
run: |
if [ -z "$EXPECTED_SHA" ]; then
echo 'needed=true' >> "$GITHUB_OUTPUT"
exit 0
fi
main_sha=$(gh api "repos/$REPO/commits/main" --jq '.sha')
if [ "$main_sha" != "$EXPECTED_SHA" ]; then
echo "::notice::CI commit $EXPECTED_SHA is superseded by main $main_sha; skipping stale deploy."
echo 'needed=false' >> "$GITHUB_OUTPUT"
exit 0
fi
live_sha=$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$OC_BOX" \
"sed -n 's/^sha=//p' /opt/orangecat/app/.release" 2>/dev/null || true)
if [ "$live_sha" = "$EXPECTED_SHA" ]; then
echo "::notice::Commit $EXPECTED_SHA is already live; skipping duplicate deploy."
echo 'needed=false' >> "$GITHUB_OUTPUT"
else
echo 'needed=true' >> "$GITHUB_OUTPUT"
fi
- name: Checkout
if: steps.live.outputs.needed == 'true'
uses: actions/checkout@v7
with:
ref: ${{ steps.ci.outputs.sha }}
- name: Setup pnpm
if: steps.live.outputs.needed == 'true'
uses: pnpm/action-setup@v6
# setup-pnpm's default store nests inside its own bin dir, which breaks
# any prepare-building dep (portable-type TS2742) — pin it outside.
- name: Pin pnpm store location
if: steps.live.outputs.needed == 'true'
run: pnpm config set store-dir ~/.pnpm-store --global
- name: Setup Node.js
if: steps.live.outputs.needed == 'true'
uses: actions/setup-node@v7
with:
node-version: 24
cache: 'pnpm'
- name: Install dependencies
if: steps.live.outputs.needed == 'true'
run: pnpm install --frozen-lockfile
- name: Download standalone artifact from the triggering CI run
# Ship the EXACT artifact CI built + tested (tested == shipped), and skip
# the rebuild. Missing artifacts on a successful CI run are an error;
# reconciliation/manual recovery without a CI artifact builds locally
# after validating that the latest green CI SHA is still main.
if: steps.live.outputs.needed == 'true' && steps.ci.outputs.run_id != ''
uses: actions/download-artifact@v8
with:
name: standalone-${{ steps.ci.outputs.sha }}
path: ${{ runner.temp }}/orangecat-ci-artifact
run-id: ${{ steps.ci.outputs.run_id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Unpack standalone artifact
# CI ships a tarball, not a directory, so the pnpm symlink farm survives
# the round-trip. The assertion below is the point of the whole change: a
# standalone tree built under pnpm ALWAYS contains symlinks, and a tree
# that lost them boots into `Cannot find module '@swc/helpers/_/…'`.
# Zero symlinks is therefore not a warning, it is the bug — fail here,
# where the cause is one line away, rather than in a boot test on the box.
# Explicitly NOT falling through to a rebuild: a silent rebuild would ship
# a green deploy and leave the artifact path broken forever.
if: steps.live.outputs.needed == 'true' && steps.ci.outputs.run_id != ''
run: |
test -f "$RUNNER_TEMP/orangecat-ci-artifact/standalone.tar.gz" || {
echo '::error::CI artifact download returned no standalone.tar.gz'
exit 1
}
mkdir -p .next/standalone
tar -xzf "$RUNNER_TEMP/orangecat-ci-artifact/standalone.tar.gz" -C .next/standalone
links=$(find .next/standalone/node_modules -type l 2>/dev/null | wc -l)
echo "symlinks preserved: $links"
[ "$links" -gt 0 ] || {
echo "ERROR: the unpacked standalone tree has NO symlinks."
echo "Next's pnpm output resolves peer deps through them; without"
echo "them the app cannot require @swc/helpers and will not boot."
exit 1
}
- name: Build standalone if no artifact (fallback / manual dispatch)
if: steps.live.outputs.needed == 'true'
env:
NODE_ENV: production
SELF_HOST: '1'
run: |
if [ -f .next/standalone/server.js ]; then
echo "Using the CI-built standalone artifact — skipping rebuild."
else
echo "No artifact (manual dispatch or download failed) — building standalone."
pnpm run build
fi
- name: Stage exact public package receipt
if: steps.live.outputs.needed == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
# No public receipt may disclose a private repository's package inventory.
test "$(gh api "repos/$GITHUB_REPOSITORY" --jq .private)" = false
producer="$RUNNER_TEMP/fleet-receipt-producer"
git init --quiet "$producer"
git -C "$producer" remote add origin https://github.com/bitbaum/fleet.git
git -C "$producer" fetch --quiet --depth 1 origin 6295eecab6effadefac4c66723da2196fcd8b300
git -C "$producer" checkout --quiet --detach FETCH_HEAD
node "$producer/scripts/ci/release-receipt.mjs" --public \
--root "$GITHUB_WORKSPACE" --repo "$GITHUB_REPOSITORY" \
--output "$RUNNER_TEMP/orangecat-release.json"
# This source public directory is assembled into standalone by the deploy verb.
mkdir -p public/.well-known
cp "$RUNNER_TEMP/orangecat-release.json" public/.well-known/fleet-release.json
- name: Deploy (atomic swap + rollback)
if: steps.live.outputs.needed == 'true'
env:
DEPLOY_COMMIT_SHA: ${{ steps.ci.outputs.sha }}
run: |
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_deploy
bash scripts/deploy-selfhost.sh --no-build
- name: Verify the served package receipt
if: steps.live.outputs.needed == 'true'
run: |
node "$RUNNER_TEMP/fleet-receipt-producer/scripts/ci/verify-live-release-receipt.mjs" \
--url https://orangecat.ch/.well-known/fleet-release.json \
--expected "$RUNNER_TEMP/orangecat-release.json"