Files
drinktracker/deploy/deploy.sh
JP 82680d9430 Correct stale deploy docs and document the new env knobs
deploy/README.md described a rewrites() block that no longer exists, and told
the reader to verify the image bucket's anonymous-download policy was set -
which is precisely the exposure that was closed. Following it would have
re-opened every stored image to the public internet.

Replaced with what is actually true: /minio-images is a session-gated route
handler with per-user key-prefix ownership, the bucket must have no anonymous
policy, and MinIO must stay bound to loopback. Also noted that the suggested
`mc anonymous get` check does not work on this host - the alias has no
credentials and returns Access Denied either way - and gave an external curl
that actually tells you something.

The same stale rationale sat in deploy.sh's build comment. Building without the
env file is still right, just for a different reason: nothing needs baking in.

Added the MCP and OAuth journal greps, an unauthenticated discovery check, and
a note that a 307 there means /.well-known fell out of PUBLIC_ROUTES. Documented
in .env.example that NEXTAUTH_URL must be the exact public origin with no
trailing slash, since it is now the OAuth issuer and MCP resource identifier,
plus the MCP_CHATGPT_TOOLS opt-out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 19:04:42 +00:00

166 lines
7.1 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Deploy drinktracker to the production LXC.
#
# The app runs natively under systemd - no Docker. Each deploy builds into
# releases/<sha> out-of-place and swaps a symlink, so the ~3 minute build happens
# while the old release keeps serving and downtime is only the restart.
#
# Usage: ./deploy/deploy.sh [--yes] [--no-build] [--rollback]
#
set -euo pipefail
HOST="${DT_HOST:-drinkadmin@192.168.2.169}"
SSH_KEY="${DT_SSH_KEY:-$HOME/.ssh/drinktracker_ed25519}"
APP_DIR="${DT_APP_DIR:-/opt/drinktracker}"
SVC_USER="${DT_SVC_USER:-drinktracker}"
KEEP_RELEASES=5
HEALTH_URL="http://localhost:3000/"
ASSUME_YES=0; BUILD=1; ROLLBACK=0
for arg in "$@"; do
case "$arg" in
--yes|-y) ASSUME_YES=1 ;;
--no-build) BUILD=0 ;;
--rollback) ROLLBACK=1 ;;
*) echo "unknown option: $arg" >&2; exit 2 ;;
esac
done
SSH=(ssh -o BatchMode=yes -o ConnectTimeout=10 -i "$SSH_KEY" "$HOST")
say() { printf '\n\033[1;36m==> %s\033[0m\n' "$*"; }
die() { printf '\n\033[1;31mFAILED: %s\033[0m\n' "$*" >&2; exit 1; }
# Run a script (on stdin) as root on the LXC, with these vars exported.
# sudoers grants drinkadmin NOPASSWD only as root, so we sudo once and `su` down
# to the service user inside rather than using `sudo -u`.
remote_root() {
"${SSH[@]}" "sudo -n env APP_DIR='$APP_DIR' SVC_USER='$SVC_USER' SHA='${SHA:-}' \
SHORT='${SHORT:-}' KEEP='$KEEP_RELEASES' bash -s"
}
health_poll() {
for i in $(seq 1 30); do
code=$("${SSH[@]}" "curl -s -o /dev/null -w '%{http_code}' -m 5 $HEALTH_URL" || echo 000)
# 307 is the unauthenticated redirect to /login - healthy.
case "$code" in 200|302|307) echo " healthy (HTTP $code) after $((i*2))s"; return 0 ;; esac
sleep 2
done
return 1
}
# ─── Rollback: repoint the symlink, no rebuild ───────────────────────
if [ "$ROLLBACK" -eq 1 ]; then
say "Rolling back"
CURRENT=$("${SSH[@]}" "basename \$(readlink $APP_DIR/current)")
PREV=$("${SSH[@]}" "ls -1t $APP_DIR/releases | grep -v '^$CURRENT\$' | head -1")
[ -n "$PREV" ] || die "no other release to roll back to"
echo " current=$CURRENT -> $PREV"
if [ "$ASSUME_YES" -ne 1 ]; then
read -r -p " proceed? [y/N] " r; [[ "$r" =~ ^[Yy]$ ]] || { echo aborted; exit 1; }
fi
SHORT="$PREV" remote_root <<'EOF'
set -e
su -s /bin/bash "$SVC_USER" -c "ln -sfn $APP_DIR/releases/$SHORT $APP_DIR/current.new && mv -Tf $APP_DIR/current.new $APP_DIR/current"
systemctl restart drinktracker
EOF
health_poll || die "app unhealthy after rollback - journalctl -u drinktracker"
say "Rolled back to $PREV"
exit 0
fi
# ─── Preflight (local) ───────────────────────────────────────────────
say "Preflight"
cd "$(dirname "$0")/.."
[ -n "$(git status --porcelain)" ] && die "working tree is dirty - commit or stash first"
BRANCH=$(git rev-parse --abbrev-ref HEAD)
[ "$BRANCH" = "main" ] || die "on branch '$BRANCH', expected main"
npx tsc --noEmit || die "typecheck failed"
echo " typecheck ok, tree clean, on main"
git -c credential.helper=store push origin main
SHA=$(git rev-parse HEAD); SHORT=${SHA:0:7}
echo " pushed $SHORT"
# ─── Preflight (remote) ──────────────────────────────────────────────
say "Checking $HOST"
"${SSH[@]}" true || die "cannot reach $HOST with key $SSH_KEY"
for unit in postgresql@16-main minio drinktracker; do
st=$("${SSH[@]}" "systemctl is-active $unit" || true)
echo " $unit: $st"
[ "$st" = "active" ] || die "$unit is not active - fix before deploying"
done
if [ "$ASSUME_YES" -ne 1 ]; then
CURRENT=$("${SSH[@]}" "basename \$(readlink $APP_DIR/current)")
echo " current release $CURRENT, deploying $SHORT"
read -r -p " proceed? [y/N] " r; [[ "$r" =~ ^[Yy]$ ]] || { echo aborted; exit 1; }
fi
# ─── Build and assemble (out-of-place; old release keeps serving) ────
say "Syncing, building and assembling $SHORT"
BUILD="$BUILD" remote_root <<'EOF'
set -e
su -s /bin/bash "$SVC_USER" <<INNER
set -e
git -C "$APP_DIR/repo" fetch --quiet origin main
git -C "$APP_DIR/repo" reset --hard "$SHA" --quiet
git -C "$APP_DIR/repo" log --oneline -1
cd "$APP_DIR/repo"
export npm_config_cache="$APP_DIR/.npm" NODE_OPTIONS=--max-old-space-size=3072
# Built WITHOUT the env file, deliberately - same as the Dockerfile. Every setting
# this app reads (NEXTAUTH_URL, MINIO_ENDPOINT, ...) is read at request time by a
# dynamic route, so nothing needs baking in and the bundle stays host-independent.
# Keep it that way: a build that depends on secrets stops being reproducible.
npm ci --prefer-offline --no-audit --fund=false
npx prisma generate
npm run build
# Mirrors Dockerfile:24-30 - standalone bundle plus static and public copied in.
REL="$APP_DIR/releases/$SHORT"
rm -rf "\$REL" && mkdir -p "\$REL/.next/cache"
cp -a "$APP_DIR/repo/.next/standalone/." "\$REL"/
cp -a "$APP_DIR/repo/.next/static" "\$REL/.next/static"
cp -a "$APP_DIR/repo/public" "\$REL/public"
du -sh "\$REL"
INNER
EOF
[ "${PIPESTATUS[0]:-0}" -eq 0 ] || die "build/assembly failed"
# ─── Schema ──────────────────────────────────────────────────────────
say "Backing up database, then applying schema"
remote_root <<'EOF'
set -e
install -d -m 0750 /var/backups/drinktracker
sudo -u postgres pg_dump drinkman | gzip -9 > "/var/backups/drinktracker/pre-$SHORT.sql.gz"
ls -lh "/var/backups/drinktracker/pre-$SHORT.sql.gz"
# db push, NOT migrate deploy: production has no _prisma_migrations table, so
# migrate deploy would try to apply the init migration against populated tables.
# --accept-data-loss means removing a field from schema.prisma DROPS the column.
su -s /bin/bash "$SVC_USER" -c "set -a; . /etc/drinktracker/drinktracker.env; set +a; cd $APP_DIR/repo && npx prisma db push --skip-generate --accept-data-loss"
EOF
[ "${PIPESTATUS[0]:-0}" -eq 0 ] || die "schema step failed"
# ─── Swap and restart ────────────────────────────────────────────────
say "Swapping to $SHORT and restarting"
remote_root <<'EOF'
set -e
su -s /bin/bash "$SVC_USER" -c "ln -sfn $APP_DIR/releases/$SHORT $APP_DIR/current.new && mv -Tf $APP_DIR/current.new $APP_DIR/current"
systemctl restart drinktracker
EOF
health_poll || die "app unhealthy - check: ${SSH[*]} 'sudo journalctl -u drinktracker -n 50'"
# ─── Verify and prune ────────────────────────────────────────────────
say "Verifying"
"${SSH[@]}" "curl -s -o /dev/null -w ' public=%{http_code}\n' -m 15 https://drinktracker.tenseconddelay.net/ || true"
remote_root <<'EOF'
journalctl -u drinktracker --since '3 min ago' | grep '\[switchboard\]' | tail -3 || echo " (no AI calls in window)"
cd "$APP_DIR/releases" && ls -1t | tail -n +$((KEEP+1)) | xargs -r rm -rf
echo " releases kept:"; ls -1t "$APP_DIR/releases" | sed 's/^/ /'
EOF
say "Deployed $SHORT"
echo "Roll back with: ./deploy/deploy.sh --rollback"