Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Podman: the host-network warning, one folder per service, no install during an update, pinned images only
milind-sonia0f0fe572414
diff --git a/deploy/e2e/podman.sh b/deploy/e2e/podman.shindex ab9b3e0ace..3566e54710 100755--- a/deploy/e2e/podman.sh+++ b/deploy/e2e/podman.sh@@ -6,9 +6,14 @@# data. It also records whether the bots' sandbox (bubblewrap) can run in a rootless container, and with what.# The files the installer places (update.sh) come from this checkout.# ONLY ON A THROWAWAY HOST (a CI runner): it writes into this user's ~/.local/share/openmausbot and removes it at the-# end, and restarts this user's systemd. It refuses to start where a MausBot Podman install already exists.+# end, and restarts this user's systemd. It refuses to start where a MausBot Podman install already exists, and anywhere+# but a CI runner (GITHUB_ACTIONS or CI set to true): it runs sudo.# OUT=<evidence folder> bash deploy/e2e/podman.shset -euo pipefail+if [ "${GITHUB_ACTIONS:-}" != true ] && [ "${CI:-}" != true ]; then+ echo "This changes the host with sudo (linger, subordinate ids, a restart of this user's systemd): it runs only on a CI runner, where GITHUB_ACTIONS or CI is true." >&2+ exit 2+fiROOT=$(cd "$(dirname "$0")/../.." && pwd)OUT=${OUT:-$(mktemp -d)}mkdir -p "$OUT"@@ -110,6 +115,10 @@ cp "$UNIT" "$OUT/openmausbot.container"contains "$OUT/quadlet-dryrun.txt" "---openmausbot.service---" "quadlet did not make the service"systemctl --user is-active --quiet openmausbot || fail "the service is not active"healthy || fail "the server does not answer on 127.0.0.1:8799"+# The health check reads the port in the container when it runs (server.env's OMB_PORT): systemd made the unit's $$ one $.+health_test=$(podman inspect -f '{{json .Config.Healthcheck.Test}}' openmausbot)+# shellcheck disable=SC2016 # the literal text the check must hold+grep -qF '${OMB_PORT:-8799}/api/health' <<<"$health_test" || fail "the health check does not read OMB_PORT when it runs: $health_test"ss -ltnH >"$OUT/listening.txt"grep -q "127.0.0.1:8799 " "$OUT/listening.txt" || fail "nothing listens on 127.0.0.1:8799: $(cat "$OUT/listening.txt")"[ -z "$(new_outside)" ] || fail "the server listens beyond this machine without --lan: $(new_outside)"@@ -199,6 +208,9 @@ server=$(ss -ltnpH "( sport = :8799 )" | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | he[ -n "$server" ] || fail "no server process to pause"# Past the health check's start period first: failures inside it do not count.for _ in $(seq 1 60); do [ "$(podman inspect -f '{{.State.Health.Status}}' openmausbot)" = healthy ] && break; sleep 5; done+[ "$(podman inspect -f '{{.State.Health.Status}}' openmausbot)" = healthy ] ||+ fail "the health check never passed: $(podman inspect -f '{{json .State.Health}}' openmausbot 2>&1 | head -c 600)"+finding "health: the check ran in the container as $health_test, and passed"podman inspect -f '{{.State.Health.Status}} {{json .Config.Healthcheck}} {{.Config.HealthcheckOnFailureAction}}' openmausbot >"$OUT/health-before.txt" 2>&1 || truesystemctl --user list-timers --all --no-pager >"$OUT/timers.txt" 2>&1 || truekill -STOP "$server"diff --git a/deploy/podman/install.sh b/deploy/podman/install.shindex ba8ded3f05..eea1881df6 100755--- a/deploy/podman/install.sh+++ b/deploy/podman/install.sh@@ -11,6 +11,10 @@# Your data stays in ~/.local/share/openmausbot/data. Running it again repairs the install and never touches your data.# Updates, with a copy of the data first and a way back: ~/.local/share/openmausbot/update.sh#+# WARNING: the server shares this machine's network, with less isolation than the Docker install (docs/self-hosting.md,+# Podman). A port a bot or tool opens on 0.0.0.0 is open on every address of the machine; bots reach every service on+# its loopback; every local account counts as the owner. Use it on a machine only you sign in to, behind a firewall.+## Nothing runs until the last line calls main, so a download that is cut off part-way runs nothing. It sends no# telemetry. It contacts the image registry (ghcr.io), GitHub's release list and this repository's files.set -eu@@ -20,6 +24,7 @@ settings() {STABLE_URL=https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.jsonRELEASES_URL=https://api.github.com/repos/milind-soni/OpenMausBot/releases/latestREPOSITORY_FILES=https://raw.githubusercontent.com/milind-soni/OpenMausBot+ PINNED='^ghcr\.io/milind-soni/openmausbot@sha256:[0-9a-f]{64}$'# One copy of this repository's files to use instead (https://… or file:///…), as deploy/install.sh takes it.SOURCE_ASKED="${OMB_INSTALL_SOURCE:-}"INSTALL_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/openmausbot"@@ -27,6 +32,7 @@ settings() {NAME=openmausbotHEALTH_WAIT_S="${OMB_INSTALL_HEALTH_WAIT_S:-240}"MODE=install+ DIR_GIVEN=noLAN=""PORT=""PUBLIC_URL=""@@ -63,7 +69,10 @@ parse() {case "$1" in--port) PORT=$2 ;;--public-url) PUBLIC_URL=$2 ;;- --dir) INSTALL_DIR=$2 ;;+ --dir)+ INSTALL_DIR=$2+ DIR_GIVEN=yes+ ;;esacshift;;@@ -85,13 +94,57 @@ parse() {*) fail "--public-url takes the https:// address people open, like https://maus.example.com." ;;esaccase "$PUBLIC_URL" in *[!A-Za-z0-9:/._-]*) fail "--public-url takes a plain address, like https://maus.example.com." ;; esac+ UNIT="$UNIT_DIR/$NAME.container"+}++# The folder the service's unit already names, from an earlier run: its settings file, else its data volume.+installed_dir() {+ [ -f "$UNIT" ] || return 1+ from=$(sed -n 's|^EnvironmentFile=\(.*\)/server\.env$|\1|p' "$UNIT" | head -n 1)+ [ -n "$from" ] || from=$(sed -n 's|^Volume=\([^:]*\)/data:/data.*$|\1|p' "$UNIT" | head -n 1)+ [ -n "$from" ] || return 1+ printf '%s' "$from"+}++# One service per user, with one folder. A run without --dir keeps the folder the service already uses (it never moves+# the service onto an empty one); a --dir that names another is refused.+choose_dir() {+ INSTALL_DIR=$(printf '%s' "$INSTALL_DIR" | sed 's|//*$||')case "$INSTALL_DIR" in- /*) ;;- *) fail "--dir takes an absolute path." ;;+ /?*) ;;+ *) fail "--dir takes an absolute path of a folder, like /srv/openmausbot." ;;esac- case "$INSTALL_DIR" in *[!A-Za-z0-9/._-]*) fail "--dir takes a path of letters, digits, dots, dashes and slashes." ;; esac+ existing=$(installed_dir || true)+ if [ -n "$existing" ] && [ "$existing" != "$INSTALL_DIR" ]; then+ if [ "$DIR_GIVEN" = yes ]; then+ fail "This user's MausBot service already uses $existing, and --dir names $INSTALL_DIR. Nothing was changed. Run this again with --dir $existing, or without --dir. To move it: --uninstall first, move the folder, then install with --dir and the new place."+ fi+ INSTALL_DIR=$existing+ note "The service already uses $INSTALL_DIR, so this run does too (--dir names it)."+ fi+ # Written into the unit, where these are plain text: letters, digits, dots, dashes, underscores, @ and slashes.+ case "$INSTALL_DIR" in *[!A-Za-z0-9/._@-]*) fail "The folder $INSTALL_DIR has characters this installer does not write into a service's unit. Name another with --dir PATH (letters, digits, dots, dashes, underscores, @ and slashes)." ;; esacDATA_DIR="$INSTALL_DIR/data"- UNIT="$UNIT_DIR/$NAME.container"+}++# A folder of the Docker install (deploy/install.sh) or of a Compose checkout: its data and .env are not this service's.+refuse_docker_dir() {+ if [ -f "$INSTALL_DIR/compose.yaml" ] || [ -f "$INSTALL_DIR/docker-compose.yml" ]; then+ fail "$INSTALL_DIR holds a Docker install (compose.yaml or docker-compose.yml). Nothing was changed. The Podman service needs a folder of its own: name another with --dir PATH."+ fi+}++# deploy/update.sh at work in this folder: its lock (a folder holding its process id), or the journal of an update it has+# not finished. The installer then changes nothing: both rewrite .env and the unit's Image=.+update_busy() {+ pid=$(cat "$INSTALL_DIR/.update/lock/pid" 2>/dev/null || true)+ case "$pid" in+ "" | *[!0-9]*) ;;+ *) if kill -0 "$pid" 2>/dev/null; then fail "An update is running here (process $pid). Nothing was changed. Wait for $INSTALL_DIR/update.sh to finish, then run this again."; fi ;;+ esac+ if [ -f "$INSTALL_DIR/.update/journal" ]; then+ fail "An update here did not finish ($INSTALL_DIR/.update/journal). Nothing was changed. Run $INSTALL_DIR/update.sh first: it finishes or undoes that update. Then run this again."+ fi}# The user's own systemd: `systemctl --user` must reach it, which a login session or linger gives.@@ -104,7 +157,7 @@ user_systemd() {}quadlet_binary() {- for candidate in /usr/libexec/podman/quadlet /usr/lib/podman/quadlet /usr/local/libexec/podman/quadlet; do+ for candidate in ${OMB_INSTALL_QUADLET:-} /usr/libexec/podman/quadlet /usr/lib/podman/quadlet /usr/local/libexec/podman/quadlet; doif [ -x "$candidate" ]; thenprintf '%s' "$candidate"return 0@@ -128,7 +181,7 @@ check_host() {*[!0-9.]* | .*) fail "Could not tell which Podman this is (podman version said: ${version:-nothing})." ;;esacif [ "$major" -lt 4 ] || { [ "$major" -eq 4 ] && [ "$minor" -lt 9 ]; }; then- fail "This needs Podman 4.9 or newer, for its systemd units; this machine has $version. Ubuntu 24.04, Debian 13, Fedora 40 and RHEL 9.4 or newer have it."+ fail "This needs Podman 4.9 or newer, for its systemd units; this machine has $version. Ubuntu 24.04 has it (the one this has been tried on)."fiok "Podman $version"[ "$(podman info --format '{{.Host.Security.Rootless}}' 2>/dev/null || true)" = true ] ||@@ -170,39 +223,83 @@ unset_env() { # file nameif grep -q "^$2=" "$1" 2>/dev/null; then { grep -v "^$2=" "$1" || true; } | write_file "$1" 600; fi}-# The image by digest: the one update.sh pinned, else the stable channel's, else the newest release's.+# The image by digest: the one update.sh pinned, else the stable channel's, else the newest release's (only while no+# version is stable: the channel answers 404). As update.sh decides it, and never a tag that moves (`latest`).choose_image() {asked="${OMB_INSTALL_IMAGE:-}"pinned=$(env_value "$INSTALL_DIR/.env" OMB_IMAGE)if [ -n "$asked" ]; thencase "$asked" in *[!A-Za-z0-9/:._@-]*) fail "OMB_INSTALL_IMAGE is not an image name." ;; esac+ case "${asked##*/}" in+ *@sha256:*) ;;+ *:latest) fail "OMB_INSTALL_IMAGE names the latest tag, which follows every commit. Name a release, like $IMAGE_REPO:v0.1.151." ;;+ *:?*) ;;+ *) fail "OMB_INSTALL_IMAGE needs a release tag, like $IMAGE_REPO:v0.1.151." ;;+ esacIMAGE=$askedok "version: $IMAGE, as asked"elif [ -n "$pinned" ]; then+ case "$pinned" in *[!A-Za-z0-9/:._@-]*) fail "OMB_IMAGE in $INSTALL_DIR/.env is not an image name." ;; esacIMAGE=$pinned- ok "version: the one already installed ($IMAGE); update.sh changes it"- else- stable=$(curl -fsS --max-time 20 "$STABLE_URL" 2>/dev/null || true)- IMAGE=$(printf '%s' "$stable" | sed -n 's/.*"image": *"\([^"]*\)".*/\1/p' | head -n 1)case "$IMAGE" in- "$IMAGE_REPO"@sha256:*) ok "version: the stable channel" ;;+ *@sha256:*) ;;*)- release=$(curl -fsS --max-time 20 "$RELEASES_URL" 2>/dev/null | sed -n 's/.*"tag_name": *"\(v[0-9][0-9.]*\)".*/\1/p' | head -n 1)- [ -n "$release" ] || fail "The newest MausBot release could not be read from api.github.com. Check this machine's outbound HTTPS, then run this again."- IMAGE="$IMAGE_REPO:$release"- ok "version: $release, the newest release"+ # update.sh's rollback can name the image that ran before by a name of this machine's own+ # (openmausbot-before-update:local), which no registry has: never pulled, pinned by the digest it came with.+ if podman image exists "$IMAGE" 2>/dev/null; then+ digest=$(podman image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE" 2>/dev/null | grep -E "^${IMAGE_REPO}@sha256:[0-9a-f]{64}$" | head -n 1 || true)+ if [ -z "$digest" ]; then+ ok "version: the one already installed ($IMAGE, an image of this machine's own, not pinned by a digest); update.sh changes it"+ return 0+ fi+ IMAGE=$digest+ fi;;esac+ ok "version: the one already installed ($IMAGE); update.sh changes it"+ else+ stable_imagefisay "Downloading MausBot (the first time is about a gigabyte)..."podman pull -q "$IMAGE" >/dev/null || fail "MausBot could not be downloaded ($IMAGE; Podman's message is above). Check this machine's outbound HTTPS, then run this again."# A tag moves; the digest does not, so a restart never brings a different version than update.sh chose.case "$IMAGE" in*@sha256:*) ;;- "$IMAGE_REPO":*)- digest=$(podman image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE" 2>/dev/null | grep "^$IMAGE_REPO@sha256:" | head -n 1 || true)- [ -z "$digest" ] || IMAGE=$digest+ *)+ repo=${IMAGE%:*}+ digest=""+ for ref in $(podman image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE" 2>/dev/null || true); do+ case "$ref" in "$repo"@sha256:* | */"$repo"@sha256:*)+ digest=$ref+ break+ ;;+ esac+ done+ [ -n "$digest" ] || fail "MausBot $IMAGE was downloaded, but Podman did not say its digest, so it cannot be pinned (a tag moves, a digest does not). Nothing was changed. Run this again, or name the image by its digest: OMB_INSTALL_IMAGE=$repo@sha256:..."+ IMAGE=$digest+ ;;+ esac+}++# The stable channel's image; the newest release only while the channel does not exist yet (404). Any other answer, or+# one that names no image pinned by digest, stops here, as deploy/update.sh does.+stable_image() {+ body=$(mktemp)+ code=$(curl -sS --max-time 20 -o "$body" -w '%{http_code}' "$STABLE_URL" 2>/dev/null || true)+ IMAGE=$(sed -n 's/.*"image": *"\([^"]*\)".*/\1/p' "$body" 2>/dev/null | head -n 1)+ rm -f "$body"+ case "$code" in+ 200)+ printf '%s' "$IMAGE" | grep -Eq "$PINNED" || fail "The stable channel ($STABLE_URL) names no image this installer accepts. Nothing was changed. Run this again later, or name a version: OMB_INSTALL_IMAGE=$IMAGE_REPO:v0.1.151"+ ok "version: the stable channel"+ ;;+ 404)+ release=$(curl -fsS --max-time 20 "$RELEASES_URL" 2>/dev/null | sed -n 's/.*"tag_name": *"\(v[0-9][0-9.]*\)".*/\1/p' | head -n 1)+ [ -n "$release" ] || fail "The newest MausBot release could not be read from api.github.com. Check this machine's outbound HTTPS, then run this again."+ IMAGE="$IMAGE_REPO:$release"+ ok "version: $release, the newest release (no version is stable yet)";;+ *) fail "The stable channel could not be read ($STABLE_URL answered ${code:-nothing}). Nothing was changed. Check this machine's outbound HTTPS, then run this again." ;;esac}@@ -219,6 +316,7 @@ image_user() {selinux_on() { command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled; }write_settings() {+ update_busySETTINGS_BEFORE=$(cat "$INSTALL_DIR/server.env" 2>/dev/null || true)mkdir -p "$INSTALL_DIR" "$UNIT_DIR"chmod 700 "$INSTALL_DIR"@@ -253,6 +351,15 @@ ENVprintf '%s\n' "$UNIT" | write_file "$INSTALL_DIR/podman.unit" 600}+# The install's folder as the app shows it in its update command: ~ for this user's home.+shown_dir() {+ # shellcheck disable=SC2088 # a ~ to show, never to expand+ case "$INSTALL_DIR" in+ "$HOME"/*) printf '~/%s' "${INSTALL_DIR#"$HOME"/}" ;;+ *) printf '%s' "$INSTALL_DIR" ;;+ esac+}+unit_text() {label=""if selinux_on; then label=":Z"; fi@@ -267,16 +374,24 @@ Documentation=https://github.com/milind-soni/OpenMausBot/blob/main/docs/self-hosContainerName=$NAMEImage=$IMAGE# The host's network, as a server started with npx has it: it listens on 127.0.0.1 (OMB_LAN=1: private addresses too),-# a program on this machine counts as its owner, and every other device pairs. No port is forwarded into a container.+# and every other device pairs. No port is forwarded into a container.+# WARNING: this isolates less than the Docker install. Any port a bot or a tool opens on 0.0.0.0 is open on every+# address of this machine, a VPS's public one too, whatever --local says; bots run unboxed beside the data folder that+# holds the engines' logins. Bots reach every service on this machine's loopback (databases, other programs' admin+# ports). Every local account and program counts as the owner on the server's port, and can attach to Chrome's+# debugging port. Use it on a machine only you sign in to, behind a host firewall.Network=host# The image's user is this user on the host, so the data folder stays yours.UserNS=keep-id:uid=$RUN_UID,gid=$RUN_GIDVolume=$DATA_DIR:/data$labelEnvironmentFile=$INSTALL_DIR/server.env+# How the app knows this install, for the update command it shows: $(shown_dir)/update.sh+Environment=OMB_PODMAN_SERVICE=$(shown_dir)# Chrome's shared memory, as the Docker install gives it. The image brings its own init (tini).ShmSize=512m-# curl's own limit: Podman 4.9 does not end a check that hangs on a server that accepts and never answers.-HealthCmd=curl -sf --max-time 4 http://127.0.0.1:$SERVER_PORT/api/health | grep -q openmausbot+# curl's own limit: Podman 4.9 does not end a check that hangs on a server that accepts and never answers. The port is+# read in the container when the check runs (server.env's OMB_PORT); systemd turns the doubled dollar into one.+HealthCmd=curl -sf --max-time 4 http://127.0.0.1:\$\${OMB_PORT:-8799}/api/health | grep -q openmausbotHealthInterval=30sHealthTimeout=5sHealthRetries=3@@ -296,17 +411,24 @@ WantedBy=default.targetUNIT}+# The unit as it will be written, read by Podman's generator in a folder of its own first: a key this Podman does not+# know would otherwise leave only "unit not found", and the unit in use stays as it was.+check_unit() {+ check_dir=$(mktemp -d)+ unit_text >"$check_dir/$NAME.container"+ check=$(QUADLET_UNIT_DIRS="$check_dir" "$QUADLET" -dryrun -user 2>&1 || true)+ rm -rf "$check_dir"+ case "$check" in+ *"---$NAME.service---"*) ;;+ *) fail "Podman could not read the unit this would write, so nothing was changed: $(printf '%s' "$check" | grep -i "$NAME\|error" | head -n 3)" ;;+ esac+}+write_unit() {CHANGED=no# A changed unit, or changed settings (--lan, --port), take a restart; a run that changes nothing restarts nothing.if [ ! -f "$UNIT" ] || [ "$(unit_text)" != "$(cat "$UNIT")" ] || [ "$SETTINGS_BEFORE" != "$(cat "$INSTALL_DIR/server.env")" ]; then CHANGED=yes; fiunit_text | write_file "$UNIT"- # A key this Podman does not know would otherwise leave only "unit not found".- check=$(QUADLET_UNIT_DIRS="$UNIT_DIR" "$QUADLET" -dryrun -user 2>&1 || true)- case "$check" in- *"---$NAME.service---"*) ;;- *) fail "Podman could not read the unit it was given ($UNIT): $(printf '%s' "$check" | grep -i "$NAME\|error" | head -n 3)" ;;- esacsystemctl --user daemon-reload}@@ -341,6 +463,7 @@ wait_healthy() {port_taken() { ss -ltnH "( sport = :$1 )" 2>/dev/null | grep -q .; }start_service() {+ update_busyif ! systemctl --user is-active --quiet "$NAME" && port_taken "$SERVER_PORT"; thenfail "Something else on this machine already listens on port $SERVER_PORT (another MausBot server?). Stop it, or run this again with --port and a free port, like --port 8811."fi@@ -355,13 +478,18 @@ start_service() {finish() {say ""say "MausBot is running as your user's service ($NAME), on http://127.0.0.1:$SERVER_PORT."- if [ "$(env_value "$INSTALL_DIR/server.env" OMB_LAN)" = 1 ]; then say "Other devices on this network can pair over plain http; nothing on the open internet can reach it."; fi+ if [ "$(env_value "$INSTALL_DIR/server.env" OMB_LAN)" = 1 ]; then say "Its port $SERVER_PORT also answers other devices on this network, from private addresses only, over plain http; each device pairs."; fisay ""say " Pair a device podman exec -it $NAME openmausbot pair"say " Log journalctl --user -u $NAME -f"say " Update $INSTALL_DIR/update.sh"say " Data $DATA_DIR"say ""+ say "Warning: it shares this machine's network, which isolates less than the Docker install. Any port a bot or a tool"+ say "opens on 0.0.0.0 is open on every address of this machine, a public one too, whatever --local says. Bots reach every"+ say "service on this machine's loopback, and every account on it counts as the owner. Use it on a machine only you sign"+ say "in to, behind a host firewall: https://github.com/milind-soni/OpenMausBot/blob/main/docs/self-hosting.md#podman-rootless-as-a-service"+ say ""if linger_on; thensay "It starts at boot, without anyone logged in."else@@ -373,9 +501,12 @@ finish() {}run_install() {+ refuse_docker_dir+ update_busycheck_hostchoose_imageimage_user+ check_unitwrite_settingswrite_unitplace_update@@ -384,6 +515,7 @@ run_install() {}run_uninstall() {+ update_busyuser_systemd || fail "systemd for your user is not reachable (systemctl --user). Log in to this machine directly or over SSH, then run this again."systemctl --user stop "$NAME" 2>/dev/null || truerm -f "$UNIT"@@ -399,6 +531,7 @@ run_uninstall() {main() {settingsparse "$@"+ choose_dircase "$MODE" ininstall) run_install ;;uninstall) run_uninstall ;;diff --git a/deploy/update.sh b/deploy/update.shindex e72985c0fe..fc66361a73 100755--- a/deploy/update.sh+++ b/deploy/update.sh@@ -80,6 +80,8 @@ unset OMB_IMAGE# unit that podman.unit names. The steps are the same, through Podman and `systemctl --user` (podman_compose below).UNIT=""STORE=Docker+# The commands this script names when a person has to step in.+STOP_HINT="docker compose stop" START_HINT="docker compose up -d" LOGS_HINT="docker compose logs $SERVICE"if [ -f podman.unit ]; thenUNIT=$(head -n 1 podman.unit)STORE=Podman@@ -118,6 +120,7 @@ image_version() { docker image inspect -f '{{index .Config.Labels "org.opencontaif [ -n "$UNIT" ]; then# The unit's name is its container's: openmausbot.container runs openmausbot.service, container openmausbot.SERVER_UNIT=$(basename "$UNIT" .container)+ STOP_HINT="systemctl --user stop $SERVER_UNIT" START_HINT="systemctl --user start $SERVER_UNIT" LOGS_HINT="journalctl --user -u $SERVER_UNIT"# Podman takes the same commands as Docker here. The helpers mount the data folder, which SELinux labels for the# server's container alone, so they run without a label of their own.docker() { if [ "$1" = run ]; then shift; podman run --security-opt label=disable "$@"; else podman "$@"; fi; }@@ -609,7 +612,7 @@ roll_back() { # why, exit code when the old version is backsay "$why"say "Putting back the version and the data from before the update…"if ! stop_server; then- say "The server could not be stopped (see $LOG), so its data was left as it is. The update's journal is kept: run ./update.sh --rollback again once docker compose stop works."+ say "The server could not be stopped (see $LOG), so its data was left as it is. The update's journal is kept: run ./update.sh --rollback again once $STOP_HINT works."exit 2fiif ! docker volume inspect "$J_backup" >/dev/null 2>&1; then@@ -623,7 +626,7 @@ roll_back() { # why, exit code when the old version is back# The settings go back with the data, never before it: an old version is not started on data a newer one left.if ! put_back "$J_backup" "$J_data" "$helper_image" >>"$LOG" 2>&1; thensay "The data could not be put back from the $STORE volume $J_backup (see $LOG). Neither was changed: the data is as $(new_name) left it, and the volume still holds the copy. The server is stopped."- say "Once the cause is fixed (often disk space), ./update.sh --rollback tries again. To run the server on the data as it is instead: docker compose up -d (that starts $(new_name) again)."+ say "Once the cause is fixed (often disk space), ./update.sh --rollback tries again. To run the server on the data as it is instead: $START_HINT (that starts $(new_name) again)."exit 2firestore_env@@ -637,7 +640,7 @@ roll_back() { # why, exit code when the old version is backif wait_healthy "$J_previous_id"; then back=yes; firm -f "$JOURNAL" "$LAST"if [ "$back" = no ]; then- say "$(old_name) and its data are back, but it did not become healthy either ($WHY). See: docker compose logs $SERVICE"+ say "$(old_name) and its data are back, but it did not become healthy either ($WHY). See: $LOGS_HINT"exit 2fisay "Your server runs $(old_name) again, with its data as it was before the update."@@ -788,6 +791,9 @@ if [ -n "$UNIT" ]; thencommand -v podman >/dev/null 2>&1 || refuse "This needs Podman (podman version)."systemctl --user show-environment >/dev/null 2>&1 || refuse "systemd for your user is not reachable (systemctl --user). Log in to this machine directly or over SSH, then run this again."[ -f "$UNIT" ] || refuse "The service's unit $UNIT is gone. Run the Podman installer again, then this."+ if [ "$(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null || true)" = no ]; then+ say "Note: your user may not run services while logged out (linger is off), so the server stops when you log out and does not start at boot. Once, as an administrator: sudo loginctl enable-linger $(id -un)"+ fielsedocker compose version >/dev/null 2>&1 || refuse "This needs Docker with the Compose plugin (docker compose version)."[ -f docker-compose.yml ] || [ -f compose.yaml ] || [ -n "${COMPOSE_FILE:-}" ] || refuse "There is no docker-compose.yml or compose.yaml in $DIR. Name the install's folder: ./update.sh --dir PATH"diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 064089ce85..13d4acf749 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -163,9 +163,23 @@ npx openmausbot pair### Podman (rootless, as a service)-On Linux with Podman 4.9 or newer (Ubuntu 24.04, Debian 13, Fedora 40,-RHEL 9.4 and later), one command run as your own user, without `sudo`, installs the-published server image as your user's systemd service:+> **Warning: this install isolates less than the Docker install.** The+> server shares the machine's network (Podman's host network), so:+>+> - Any port a bot or a tool opens on `0.0.0.0` is open on every interface+> of the machine, including a VPS's public IP, whatever `--local` says.+> Bots run unboxed, beside the data folder that holds the engines' logins.+> - Bots can reach every loopback service on the machine: databases, other+> apps' admin ports.+> - Every local account and process on the machine counts as the owner on+> the server's port, and can attach to Chrome's debugging port.+>+> Use it on a machine only you sign in to, and put a host firewall in front+> (`ufw`, `firewalld`) that lets in only what you mean to serve.++It needs Linux and Podman 4.9 or newer. One command run as your own user,+without `sudo`, installs the published server image as your user's systemd+service:```shcurl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/podman/install.sh | sh@@ -185,18 +199,25 @@ sudo loginctl enable-linger "$USER"The server uses the host's network, as `npx openmausbot serve` does. Itlistens on `127.0.0.1:8799` only, and a program on this machine counts as itsowner ([Loopback trust](#loopback-trust-owner-or-service)). Nothing is-forwarded into a container. Options, given after `sh -s --`:+forwarded into a container. `--local` and `--lan` decide only which+addresses the server's own port answers; they do not limit other ports (see+the warning above). Options, given after `sh -s --`:| Option | Does ||---|---|-| `--lan` | Also answers other devices on this network, over plain http, and only from private addresses. Each device pairs. |+| `--lan` | The server's port also answers other devices on this network, over plain http, and only from private addresses. Each device pairs. || `--local` | Back to this machine only (the default). || `--port N` | Another port, when 8799 is taken (webhooks use the next one). || `--public-url URL` | The HTTPS address a tunnel or proxy in front of it serves, for pairing links. |+| `--dir PATH` | Another folder for the data and settings (not a Docker install's folder). || `--uninstall` | Stops and removes the service. Keeps the data. |Running the command again repairs the install and keeps the version, the-data and your settings. It restarts the server only when something changed.+folder, the data and your settings. It restarts the server only when+something changed. Without `--dir` it keeps the folder the service already+uses; a `--dir` that names another folder is refused. It also refuses while+`update.sh` is running, or after an update that did not finish: run+`update.sh` first.| | Where ||---|---|@@ -214,6 +235,10 @@ the server answers and can still start bots. If it cannot, the old image andthe copy of the data go back. `update.sh --rollback` goes back after an updatethat worked. Run it as your user, without `sudo`. The app's **Update server**button does not run it on this install yet: run `update.sh` yourself.+When a rollback cannot find the old version by its digest, it names the+copy it kept on this machine, `openmausbot-before-update:local`, in the+unit and in `.env`. Running the installer again keeps that image (it is+never downloaded) until the next `update.sh`.**Uninstall.** Run the same command with `--uninstall`. The data stays.Some of its files can belong to the container's other user ids, so remove@@ -241,8 +266,9 @@ copy of the data the last update kept is a Podman volume:the full stack with them.Tested on Ubuntu 24.04 (x86-64, Podman 4.9.3), with-`kernel.apparmor_restrict_unprivileged_userns=1`. SELinux hosts (Fedora,-RHEL), Podman 5 and ARM64 have not been tried yet.+`kernel.apparmor_restrict_unprivileged_userns=1`, and nowhere else yet.+Other distributions with Podman 4.9 or newer (RHEL 9.4, or Podman 5 on+Debian 13 and Fedora), SELinux hosts and ARM64 have not been tried.## Troubleshootingdiff --git a/electron/server-status.d.mts b/electron/server-status.d.mtsindex 67f13156df..71a23f9793 100644--- a/electron/server-status.d.mts+++ b/electron/server-status.d.mts@@ -1,7 +1,7 @@export declare const RECONNECT: Readonly<{ baseMs: number; capMs: number; healthyMs: number; cantReachAfterMs: number; timeoutMs: number; refocusMs: number }>;/** How a server saved by hand was installed, as its descriptor says, so the update command fits it. */-export type ServerInstall = "npx" | "global" | "docker" | "source";+export type ServerInstall = "npx" | "global" | "docker" | "source" | "podman-service";/** checking: the first look; connected; reconnecting / cantReach: a passing problem (cantReach after two minutes);* signedOut: it needs a new pairing code; insecure: a public http address, never contacted. */export type ServerState = "checking" | "connected" | "reconnecting" | "cantReach" | "signedOut" | "insecure";diff --git a/electron/server-status.mjs b/electron/server-status.mjsindex 9f4daef3c3..2fd0e3e71d 100644--- a/electron/server-status.mjs+++ b/electron/server-status.mjs@@ -3,7 +3,7 @@import { allowedServerOrigin } from "./server-address.mjs";export const RECONNECT = Object.freeze({ baseMs: 2_000, capMs: 300_000, healthyMs: 60_000, cantReachAfterMs: 120_000, timeoutMs: 15_000, refocusMs: 5_000 });-const INSTALLS = new Set(["npx", "global", "docker", "source"]);+const INSTALLS = new Set(["npx", "global", "docker", "source", "podman-service"]);/** Equal jitter: half of the doubled wait for sure, the other half at random, never past the cap. */export function reconnectDelay(attempt, random = Math.random, { baseMs, capMs } = RECONNECT) {diff --git a/packages/phone-protocol/src/environment.ts b/packages/phone-protocol/src/environment.tsindex ba6fc8115a..00d70bff14 100644--- a/packages/phone-protocol/src/environment.ts+++ b/packages/phone-protocol/src/environment.ts@@ -2,7 +2,7 @@export type ServerPlatform = "aix" | "android" | "cygwin" | "darwin" | "freebsd" | "haiku" | "linux" | "netbsd" | "openbsd" | "sunos" | "win32";/** How an operator's server was installed. */-export type ServerInstall = "npx" | "global" | "docker" | "source";+export type ServerInstall = "npx" | "global" | "docker" | "source" | "podman-service";/** GET /.well-known/openmausbot/environment, served without auth, and the `environment` of a POST /api/auth/pair answer:* a saved connection checks it still reaches the same server. */diff --git a/scripts/testing/deploy-update-podman.test.ts b/scripts/testing/deploy-update-podman.test.tsindex e1414104b5..4d10a21284 100644--- a/scripts/testing/deploy-update-podman.test.ts+++ b/scripts/testing/deploy-update-podman.test.ts@@ -34,8 +34,9 @@ function tree(dir: string, prefix = ""): Record<string, string> {const unitText = (image: string) => `[Container]\nContainerName=openmausbot\nImage=${image}\nNetwork=host\n\n[Service]\nRestart=on-failure\n`;-/** A Podman install on 0.1.150, its unit and settings as the installer writes them, and a stable channel naming `target`. */-function install(target: Record<string, unknown> = {}) {+/** A Podman install on 0.1.150, its unit and settings as the installer writes them, and a stable channel naming `target`.+ * `extra`: the fake's own switches (failRestore); `old`: what the running version does when it is started again. */+function install(target: Record<string, unknown> = {}, extra: Record<string, unknown> = {}, old: Record<string, unknown> = {}) {const root = mkdtempSync(join(tmpdir(), "omb-update-podman-"));dirs.push(root);const home = join(root, "share", "openmausbot");@@ -73,14 +74,17 @@ function install(target: Record<string, unknown> = {}) {"shift",'case "$1" in'," show-environment | daemon-reload) exit 0 ;;",- ` stop) exec ${node} "${FAKE}" compose stop ;;`,+ // stop-fails-on-new: the new version, once started, cannot be stopped (a rollback's stop fails).+ ` stop) if [ -f "$FAKE_DOCKER_DIR/stop-fails-on-new" ] && grep -qx "Image=${NEW.refs[0]}" "${unit}"; then echo "Failed to stop openmausbot.service" >&2; exit 1; fi; exec ${node} "${FAKE}" compose stop ;;`,` restart) OMB_IMAGE=$(sed -n 's/^Image=//p' "${unit}") exec ${node} "${FAKE}" compose up -d ;;`,"esac","exit 64",].join("\n"));shim("journalctl", `exec ${node} "${FAKE}" compose logs`);+ // Linger on, as on a server; FAKE_LINGER=no for a user whose services stop at logout.+ shim("loginctl", '[ "$1" = show-user ] && echo "${FAKE_LINGER:-yes}"');writeFileSync(join(fake, "state.json"), JSON.stringify({- serial: 1, composeReadsPin: true, defaultImage: OLD.refs[1], dataVolume: "deploy_data", images: [OLD, { ...NEW, ...target }],+ ...extra, serial: 1, composeReadsPin: true, defaultImage: OLD.refs[1], dataVolume: "deploy_data", images: [{ ...OLD, ...old }, { ...NEW, ...target }],containers: { omb: { id: "omb-1", image: OLD.id, status: "running", restarts: 0 } },}));writeFileSync(join(root, "stable.json"), JSON.stringify({ channel: "stable", version: "0.1.151", image: NEW.refs[0], history: [] }));@@ -98,7 +102,7 @@ function install(target: Record<string, unknown> = {}) {const log = (name: string) => (existsSync(join(fake, `${name}.log`)) ? readFileSync(join(fake, `${name}.log`), "utf8").trim().split("\n") : []);const copies = () => readdirSync(join(fake, "volumes")).filter((name) => name.includes("-before-update-")).sort();return {- data, run, log, copies,+ data, run, log, copies, fake,state: () => JSON.parse(readFileSync(join(fake, "state.json"), "utf8")),env: () => readFileSync(join(home, ".env"), "utf8"),unit: () => readFileSync(unit, "utf8"),@@ -149,6 +153,36 @@ describe.skipIf(!posix)("deploy/update.sh on a Podman install", () => {expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });});+ it("names systemctl and journalctl, never docker compose, when a person has to step in", () => {+ // The data cannot be put back: the way to run the server on the data as it is.+ const restore = install({ behaviour: "silent" }, { failRestore: true });+ const failed = restore.run([], { OMB_UPDATE_WAIT_S: "2" });+ expect(failed.status).toBe(2);+ expect(failed.stdout).toContain("To run the server on the data as it is instead: systemctl --user start openmausbot (that starts 0.1.151 again).");+ expect(failed.stdout).not.toContain("docker compose");++ // The old version is back but does not become healthy either: its log.+ const unhealthy = install({ behaviour: "silent" }, {}, { behaviour: "crashes", lastWords: "the old one fails too" });+ const back = unhealthy.run([], { OMB_UPDATE_WAIT_S: "2" });+ expect(back.status).toBe(2);+ expect(back.said.at(-1)).toBe("0.1.150 and its data are back, but it did not become healthy either (it kept stopping as it started (the old one fails too)). See: journalctl --user -u openmausbot");++ // The new version cannot be stopped to roll back: the command to stop it.+ const stuck = install({ behaviour: "silent" });+ writeFileSync(join(stuck.fake, "stop-fails-on-new"), "");+ const kept = stuck.run([], { OMB_UPDATE_WAIT_S: "2" });+ expect(kept.status).toBe(2);+ expect(kept.said.at(-1)).toContain("run ./update.sh --rollback again once systemctl --user stop openmausbot works.");+ });++ it("says when the user's services stop at logout (linger off), and goes on", () => {+ const box = install();+ const done = box.run([], { FAKE_LINGER: "no" });+ expect(done.status, done.stdout + done.stderr).toBe(0);+ expect(done.said[0]).toBe("Note: your user may not run services while logged out (linger is off), so the server stops when you log out and does not start at boot. Once, as an administrator: sudo loginctl enable-linger " + spawnSync("id", ["-un"], { encoding: "utf8" }).stdout.trim());+ expect(done.said.at(-2)).toMatch(/^The data from before the update is kept in the Podman volume /);+ });+it("refuses to run as root, whose Podman is not this install's", () => {if (process.getuid?.() !== 0) {const box = install();diff --git a/scripts/testing/podman-installer.test.ts b/scripts/testing/podman-installer.test.tsnew file mode 100644index 0000000000..a136129140--- /dev/null+++ b/scripts/testing/podman-installer.test.ts@@ -0,0 +1,328 @@+// deploy/podman/install.sh with stand-ins for Podman, its generator (quadlet), the user's systemd, loginctl and curl: which+// image it pins, which folder it keeps, what it refuses, and the unit it writes. The real thing runs in+// deploy/e2e/podman.sh on a CI runner.+import { spawnSync } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++const SCRIPT = join(import.meta.dirname, "..", "..", "deploy", "podman", "install.sh");+const REPO = "ghcr.io/milind-soni/openmausbot";+const DIGEST = `${REPO}@sha256:${"2".repeat(64)}`;+const STABLE = `${REPO}@sha256:${"5".repeat(64)}`;+const posix = process.platform !== "win32";+// The shell the one-line install runs in on Debian and Ubuntu.+const SHELL = existsSync("/bin/dash") ? "/bin/dash" : "/bin/sh";+const REAL_TOOLS = ["sed", "grep", "cat", "head", "tail", "mktemp", "chmod", "mv", "rm", "mkdir", "cut", "sh", "cp", "tr"];++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/** Each stand-in logs its call to $FAKE/<name>.log and answers from FAKE_ settings and files in $FAKE. */+const STUBS: Record<string, string> = {+ uname: "echo Linux",+ id: 'case "$1" in -u) echo 1000 ;; -un) echo maus-tester ;; *) echo 1000 ;; esac',+ sleep: ":",+ ss: ":",+ loginctl: 'echo "${FAKE_LINGER:-yes}"',+ // version, rootless, pull, the image's digests and label, which images this machine has, and the image's user.+ podman: `case "$1 $2" in+ "version --format"*) echo 4.9.3 ;;+ "info --format"*) echo true ;;+ "pull -q") [ -z "\${FAKE_PULL_FAILS:-}" ] || { echo "Error: pull failed" >&2; exit 125; }; echo "$3" >>"$FAKE/pulled" ;;+ "image exists") grep -qx "$3" "$FAKE/local" 2>/dev/null ;;+ "image inspect")+ case "$4" in *RepoDigests*) printf '%s' "\${FAKE_DIGESTS-${DIGEST}}" | tr ' ' '\\n'; echo ;; *) echo v0.1.151 ;; esac ;;+ "run --rm") echo 1000 ;;+ *) echo "podman stand-in: $*" >&2; exit 64 ;;+esac`,+ // Podman's generator: what it was given, and the service it makes of it.+ quadlet: `cp "$QUADLET_UNIT_DIRS/openmausbot.container" "$FAKE/dryrun.container"; echo "$QUADLET_UNIT_DIRS" >"$FAKE/dryrun.dir"+[ -z "\${FAKE_QUADLET_FAILS:-}" ] || { echo "quadlet-generator[1]: converting \\"openmausbot.container\\": unsupported key 'HealthOnFailure'"; exit 0; }+echo "---openmausbot.service---"`,+ systemctl: `[ "$1" = --user ] || exit 64+case "$2" in+ show-environment | daemon-reload) ;;+ is-active) [ -f "$FAKE/active" ] ;;+ restart | start) : >"$FAKE/active" ;;+ stop) rm -f "$FAKE/active" ;;+ *) exit 64 ;;+esac`,+ // The stable channel (FAKE_STABLE_CODE, FAKE_STABLE_BODY), GitHub's newest release, update.sh's file, the health check.+ curl: `out=""; prev=""+for arg; do [ "$prev" = -o ] && out=$arg; prev=$arg; done+case "$*" in+ *channels/stable.json*) [ "\${FAKE_STABLE_CODE:-404}" = 000 ] && { printf 000; exit 7; }; printf '%s' "\${FAKE_STABLE_BODY:-}" >"$out"; printf '%s' "\${FAKE_STABLE_CODE:-404}" ;;+ *releases/latest*) printf '{"tag_name": "v0.1.151"}' ;;+ */deploy/update.sh*) echo "# the updater; it reads podman.unit" >"$out" ;;+ */api/health*) [ -f "$FAKE/active" ] && echo '{"app":"openmausbot"}' ;;+ *) exit 22 ;;+esac`,+};++function machine(options: { home?: string } = {}) {+ const root = mkdtempSync(join(tmpdir(), "omb-podman-install-"));+ dirs.push(root);+ const bin = join(root, "bin");+ const fake = join(root, "fake");+ const home = join(root, options.home ?? "home");+ for (const dir of [bin, fake, home]) mkdirSync(dir, { recursive: true });+ for (const name of REAL_TOOLS) {+ const found = ["/usr/bin", "/bin"].map((folder) => join(folder, name)).find((path) => existsSync(path));+ if (found) symlinkSync(found, join(bin, name));+ }+ for (const [name, body] of Object.entries(STUBS)) {+ writeFileSync(join(bin, name), `#!/bin/sh\necho "$*" >>"$FAKE/${name}.log"\n${body}\n`);+ chmodSync(join(bin, name), 0o755);+ }+ const dir = join(home, ".local", "share", "openmausbot");+ const unitPath = join(home, ".config", "containers", "systemd", "openmausbot.container");+ const run = (args: string[] = [], env: Record<string, string> = {}) => {+ const result = spawnSync(SHELL, [SCRIPT, ...args], {+ encoding: "utf8", timeout: 30_000,+ env: { PATH: bin, HOME: home, XDG_RUNTIME_DIR: root, FAKE: fake, OMB_INSTALL_QUADLET: join(bin, "quadlet"), OMB_INSTALL_HEALTH_WAIT_S: "6", ...env },+ });+ return { ...result, out: result.stdout + result.stderr };+ };+ const read = (path: string) => (existsSync(path) ? readFileSync(path, "utf8") : null);+ const log = (name: string) => (read(join(fake, `${name}.log`)) ?? "").trim().split("\n").filter(Boolean);+ return {+ root, home, dir, fake, run, log, read,+ unit: () => read(unitPath),+ unitPath,+ pulled: () => (read(join(fake, "pulled")) ?? "").trim().split("\n").filter(Boolean),+ reset: () => { for (const name of ["pulled", "podman.log", "systemctl.log", "dryrun.dir"]) rmSync(join(fake, name), { force: true }); },+ };+}++describe.skipIf(!posix)("deploy/podman/install.sh", () => {+ it("parses in a POSIX shell and in dash", () => {+ expect(spawnSync("sh", ["-n", SCRIPT]).status).toBe(0);+ if (existsSync("/bin/dash")) expect(spawnSync("/bin/dash", ["-n", SCRIPT]).status).toBe(0);+ });++ it("installs the newest release while nothing is stable, pinned by digest, with a health check that reads the port when it runs", () => {+ const box = machine();+ const done = box.run(["--port", "8811"]);+ expect(done.status, done.out).toBe(0);+ expect(done.stdout).toContain("ok version: v0.1.151, the newest release (no version is stable yet)");+ expect(box.pulled()).toEqual([`${REPO}:v0.1.151`]);+ const unit = box.unit()!;+ expect(unit).toContain(`Image=${DIGEST}\n`);+ // systemd turns $$ into $, so the container's shell reads OMB_PORT from server.env at each check.+ expect(unit).toContain("HealthCmd=curl -sf --max-time 4 http://127.0.0.1:$${OMB_PORT:-8799}/api/health | grep -q openmausbot\n");+ expect(unit).not.toContain("8811");+ expect(box.read(join(box.dir, "server.env"))).toContain("OMB_PORT=8811\n");+ expect(unit).toContain(`EnvironmentFile=${box.dir}/server.env\n`);+ expect(unit).toContain("Environment=OMB_PODMAN_SERVICE=~/.local/share/openmausbot\n");+ expect(unit).toContain("WARNING: this isolates less than the Docker install.");+ // The generator read a copy in a folder of its own, never the live unit's folder.+ expect(box.read(join(box.fake, "dryrun.container"))).toBe(unit);+ expect(box.read(join(box.fake, "dryrun.dir"))!.trim()).not.toBe(join(box.home, ".config", "containers", "systemd"));+ expect(box.read(join(box.dir, ".env"))).toBe(`OMB_IMAGE=${DIGEST}\n`);+ expect(done.stdout).toContain("MausBot is running as your user's service (openmausbot), on http://127.0.0.1:8811.");+ expect(done.stdout).toContain("Warning: it shares this machine's network, which isolates less than the Docker install.");+ expect(done.stdout).toContain("It starts at boot, without anyone logged in.");+ });++ it("speaks of the server's own port alone under --lan", () => {+ const box = machine();+ const done = box.run(["--lan"]);+ expect(done.status, done.out).toBe(0);+ expect(done.stdout).toContain("Its port 8799 also answers other devices on this network, from private addresses only, over plain http; each device pairs.");+ expect(done.stdout).not.toContain("nothing on the open internet can reach it");+ });++ it("takes the stable channel's image, and refuses a channel that fails or names no digest instead of falling back", () => {+ const stable = machine();+ const done = stable.run([], { FAKE_STABLE_CODE: "200", FAKE_STABLE_BODY: `{"channel": "stable", "version": "0.1.150", "image": "${STABLE}"}` });+ expect(done.status, done.out).toBe(0);+ expect(done.stdout).toContain("ok version: the stable channel");+ expect(stable.pulled()).toEqual([STABLE]);+ expect(stable.unit()).toContain(`Image=${STABLE}\n`);++ for (const [env, words] of [+ [{ FAKE_STABLE_CODE: "500" }, "The stable channel could not be read (https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json answered 500)."],+ [{ FAKE_STABLE_CODE: "000" }, "answered 000"],+ [{ FAKE_STABLE_CODE: "200", FAKE_STABLE_BODY: `{"image": "${REPO}:stable"}` }, "names no image this installer accepts"],+ ] as const) {+ const box = machine();+ const refused = box.run([], env);+ expect(refused.status, refused.out).toBe(1);+ expect(refused.stderr).toContain(words);+ expect(box.pulled()).toEqual([]);+ expect(box.log("curl").some((call) => call.includes("releases/latest"))).toBe(false);+ expect(box.unit()).toBeNull();+ expect(existsSync(box.dir)).toBe(false);+ }+ });++ it("never keeps a tag it cannot pin by digest, and refuses the latest tag as the Docker installer does", () => {+ const box = machine();+ const unpinned = box.run([], { FAKE_DIGESTS: "" });+ expect(unpinned.status).toBe(1);+ expect(unpinned.stderr).toContain(`MausBot ${REPO}:v0.1.151 was downloaded, but Podman did not say its digest, so it cannot be pinned`);+ expect(box.unit()).toBeNull();+ expect(existsSync(join(box.dir, ".env"))).toBe(false);++ // A digest of another repository is not this image's.+ const other = machine().run([], { FAKE_DIGESTS: `docker.io/someone/else@sha256:${"9".repeat(64)}` });+ expect(other.status).toBe(1);+ expect(other.stderr).toContain("cannot be pinned");++ for (const [image, words] of [+ [`${REPO}:latest`, "OMB_INSTALL_IMAGE names the latest tag, which follows every commit."],+ [REPO, "OMB_INSTALL_IMAGE needs a release tag"],+ [`${REPO}:v1;rm`, "OMB_INSTALL_IMAGE is not an image name."],+ ] as const) {+ const refused = machine();+ const result = refused.run([], { OMB_INSTALL_IMAGE: image });+ expect(result.status, image).toBe(1);+ expect(result.stderr).toContain(words);+ expect(refused.pulled()).toEqual([]);+ }++ const asked = machine();+ const pinned = asked.run([], { OMB_INSTALL_IMAGE: `${REPO}:v0.1.150` });+ expect(pinned.status, pinned.out).toBe(0);+ expect(asked.unit()).toContain(`Image=${DIGEST}\n`);+ });++ it("changes nothing while update.sh runs here, or after an update it did not finish", () => {+ const box = machine();+ expect(box.run().status).toBe(0);+ const unit = box.unit();+ const env = box.read(join(box.dir, ".env"));+ mkdirSync(join(box.dir, ".update", "lock"), { recursive: true });+ // This test's own process: alive for as long as the run.+ writeFileSync(join(box.dir, ".update", "lock", "pid"), `${process.pid}\n`);+ box.reset();+ for (const args of [["--lan"], ["--uninstall"]]) {+ const busy = box.run(args);+ expect(busy.status, args.join(" ")).toBe(1);+ expect(busy.stderr).toContain(`An update is running here (process ${process.pid}). Nothing was changed. Wait for ${box.dir}/update.sh to finish`);+ }+ expect(box.pulled()).toEqual([]);+ expect(box.log("systemctl")).toEqual([]);+ expect(box.unit()).toBe(unit);+ expect(box.read(join(box.dir, ".env"))).toBe(env);+ expect(box.read(join(box.dir, "server.env"))).not.toContain("OMB_LAN=1");++ // A lock its process left behind is no update.+ const gone = spawnSync("sh", ["-c", "echo $$"], { encoding: "utf8" }).stdout.trim();+ writeFileSync(join(box.dir, ".update", "lock", "pid"), `${gone}\n`);+ writeFileSync(join(box.dir, ".update", "journal"), "phase=wait\n");+ const unfinished = box.run();+ expect(unfinished.status).toBe(1);+ expect(unfinished.stderr).toContain(`An update here did not finish (${box.dir}/.update/journal). Nothing was changed. Run ${box.dir}/update.sh first`);+ expect(box.unit()).toBe(unit);++ rmSync(join(box.dir, ".update", "journal"));+ const after = box.run();+ expect(after.status, after.out).toBe(0);+ });++ it("keeps the folder the service already uses when run again without --dir, and refuses a --dir that names another", () => {+ const box = machine();+ const elsewhere = join(box.root, "srv", "omb");+ expect(box.run(["--dir", elsewhere]).status).toBe(0);+ const unit = box.unit()!;+ expect(unit).toContain(`Volume=${elsewhere}/data:/data\n`);+ expect(unit).toContain(`Environment=OMB_PODMAN_SERVICE=${elsewhere}\n`);+ writeFileSync(join(elsewhere, "data", "bots.json"), "[]");++ const again = box.run(["--lan"]);+ expect(again.status, again.out).toBe(0);+ expect(again.stdout).toContain(`note The service already uses ${elsewhere}, so this run does too (--dir names it).`);+ expect(box.unit()).toBe(unit);+ expect(box.read(join(elsewhere, "server.env"))).toContain("OMB_LAN=1\n");+ expect(existsSync(box.dir)).toBe(false);++ // The same folder, spelled with a trailing slash, is the same folder.+ expect(box.run(["--dir", `${elsewhere}/`]).status).toBe(0);++ const other = box.run(["--dir", join(box.root, "srv", "other")]);+ expect(other.status).toBe(1);+ expect(other.stderr).toContain(`This user's MausBot service already uses ${elsewhere}, and --dir names ${join(box.root, "srv", "other")}. Nothing was changed.`);+ expect(existsSync(join(box.root, "srv", "other"))).toBe(false);+ expect(box.unit()).toBe(unit);++ const refusedUninstall = box.run(["--uninstall", "--dir", join(box.root, "srv", "other")]);+ expect(refusedUninstall.status).toBe(1);+ expect(box.unit()).toBe(unit);++ const removed = box.run(["--uninstall"]);+ expect(removed.status, removed.out).toBe(0);+ expect(removed.stdout).toContain(`Your data stays in ${elsewhere}/data.`);+ expect(box.unit()).toBeNull();+ expect(existsSync(join(elsewhere, "podman.unit"))).toBe(false);+ expect(readFileSync(join(elsewhere, "data", "bots.json"), "utf8")).toBe("[]");+ });++ it("refuses a Docker install's folder", () => {+ for (const file of ["compose.yaml", "docker-compose.yml"]) {+ const box = machine();+ const docker = join(box.root, "opt", "openmausbot");+ mkdirSync(docker, { recursive: true });+ writeFileSync(join(docker, file), "services: {}\n");+ writeFileSync(join(docker, ".env"), "DOMAIN=maus.example.com\n");+ const refused = box.run(["--dir", docker]);+ expect(refused.status).toBe(1);+ expect(refused.stderr).toContain(`${docker} holds a Docker install (compose.yaml or docker-compose.yml). Nothing was changed.`);+ expect(readFileSync(join(docker, ".env"), "utf8")).toBe("DOMAIN=maus.example.com\n");+ expect(box.unit()).toBeNull();+ }+ });++ it("leaves the unit in use and the settings as they were when Podman cannot read the new unit", () => {+ const box = machine();+ expect(box.run().status).toBe(0);+ const unit = box.unit();+ const settings = box.read(join(box.dir, "server.env"));+ box.reset();+ const failed = box.run(["--port", "8811"], { FAKE_QUADLET_FAILS: "1" });+ expect(failed.status).toBe(1);+ expect(failed.stderr).toContain("Podman could not read the unit this would write, so nothing was changed: quadlet-generator[1]: converting");+ expect(box.unit()).toBe(unit);+ expect(box.read(join(box.dir, "server.env"))).toBe(settings);+ expect(box.log("systemctl").some((call) => call.includes("restart") || call.includes("daemon-reload"))).toBe(false);+ });++ it("installs in a home with @ in its name (realmd and SSSD homes), and names the folder when its characters cannot go in a unit", () => {+ const box = machine({ home: "home/[email protected]" });+ const done = box.run();+ expect(done.status, done.out).toBe(0);+ expect(box.unit()).toContain(`Volume=${box.dir}/data:/data\n`);++ const spaced = machine({ home: "home/maus tester" });+ const refused = spaced.run();+ expect(refused.status).toBe(1);+ expect(refused.stderr).toContain(`The folder ${spaced.dir} has characters this installer does not write into a service's unit. Name another with --dir PATH`);+ });++ it("keeps the image a rollback named by this machine's own name, pinned by the digest it came with, and never pulls that name", () => {+ const box = machine();+ expect(box.run().status).toBe(0);+ const keep = "openmausbot-before-update:local";+ writeFileSync(join(box.dir, ".env"), `OMB_IMAGE=${keep}\n`);+ writeFileSync(join(box.fake, "local"), `${keep}\n`);+ box.reset();+ const again = box.run();+ expect(again.status, again.out).toBe(0);+ expect(again.stdout).toContain(`ok version: the one already installed (${DIGEST}); update.sh changes it`);+ expect(box.pulled()).toEqual([DIGEST]);+ expect(box.unit()).toContain(`Image=${DIGEST}\n`);++ // An image of this machine's own that no registry knows: kept as it is, and said so.+ writeFileSync(join(box.dir, ".env"), `OMB_IMAGE=${keep}\n`);+ box.reset();+ const local = box.run([], { FAKE_DIGESTS: "" });+ expect(local.status, local.out).toBe(0);+ expect(local.stdout).toContain(`ok version: the one already installed (${keep}, an image of this machine's own, not pinned by a digest); update.sh changes it`);+ expect(box.pulled()).toEqual([]);+ expect(box.unit()).toContain(`Image=${keep}\n`);+ });+});diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex e19ac6d987..3cdbe0f83d 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -43,7 +43,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS","OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_LOOP_GUARD_UNATTENDED_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_NETLIFY_API_URL", "OMB_OPENAI_API_KEY","OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",- "OMB_OPENROUTER_DECIDER_KEY", "OMB_OWN_MCP_HTTP", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",+ "OMB_OPENROUTER_DECIDER_KEY", "OMB_OWN_MCP_HTTP", "OMB_PERSON_FIRST_MS", "OMB_PHONE_PUSH", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PODMAN_SERVICE", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY","OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_PUSH_CREDENTIAL", "OMB_QUOTA_SWITCH","OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME","OMB_SERVER_UPDATE_DIR",diff --git a/server/environment.test.ts b/server/environment.test.tsindex d7c9253238..b74ce741b3 100644--- a/server/environment.test.ts+++ b/server/environment.test.ts@@ -133,6 +133,8 @@ describe("environment identity", () => {expect(serverInstall({}, "/app/dist-server/index.js", () => true)).toBe("docker");expect(serverInstall({}, "/repo/server/index.ts", none)).toBe("source");expect(serverInstall({}, "/usr/lib/node_modules/openmausbot/dist-server/index.js", none)).toBe("global");+ // The rootless Podman service: its unit marks it, whatever its CLI prefix says.+ expect(serverInstall({ OMB_PODMAN_SERVICE: "~/.local/share/openmausbot", OMB_CLI_PREFIX: "podman exec -it openmausbot openmausbot" }, "/app/dist-server/index.js", none)).toBe("podman-service");expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: false }).capabilities).not.toHaveProperty("sharedComputers");expect(environmentDescriptor({ environmentId: "abc", desktopManaged: true, sharedComputers: true }).capabilities)diff --git a/server/environment.ts b/server/environment.tsindex 1fd5e4b289..eb5a31ac1f 100644--- a/server/environment.ts+++ b/server/environment.ts@@ -112,9 +112,10 @@ export function reportableServerVersion(version = serverVersion()): string | undreturn RELEASE_VERSION.test(version) ? version : undefined;}-/** How this server was started: the Docker image (OMB_CLI_PREFIX, or Docker's own /.dockerenv), a checkout, npx, or a- * global install. */+/** How this server was started: the rootless Podman service (its unit sets OMB_PODMAN_SERVICE), the Docker image+ * (OMB_CLI_PREFIX, or Docker's own /.dockerenv), a checkout, npx, or a global install. */export function serverInstall(env: NodeJS.ProcessEnv = process.env, script = process.argv[1] ?? "", docker = () => existsSync("/.dockerenv")): ServerInstall {+ if (env.OMB_PODMAN_SERVICE?.trim()) return "podman-service";const prefix = cliPrefix(env, script);if (prefix.includes("docker") || docker()) return "docker";if (prefix === "pnpm omb" || script.endsWith(".ts")) return "source";diff --git a/server/update-check.test.ts b/server/update-check.test.tsindex 537b924b42..d52a0c3c24 100644--- a/server/update-check.test.ts+++ b/server/update-check.test.ts@@ -1,7 +1,7 @@import { join, sep } from "node:path";import { describe, expect, it, vi } from "vitest";-import { createUpdateChecker, installKind, isNewerVersion, LATEST_RELEASE_URL, STABLE_CHANNEL_URL, updateChannel } from "./update-check.ts";+import { createUpdateChecker, installKind, isNewerVersion, LATEST_RELEASE_URL, STABLE_CHANNEL_URL, updateChannel, updateCommand } from "./update-check.ts";const release = (tag: string) =>({ ok: true, status: 200, json: async () => ({ tag_name: tag, html_url: `https://github.com/milind-soni/OpenMausBot/releases/tag/${tag}` }) }) as Response;@@ -29,6 +29,23 @@ describe("server update check", () => {expect(installKind({ desktopManaged: false, managed: false, serverRoot: root, exists: none })).toBe("unknown");});+ it("knows the rootless Podman service by its unit's mark, and gives its own update.sh, not the Compose recipe", () => {+ const root = ["", "app", "dist-server"].join(sep);+ const env = { OMB_PODMAN_SERVICE: "~/.local/share/openmausbot" };+ expect(installKind({ desktopManaged: false, managed: false, serverRoot: root, exists: (path) => path === "/run/.containerenv", env })).toBe("podman-service");+ expect(installKind({ desktopManaged: false, managed: false, serverRoot: root, exists: (path) => path === "/run/.containerenv", env: {} })).toBe("podman");+ expect(installKind({ desktopManaged: false, managed: true, serverRoot: root, exists: () => false, env })).toBe("managed");+ expect(updateCommand("podman-service", undefined, env)).toEqual({ command: "~/.local/share/openmausbot/update.sh", restart: false });+ expect(updateCommand("podman-service", { version: "0.1.170", stable: false }, env)?.command).toBe("~/.local/share/openmausbot/update.sh --version 0.1.170");+ expect(updateCommand("podman-service", { version: "0.1.170", stable: true }, { OMB_PODMAN_SERVICE: "/srv/omb@corp/" })?.command).toBe("/srv/omb@corp/update.sh");+ // Anything but a plain path stands for nothing: the installer's own folder.+ for (const bad of ["1", "~/x; rm -rf /", "/srv/../etc", "relative/dir", "$(id)"]) {+ expect(updateCommand("podman-service", undefined, { OMB_PODMAN_SERVICE: bad })?.command, bad).toBe("~/.local/share/openmausbot/update.sh");+ }+ expect(updateCommand("docker", { version: "0.1.170", stable: false })?.command).toBe("git pull && ./update.sh --version 0.1.170");+ expect(updateCommand("docker", { version: "0.1.170", stable: true })?.command).toBe("git pull && ./update.sh");+ });+it("compares release versions numerically and never reports a malformed one", () => {expect(isNewerVersion("v0.1.93", "0.1.92")).toBe(true);expect(isNewerVersion("0.1.10", "0.1.9")).toBe(true);diff --git a/server/update-check.ts b/server/update-check.tsindex 81a330efea..1c83874b85 100644--- a/server/update-check.ts+++ b/server/update-check.ts@@ -9,8 +9,18 @@ const CACHE_MS = 60 * 60_000;/** How long the last answer stands in when the channel cannot be read: an outage of GitHub is no reason to say nothing. */const STALE_MS = 24 * 60 * 60_000;-/** "managed" is a hosted or Cloud server that is updated for its owner. */-export type InstallKind = "desktop" | "managed" | "docker" | "podman" | "npm" | "git" | "unknown";+/** "managed" is a hosted or Cloud server that is updated for its owner. "podman" is deploy/podman's Compose recipe;+ * "podman-service" the rootless service deploy/podman/install.sh writes, whose unit sets OMB_PODMAN_SERVICE. */+export type InstallKind = "desktop" | "managed" | "docker" | "podman" | "podman-service" | "npm" | "git" | "unknown";++/** Where deploy/podman/install.sh puts the install unless told otherwise. */+export const PODMAN_SERVICE_DIR = "~/.local/share/openmausbot";++/** The install's folder on the host, as the unit gives it in OMB_PODMAN_SERVICE (`~/…` or an absolute path). */+export function podmanServiceDir(env: NodeJS.ProcessEnv = process.env): string {+ const dir = env.OMB_PODMAN_SERVICE?.trim() ?? "";+ return /^(?:~\/|\/)[A-Za-z0-9/._@-]+$/.test(dir) && !dir.split("/").includes("..") ? dir.replace(/\/+$/, "") : PODMAN_SERVICE_DIR;+}/** `stable` follows the promoted version; `newest` follows every release, as soon as it is published. */export type UpdateChannel = "stable" | "newest";@@ -24,9 +34,11 @@ export function updateChannel(env: NodeJS.ProcessEnv = process.env): UpdateChann* As docs/self-hosting.md and deploy/podman/README.md give them. `version` is the one the channel names: an npm install* is pinned to it, and a Docker install passes it to deploy/update.sh unless that is the stable one update.sh takes anyway.*/-export function updateCommand(install: InstallKind, target?: { version: string; stable: boolean }): { command: string; restart: boolean } | undefined {+export function updateCommand(install: InstallKind, target?: { version: string; stable: boolean }, env: NodeJS.ProcessEnv = process.env): { command: string; restart: boolean } | undefined {+ const version = target && !target.stable ? ` --version ${target.version}` : "";switch (install) {- case "docker": return { command: target && !target.stable ? `git pull && ./update.sh --version ${target.version}` : "git pull && ./update.sh", restart: false };+ case "docker": return { command: `git pull && ./update.sh${version}`, restart: false };+ case "podman-service": return { command: `${podmanServiceDir(env)}/update.sh${version}`, restart: false };case "podman": return { command: "git pull && cd deploy/podman && PODMAN_COMPOSE_PROVIDER=podman-compose podman compose --env-file .env -f compose.yaml up -d --build", restart: false };case "npm": return { command: `npm install -g openmausbot@${target?.version ?? "latest"}`, restart: true };case "git": return { command: "git pull && pnpm install", restart: true };@@ -39,10 +51,12 @@ export function installKind(input: {managed: boolean;serverRoot: string;exists?: (path: string) => boolean;+ env?: NodeJS.ProcessEnv;}): InstallKind {const exists = input.exists ?? existsSync;if (input.desktopManaged) return "desktop";if (input.managed) return "managed";+ if ((input.env ?? process.env).OMB_PODMAN_SERVICE?.trim()) return "podman-service";if (exists("/.dockerenv")) return "docker";if (exists("/run/.containerenv")) return "podman";if (input.serverRoot.split(sep).includes("node_modules")) return "npm";diff --git a/src/components/ServerList.test.ts b/src/components/ServerList.test.tsindex 31ad0e60a4..d7b3a48f31 100644--- a/src/components/ServerList.test.ts+++ b/src/components/ServerList.test.ts@@ -76,6 +76,7 @@ it("the update note shows only for a server behind this app, with the command thexpect(updateCommand("npx", "0.1.147")).toBe("npx [email protected] serve");expect(updateCommand(null, "0.1.147")).toBe("npx [email protected] serve");expect(updateCommand("global", "0.1.147")).toBe("npm install -g [email protected]");+ expect(updateCommand("podman-service", "0.1.147")).toBe("~/.local/share/openmausbot/update.sh");});it("Pair again opens the Connect sheet with the address locked and the code field ready; Remove only asks main", async () => {diff --git a/src/components/ServerList.tsx b/src/components/ServerList.tsxindex 2c1e9174ee..e3c5df5a85 100644--- a/src/components/ServerList.tsx+++ b/src/components/ServerList.tsx@@ -24,6 +24,8 @@ const clock = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: "2-dig/** The update command that fits how the server was installed, pinned to this app's version. */export function updateCommand(install: ServerInstall | null, version: string): string {if (install === "docker") return "git pull && ./update.sh";+ // The rootless Podman service's own update.sh, in the folder its installer uses unless told another.+ if (install === "podman-service") return "~/.local/share/openmausbot/update.sh";if (install === "global") return `npm install -g openmausbot@${version}`;if (install === "source") return "git pull && pnpm install";return `npx openmausbot@${version} serve`;diff --git a/src/lib/server-update.ts b/src/lib/server-update.tsindex 702661df15..2e9fa9a831 100644--- a/src/lib/server-update.ts+++ b/src/lib/server-update.ts@@ -9,7 +9,7 @@ export type { ServerUpdateStatus };/** GET /api/updates/check (server/update-check.ts). */export interface ServerUpdateCheck {current: string;- install: "desktop" | "managed" | "docker" | "podman" | "npm" | "git" | "unknown";+ install: "desktop" | "managed" | "docker" | "podman" | "podman-service" | "npm" | "git" | "unknown";channel?: "stable" | "newest";latest?: string;available: boolean;