Files
superbrain/deploy/federated/lib-superbrain.sh
T
Andrew S Erwin ceb4973359
release gate / check (push) Failing after 6m46s
release / smoke (push) Successful in 10m40s
release / publish (push) Failing after 9m59s
Reset version scheme to 0.x (pre-beta); release 0.2.14
Superbrain is not yet beta, so the release line moves from 1.2.x to 0.2.x.
0.2.14 is the same code as 1.2.14 (the Nextcloud DAV connection fix) under
the new number; future releases continue from 0.2.15. Existing 1.2.x tags
and images stay published and untouched; CHANGELOG keeps the 1.2.x entries
as history and notes the reset.

Bumps in lockstep: federated service VERSION, installer
SUPERBRAIN_IMAGE_VERSION, superbrain-mcp package version (pyproject +
__init__). Also fixes the outbound MCP client implementation string, which
still reported a stale hardcoded 1.2.7, to the release version. README
release examples updated to the new scheme.

The house upgrade flow compares version tags by string equality, so the
1.2.14 -> 0.2.14 transition deploys through the standard update.sh path
(no downgrade special-casing needed).
2026-11-16 21:51:02 -06:00

469 lines
22 KiB
Bash

#!/bin/bash
#
# Superbrain Service
#
# Superbrain is a Go API + Next.js web stack, installed from REGISTRY
# IMAGES (no source on the host):
#
# federatedcomputer/superbrain-app (Go API, scratch)
# federatedcomputer/superbrain-web (Next.js standalone)
# federatedcomputer/superbrain-migrate (db/ baked in: bootstrap.sh applies
# schema.sql on an empty database,
# then always runs the ledger)
#
# All three share ONE version tag per release (IMAGE_VERSION in .env,
# VERSION in the service file — the generic `upgrade` flow compares them,
# pulls, btrfs-snapshots and rewrites .env). Images are published by the
# repo's release workflow on semver tags without a v prefix (1.0.0).
# Install is the standard house flow: /federated/bin/installapp superbrain.
#
# upgrade_app() pulls only the FIRST image: line of the compose (the app);
# the services/superbrain/upgrade/pre hook pulls web+migrate at the target
# version before the redeploy. CONTAINER in the service file must equal
# that first image's repository, and the web container must be named
# exactly "superbrain" (upgrade_app probes it by name).
#
# Database: the shared suite postgres (container "postgresql",
# postgresql.$DOMAIN on the core network). The migrate image owns schema
# lifecycle end to end: empty database => schema.sql applied AS the
# superbrain user (object ownership! migrations must be able to ALTER
# these objects), then the checksummed ledger on top — migrations are NOT
# a full schema by themselves (see db/check-convergence.sh in the repo).
#
# Networking: fixed core IPs — web 192.168.0.93 (traefik target; container
# name MUST be "superbrain" for upgrade_app()/monitor tooling), app .94,
# migrate .95. Nothing is published on host ports (127.0.0.1:8080 is taken
# on this box; web reaches app via container-name DNS on core).
#
# Rate limiting: TRUSTED_PROXY is deliberately NOT set — web only trusts
# X-Real-IP, which traefik does not send; all clients share one rate-limit
# bucket until that is solved (web logs a warning at startup).
PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
get_appvars
. /etc/federated
SUPERBRAIN_WEB_IP="192.168.0.93"
SUPERBRAIN_APP_IP="192.168.0.94"
SUPERBRAIN_MIGRATE_IP="192.168.0.95"
# Release to install; the generic `upgrade` flow keeps .env in step with the
# service file's VERSION afterwards.
SUPERBRAIN_IMAGE_VERSION="0.2.14"
# render_superbrain_compose writes the app-dir compose file. Called by
# config_superbrain (install) and by deploy/federated/update.sh after a lib
# sync, so a release that changes the compose shape can be applied without
# reinstalling. Requires DOMAIN, EXTERNALIP (get_appvars / /etc/federated)
# and the SUPERBRAIN_*_IP constants below.
render_superbrain_compose() {
# app is deliberately the FIRST service with an image: key — upgrade_app()
# reads the first image: line and compares it to CONTAINER in the service
# file (federatedcomputer/superbrain-app).
cat > /federated/apps/superbrain/docker-compose.yml <<EOF
services:
app:
image: federatedcomputer/superbrain-app:\${IMAGE_VERSION}
container_name: superbrain-app
restart: always
depends_on:
migrate: {condition: service_completed_successfully}
env_file:
- ./.env
# Split-horizon DNS: nextcloud.$DOMAIN resolves to a private container IP
# inside the core network, where nothing listens on 443 (traefik holds
# TLS on the public address) and netguard refuses private dials anyway.
# Pin the public IP - the same house pattern the web service uses for
# authelia - so the WebDAV/CalDAV/CardDAV connectors reach the deployment's
# Nextcloud over the public, netguard-clean route. No guard relaxation.
extra_hosts:
- "nextcloud.$DOMAIN:$EXTERNALIP"
healthcheck:
test: [CMD, /superbrain, --healthcheck]
interval: 3s
timeout: 4s
retries: 20
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
networks:
core:
ipv4_address: $SUPERBRAIN_APP_IP
web:
image: federatedcomputer/superbrain-web:\${IMAGE_VERSION}
# MUST be named exactly "superbrain": upgrade_app() probes
# "docker container inspect superbrain" and skips apps whose primary
# container it cannot find under the app name. (No backticks in this
# heredoc: it is unquoted, so they would become command substitution —
# hit in production 2026-11-05 when a re-render with the container
# running injected inspect JSON into the compose file.)
container_name: superbrain
hostname: superbrain.$DOMAIN
restart: always
depends_on:
app: {condition: service_healthy}
env_file:
- ./.env
# OIDC discovery targets the public authelia hostname; pin it like
# gitea/vaultwarden/immich do so the lookup doesn't hairpin via DNS.
extra_hosts:
- "authelia.$DOMAIN:$EXTERNALIP"
healthcheck:
# busybox wget from the alpine base; /login renders without a session.
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/login"]
interval: 10s
timeout: 4s
retries: 3
start_period: 20s
read_only: true
tmpfs: [/tmp]
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
networks:
core:
ipv4_address: $SUPERBRAIN_WEB_IP
labels:
- "traefik.enable=true"
- "traefik.http.routers.superbrain.rule=Host(\`superbrain.$DOMAIN\`)"
- "traefik.http.routers.superbrain.entrypoints=websecure"
- "traefik.http.routers.superbrain.tls.certresolver=letsencrypt"
- "traefik.http.services.superbrain.loadbalancer.server.port=3000"
migrate:
# Self-contained: db/ is baked into the image (bootstrap.sh applies
# schema.sql on an empty database, then always runs the ledger).
# DB_HOST/DB_USER/DB_NAME/PGPASSWORD arrive via the env_file.
image: federatedcomputer/superbrain-migrate:\${IMAGE_VERSION}
container_name: superbrain-migrate
restart: "no"
env_file:
- ./.env
networks:
core:
ipv4_address: $SUPERBRAIN_MIGRATE_IP
networks:
core:
external: true
EOF
}
config_superbrain() {
echo -ne "* Configuring Superbrain container.."
mkdir -p /federated/apps/superbrain
SUPERBRAIN_DB_PASSWORD=$(create_password)
SUPERBRAIN_AUTH_SECRET=$(create_password)
SUPERBRAIN_ENCRYPTION_KEY=$(create_password)
# Shared house SMTP sender credential (fcore) for the notification
# engine's email channel. Reuse the secret other apps already hold; never
# generate a new one — the mail server is LDAP-provisioned and
# `setup email add` does not exist there (ACCOUNT_PROVISIONER is not
# FILE). Verified end-to-end 2026-10-26: net/smtp STARTTLS + AUTH PLAIN
# to mail.$DOMAIN:587 from the core network delivers with a per-app From
# address (sender != login user is allowed; authelia does the same).
if [ -f /federated/apps/authelia/data/secrets/NOTIFIER_SMTP_PASSWORD ]; then
SUPERBRAIN_SMTP_PASSWORD=$(cat /federated/apps/authelia/data/secrets/NOTIFIER_SMTP_PASSWORD)
else
SUPERBRAIN_SMTP_PASSWORD=$(sed -n 's/^EMAIL_HOST_PASSWORD=//p' /federated/apps/superpanel/.env | tail -1)
fi
[ -n "$SUPERBRAIN_SMTP_PASSWORD" ] || failcheck "could not find the fcore SMTP password (authelia secret or superpanel .env)"
# app is deliberately the FIRST service with an image: key — upgrade_app()
# reads the first image: line and compares it to CONTAINER in the service file.
render_superbrain_compose
cat > /federated/apps/superbrain/.env <<EOF
# Registry mode: one shared version tag for app/web/migrate. The generic
# `upgrade` flow compares this against the service file, pulls, snapshots
# and rewrites this line. NOTE: upgrade_app's sed rewrites EVERY line
# whose text contains that variable name plus "=" — this must stay the
# only such line in this file (comments included).
IMAGE_VERSION="$SUPERBRAIN_IMAGE_VERSION"
# --- Database (shared suite postgres; user+db created below) ---
DB_HOST=postgresql.$DOMAIN
DB_USER=superbrain
DB_NAME=superbrain
PGPASSWORD=$SUPERBRAIN_DB_PASSWORD
DATABASE_URL=postgres://superbrain:$SUPERBRAIN_DB_PASSWORD@postgresql.$DOMAIN:5432/superbrain?sslmode=disable
# --- Secrets — BACK THESE UP. Sessions and stored IMAP passwords are
# --- cryptographically bound to AUTH_SECRET/ENCRYPTION_KEY; losing them
# --- signs everyone out and destroys saved credentials even if the DB lives.
AUTH_SECRET=$SUPERBRAIN_AUTH_SECRET
NEXTAUTH_SECRET=$SUPERBRAIN_AUTH_SECRET
ENCRYPTION_KEY=$SUPERBRAIN_ENCRYPTION_KEY
# --- Web (NextAuth) ---
# Must be the exact browser-facing origin — the API proxy 403s every
# mutating request on an origin mismatch.
NEXTAUTH_URL=https://superbrain.$DOMAIN
AUTH_TRUST_HOST=true
API_BASE_URL=http://superbrain-app:8080
# --- Access policy ---
# Decision 2026-10-26: the core/federated install is the CORE TIER —
# TIER=core derives AUTH_MODE=oidc (Authelia only: Go refuses password
# login, signup and password reset at the API), signup off and bootstrap
# off; no explicit overrides are set here on purpose, so the tier defaults
# are the single source of truth. Accounts are provisioned upstream
# (Superpanel -> LDAP -> Authelia) and materialize locally on first SSO
# login. ADMIN_EMAILS makes a listed address ADMIN at first SSO login —
# the only bootstrap path in this tier. The operator account is seeded
# password-less; a pre-existing password account can be linked offline:
# docker exec -e SEED_EMAIL=... -e SEED_SUBJECT=... superbrain-app
# /superbrain --seed (needed because the SSO bridge refuses to auto-link
# password accounts by email alone). The hosted self-service product is
# the other tier: TIER=multi (AUTH_MODE=password, signup + SMTP-backed
# self-reset; see RUNNING.md).
ADMIN_EMAILS=admin@$DOMAIN
TIER=core
COOKIE_SECURE=1
# TRUSTED_PROXY deliberately unset — traefik does not send X-Real-IP.
# --- Transactional mail (notification engine email channel) ---
# House pattern: authenticated submission via mail.$DOMAIN:587 as the
# shared sender account fcore with a per-app From address (authelia and
# superpanel do the same). Password reset stays refused on this tier
# (oidc mode); this relay exists for notification deliveries.
# Split-horizon DNS: mail.$DOMAIN resolves to the private container IP
# inside the core network, hence the netguard pin (verified 2026-10-26).
SMTP_HOST=mail.$DOMAIN
SMTP_PORT=587
SMTP_USERNAME=fcore
SMTP_PASSWORD=$SUPERBRAIN_SMTP_PASSWORD
SMTP_FROM=superbrain@$DOMAIN
NETGUARD_TRUSTED_HOSTS=mail.$DOMAIN
# --- DAV shares (Settings → WebDAV / CalDAV / CardDAV) ----------------------
# Nextcloud runs on this core, so Superbrain offers it as a one-click prefill
# for file shares, calendars and address books (purely a hint - every
# connection still needs the person's own username and app password; see the
# three DAV sections in API.md).
NEXTCLOUD_URL=https://nextcloud.$DOMAIN
EOF
chmod 600 /federated/apps/superbrain/.env
# Create PostgreSQL database and user (house pattern). Schema lifecycle
# belongs to the migrate image: bootstrap.sh detects the empty database
# and applies schema.sql as the superbrain user, then runs the ledger.
docker exec postgresql psql -U postgres -c "CREATE USER superbrain WITH PASSWORD '$SUPERBRAIN_DB_PASSWORD'" &>/dev/null
docker exec postgresql psql -U postgres -c "CREATE DATABASE superbrain" &>/dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE superbrain TO superbrain" &>/dev/null
docker exec postgresql psql -U postgres -c "ALTER DATABASE superbrain OWNER TO superbrain" &>/dev/null
# Pull the release images up front so registry/auth problems fail here
# with a clear message instead of mid-`up`.
echo -ne "\n* Pulling superbrain images ($SUPERBRAIN_IMAGE_VERSION)..\n"
(cd /federated/apps/superbrain && docker compose pull) || failcheck "could not pull federatedcomputer/superbrain-*:$SUPERBRAIN_IMAGE_VERSION - does the release exist on Docker Hub?"
echo -ne "done.\n"
}
start_superbrain() {
start_service "superbrain" "nc -z $SUPERBRAIN_WEB_IP 3000 &> /dev/null" "30"
docker exec pdns pdnsutil add-record $DOMAIN superbrain.$DOMAIN A 86400 $EXTERNALIP &>/dev/null
# Provision the operator account. Verified idempotent (no-op when the email
# already exists); grants ADMIN because admin@$DOMAIN is in ADMIN_EMAILS.
# Password-less on purpose (AUTH_MODE=oidc): a password would be unusable
# with login disabled AND would block the SSO bridge's verified-email
# auto-link (409). First Authelia login links the account; if Authelia ever
# stops asserting email_verified, link offline instead with
# -e SEED_SUBJECT=<authelia sub> on the same command.
for i in $(seq 1 10); do
docker exec -e SEED_EMAIL="admin@$DOMAIN" -e SEED_NAME="Admin" \
superbrain-app /superbrain --seed &>/dev/null && break
sleep 3
done
echo -ne "done.\n"
}
uninstall_superbrain() {
echo -ne "* Uninstalling superbrain container.."
docker compose -f /federated/apps/superbrain/docker-compose.yml -p superbrain down &>/dev/null
docker images --format '{{.Repository}}:{{.Tag}}' | grep '^federatedcomputer/superbrain-' | xargs -r docker image rm &>/dev/null || true
docker exec postgresql psql -U postgres -c "DROP DATABASE IF EXISTS superbrain" &>/dev/null
docker exec postgresql psql -U postgres -c "DROP USER IF EXISTS superbrain" &>/dev/null
rm -rf /federated/apps/superbrain
docker exec pdns pdnsutil delete-rrset $DOMAIN superbrain.$DOMAIN A &>/dev/null
# Remove Authelia SSO config if present (immich pattern). Two blocks exist:
# the claims policy ("### Superbrain claims", possibly with the
# claims_policies: key we created) and the client ("### Superbrain").
# Remove the claims block FIRST and by exact line count - the client-block
# range deletion below starts at the first "### Superbrain" match, and a
# leftover claims marker would make it eat the claims_policies:/clients: keys.
AUTH_YML=/federated/apps/authelia/data/config/idproviders.yml
if grep -q "### Superbrain" "$AUTH_YML" 2>/dev/null; then
sed -i '/### Superbrain claims/{N;N;d}' "$AUTH_YML"
# Drop claims_policies: again when our policy was its only entry.
awk '
/^ claims_policies:$/ {
if ((getline nxt) > 0) {
if (nxt ~ /^ /) { print; print nxt } else { print nxt }
}
next
}
{ print }
' "$AUTH_YML" > "$AUTH_YML.tmp" && mv "$AUTH_YML.tmp" "$AUTH_YML"
sed -i '/### Superbrain/,/### /{/### [A-Z]/!{/### /!d}}' "$AUTH_YML"
sed -i '/### Superbrain/d' "$AUTH_YML"
docker exec authelia authelia validate-config --config /config/configuration.yml --config /config/idproviders.yml --config.experimental.filters template \
|| echo "WARNING: Authelia config does not validate after superbrain removal - inspect $AUTH_YML before relying on SSO"
restart_service authelia
fi
echo -ne "done.\n"
}
configsso_superbrain() {
echo -ne "* Configuring superbrain SSO with Authelia.."
[ ! -d "/federated/apps/authelia" ] && failcheck "Authelia is not installed. You need this first before continuing."
[ ! -f "/federated/apps/authelia/data/config/idproviders.yml" ] && failcheck "Authelia idproviders.yml is missing."
[[ $(grep "### Superbrain" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Superbrain configuration."
SUPERBRAIN_CLIENT_SECRET=$(create_password)
SUPERBRAIN_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $SUPERBRAIN_CLIENT_SECRET | awk '{ print $2 }')
# Authelia only includes claims listed in a claims policy's id_token set in
# the ID token, and Auth.js builds the OIDC profile EXCLUSIVELY from ID-token
# claims (it only calls userinfo when a provider sets idToken:false, which
# superbrain must not). Without email in the id_token the Go bridge answers
# 400 "Subject and email are required" and every SSO login ends in
# AccessDenied (hit in production 2026-10-25). Register the policy next to
# the client; the uninstall path removes both.
AUTH_YML=/federated/apps/authelia/data/config/idproviders.yml
SUPERBRAIN_CLAIMS="['email', 'email_verified', 'name', 'preferred_username']"
cp -a "$AUTH_YML" "$AUTH_YML.bak-superbrain"
if grep -q '^ superbrain:$' "$AUTH_YML"; then
echo " claims policy 'superbrain' already present, keeping it"
elif grep -q '^ claims_policies:' "$AUTH_YML"; then
sed -i "/^ claims_policies:/a\\ ### Superbrain claims\n superbrain:\n id_token: $SUPERBRAIN_CLAIMS" "$AUTH_YML"
else
sed -i "/^ clients:/i\\ claims_policies:\n ### Superbrain claims\n superbrain:\n id_token: $SUPERBRAIN_CLAIMS" "$AUTH_YML"
fi
SUPERBRAIN_OIDC_CLIENT_YAML=$(cat <<EOF
### Superbrain
- client_id: 'superbrain'
client_name: 'Superbrain'
claims_policy: 'superbrain'
client_secret: $SUPERBRAIN_CLIENT_SECRET_HASH
consent_mode: 'implicit'
public: false
authorization_policy: 'one_factor'
redirect_uris:
- 'https://superbrain.$DOMAIN/api/auth/callback/authelia'
scopes:
- 'openid'
- 'profile'
- 'email'
userinfo_signed_response_alg: 'none'
EOF
)
printf '%s\n' "$SUPERBRAIN_OIDC_CLIENT_YAML" >> "$AUTH_YML"
printf '%s\n' "$SUPERBRAIN_OIDC_CLIENT_YAML" > /federated/apps/superbrain/.superbrain.oidc-client.yml
chmod 600 /federated/apps/superbrain/.superbrain.oidc-client.yml
# idproviders.yml is shared by every SSO app: validate the merged config
# before restarting, and restore the backup when it does not parse.
if ! docker exec authelia authelia validate-config --config /config/configuration.yml --config /config/idproviders.yml --config.experimental.filters template; then
cp -a "$AUTH_YML.bak-superbrain" "$AUTH_YML"
failcheck "Authelia config invalid after adding superbrain - restored $AUTH_YML.bak-superbrain"
fi
rm -f "$AUTH_YML.bak-superbrain"
restart_service authelia
# env_file pattern: appending here is enough — web picks the values up on
# restart, no compose rewrite needed.
cat >> /federated/apps/superbrain/.env <<EOF
# --- SSO (Authelia OIDC, written by configsso_superbrain) ---
OIDC_ISSUER=https://authelia.$DOMAIN
OIDC_CLIENT_ID=superbrain
OIDC_CLIENT_SECRET=$SUPERBRAIN_CLIENT_SECRET
EOF
# env_file gotcha (verified in production): compose stop/start or up -d do
# NOT recreate a container when only env_file CONTENT changed, so the
# appended OIDC_* vars would never reach web. Force-recreate explicitly.
(cd /federated/apps/superbrain && docker compose -p superbrain up -d --force-recreate web) || failcheck "could not recreate superbrain web after SSO configuration"
# NOTE: SSO auto-provisions NEW users only. Pre-existing password accounts
# (e.g. the seeded admin) must be explicitly linked by an administrator via
# POST /api/admin/oidc-link — email match alone is intentionally not proof.
echo -ne "done.\n"
}
# --- mcpserver link ---------------------------------------------------------
# Supersedes the old "drop for now" decision (STRATEGY.md): Superbrain grew
# a real API-key mechanism (personal "sb_..." keys, internal/auth/apikeys.go)
# and ships its own MCP server package (mcp/ in the repo, spawned by the
# gateway as `superbrain-mcp`). Credential minting follows the immich/plane
# house pattern — direct into the app's database — because the keys API is
# session-gated and the operator account on this tier is password-less.
config_mcpserver_superbrain() {
echo -ne "* Linking superbrain into mcpserver.."
local admin_id key hash prefix key_id
admin_id=$(docker exec postgresql psql -U superbrain -d superbrain -t -A \
-c "select id from \"User\" where email='admin@$DOMAIN' limit 1;")
if [ -z "$admin_id" ]; then
echo -ne "failed -- admin@$DOMAIN not found in Superbrain.\n"
return 1
fi
# Key shape (must match internal/auth/apikeys.go): "sb_" + 43 base64url
# chars over 32 random bytes; the database stores only the SHA-256 hash.
key="sb_$(openssl rand 32 | openssl base64 -A | tr '+/' '-_' | tr -d '=')"
hash=$(printf '%s' "$key" | sha256sum | awk '{print $1}')
prefix=${key:0:11}
key_id=$(openssl rand -hex 16)
# Idempotent: relinking rotates cleanly — exactly one dedicated key, the
# old one is deleted first so it never keeps working.
docker exec postgresql psql -U superbrain -d superbrain -c \
"DELETE FROM \"ApiKey\" WHERE \"ownerId\"='$admin_id' AND name='mcpserver';" &>/dev/null
docker exec postgresql psql -U superbrain -d superbrain -c \
"INSERT INTO \"ApiKey\" (id, \"ownerId\", name, prefix, \"keyHash\") VALUES ('$key_id','$admin_id','mcpserver','$prefix','$hash');" &>/dev/null
# The Go API directly, via container-name DNS on the core network. The web
# proxy signs browser assertions and never forwards a Bearer key, and no
# extra_hosts hairpin is needed either: the app container speaks plain HTTP
# internally (only web is traefik-routed). Keys are plan-gated on the
# mcp-core connector — this tier runs TIER=core, whose plan includes it.
set_mcpserver_env SUPERBRAIN_API_URL "http://superbrain-app:8080"
set_mcpserver_env SUPERBRAIN_API_KEY "$key"
echo -ne "done.\n"
}
# Reverses config_mcpserver_superbrain(): deletes the dedicated key and
# mcpserver's env vars. Called by /federated/bin/uninstallapp-mcpserver
# superbrain, and from lib/mcpserver.sh's uninstall_mcpserver() when the
# whole gateway is removed (the &>/dev/null tolerates a dropped database
# during a full superbrain uninstall).
uninstall_mcpserver_superbrain() {
echo -ne "* Unlinking superbrain from mcpserver.."
docker exec postgresql psql -U superbrain -d superbrain -c \
"DELETE FROM \"ApiKey\" WHERE name='mcpserver';" &>/dev/null
unset_mcpserver_env SUPERBRAIN_API_URL
unset_mcpserver_env SUPERBRAIN_API_KEY
echo -ne "done.\n"
}