Files
coreapp-dev/bin/coreapp
T
davidandClaude Opus 5.5 bef3b86970 Install apps from their repository, including private ones
coreapps plan|install <https://host/owner/repo>[@tag] reads only
coreapp.toml and icon.png at the tag's commit (depth 1, blobs on demand,
regular files only), with git limited to https and no prompts or system
settings. The default tag is the newest numeric release; version must
match the tag; the image is always pulled. The marker records source,
tag and commit; the same name from another repository is refused.
coreapps update <name> moves to the newest release. On the workstation:
coreapp install <url> (shows the app and its needs, asks) and update.

Private apps: coreapps login <host> <user> keeps a read-only token (from
stdin) in /etc/coreapps/credentials (root only), checked with the host's
registry first. git gets it as an extraHeader for that host only, docker
in a config made for each pull. coreapp login/logout/logins on the
workstation. Tested with a private repository and package on Federated's
Gitea.

Fixed: old images of docker.io/library/... weren't deleted (docker lists
them by short name); remove force-deleted images another app could use;
coreapp help cut off multi-line descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:51:41 -07:00

518 lines
20 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Purpose : Make, deploy and test apps for Federated Core, against the Core
# in coreapp-dev's VM (coreapp-vm).
#
# coreapp new [--postgres] [--sso] <name>
# make a new app in ./<name> (with its own database,
# sign-in through the Core's Authelia, or both)
# coreapp deploy [--recreate]
# build, copy to the Core, install or update
# (--recreate: a new container even if nothing changed)
# coreapp check the app answers at https://<name>.<domain>/
# coreapp status its container, address and URL
# coreapp logs [-f] its log
# coreapp shell [command] a shell in its container, or run one command there
# coreapp remove uninstall it from the Core (asks first)
# coreapp list the apps on the Core installed this way
# coreapp install <https://host/owner/repo>[@tag]
# install a published app from its repository, as
# a Core's owner would (shows what it needs first)
# coreapp update <name> update an app installed from a repository to its
# newest release
# coreapp login <host> give the Core a token for private apps from host
# (asks for the user and token); logout <host>,
# logins: forget one, list them
# coreapp publish [--platform <list>]
# build the release image and push it to the
# registry in coreapp.toml, and tag the commit
#
# Run deploy, check, status, logs, shell, remove and publish in the app's
# folder (the one with coreapp.toml). COREAPP_VM picks the VM (default coreserver).
set -euo pipefail
SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
TEMPLATES="$(dirname "$SELF_DIR")/templates"
TEMPLATE="$TEMPLATES/app"
# The installer that runs on the Core (coreapps), and where it goes there
INSTALLER="$(dirname "$SELF_DIR")/core"
REMOTE_INSTALLER=/opt/coreapps
DATA="$HOME/.local/share/coreapp-dev"
SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts"
VM="${COREAPP_VM:-coreserver}"
die() { echo "$*" >&2; exit 1; }
usage() {
# The command list at the top of this file, continuation lines included
sed -n '/^# coreapp new/,/^#$/{/^#$/d;s/^# //p}' "${BASH_SOURCE[0]}"
}
# --- The Core -------------------------------------------------------------
CORE_IP=""
# Look up the VM's address once, in this shell (not in a $(...) subshell,
# which would forget it)
init_core() {
if [[ -z "$CORE_IP" ]]; then
CORE_IP="$("$SELF_DIR/coreapp-vm" ip "$VM" 2> /dev/null)" \
|| die "The Core's VM '$VM' isn't running: coreapp-vm start $VM"
fi
}
core_ip() { init_core; echo "$CORE_IP"; }
# Run a shell command on the Core as root (stdin is passed through)
core() {
ssh -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
-o StrictHostKeyChecking=accept-new -o BatchMode=yes \
"root@$(core_ip)" "$1"
}
# The same, with a terminal (for shells and following logs)
core_tty() {
ssh -t -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
-o StrictHostKeyChecking=accept-new "root@$(core_ip)" "$1"
}
DOMAIN=""
core_domain() {
if [[ -z "$DOMAIN" ]]; then
# shellcheck disable=SC2016 # expanded on the Core
DOMAIN="$(core '. /etc/federated; echo "$DOMAIN"')"
[[ -n "$DOMAIN" ]] || die "The VM has no Core installed yet (no DOMAIN in /etc/federated)."
fi
echo "$DOMAIN"
}
# --- The app in the current folder ---------------------------------------
# From coreapp.toml, as checked by the installer
NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS=""
load_app() {
load_manifest
init_core
}
# coreapp.toml's values, checked by the installer (no Core needed)
load_manifest() {
local values key value
[[ -f coreapp.toml ]] \
|| die "No app here: run this in an app's folder (one with coreapp.toml), or make one with coreapp new <name>."
values="$(python3 "$INSTALLER/coreapps" manifest .)" || exit 1
while IFS='=' read -r key value; do
case "$key" in
name) NAME="$value" ;;
title) TITLE="$value" ;;
version) VERSION="$value" ;;
image) IMAGE="$value" ;;
port) PORT="$value" ;;
health) HEALTH="$value" ;;
needs) NEEDS="$value" ;;
esac
done <<< "$values"
}
image() { echo "$IMAGE:$VERSION"; }
# Put the installer on the Core, as this coreapp-dev has it
sync_installer() {
tar -C "$INSTALLER" --exclude=__pycache__ --exclude=.claude -cf - . | core "
set -e
rm -rf $REMOTE_INSTALLER.new && mkdir -p $REMOTE_INSTALLER.new
tar --no-same-owner -xf - -C $REMOTE_INSTALLER.new
rm -rf $REMOTE_INSTALLER && mv $REMOTE_INSTALLER.new $REMOTE_INSTALLER"
}
# Run the installer on the Core with this app's coreapp.toml and icon.png,
# copied to a temporary folder there: coreapps <command> [options] <folder>
installer() {
local files=(coreapp.toml)
[[ -f icon.png ]] && files+=(icon.png)
tar -cf - "${files[@]}" | core "
d=\$(mktemp -d) && tar --no-same-owner -xf - -C \$d || exit 1
$REMOTE_INSTALLER/coreapps $* \$d; status=\$?
rm -rf \$d; exit \$status"
}
# --- new --------------------------------------------------------------------
# Lay an overlay over the app in $1: its files replace the app's, except
# *.append (added to the end of the app's file), .remove (app files it
# doesn't use) and .needs (what it needs from the Core, for coreapp.toml)
apply_overlay() {
local app="$1" overlay="$2" f
tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.needs \
--exclude='*.append' -cf - . | tar -C "$app" -xf -
for f in "$overlay"/*.append; do
[[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)"
done
if [[ -f "$overlay/.remove" ]]; then
while read -r f; do [[ -n "$f" ]] && rm -rf "${app:?}/$f"; done < "$overlay/.remove"
fi
}
cmd_new() {
local name="" postgres="" sso="" title dbname f needs="" what=""
local overlays=()
while [[ $# -gt 0 ]]; do
case "$1" in
--postgres) postgres=1 ;;
--sso) sso=1 ;;
-*) die "Unknown option $1. Usage: coreapp new [--postgres] [--sso] <name>" ;;
*) name="$1" ;;
esac
shift
done
[[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
[[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] <name> (lowercase letters, digits and -)"
[[ "$name" =~ ^[a-z]([a-z0-9-]{0,29}[a-z0-9])$ ]] \
|| die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter and not ending with -. It becomes https://$name.<domain>."
[[ ! -e "$name" ]] || die "./$name already exists."
# In this order; with both, the combined example app goes on top
[[ -n "$postgres" ]] && overlays+=("$TEMPLATES/postgres")
[[ -n "$sso" ]] && overlays+=("$TEMPLATES/sso")
[[ -n "$postgres" && -n "$sso" ]] && overlays+=("$TEMPLATES/postgres-sso")
for f in "${overlays[@]}"; do
[[ -d "$f" ]] || die "The template $f is missing."
done
# "my-app" -> "My App". The database name is the installer's (coreapps)
title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')"
dbname="coreapp_${name//-/_}"
mkdir "$name"
tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
for f in "${overlays[@]}"; do
apply_overlay "$name" "$f"
[[ -f "$f/.needs" ]] && needs="$needs, \"$(cat "$f/.needs")\""
done
sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml"
# The example apps with a database or sign-in have a /health path
[[ ${#overlays[@]} -gt 0 ]] && sed -i 's|^health = .*|health = "/health"|' "$name/coreapp.toml"
while IFS= read -r -d '' f; do
sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{DBNAME}}/$dbname/g" "$f"
done < <(find "$name" -type f ! -name '*.png' -print0)
[[ -n "$postgres" ]] && what=", with a database"
[[ -n "$sso" ]] && what="$what, with sign-in through Authelia"
echo "Made $title in ./$name$what."
echo "Next: cd $name && coreapp deploy"
}
# --- deploy -----------------------------------------------------------------
cmd_deploy() {
local plan state tier answer local_id core_id addon="" recreate=""
case "${1:-}" in
--recreate) recreate=--recreate ;;
"") ;;
*) die "Usage: coreapp deploy [--recreate]" ;;
esac
load_app
echo "Updating the installer on the Core ($REMOTE_INSTALLER)..."
sync_installer
# What installing would do (and whether the Core refuses it: name taken...)
plan="$(installer plan)" || exit 1
state="$(sed -n 's/^state=//p' <<< "$plan")"
tier="$(sed -n 's/^tier=//p' <<< "$plan")"
if grep -qx 'addon=yes' <<< "$plan"; then
echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app"
echo "(ADDON_APPS in /etc/federated), which Federated may bill for."
read -r -p "Install anyway? [y/N] " answer
[[ "$answer" =~ ^[Yy] ]] || die "Not deployed."
addon=--addon-ok
fi
echo "Building $(image)..."
docker build -q -t "$(image)" . > /dev/null
# localhost/ images exist only where they're copied; others the Core can
# pull, but while developing, the one just built is the one to test
local_id="$(docker image inspect -f '{{.Id}}' "$(image)")"
core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")"
if [[ "$local_id" != "$core_id" ]]; then
echo "Copying the image to the Core ($(docker image inspect -f '{{.Size}}' "$(image)" | numfmt --to=iec))..."
docker save "$(image)" | core "docker load -q > /dev/null"
else
echo "The Core already has this image."
fi
# Install, or update (which recreates the container if the image changed,
# even under the same version)
installer install $addon $recreate || exit 1
[[ "$state" == new ]] && echo "(coreapp check tests it from the internet.)"
return 0
}
# --- check, status, logs, shell, remove ------------------------------------
cmd_check() {
local domain url result code verify tries=24
load_app
domain="$(core_domain)"
url="https://$NAME.$domain$HEALTH"
echo "Checking $url (expecting HTTP 2xx and a valid certificate)..."
# A new app's certificate can take a minute: traefik gets it from Let's
# Encrypt through the Core's DNS
while true; do
result="$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{ssl_verify_result}' "$url" 2>&1 || true)"
code="${result%% *}"
verify="${result##* }"
if [[ "$code" =~ ^2 && "$verify" == 0 ]]; then
echo "OK: HTTP $code, valid certificate."
return 0
fi
tries=$((tries - 1))
if ((tries == 0)); then break; fi
sleep 5
done
echo "Not OK: $result (HTTP code, then 0 if the certificate is valid)." >&2
# Is it the app, or the way in?
result="$(curl -sSk -o /dev/null --max-time 15 -w '%{http_code}' \
--resolve "$NAME.$domain:443:$(core_ip)" "$url" 2>&1 || true)"
echo "Straight to the VM, skipping DNS and the relay: HTTP $result." >&2
exit 1
}
cmd_status() {
local domain
load_app
domain="$(core_domain)"
core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}} {{.Status}} image {{.Image}}'
[ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'"
echo "App: $TITLE $(image)"
echo "Address on the Core: $(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null"), port $PORT"
echo "Needs: ${NEEDS:-nothing}"
echo "URL: https://$NAME.$domain/"
}
cmd_logs() {
load_app
if [[ "${1:-}" == -f ]]; then
core_tty "docker logs -f --tail 50 $NAME"
else
core "docker logs --tail 200 $NAME 2>&1"
fi
}
cmd_shell() {
load_app
if [[ $# -gt 0 ]]; then
# One command, without a terminal, so scripts and agents can use it:
# coreapp shell 'ls -l /data'
core "docker exec $NAME sh -c $(printf '%q' "$*")"
else
core_tty "docker exec -it $NAME sh -c 'command -v bash > /dev/null && exec bash || exec sh'"
fi
}
cmd_remove() {
local answer
load_app
echo "This uninstalls $NAME from the Core in '$VM', with its settings and data"
echo "there${NEEDS:+ (and what it has in: $NEEDS)}. This folder stays as it is."
read -r -p "Remove it? [y/N] " answer
[[ "$answer" =~ ^[Yy] ]] || die "Not removed."
sync_installer
core "$REMOTE_INSTALLER/coreapps remove $NAME"
}
cmd_list() {
init_core
sync_installer
core "$REMOTE_INSTALLER/coreapps list"
}
# --- install, update (published apps) -----------------------------------
cmd_install() {
local source="${1:-}" plan key value answer addon=""
local -A info=()
[[ $# -eq 1 && "$source" == https://* ]] \
|| die "Usage: coreapp install <https://host/owner/repo>[@tag] (default: its newest release)"
init_core
sync_installer
echo "Reading $source..."
plan="$(core "$REMOTE_INSTALLER/coreapps plan $(printf '%q' "$source")")" || exit 1
while IFS='=' read -r key value; do info[$key]="$value"; done <<< "$plan"
echo
echo " ${info[title]} ${info[version]}${info[description]:+: ${info[description]}}"
echo " From: ${info[source]} (${info[tag]}, commit ${info[commit]:0:12})"
echo " Image: ${info[image]}:${info[version]}"
echo " Needs: ${info[needs]:-nothing from the Core}"
if [[ "${info[state]}" == update ]]; then
echo " Updates the installed ${info[name]}, keeping its settings and data."
else
echo " Installs it at ${info[url]}"
fi
echo
if [[ "${info[addon]}" == yes ]]; then
echo "This Core's tier is '${info[tier]}'. Installing records '${info[name]}' as an add-on"
echo "app (ADDON_APPS in /etc/federated), which Federated may bill for."
addon=--addon-ok
fi
read -r -p "Install it? [y/N] " answer
[[ "$answer" =~ ^[Yy] ]] || die "Not installed."
core "$REMOTE_INSTALLER/coreapps install $addon $(printf '%q' "$source")"
}
cmd_update() {
local name="${1:-}"
[[ $# -eq 1 && "$name" =~ ^[a-z][a-z0-9-]*$ ]] || die "Usage: coreapp update <name>"
init_core
sync_installer
core "$REMOTE_INSTALLER/coreapps update $name"
}
cmd_login() {
local host="${1:-}" user token
[[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] \
|| die "Usage: coreapp login <host> (e.g. coreapp login gitea.federated.computer)"
echo "The Core in '$VM' keeps this token to install private apps from $host:"
echo "their repositories and images. For Gitea, make a token for it with read"
echo "access to repositories and packages (Settings > Applications)."
read -r -p "User on $host: " user
[[ "$user" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "'$user' isn't a user name."
read -r -s -p "Token: " token
echo
init_core
sync_installer
# On stdin, so it's never in a command line
printf '%s\n' "$token" | core "$REMOTE_INSTALLER/coreapps login $host $user"
}
cmd_logout() {
local host="${1:-}"
[[ $# -eq 1 && "$host" =~ ^[a-z0-9][a-z0-9.:-]*$ ]] || die "Usage: coreapp logout <host>"
init_core
sync_installer
core "$REMOTE_INSTALLER/coreapps logout $host"
}
cmd_logins() {
init_core
sync_installer
core "$REMOTE_INSTALLER/coreapps logins"
}
# --- publish ----------------------------------------------------------------
# A registry image name from the repository's git remote, as a suggestion:
# https://host/Owner/Repo.git or git@host:Owner/Repo.git -> host/owner/repo
image_from_remote() {
local url host path
url="$(git remote get-url origin 2> /dev/null)" || return 1
case "$url" in
https://*) url="${url#https://}"; host="${url%%/*}"; path="${url#*/}" ;;
ssh://*) url="${url#ssh://}"; url="${url#*@}"; host="${url%%/*}"; host="${host%%:*}"; path="${url#*/}" ;;
*@*:*) url="${url#*@}"; host="${url%%:*}"; path="${url#*:}" ;;
*) return 1 ;;
esac
path="${path%.git}"
[[ "$path" == */* ]] || return 1
echo "$host/${path,,}"
}
cmd_publish() {
local platform=linux/amd64 ref tag registry source="" commit check digest suggestion
while [[ $# -gt 0 ]]; do
case "$1" in
--platform) platform="${2:?--platform needs a value, e.g. linux/amd64,linux/arm64}"; shift ;;
*) die "Usage: coreapp publish [--platform linux/amd64[,linux/arm64]]" ;;
esac
shift
done
load_manifest
ref="$(image)"
tag="v$VERSION"
registry="${IMAGE%%/*}"
if [[ "$IMAGE" == localhost/* ]]; then
suggestion="$(image_from_remote || true)"
if [[ -n "$suggestion" ]]; then
suggestion=", e.g. image = \"$suggestion\" (from the git remote)"
fi
die "image = \"$IMAGE\" in coreapp.toml only exists where coreapp deploy copies it.
To publish, set image to your registry$suggestion.
coreapp deploy keeps working with that name."
fi
# A release is a commit: the image is built from it, and the Core installs
# the app from the repository at its tag
git rev-parse --is-inside-work-tree > /dev/null 2>&1 \
|| die "This folder isn't a git repository. A published app is one (its tag is the release)."
[[ -z "$(git status --porcelain)" ]] \
|| die "There are uncommitted changes (git status). Commit them first, so the release matches a commit."
commit="$(git rev-parse HEAD)"
if git rev-parse -q --verify "refs/tags/$tag" > /dev/null; then
[[ "$(git rev-parse "$tag^{commit}")" == "$commit" ]] \
|| die "The tag $tag already exists on another commit. Raise version in coreapp.toml for a new release."
fi
case "$(git remote get-url origin 2> /dev/null || true)" in
https://*) source="$(git remote get-url origin)"; source="${source%.git}" ;;
esac
# Never replace a published version: Cores may have installed it
echo "Checking $registry for $ref..."
# (Only "not found" means it isn't there; any other error stops here)
if check="$(docker buildx imagetools inspect "$ref" 2>&1)"; then
die "$ref is already published. Raise version in coreapp.toml for a new release."
fi
case "$check" in
*"not found"* | *"manifest unknown"*) ;;
*unauthorized* | *denied* | *"authentication required"* | *401* | *403*)
die "$registry wants you to log in first: docker login $registry
(For Gitea, use a token with the write:package scope as the password.)" ;;
*) die "Couldn't check $registry for $ref: $check" ;;
esac
echo "Building $ref for $platform..."
local labels=(--label "org.opencontainers.image.version=$VERSION"
--label "org.opencontainers.image.revision=$commit"
--label "org.opencontainers.image.title=$TITLE")
[[ -n "$source" ]] && labels+=(--label "org.opencontainers.image.source=$source")
if [[ "$platform" == *,* ]]; then
# Several platforms at once can only be pushed straight from buildx
docker buildx build --platform "$platform" "${labels[@]}" -t "$ref" --push . \
|| die "Building or pushing failed (above). Several platforms need a buildx builder that supports them: docker buildx create --use"
else
docker build -q --platform "$platform" "${labels[@]}" -t "$ref" . > /dev/null
echo "Pushing it..."
docker push -q "$ref" > /dev/null \
|| die "Pushing failed. Log in first if you haven't: docker login $registry"
fi
digest="$(docker buildx imagetools inspect "$ref" --format '{{.Manifest.Digest}}' 2> /dev/null || true)"
git rev-parse -q --verify "refs/tags/$tag" > /dev/null || git tag -a "$tag" -m "${TITLE} $VERSION"
echo "Published $ref${digest:+ ($digest)}."
echo "Tagged this commit $tag. Push the commit and the tag, so the release is in the repository:"
echo " git push && git push origin $tag"
}
cmd="${1:-help}"
[[ $# -gt 0 ]] && shift
case "$cmd" in
new) cmd_new "$@" ;;
deploy) cmd_deploy "$@" ;;
check) cmd_check ;;
status) cmd_status ;;
logs) cmd_logs "$@" ;;
shell) cmd_shell "$@" ;;
remove | rm) cmd_remove ;;
list | ls) cmd_list ;;
publish) cmd_publish "$@" ;;
install) cmd_install "$@" ;;
update) cmd_update "$@" ;;
login) cmd_login "$@" ;;
logout) cmd_logout "$@" ;;
logins) cmd_logins ;;
help | -h | --help) usage ;;
*) usage >&2; exit 1 ;;
esac