Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Update server button: a self-hosted server updates itself from the app (after #5332) (#5354)

Milind Soniacb1159dc09d
diff --git a/.github/workflows/server-installer.yml b/.github/workflows/server-installer.yml
index 13475bdf0f..08cc1a1406 100644
--- a/.github/workflows/server-installer.yml
+++ b/.github/workflows/server-installer.yml
@@ -10,6 +10,7 @@ on:
- deploy/e2e/**
- deploy/box/**
- deploy/update.sh
+ - deploy/update-runner.sh
- connector/profiles/**
- deploy/Caddyfile
- deploy/docker-compose.yml
@@ -34,7 +35,7 @@ jobs:
with:
persist-credentials: false
- name: shellcheck
- run: shellcheck deploy/install.sh deploy/e2e/run.sh
+ run: shellcheck deploy/install.sh deploy/update-runner.sh deploy/e2e/run.sh
- uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
diff --git a/.github/workflows/server-update-e2e.yml b/.github/workflows/server-update-e2e.yml
index 3500cd2124..66a863a4d8 100644
--- a/.github/workflows/server-update-e2e.yml
+++ b/.github/workflows/server-update-e2e.yml
@@ -8,6 +8,7 @@ on:
pull_request:
paths:
- deploy/update.sh
+ - deploy/update-runner.sh
- deploy/e2e/update.sh
- deploy/docker-compose.yml
- .github/workflows/server-update-e2e.yml
@@ -34,7 +35,7 @@ jobs:
with:
persist-credentials: false
- name: shellcheck
- run: shellcheck -S warning deploy/update.sh deploy/e2e/update.sh
+ run: shellcheck -S warning deploy/update.sh deploy/update-runner.sh deploy/e2e/update.sh
- name: Update, roll back and recover
env:
LAYOUT: ${{ matrix.layout }}
diff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
index c2a2ee8bcc..0694d20b56 100644
--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx
+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
@@ -365,6 +365,115 @@ compares your server with the stable version. To hear of every release as soon
as it is published instead, set `OMB_UPDATE_CHANNEL=newest` in the server's
environment.
+### From the app: Update server
+
+On a Docker install, the server's admins can update it from **Settings →
+Updates → Update server**, in the desktop app or a browser. It runs the
+`update.sh` described below: the stable version, a copy of the data first, and
+the old version and its data back when the new one is not healthy. The app asks
+first (the server restarts, so anything running stops, and it says how many
+chats have a bot answering), shows "Updating the server…" while the server is
+away, reconnects by itself, then says which version it runs now, or that it
+went back and why. After 15 minutes without the server it says so, with the
+commands to see its log and to go back. In the desktop app, once the server is
+newer than the app, the same row offers the app's own update. With
+`OMB_UPDATE_CHANNEL=newest` the app shows the command instead, because
+`update.sh` takes the stable version. A server on a build of main (the `latest`
+image, which a checkout runs when `.env` names no `OMB_IMAGE`) gets no button:
+the app says so, with `sudo ./update.sh`, which moves it to the stable version
+once that is newer than the build.
+
+The installer sets this up, and every run of the installer refreshes it. In a
+checkout of this repository, add it from `OpenMausBot/deploy` (it needs
+systemd, and restarts the server once), and run the same command again after
+each `git pull`: until you do, the button runs nothing and the app shows this
+command.
+
+```sh
+git pull && sudo ./update-runner.sh --install
+```
+
+That places `/usr/local/sbin/openmausbot-update-runner`, the systemd units
+`openmausbot-update.path` and `openmausbot-update.service`, and root's folder
+`/var/lib/openmausbot-update`: root's own copy of `update.sh`, which is what
+the button runs, `request`, which the server's container writes, and `status`,
+which it reads and cannot write. One install per server: a second folder is
+refused until `--remove` on the first, and `--remove` for any other folder
+removes nothing. A checkout gets
+`docker-compose.override.yml` to mount the two (an override of your own, or a
+link, is left alone, and the script says what to add). `sudo
+./update-runner.sh --remove` takes it all away.
+
+**A checkout's owner decides what root runs.** The button's update runs as
+root, but in your checkout: its Compose files and `.env` decide what `docker
+compose up` starts. So whoever owns that folder can change what root runs
+when the app asks for an update. `--install` accepts a folder owned by root or
+by someone in the `docker` group (who can run anything as root through Docker
+already), and anyone else only with `--trust-folder-owner`. The folder, and
+every folder above it, may be changed by root and that owner only: not by
+everyone (unless it has its sticky bit, as `/tmp` does), and not by a group
+other than root's or the owner's own private group (the one Ubuntu and Fedora
+give each user, which their default umask makes new folders writable by). The
+runner checks all this again at every run, and runs nothing when it no longer
+holds; the refusal names the folder, its owner, group and mode, and the app
+shows it with the `--install` command. A fresh server installed with the
+installer passes as it is. On an update the
+app asked for, `update.sh` writes nothing through a link there (`.update`,
+`.env`, the Compose files and its temporary files), nor into a `.update` that
+belongs to anyone but you or the folder's owner; your own run of
+`./update.sh` uses links there as before.
+
+**Who can ask.** Only an admin's own signed-in session sees and presses the
+button; members never see it, and Clouds that MausBot runs never show it. The
+request itself is a file in a folder of the server's user, and until the bots'
+sandbox is on for self-hosted servers, bots run as that user: anything running
+on the server as that user, a bot or a prompt injection included, can leave the
+same file. So the runner treats whoever asks as hostile. What any number of
+requests can cause:
+
+- For each stable image that is out, at most one update: the server stops, its
+ data is copied, the new version starts, and if it is not healthy the old
+ version and the copy come back. That stable image is then not tried again
+ from the app on this server until you run `./update.sh` yourself or another
+ stable image is out. So a compromised server can keep one stable release from
+ being tried from the app, by making it fail on purpose; whoever presses the
+ button is told, with the command to try it by hand. It is taken only when
+ the running image's own label is
+ not newer (never by the version the server says it runs; when the two
+ disagree nothing changes); a stable image that names the same version as the
+ running one under a new digest (a re-published image) is taken too.
+- At most three copies of the data: the two newest that updates from the app
+ made, and the last one your own run of `./update.sh` made, which an update
+ from the app never removes. While the next copy is made and checked, that is
+ about three times the data plus the new copy; `update.sh` refuses to start
+ when the disk has no room for it, and the app then says so, with the commands
+ to list and remove old copies (below).
+- Updates that stop the server at most once every four minutes. A run with
+ nothing to do stops nothing and does not count, and for five minutes the
+ same answer is given without asking GitHub or the registry again (when the
+ server's own check knows of a newer version, only GitHub is asked whether
+ the stable image changed); any two runs are at least 30 seconds apart. A run during which the server restarts
+ by itself counts as one that stopped it, so it can delay an admin's press by
+ up to four minutes.
+- Nothing while `/etc/mausbot/policy.json` holds updates
+ (`"updates": "hold"`).
+
+It cannot choose a version, image, URL, flag or path, cannot downgrade or roll
+back (an update an earlier run left unfinished waits for you at a terminal), and
+cannot write the runner's status, `update.sh`, `.env` or the Compose files. So
+the most it can cause is one stop, copy and restart (and rollback, when the
+version fails here) per stable release, which the admins would have pressed for
+anyway.
+
+**Copies of the data.** An update asked for from the app keeps your own last
+copy and its own two newest ones. A run of `./update.sh` at a terminal removes all
+but its own once that one has been checked, as above. To see them:
+`docker volume ls --filter label=com.mausbot.role=update-backup`; to remove one
+yourself: `docker volume rm <name>`.
+
+Without the runner (no systemd, an npm install, Podman) the app shows the
+command to run on the server instead.
+
### Path B (Docker): one command, with a way back
From `OpenMausBot/deploy`:
diff --git a/deploy/e2e/run.sh b/deploy/e2e/run.sh
index 7e55684100..905a2eb89d 100755
--- a/deploy/e2e/run.sh
+++ b/deploy/e2e/run.sh
@@ -80,6 +80,26 @@ install_until_https() { # evidence-file [the install command, when not the usual
through_caddy "the install"
}
+# The folders above the install, as the Update server button checks them (update-runner.sh): a fresh Ubuntu server has
+# / and /opt root's and closed to others. A CI image may not; it is set as a server has it, never the check weakened.
+prepare_like_a_server() {
+ stat -c '%U:%G %a %n' / /opt /srv 2>/dev/null || true
+ getfacl -p / /opt /srv 2>/dev/null || true
+ for folder in / /opt /srv; do
+ [ -d "$folder" ] || continue
+ # A default ACL hands new folders under it modes no umask decides; a server has none.
+ if getfacl -p "$folder" 2>/dev/null | grep -q '^default:'; then
+ echo "CI host: $folder has a default ACL; removed, as on a server"
+ sudo setfacl -b "$folder"
+ fi
+ if [ "$(stat -c %u "$folder")" != 0 ] || [ $((8#$(stat -c %a "$folder") & 8#022)) != 0 ]; then
+ echo "CI host: $folder is $(stat -c '%U:%G %a' "$folder"); made root's and closed to others, as on a server"
+ sudo chown root:root "$folder" && sudo chmod go-w "$folder"
+ fi
+ done
+}
+prepare_like_a_server
+
step "the checks alone, with a name that points nowhere: one thing to fix, nothing changed"
status=0
containers_before=$(sudo docker ps -aq | sort)
@@ -150,6 +170,16 @@ else
echo "this checkout has no deploy/update.sh; nothing to place"
fi
+step "the Update server button: systemd watches for the server's request, which only the server's own folder takes"
+if [ -f "$ROOT/deploy/update-runner.sh" ]; then
+ systemctl is-enabled --quiet openmausbot-update.path || fail "the button's path unit is not enabled"
+ sudo grep -qx "layout=installer" /var/lib/openmausbot-update/status/runner || fail "the runner did not say it is there"
+ in_server() { (cd "$DIR" && sudo docker compose exec -T omb sh -c "$1"); }
+ in_server 'test -w /run/omb-update/request' || fail "the server cannot leave a request"
+ if in_server 'echo x > /run/omb-update/status/last' 2>/dev/null; then fail "the server can write the runner's status"; fi
+ echo "the request folder is the server's, the status folder is read-only to it"
+fi
+
step "HTTPS comes back by itself whenever the server restarts without Caddy"
# Caddy used to share the server's network, and stayed in the old, dead one after each of these, with 443 refused.
(cd "$DIR" && sudo docker compose restart >/dev/null 2>&1) && healthy_again && through_caddy "docker compose restart"
diff --git a/deploy/e2e/update.sh b/deploy/e2e/update.sh
index 2b1485d93b..e9fa53b6d2 100755
--- a/deploy/e2e/update.sh
+++ b/deploy/e2e/update.sh
@@ -5,7 +5,8 @@
# answers and damages the data (it must roll back and leave every file as it was), an update killed with SIGKILL while
# it waits (the next run asks before it puts the data back), a rollback whose restore fails (data and copy untouched,
# tried again on request), an update whose terminal hangs up half-way (it finishes), a refused downgrade, and a
-# `docker compose stop` that fails (no copy, nothing changed).
+# `docker compose stop` that fails (no copy, nothing changed), and the Update server button (deploy/update-runner.sh
+# under systemd): a request the server writes, carrying flags and another image, still runs only the standard update.
# LAYOUT=installer /opt/openmausbot with compose.yaml and a ./data folder, as deploy/install.sh lays it out
# LAYOUT=checkout a copy of deploy/ with docker-compose.yml and the named volume `data`
# OUT=<evidence folder> LAYOUT=installer bash deploy/e2e/update.sh
@@ -44,6 +45,26 @@ copy() {
# Every file of the data with its owner, mode and checksum. Read while the server is stopped.
manifest() { docker run --rm --network none --user 0:0 -v "$1:/d:ro" --entrypoint sh "$REPO:v$FROM" -c 'cd /d && find . -type f -print0 | sort -z | xargs -0 -r stat -c "%u:%g %a %n"; find . -type f -print0 | sort -z | xargs -0 -r sha256sum'; }
+# The folders above the install, as the Update server button checks them (update-runner.sh): a fresh Ubuntu server has
+# / and /opt root's and closed to others. A CI image may not; it is set as a server has it, never the check weakened.
+prepare_like_a_server() {
+ stat -c '%U:%G %a %n' / /opt /srv 2>/dev/null || true
+ getfacl -p / /opt /srv 2>/dev/null || true
+ for folder in / /opt /srv; do
+ [ -d "$folder" ] || continue
+ # A default ACL hands new folders under it modes no umask decides; a server has none.
+ if getfacl -p "$folder" 2>/dev/null | grep -q '^default:'; then
+ echo "CI host: $folder has a default ACL; removed, as on a server"
+ setfacl -b "$folder"
+ fi
+ if [ "$(stat -c %u "$folder")" != 0 ] || [ $((8#$(stat -c %a "$folder") & 8#022)) != 0 ]; then
+ echo "CI host: $folder is $(stat -c '%U:%G %a' "$folder"); made root's and closed to others, as on a server"
+ chown root:root "$folder" && chmod go-w "$folder"
+ fi
+ done
+}
+prepare_like_a_server
+
step "a $LAYOUT install on $FROM"
for old in /opt/openmausbot /srv/openmausbot-e2e/deploy; do
if [ -d "$old" ]; then (cd "$old" && docker compose down -v) >/dev/null 2>&1; fi
@@ -245,6 +266,28 @@ cmp -s "$DIR/.env" "$OUT/env.before-stop" || fail "after the failed stop .env di
[ ! -f "$DIR/.update/journal" ] || fail "the failed stop left a journal"
cp "$DIR/.update/update.log" "$OUT/update.log"
+step "11. the Update server button: the server asks with a file, systemd runs the standard update, the outcome is written back"
+"${UPDATE[@]}" --rollback --yes >"$OUT/11-back.txt" 2>&1 || fail "could not go back to $FROM for the button's run"
+[ "$(version)" = "$FROM" ] || fail "not on $FROM before the button's run"
+cp "$ROOT/deploy/update.sh" "$DIR/update.sh"
+OMB_RUNNER_GAP_S=0 OMB_RUNNER_QUIET_S=0 bash "$ROOT/deploy/update-runner.sh" --install --dir "$DIR" | tee "$OUT/11-install.txt"
+[ "${PIPESTATUS[0]}" = 0 ] || fail "update-runner.sh --install failed"
+systemctl is-active --quiet openmausbot-update.path || fail "the path unit is not watching"
+wait_version "$FROM" || fail "$FROM did not come back with the button's folders"
+in_server() { (cd "$DIR" && docker compose exec -T omb sh -c "$1"); }
+if in_server 'echo x > /run/omb-update/status/last' 2>/dev/null; then fail "the server can write the runner's status"; fi
+# As a server that wants more than "update now" would: flags, an image of its choosing, an older version.
+in_server "printf '%s\\n' --rollback --allow-older 'image=$REPO:v$FROM' 'version=0.1.1' > /run/omb-update/request/request" || fail "the server could not leave its request"
+for _ in $(seq 1 120); do grep -qx 'state=done' /var/lib/openmausbot-update/status/last && grep -qx 'run=1' /var/lib/openmausbot-update/status/last && break; sleep 3; done
+tee "$OUT/11-last.txt" </var/lib/openmausbot-update/status/last
+grep -qx 'result=updated' /var/lib/openmausbot-update/status/last || fail "the button's update did not end as updated"
+wait_version "$TO" || fail "after the button's update the server says $(version)"
+grep -qx "OMB_IMAGE=$STABLE" "$DIR/.env" || fail "the button's update did not pin the stable image"
+[ ! -e /var/lib/openmausbot-update/request/request ] || fail "the request was left behind"
+journalctl -u openmausbot-update.service --no-pager >"$OUT/11-journal.txt" 2>&1 || true
+bash "$ROOT/deploy/update-runner.sh" --remove --dir "$DIR" >/dev/null || fail "update-runner.sh --remove failed"
+[ ! -e /etc/systemd/system/openmausbot-update.path ] || fail "--remove left the path unit"
+
(cd "$DIR" && docker compose down -v) >/dev/null 2>&1
for volume in $(copies); do docker volume rm -f "$volume" >/dev/null 2>&1; done
docker image rm -f omb-e2e-broken:1 openmausbot-before-update:local >/dev/null 2>&1
diff --git a/deploy/install.sh b/deploy/install.sh
index 936be0f27b..a4e21d1cf2 100755
--- a/deploy/install.sh
+++ b/deploy/install.sh
@@ -647,6 +647,10 @@ services:
volumes:
- ./data:/data
- edge:/run/openmausbot
+ # The Update server button (update-runner.sh, root's folder): the server leaves a request in the first, reads the
+ # outcome in the second.
+ - /var/lib/openmausbot-update/request:/run/omb-update/request
+ - /var/lib/openmausbot-update/status:/run/omb-update/status:ro
environment:
OMB_PORT: "8799"
OMB_WEBHOOK_PORT: "8800"
@@ -808,10 +812,36 @@ place_update() {
if from_repository fetch_update; then note "update.sh is $SOURCE_NAME."; fi
}
+fetch_runner() {
+ fetch deploy/update-runner.sh "$INSTALL_DIR/update-runner.sh" 755
+}
+
+data_owner() { # the data folder's user and group, as numbers: the server's container runs as them
+ stat -c '%u:%g' "$INSTALL_DIR/data" 2>/dev/null || stat -f '%u:%g' "$INSTALL_DIR/data" 2>/dev/null
+}
+
+# The Update server button: update-runner.sh (deploy/update-runner.sh) has systemd run update.sh when the server asks,
+# and nothing else. Without it, or without systemd, the app shows the command to run here instead.
+place_button() {
+ [ -f "$INSTALL_DIR/update.sh" ] || return 0
+ if ! from_repository fetch_runner; then
+ note "The app cannot update this server: update-runner.sh could not be downloaded. Update it with: sudo $INSTALL_DIR/update.sh"
+ return 0
+ fi
+ button_log=$(mktemp)
+ if sh "$INSTALL_DIR/update-runner.sh" --install --dir "$INSTALL_DIR" --user "$(data_owner)" --no-restart >"$button_log" 2>&1; then
+ note "The app can update this server: Settings, Updates, Update server."
+ else
+ reason=$(tail -n 1 "$button_log")
+ note "The app cannot update this server${reason:+ ($reason)}. Update it with: sudo $INSTALL_DIR/update.sh"
+ fi
+ rm -f "$button_log"
+}
+
# The sandbox's host preparation and Compose settings are this repository's own (deploy/box, connector/profiles),
# fetched and used as they are, all four from the same place.
fetch_sandbox() {
- install -d -m 755 "$INSTALL_DIR/box" "$INSTALL_DIR/box/profiles"
+ make_folders "$INSTALL_DIR/box" "$INSTALL_DIR/box/profiles"
fetch deploy/box/prepare-host.sh "$INSTALL_DIR/box/prepare-host.sh" 755 &&
fetch deploy/box/compose.box.yaml "$INSTALL_DIR/compose.box.yaml" &&
fetch "connector/profiles/$SECCOMP" "$INSTALL_DIR/box/profiles/$SECCOMP" &&
@@ -940,19 +970,26 @@ wait_https() {
# An install's folder, or its data, that others may write to (made by hand, or by an installer before this one) is closed
# to them: root runs what is in it.
-close_to_others() { # folder
- if [ -n "$(find "$1" -prune \( -perm -020 -o -perm -002 \) 2>/dev/null)" ]; then
+close_to_others() { # folder, judged where a link to it leads
+ if [ -n "$(find -H "$1" -prune \( -perm -020 -o -perm -002 \) 2>/dev/null)" ]; then
chmod go-w "$1"
note "$1 could be changed by others on this server; now only its owner can change it."
fi
}
+# A new folder is made 755; one that is there keeps its own mode, only closed to others when it was open (a folder its
+# owner made 700 stays 700).
+make_folders() { # folder...
+ for folder in "$@"; do
+ if [ -d "$folder" ]; then close_to_others "$folder"; else install -d -m 755 "$folder"; fi
+ done
+}
+
install_server() {
say ""
say "Installing MausBot in $INSTALL_DIR..."
- if [ -d "$INSTALL_DIR" ]; then close_to_others "$INSTALL_DIR"; fi
if [ -d "$INSTALL_DIR/data" ]; then close_to_others "$INSTALL_DIR/data"; fi
- install -d -m 755 "$INSTALL_DIR" "$INSTALL_DIR/caddy" "$INSTALL_DIR/caddy/data" "$INSTALL_DIR/caddy/config"
+ make_folders "$INSTALL_DIR" "$INSTALL_DIR/caddy" "$INSTALL_DIR/caddy/data" "$INSTALL_DIR/caddy/config"
write_compose
write_caddyfile
write_settings
@@ -961,6 +998,7 @@ install_server() {
place_update
prepare_sandbox
prepare_data
+ place_button
say "Starting MausBot..."
compose_quietly up -d --remove-orphans || fail "MausBot could not be started (Docker's message is above). Fix that, then run this again."
wait_healthy || fail "MausBot started but did not report healthy within $HEALTH_WAIT_S seconds. Its log: cd $INSTALL_DIR && sudo docker compose logs omb --tail 50"
@@ -1071,6 +1109,7 @@ run_uninstall() {
command -v docker >/dev/null 2>&1 || fail "Docker isn't installed here, so MausBot isn't running. Your data is in $INSTALL_DIR/data."
say "Stopping MausBot..."
compose_quietly down --remove-orphans || fail "MausBot could not be stopped (Docker's message is above)."
+ if [ -f "$INSTALL_DIR/update-runner.sh" ]; then sh "$INSTALL_DIR/update-runner.sh" --remove --dir "$INSTALL_DIR" >/dev/null 2>&1 || true; fi
say "MausBot is stopped and its containers are removed."
say "Your data is kept in $INSTALL_DIR/data, your settings in $INSTALL_DIR/.env and the HTTPS certificates in $INSTALL_DIR/caddy."
say "To start it again: $(command_line "--domain $(env_value DOMAIN)")"
diff --git a/deploy/update-runner.sh b/deploy/update-runner.sh
new file mode 100644
index 0000000000..a3b1d31a50
--- /dev/null
+++ b/deploy/update-runner.sh
@@ -0,0 +1,402 @@
+#!/bin/sh
+# The Update server button's host side, for a Docker Compose install (the installer's /opt/openmausbot, or the deploy/
+# folder of a git checkout). A server in a container cannot replace its own image, so it only leaves a file in a folder
+# it was given; systemd sees the file (openmausbot-update.path) and runs this, as root, outside every container. This
+# runs root's own copy of update.sh on the install, and writes how that ended where the server reads it.
+#
+# sudo ./update-runner.sh --install adds the button to this install, or refreshes it (run it again after git pull)
+# sudo ./update-runner.sh --remove takes it away again (your data and update.sh stay)
+#
+# SECURITY: anything that runs as the server's user can leave the request, a bot included where the bots' sandbox is
+# off, so the requester is treated as hostile. The request is a file that exists, and nothing else: this script never
+# reads it, follows it or passes on anything from it. What any request can cause, at most once per stable image:
+# - root's copy of update.sh, run with OMB_UPDATE_BY_RUNNER=1: the stable version, only when it is not older than the
+# running image's own label (never what the server says it runs), a copy of the data first, and the old version
+# back when the new one is not healthy;
+# - after a rollback, never that same stable image again on this server until a person runs update.sh or another
+# stable image is out (STATE/blocked), so a server that fails a version cannot be stopped and copied over and over;
+# - the runner's own copies of the data are capped at the two newest; a person's own copy is never removed.
+# Runs that stop the server are GAP_S apart; runs with nothing to do are answered from STATE/idle for IDLE_S without
+# asking GitHub or the registry, and any two runs are QUIET_S apart. It cannot choose a version, an image, a URL, a flag
+# or a path, and cannot roll back. Every file this writes is in STATE, root's folder, of which the server's container
+# sees only `request` (its own) and `status` (read-only). In a checkout, the folder's owner decides what root's
+# `docker compose up` starts (the Compose files and .env are theirs), so --install and every run want that owner to be
+# root, able to run Docker already, or trusted at --install, and the folder and those above it closed to anyone else.
+set -u
+# Every file and folder this makes has its mode set by the write; nothing is left to the caller's umask.
+umask 022
+
+SBIN_DIR=${OMB_SBIN_DIR:-/usr/local/sbin}
+SYSTEMD_DIR=${OMB_SYSTEMD_DIR:-/etc/systemd/system}
+STATE=${OMB_UPDATE_STATE_DIR:-/var/lib/openmausbot-update}
+POLICY=${OMB_UPDATE_POLICY:-/etc/mausbot/policy.json}
+GAP_S=${OMB_RUNNER_GAP_S:-240}
+QUIET_S=${OMB_RUNNER_QUIET_S:-30}
+IDLE_S=${OMB_RUNNER_IDLE_S:-300}
+UNIT=openmausbot-update
+RUNNER=openmausbot-update-runner
+INSTALLER_MARK="# Written by MausBot's installer (deploy/install.sh)"
+OVERRIDE_MARK="# Written by update-runner.sh --install"
+# Where the server's container finds the two folders (SERVER_UPDATE_DIR in server/server-update.ts).
+IN_CONTAINER=/run/omb-update
+REQUESTS="$STATE/request"
+STATUS="$STATE/status"
+UPDATER="$STATE/update.sh"
+BLOCKED="$STATE/blocked"
+IDLE="$STATE/idle"
+TRUST="$STATE/trust"
+VERSION_LABEL=org.opencontainers.image.version
+
+say() { printf '%s\n' "$*"; }
+fail() {
+ printf '%s\n' "$*" >&2
+ exit 1
+}
+
+DIR=${OMB_INSTALL_DIR:-}
+MODE=run
+USER_IDS=""
+RESTART=yes
+TRUST_OWNER=no
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --install) MODE=install ;;
+ --remove) MODE=remove ;;
+ --dir) [ $# -ge 2 ] || fail "--dir needs a folder."; DIR=$2; shift ;;
+ --user) [ $# -ge 2 ] || fail "--user needs UID:GID."; USER_IDS=$2; shift ;;
+ --no-restart) RESTART=no ;;
+ --trust-folder-owner) TRUST_OWNER=yes ;;
+ -h | --help) sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
+ *) fail "Unknown option: $1" ;;
+ esac
+ shift
+done
+if [ -z "$DIR" ]; then
+ DIR=$(cd "$(dirname "$0")" && pwd)
+ if [ ! -f "$DIR/compose.yaml" ] && [ ! -f "$DIR/docker-compose.yml" ] && [ -f /opt/openmausbot/compose.yaml ]; then DIR=/opt/openmausbot; fi
+fi
+case "$DIR" in
+ /*) ;;
+ *) fail "--dir needs a full path, like /opt/openmausbot." ;;
+esac
+case "$DIR" in
+ *[!A-Za-z0-9/._-]*) fail "The install's folder may hold only letters, digits, / . _ and -." ;;
+esac
+
+# Writes stdin to `target` through a temporary file in STATE, root's folder, never through a path in the install's
+# folder; a target that is a link is refused, never written through.
+place() { # target mode
+ [ ! -L "$1" ] || fail "$1 is a link, so it was left alone."
+ tmp=$(mktemp "$STATE/.place.XXXXXX") || fail "Could not write in $STATE."
+ if ! cat >"$tmp" || ! chmod "$2" "$tmp" || ! mv -f "$tmp" "$1"; then
+ rm -f "$tmp"
+ fail "Could not write $1."
+ fi
+}
+write_status() { # file, then key=value lines
+ file=$1
+ shift
+ printf '%s\n' "$@" | place "$STATUS/$file" 644
+}
+status_value() { sed -n "s/^$2=//p" "$STATUS/$1" 2>/dev/null | head -n 1; }
+state_value() { sed -n "s/^$2=//p" "$STATE/$1" 2>/dev/null | head -n 1; }
+number() { case "$1" in '' | *[!0-9]*) echo 0 ;; *) echo "$1" ;; esac; }
+held() { grep -Eq '"updates"[[:space:]]*:[[:space:]]*"hold"' "$POLICY" 2>/dev/null; }
+held_word() { if held; then echo yes; else echo no; fi; }
+server_container() { (cd "$DIR" && docker compose ps -aq omb) 2>/dev/null | head -n 1; }
+# The server's container, and when it started: unchanged across a run, the run stopped nothing. A server that restarts by
+# itself during a run makes that run count as one that did.
+server_mark() {
+ cid=$(server_container)
+ [ -z "$cid" ] || docker inspect -f '{{.Id}} {{.State.StartedAt}}' "$cid" 2>/dev/null
+}
+server_image() {
+ cid=$(server_container)
+ [ -z "$cid" ] || docker inspect -f '{{.Image}}' "$cid" 2>/dev/null
+}
+# yes when the running image is labelled with a released version (a build of main is labelled with its branch).
+released() {
+ image=$(server_image)
+ label=$( [ -z "$image" ] || docker image inspect -f "{{index .Config.Labels \"$VERSION_LABEL\"}}" "$image" 2>/dev/null)
+ if printf '%s' "$label" | grep -Eqx 'v?[0-9]+\.[0-9]+\.[0-9]+'; then echo yes; else echo no; fi
+}
+write_runner() { write_status runner "layout=$1" "dir=$DIR" "held=$(held_word)" "release=$(released)"; }
+# The install's update.sh, when it is a file and root's copy is the same; a checkout's after a git pull is newer.
+# A file swapped for a pipe after the check would hold cmp for ever, and with it this oneshot: it gets ten seconds.
+same_updater() {
+ [ -f "$DIR/update.sh" ] && [ ! -L "$DIR/update.sh" ] || return 1
+ if command -v timeout >/dev/null 2>&1; then timeout 10 cmp -s "$DIR/update.sh" "$UPDATER"; else cmp -s "$DIR/update.sh" "$UPDATER"; fi
+}
+owner_of() { stat -L -c %u "$1" 2>/dev/null || stat -L -f %u "$1" 2>/dev/null; }
+mode_of() { # the permission bits, sticky included, as a number
+ m=$(stat -L -c %a "$1" 2>/dev/null) || m=$(stat -L -f %p "$1" 2>/dev/null | sed 's/.*\(....\)$/\1/')
+ printf '%d' "0$m"
+}
+stat_of() { stat -L -c "$1" "$3" 2>/dev/null || stat -L -f "$2" "$3" 2>/dev/null; }
+# "user:group mode" of a folder, as the refusal names it.
+folder_line() { printf '%s %o' "$(stat_of '%U:%G' '%Su:%Sg' "$1")" "$(mode_of "$1")"; }
+# A group whose only member is the folder's owner, of the owner's own name: the private group Ubuntu and Fedora give each
+# user, which their umask 002 makes every new folder writable by.
+private_group() {
+ user=$(stat_of %U %Su "$1")
+ # GNU stat says UNKNOWN for an id with no name: two of those are not one user's group.
+ [ -n "$user" ] && [ "$user" != UNKNOWN ] && [ "$user" = "$(stat_of %G %Sg "$1")" ] || return 1
+ entry=$(getent group "$user" 2>/dev/null) && [ -n "$entry" ] || return 1
+ members=$(printf '%s' "$entry" | cut -d: -f4)
+ [ -z "$members" ] || [ "$members" = "$user" ] || return 1
+ # Nor when anyone else has it as their own group, or the users cannot be listed to tell.
+ users=$(getent passwd 2>/dev/null) && [ -n "$users" ] || return 1
+ [ -z "$(printf '%s\n' "$users" | awk -F: -v gid="$(printf '%s' "$entry" | cut -d: -f3)" -v user="$user" '$4 == gid && $1 != user')" ]
+}
+# True when someone besides root and the folder's owner may change it: writable by all without the sticky bit, or by a
+# group other than root's or the owner's private one.
+open_to_others() {
+ mode=$(mode_of "$1")
+ [ $((mode & 512)) = 0 ] || return 1
+ [ $((mode & 2)) = 0 ] || return 0
+ [ $((mode & 16)) != 0 ] || return 1
+ [ "$(stat_of %g %g "$1")" != 0 ] || return 1
+ ! private_group "$1"
+}
+# SECURITY: in a checkout the folder's owner can change what root runs here (its Compose files and .env decide what
+# `docker compose up` starts), and so can whoever may change the folder or rename one above it. Prints the problem and the
+# folder it is in, as "owner|writable PATH user:group mode": `owner` when the owner is neither root, nor in the docker
+# group, nor trusted at --install; `writable` when the folder, or one above it, is open to others (open_to_others), or a
+# folder above it belongs to anyone but root and that owner.
+folder_problem() {
+ owner=$(owner_of "$DIR")
+ if [ "$owner" != 0 ]; then
+ name=$(stat_of %U %Su "$DIR")
+ case " $(id -nG "$name" 2>/dev/null) " in
+ *" docker "*) ;;
+ *) [ "$TRUST_OWNER" = yes ] || { [ "$MODE" = run ] && [ "$(state_value trust dir)" = "$DIR" ]; } || { echo "owner $DIR $(folder_line "$DIR")"; return 0; } ;;
+ esac
+ fi
+ if open_to_others "$DIR"; then echo "writable $DIR $(folder_line "$DIR")"; return 0; fi
+ parent=$(dirname "$DIR")
+ while :; do
+ up=$(owner_of "$parent")
+ if { [ "$up" != 0 ] && [ "$up" != "$owner" ]; } || open_to_others "$parent"; then echo "writable $parent $(folder_line "$parent")"; return 0; fi
+ [ "$parent" = / ] && return 0
+ parent=$(dirname "$parent")
+ done
+}
+
+# update.sh's exit code, as the server reads it (deploy/update.sh lists them).
+result_of() {
+ case "$1" in
+ 0) echo updated ;;
+ 1) echo rolled-back ;;
+ 2) echo rollback-failed ;;
+ 3) echo busy ;;
+ 4) echo refused ;;
+ 5) echo older ;;
+ 6) echo no-room ;;
+ *) echo failed ;;
+ esac
+}
+
+# systemd starts this when the request appears, the owner's policy changes or .env does (an update pins its image there):
+# what the status says of the hold and of the running image is said again each time.
+run_requested() {
+ [ -d "$STATUS" ] || exit 0
+ layout=$(status_value runner layout)
+ if [ -n "$layout" ]; then write_runner "$layout"; fi
+ [ -e "$REQUESTS/request" ] || [ -L "$REQUESTS/request" ] || exit 0
+ # The server's files, in the server's folder: removed (a link itself, never what it names), never read. `fresh` says the
+ # server's own check knows of a newer stable version than the last answer: then that answer is checked, not reused.
+ fresh=no
+ if [ -e "$REQUESTS/fresh" ] || [ -L "$REQUESTS/fresh" ]; then fresh=yes; fi
+ rm -rf -- "$REQUESTS/request" "$REQUESTS/fresh"
+ run=$(($(number "$(status_value last run)") + 1))
+ ran=$(number "$(status_value last ran)")
+ since=$(($(date +%s) - $(number "$(status_value last at)")))
+ if [ "$since" -lt "$QUIET_S" ]; then sleep $((QUIET_S - since)); fi
+ now=$(date +%s)
+ version=""
+ detail=""
+ done_with() { write_status last "run=$run" state=done "result=$1" "at=$(date +%s)" "ran=$ran" ${version:+"version=$version"} ${detail:+"detail=$detail"}; }
+ if held; then done_with held; return; fi
+ problem=$(folder_problem)
+ if [ -n "$problem" ]; then detail=${problem#* }; done_with unsafe; return; fi
+ image=$(server_image)
+ if [ "$(released)" != yes ]; then done_with unreleased; return; fi
+ if [ ! -f "$UPDATER" ] || [ ! -f "$DIR/update.sh" ] || [ -L "$DIR/update.sh" ]; then done_with no-updater; return; fi
+ if ! same_updater; then done_with stale; return; fi
+ ask_target() { OMB_UPDATE_BY_RUNNER=1 bash "$UPDATER" --dir "$DIR" --print-target </dev/null 2>/dev/null; }
+ target=""
+ # Nothing to do a moment ago, on the same image: the same answer, without asking GitHub or the registry again; when the
+ # server knows of a newer version, only GitHub is asked whether the stable image is still the same.
+ if [ "$(state_value idle image)" = "$image" ] && [ $((now - $(number "$(state_value idle at)"))) -lt "$IDLE_S" ]; then
+ if [ "$fresh" = yes ]; then target=$(ask_target) || { done_with refused; return; }; fi
+ if [ "$fresh" = no ] || [ "${target% *}" = "$(state_value idle target)" ]; then
+ version=$(state_value idle version)
+ done_with updated
+ return
+ fi
+ fi
+ if [ $((now - ran)) -lt "$GAP_S" ]; then done_with too-soon; return; fi
+ [ -n "$target" ] || target=$(ask_target) || { done_with refused; return; }
+ version=${target##* }
+ if [ "$(state_value blocked image)" = "$image" ] && [ "$(state_value blocked target)" = "${target% *}" ]; then done_with not-retried; return; fi
+ write_status last "run=$run" state=running "at=$now" "ran=$ran" "version=$version"
+ before=$(server_mark)
+ code=0
+ OMB_UPDATE_BY_RUNNER=1 bash "$UPDATER" --dir "$DIR" </dev/null || code=$?
+ if [ -z "$before" ] || [ "$before" != "$(server_mark)" ]; then ran=$now; fi
+ rm -f "$IDLE"
+ if [ "$code" = 0 ] && [ "$ran" != "$now" ]; then printf '%s\n' "image=$image" "at=$now" "target=${target% *}" "version=$version" | place "$IDLE" 600; fi
+ if [ "$code" = 1 ]; then printf '%s\n' "image=$image" "target=${target% *}" | place "$BLOCKED" 600; fi
+ if [ "$code" = 0 ] && [ "$ran" = "$now" ]; then rm -f "$BLOCKED"; fi
+ done_with "$(result_of "$code")"
+}
+
+need_root() {
+ [ "$(id -u)" = 0 ] || fail "Run this as root: sudo $0 $*"
+}
+
+layout_of() {
+ if [ -f "$DIR/compose.yaml" ] && grep -qF "$INSTALLER_MARK" "$DIR/compose.yaml"; then echo installer
+ elif [ -f "$DIR/compose.yaml" ] || [ -f "$DIR/docker-compose.yml" ]; then echo compose
+ fi
+}
+
+# The checkout's own Compose file stays as git has it: the two folders go in Compose's override file beside it.
+override_file() {
+ if [ -f "$DIR/compose.yaml" ]; then echo "$DIR/compose.override.yaml"; else echo "$DIR/docker-compose.override.yml"; fi
+}
+
+check_override() {
+ file=$(override_file)
+ [ ! -L "$file" ] || fail "$file is a link, so it was left alone."
+ if [ -f "$file" ] && ! grep -qF "$OVERRIDE_MARK" "$file"; then
+ fail "$file is yours, so it was left alone. Add this to its omb service, then run this again:
+ volumes:
+ - $REQUESTS:$IN_CONTAINER/request
+ - $STATUS:$IN_CONTAINER/status:ro"
+ fi
+ if grep -q '^COMPOSE_FILE=' "$DIR/.env" 2>/dev/null; then
+ fail "$DIR/.env names its Compose files (COMPOSE_FILE), so Compose would not read $file. Add $(basename "$file") to COMPOSE_FILE, then run this again."
+ fi
+}
+
+write_override() {
+ place "$(override_file)" 644 <<OVERRIDE
+$OVERRIDE_MARK: the Update server button's two folders, the request one the server writes to and the status one
+# it reads. update-runner.sh --remove takes this file away.
+services:
+ omb:
+ volumes:
+ - $REQUESTS:$IN_CONTAINER/request
+ - $STATUS:$IN_CONTAINER/status:ro
+OVERRIDE
+}
+
+# The user and group that own the server's /data on the host, as numbers: the container runs as them.
+data_owner() {
+ cid=$( (cd "$DIR" && docker compose ps -aq omb) 2>/dev/null | head -n 1)
+ [ -n "$cid" ] || return 0
+ source=$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Source}}{{end}}{{end}}' "$cid" 2>/dev/null)
+ [ -n "$source" ] || return 0
+ stat -c '%u:%g' "$source" 2>/dev/null || stat -f '%u:%g' "$source" 2>/dev/null
+}
+
+# SECURITY: in a checkout the folder's owner can change what root runs here (its Compose files and .env decide what
+# `docker compose up` starts). Fine when that owner is root or may run Docker already; anyone else, only when asked.
+check_owner() {
+ problem=$(folder_problem)
+ where=${problem#* }
+ case "$problem" in
+ owner*) fail "${where% * *} (${where#* }) belongs to someone who cannot run Docker. Whoever owns it can change what root runs when the app asks for an update (its Compose files and .env decide what docker compose up starts). Move it to a folder root owns, or run this again with --trust-folder-owner if that is what you want." ;;
+ writable*) fail "${where% * *} (${where#* }) can be changed by someone other than root and the owner of $DIR, who could then change what root runs when the app asks for an update. Make it writable by its owner only (chmod go-w ${where% * *}), then run this again." ;;
+ esac
+}
+
+install_button() {
+ need_root --install
+ if ! command -v systemctl >/dev/null 2>&1 || [ ! -d "$SYSTEMD_DIR" ]; then
+ fail "This server has no systemd, so the app cannot update it. Update it here instead: cd $DIR && sudo ./update.sh"
+ fi
+ [ -f "$DIR/update.sh" ] || fail "There is no update.sh in $DIR. Get it first (git pull, or run the installer again)."
+ layout=$(layout_of)
+ [ -n "$layout" ] || fail "There is no compose.yaml or docker-compose.yml in $DIR. Name the install's folder: --dir PATH"
+ [ "$layout" = installer ] || check_override
+ check_owner
+ other=$(status_value runner dir)
+ if [ -n "$other" ] && [ "$other" != "$DIR" ]; then
+ fail "This server's button already updates $other: one install per server. To move it: sudo $0 --remove --dir $other, then run this again."
+ fi
+ [ -n "$USER_IDS" ] || USER_IDS=$(data_owner)
+ case "$USER_IDS" in
+ *[!0-9:]* | : | :* | *: | *:*:* | "") fail "Could not tell who owns the server's data. Start it first (docker compose up -d), or name the owner: --user UID:GID" ;;
+ esac
+ [ ! -L "$STATE" ] || fail "$STATE is a link, so it was left alone."
+ install -d -m 0755 -o 0 -g 0 "$STATE" "$STATUS"
+ install -d -m 0700 -o "${USER_IDS%%:*}" -g "${USER_IDS##*:}" "$REQUESTS"
+ install -d -m 0755 "$SBIN_DIR"
+ # Root's own copies: a checkout's folder is its owner's, so what root runs never comes from it at the time of a run.
+ place "$UPDATER" 755 <"$DIR/update.sh"
+ place "$SBIN_DIR/$RUNNER" 755 <"$0"
+ # Root's own settings at the time of the install, never anything the server writes.
+ extra=""
+ for name in OMB_STABLE_URL OMB_NEWEST_URL OMB_UPDATE_WAIT_S OMB_RUNNER_GAP_S OMB_RUNNER_QUIET_S OMB_RUNNER_IDLE_S; do
+ value=$(printenv "$name" || true)
+ case "$value" in '' | *[!A-Za-z0-9:/._-]*) ;; *) extra="$extra $name=$value" ;; esac
+ done
+ place "$SYSTEMD_DIR/$UNIT.path" 644 <<UNIT
+[Unit]
+Description=Runs MausBot's update.sh when the server asks (Settings, Update server)
+
+[Path]
+PathExists=$REQUESTS/request
+PathChanged=$POLICY
+PathChanged=$DIR/.env
+
+[Install]
+WantedBy=multi-user.target
+UNIT
+ place "$SYSTEMD_DIR/$UNIT.service" 644 <<UNIT
+[Unit]
+Description=MausBot's update.sh for $DIR, asked for from the app
+
+[Service]
+Type=oneshot
+Environment=HOME=/root OMB_INSTALL_DIR=$DIR$extra
+ExecStart=$SBIN_DIR/$RUNNER
+TimeoutStartSec=4h
+UNIT
+ systemctl daemon-reload >/dev/null 2>&1 || true
+ systemctl enable --now "$UNIT.path" >/dev/null 2>&1 || fail "systemd did not switch on $UNIT.path. See: systemctl status $UNIT.path"
+ [ "$layout" = installer ] || write_override
+ [ -f "$STATUS/last" ] || write_status last run=0 state=done result=updated at=0 ran=0
+ rm -f "$BLOCKED" "$IDLE" "$TRUST"
+ if [ "$TRUST_OWNER" = yes ]; then printf '%s\n' "dir=$DIR" | place "$TRUST" 600; fi
+ write_runner "$layout"
+ if [ "$RESTART" = yes ]; then
+ say "Restarting the server so it sees the button's folders..."
+ (cd "$DIR" && docker compose up -d --no-build) >/dev/null || fail "docker compose up -d did not finish. Run it in $DIR."
+ fi
+ say "The app can update this server now: Settings, Updates, Update server. After a git pull, run this again so it uses the new update.sh. To take the button away: sudo $0 --remove"
+}
+
+remove_button() {
+ need_root --remove
+ other=$(status_value runner dir)
+ if [ -n "$other" ] && [ "$other" != "$DIR" ]; then
+ fail "This server's button updates $other, not $DIR, so nothing was removed. To remove it: sudo $0 --remove --dir $other"
+ fi
+ if command -v systemctl >/dev/null 2>&1; then systemctl disable --now "$UNIT.path" >/dev/null 2>&1 || true; fi
+ rm -f "$SYSTEMD_DIR/$UNIT.path" "$SYSTEMD_DIR/$UNIT.service" "$SBIN_DIR/$RUNNER"
+ if command -v systemctl >/dev/null 2>&1; then systemctl daemon-reload >/dev/null 2>&1 || true; fi
+ for file in "$DIR/compose.override.yaml" "$DIR/docker-compose.override.yml"; do
+ if [ -f "$file" ] && [ ! -L "$file" ] && grep -qF "$OVERRIDE_MARK" "$file"; then rm -f "$file"; fi
+ done
+ if [ ! -L "$STATE" ]; then rm -rf -- "$STATE"; fi
+ say "The app no longer updates this server. Update it here: cd $DIR && sudo ./update.sh"
+}
+
+case "$MODE" in
+ install) install_button ;;
+ remove) remove_button ;;
+ *) run_requested ;;
+esac
diff --git a/deploy/update.sh b/deploy/update.sh
index 9ee7f5c02a..142df1ea25 100755
--- a/deploy/update.sh
+++ b/deploy/update.sh
@@ -26,6 +26,8 @@
# 3 another update is running here
# 4 nothing was changed: refused, could not download, the folder cannot be written, or a question was not answered
# 5 nothing was changed: the version asked for is older than the one running, or either version cannot be told
+# 6 nothing was changed: not enough free disk for a copy of the data (only on a run update-runner.sh started;
+# anyone else gets 4)
# 130 interrupted (Ctrl-C) before the new version started: nothing was changed, and the server was started again
set -uo pipefail
# SECURITY: the files this writes beside the Compose file (compose.yaml, Caddyfile) are what root starts; their modes never
@@ -45,6 +47,13 @@ SERVICE=${OMB_UPDATE_SERVICE:-omb}
WAIT_S=${OMB_UPDATE_WAIT_S:-120}
ENGINE_WAIT_S=${OMB_UPDATE_ENGINE_WAIT_S:-120}
POLL_S=${OMB_UPDATE_POLL_S:-5}
+# Set by update-runner.sh: an update the server asked for (the app's Update server button). Whatever runs as the server's
+# user can ask, so such a run trusts nothing the server says, writes nothing through a link in the install's folder,
+# labels its copy of the data as the runner's, and keeps the runner's two newest copies and every copy a person's run made.
+BY_RUNNER=${OMB_UPDATE_BY_RUNNER:-}
+RUNNER_COPY="com.mausbot.by=runner"
+# The runner's own folder: a person's run here lets the button try again a version it gave up on (update-runner.sh).
+RUNNER_STATE=${OMB_UPDATE_STATE_DIR:-/var/lib/openmausbot-update}
KEEP_TAG="openmausbot-before-update:local"
BACKUP_ROLE="com.mausbot.role=update-backup"
@@ -75,7 +84,7 @@ exec 3>&1
exec 4<&0 </dev/null
say() {
printf '%s\n' "$*" >&3 2>/dev/null
- if [ -d "$STATE" ]; then printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG" 2>/dev/null; fi
+ if [ -d "$STATE" ] && [ ! -L "$STATE" ] && [ ! -L "$LOG" ]; then printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG" 2>/dev/null; fi
return 0
}
refuse() {
@@ -197,7 +206,29 @@ phase() {
write_record "$JOURNAL"
}
+file_owner() { stat -c %u "$1" 2>/dev/null || stat -f %u "$1" 2>/dev/null; }
+# SECURITY: at the server's request, root runs this in a folder its owner can change (a checkout): then nothing is written
+# through a link there, nor into a .update that belongs to anyone but this user or the folder's owner. A person's own run
+# is theirs to decide, links included.
+unsafe_path() {
+ local path owner
+ for path in "$STATE" "$JOURNAL" "$JOURNAL.tmp" "$LAST" "$LAST.tmp" "$LOCK" "$LOG" "$STATE/env.before" "$STATE/env.absent" \
+ "$STATE/compose.yaml.before" "$STATE/Caddyfile.before" .env .env.update.tmp compose.yaml compose.yaml.update.tmp Caddyfile Caddyfile.update.tmp; do
+ if [ -L "$path" ]; then printf '%s is a link' "${path#"$DIR"/}"; return 0; fi
+ done
+ if [ -d "$STATE" ]; then
+ owner=$(file_owner "$STATE")
+ if [ "$owner" != "$(id -u)" ] && [ "$owner" != "$(file_owner "$DIR")" ]; then printf '.update belongs to someone else'; return 0; fi
+ fi
+ return 1
+}
+
take_lock() {
+ local unsafe
+ if [ "$BY_RUNNER" = 1 ] && unsafe=$(unsafe_path); then
+ printf '%s\n' "$DIR/$unsafe, so nothing was changed: this script does not write through it. Remove it, then run this again."
+ exit 4
+ fi
if ! mkdir -p "$STATE" 2>/dev/null || ! chmod 700 "$STATE" 2>/dev/null || [ ! -w "$STATE" ] || [ ! -w "$DIR" ]; then
printf '%s\n' "$DIR cannot be written by this user, so the update could not keep its journal or change .env. Nothing was changed. Run it as the user who owns $DIR, or with sudo."
exit 4
@@ -241,15 +272,26 @@ new_backup_name() {
printf '%s' "$name"
}
make_backup_volume() { # name image
- docker volume create --label "$BACKUP_ROLE" --label "com.mausbot.project=$J_project" --label "com.mausbot.data=$J_data" --label "com.mausbot.image=$2" "$1" >/dev/null
+ local by=()
+ [ "$BY_RUNNER" = 1 ] && by=(--label "$RUNNER_COPY")
+ docker volume create --label "$BACKUP_ROLE" --label "com.mausbot.project=$J_project" --label "com.mausbot.data=$J_data" --label "com.mausbot.image=$2" ${by[@]+"${by[@]}"} "$1" >/dev/null
}
copy_aside() { # data backup image: copy, then check the copy against the data, file by file
docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint cp "$3" -a /from/. /to/ || return 1
helper "$3" "$1:/from:ro" "$2:/to:ro" -- "$VERIFY"'same /from /to'
}
-# Every copy of this install's data but the one this update made: dropped once that one has been checked.
+# Every copy of this install's data but the one this update made, dropped once that one has been checked. On a run the
+# server asked for, only the runner's own, and never the newest one before this: a server that damaged its data and then
+# asked would otherwise leave only the damaged copy.
drop_older_copies() {
- local volume
+ local volume keep=1
+ if [ "$BY_RUNNER" = 1 ]; then
+ for volume in $(docker volume ls -q --filter "label=$BACKUP_ROLE" --filter "label=com.mausbot.data=$J_data" --filter "label=$RUNNER_COPY" 2>/dev/null | LC_ALL=C sort -r); do
+ [ "$volume" = "$J_backup" ] && continue
+ if [ "$keep" -gt 0 ]; then keep=$((keep - 1)); else docker volume rm -f "$volume" >>"$LOG" 2>&1; fi
+ done
+ return 0
+ fi
for volume in $(docker volume ls -q --filter "label=$BACKUP_ROLE" --filter "label=com.mausbot.data=$J_data" 2>/dev/null); do
[ "$volume" = "$J_backup" ] || docker volume rm -f "$volume" >>"$LOG" 2>&1
done
@@ -343,6 +385,10 @@ services:
volumes:
- ./data:/data
- edge:/run/openmausbot
+ # The Update server button (update-runner.sh, root's folder): the server leaves a request in the first, reads the
+ # outcome in the second.
+ - /var/lib/openmausbot-update/request:/run/omb-update/request
+ - /var/lib/openmausbot-update/status:/run/omb-update/status:ro
environment:
OMB_PORT: "8799"
OMB_WEBHOOK_PORT: "8800"
@@ -625,6 +671,38 @@ interrupted() {
exit 130
}
+# The image and version a plain run takes: the stable channel's, or the newest release before any is stable. Sets
+# CHANNEL, J_target and J_version, or refuses.
+resolve_target() {
+ CHANNEL=""
+ if [ -n "$WANT_IMAGE" ]; then
+ J_target=$WANT_IMAGE
+ elif [ -n "$WANT_VERSION" ]; then
+ J_target="$REPO:v$WANT_VERSION"
+ J_version=$WANT_VERSION
+ else
+ fetch "$STABLE_URL"
+ case $? in
+ 0)
+ CHANNEL=stable
+ J_target=$(printf '%s' "$BODY" | json_top image)
+ J_version=$(printf '%s' "$BODY" | json_top version)
+ printf '%s' "$J_target" | grep -Eq "$PINNED" && is_version "$J_version" || refuse "The stable channel names no image this script accepts. Nothing was changed."
+ ;;
+ 1)
+ # No version has been made stable yet: the newest release, as the server's own update check says then.
+ fetch "$NEWEST_URL" || refuse "Could not find the newest release ($NEWEST_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z"
+ J_version=$(printf '%s' "$BODY" | json_top tag_name)
+ J_version=${J_version#v}
+ is_version "$J_version" || refuse "The newest release names no version this script accepts. Nothing was changed."
+ CHANNEL=newest
+ J_target="$REPO:v$J_version"
+ ;;
+ *) refuse "Could not read the stable channel ($STABLE_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z" ;;
+ esac
+ fi
+}
+
usage() {
sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'
exit "${1:-0}"
@@ -641,6 +719,7 @@ while [ $# -gt 0 ]; do
--yes | -y) ASSUME_YES=yes ;;
--replace-local-build) REPLACE_BUILD=yes ;;
--allow-older) ALLOW_OLDER=yes ;;
+ --print-target) MODE=target ;;
-h | --help) usage 0 ;;
*) printf 'Unknown option: %s\n\n' "$1"; usage 4 ;;
esac
@@ -648,12 +727,20 @@ while [ $# -gt 0 ]; do
done
if [ -n "$WANT_VERSION" ] && ! is_version "$WANT_VERSION"; then refuse "--version takes a released version such as 0.1.151."; fi
+# update-runner.sh asks what a plain run would take before it runs one: "image version", nothing changed.
+if [ "$MODE" = target ]; then
+ resolve_target
+ printf '%s %s\n' "$J_target" "$J_version"
+ exit 0
+fi
+
docker 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"
if [ "$MODE" != check ]; then
take_lock
trap interrupted INT TERM
+ if [ "$BY_RUNNER" != 1 ] && grep -qx "dir=$DIR" "$RUNNER_STATE/status/runner" 2>/dev/null; then rm -f "$RUNNER_STATE/blocked" 2>/dev/null; fi
recover
fi
@@ -681,36 +768,16 @@ if [ "$(inspect '{{.State.Running}}' "$CID")" = true ]; then J_running=yes; else
# branch, not a version, and says the version of the release it was built after.
RUNNING_VERSION=""
[ "$J_running" = yes ] && RUNNING_VERSION=$(reported_version)
-is_version "$RUNNING_VERSION" || RUNNING_VERSION=$J_previous_version
-
-CHANNEL=""
-if [ -n "$WANT_IMAGE" ]; then
- J_target=$WANT_IMAGE
-elif [ -n "$WANT_VERSION" ]; then
- J_target="$REPO:v$WANT_VERSION"
- J_version=$WANT_VERSION
-else
- fetch "$STABLE_URL"
- case $? in
- 0)
- CHANNEL=stable
- J_target=$(printf '%s' "$BODY" | json_top image)
- J_version=$(printf '%s' "$BODY" | json_top version)
- printf '%s' "$J_target" | grep -Eq "$PINNED" && is_version "$J_version" || refuse "The stable channel names no image this script accepts. Nothing was changed."
- ;;
- 1)
- # No version has been made stable yet: the newest release, as the server's own update check says then.
- fetch "$NEWEST_URL" || refuse "Could not find the newest release ($NEWEST_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z"
- J_version=$(printf '%s' "$BODY" | json_top tag_name)
- J_version=${J_version#v}
- is_version "$J_version" || refuse "The newest release names no version this script accepts. Nothing was changed."
- CHANNEL=newest
- J_target="$REPO:v$J_version"
- ;;
- *) refuse "Could not read the stable channel ($STABLE_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z" ;;
- esac
+if [ "$BY_RUNNER" = 1 ]; then
+ # SECURITY: a server that says it is older than its image would be "updated" down onto data a newer version wrote.
+ if [ -n "$RUNNING_VERSION" ] && [ "$RUNNING_VERSION" != "$J_previous_version" ]; then
+ refuse "The server says it is version $RUNNING_VERSION, but its image is ${J_previous_version:-not a released version}. An update asked for from the app goes by the image alone, so nothing was changed. To update anyway, run ./update.sh here."
+ fi
+ RUNNING_VERSION=$J_previous_version
fi
+is_version "$RUNNING_VERSION" || RUNNING_VERSION=$J_previous_version
+resolve_target
# Why the version asked for may not replace the one running without --allow-older, or nothing.
older_reason() {
if [ -z "$J_version" ]; then
@@ -782,7 +849,9 @@ fi
BACKUP_MADE=yes
if ! make_backup_volume "$J_backup" "$J_previous_id" || ! room_for_copy "$J_data" "$J_backup" "$J_previous_id"; then
abandon
- refuse "There is not enough free disk for a copy of the data: it needs about ${NEEDED_MB:-?} MB and ${FREE_MB:-?} MB are free. Free some space, then run this again. Nothing was changed."
+ say "There is not enough free disk for a copy of the data: it needs about ${NEEDED_MB:-?} MB and ${FREE_MB:-?} MB are free. Free some space, then run this again. Nothing was changed."
+ if [ "$BY_RUNNER" = 1 ]; then exit 6; fi
+ exit 4
fi
J_engine=unknown
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index 2e1ec8f683..1047dcefd3 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -349,6 +349,115 @@ compares your server with the stable version. To hear of every release as soon
as it is published instead, set `OMB_UPDATE_CHANNEL=newest` in the server's
environment.
+### From the app: Update server
+
+On a Docker install, the server's admins can update it from **Settings →
+Updates → Update server**, in the desktop app or a browser. It runs the
+`update.sh` described below: the stable version, a copy of the data first, and
+the old version and its data back when the new one is not healthy. The app asks
+first (the server restarts, so anything running stops, and it says how many
+chats have a bot answering), shows "Updating the server…" while the server is
+away, reconnects by itself, then says which version it runs now, or that it
+went back and why. After 15 minutes without the server it says so, with the
+commands to see its log and to go back. In the desktop app, once the server is
+newer than the app, the same row offers the app's own update. With
+`OMB_UPDATE_CHANNEL=newest` the app shows the command instead, because
+`update.sh` takes the stable version. A server on a build of main (the `latest`
+image, which a checkout runs when `.env` names no `OMB_IMAGE`) gets no button:
+the app says so, with `sudo ./update.sh`, which moves it to the stable version
+once that is newer than the build.
+
+The installer sets this up, and every run of the installer refreshes it. In a
+checkout of this repository, add it from `OpenMausBot/deploy` (it needs
+systemd, and restarts the server once), and run the same command again after
+each `git pull`: until you do, the button runs nothing and the app shows this
+command.
+
+```sh
+git pull && sudo ./update-runner.sh --install
+```
+
+That places `/usr/local/sbin/openmausbot-update-runner`, the systemd units
+`openmausbot-update.path` and `openmausbot-update.service`, and root's folder
+`/var/lib/openmausbot-update`: root's own copy of `update.sh`, which is what
+the button runs, `request`, which the server's container writes, and `status`,
+which it reads and cannot write. One install per server: a second folder is
+refused until `--remove` on the first, and `--remove` for any other folder
+removes nothing. A checkout gets
+`docker-compose.override.yml` to mount the two (an override of your own, or a
+link, is left alone, and the script says what to add). `sudo
+./update-runner.sh --remove` takes it all away.
+
+**A checkout's owner decides what root runs.** The button's update runs as
+root, but in your checkout: its Compose files and `.env` decide what `docker
+compose up` starts. So whoever owns that folder can change what root runs
+when the app asks for an update. `--install` accepts a folder owned by root or
+by someone in the `docker` group (who can run anything as root through Docker
+already), and anyone else only with `--trust-folder-owner`. The folder, and
+every folder above it, may be changed by root and that owner only: not by
+everyone (unless it has its sticky bit, as `/tmp` does), and not by a group
+other than root's or the owner's own private group (the one Ubuntu and Fedora
+give each user, which their default umask makes new folders writable by). The
+runner checks all this again at every run, and runs nothing when it no longer
+holds; the refusal names the folder, its owner, group and mode, and the app
+shows it with the `--install` command. A fresh server installed with the
+installer passes as it is. On an update the
+app asked for, `update.sh` writes nothing through a link there (`.update`,
+`.env`, the Compose files and its temporary files), nor into a `.update` that
+belongs to anyone but you or the folder's owner; your own run of
+`./update.sh` uses links there as before.
+
+**Who can ask.** Only an admin's own signed-in session sees and presses the
+button; members never see it, and Clouds that MausBot runs never show it. The
+request itself is a file in a folder of the server's user, and until the bots'
+sandbox is on for self-hosted servers, bots run as that user: anything running
+on the server as that user, a bot or a prompt injection included, can leave the
+same file. So the runner treats whoever asks as hostile. What any number of
+requests can cause:
+
+- For each stable image that is out, at most one update: the server stops, its
+ data is copied, the new version starts, and if it is not healthy the old
+ version and the copy come back. That stable image is then not tried again
+ from the app on this server until you run `./update.sh` yourself or another
+ stable image is out. So a compromised server can keep one stable release from
+ being tried from the app, by making it fail on purpose; whoever presses the
+ button is told, with the command to try it by hand. It is taken only when
+ the running image's own label is
+ not newer (never by the version the server says it runs; when the two
+ disagree nothing changes); a stable image that names the same version as the
+ running one under a new digest (a re-published image) is taken too.
+- At most three copies of the data: the two newest that updates from the app
+ made, and the last one your own run of `./update.sh` made, which an update
+ from the app never removes. While the next copy is made and checked, that is
+ about three times the data plus the new copy; `update.sh` refuses to start
+ when the disk has no room for it, and the app then says so, with the commands
+ to list and remove old copies (below).
+- Updates that stop the server at most once every four minutes. A run with
+ nothing to do stops nothing and does not count, and for five minutes the
+ same answer is given without asking GitHub or the registry again (when the
+ server's own check knows of a newer version, only GitHub is asked whether
+ the stable image changed); any two runs are at least 30 seconds apart. A run during which the server restarts
+ by itself counts as one that stopped it, so it can delay an admin's press by
+ up to four minutes.
+- Nothing while `/etc/mausbot/policy.json` holds updates
+ (`"updates": "hold"`).
+
+It cannot choose a version, image, URL, flag or path, cannot downgrade or roll
+back (an update an earlier run left unfinished waits for you at a terminal), and
+cannot write the runner's status, `update.sh`, `.env` or the Compose files. So
+the most it can cause is one stop, copy and restart (and rollback, when the
+version fails here) per stable release, which the admins would have pressed for
+anyway.
+
+**Copies of the data.** An update asked for from the app keeps your own last
+copy and its own two newest ones. A run of `./update.sh` at a terminal removes all
+but its own once that one has been checked, as above. To see them:
+`docker volume ls --filter label=com.mausbot.role=update-backup`; to remove one
+yourself: `docker volume rm <name>`.
+
+Without the runner (no systemd, an npm install, Podman) the app shows the
+command to run on the server instead.
+
### Path B (Docker): one command, with a way back
From `OpenMausBot/deploy`:
diff --git a/docs/design/self-hosted-design.md b/docs/design/self-hosted-design.md
index a54ac1613c..2b0583d84e 100644
--- a/docs/design/self-hosted-design.md
+++ b/docs/design/self-hosted-design.md
@@ -62,7 +62,14 @@ The published lists of principles 5 and 6 are the docs page
previous image and the backup, and report it.
- The rule that makes rollback safe: version N's data must stay readable by N-1. The data directory carries a schema
marker; a change that breaks the rule ships in two releases (read the new format first, write it one release later).
-- Standalone servers get the same update as one command they run themselves.
+- Standalone servers get the same update as one command they run themselves, or from **Update server** in the app on a
+ Docker install whose host has `deploy/update-runner.sh` (the installer adds it): the server only leaves a request
+ file, and root's runner on the host runs its own copy of `update.sh` with no arguments taken from it. Anything
+ running as the server's user can leave that file (bots too, while the sandbox is off on self-hosted servers), so such
+ a run goes by the image's label only, tries each stable image once (never again after a rollback until a person runs
+ update.sh), keeps the person's own copy of the data and its own two newest ones, and stops the server at most every
+ four minutes. Not through the connector:
+ that needs enrolling, and its runner takes an image from its request.
- Skew: desktop and phone apps work with any stable server from the last 90 days; an older server shows a banner.
## Entitlements
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 0c0ae0d930..f0a680f775 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1501,6 +1501,13 @@ every release instead.
A server installed with the [installer](deploy-vps.md#quick-start-one-command-on-your-own-domain)
updates with `sudo /opt/openmausbot/update.sh`, which the installer puts there.
+Its admins can also press **Update server** in **Settings → Updates**, which runs
+that same script on the server; a Docker checkout gets the button with
+`sudo deploy/update-runner.sh --install`. Until the bots' sandbox is on for
+self-hosted servers, a bot can ask for the same update, so the runner allows only
+the standard forward update, once per stable release, and never removes your own
+copy of the data. [How it works and
+what it can and cannot do](deploy-vps.md#from-the-app-update-server).
```sh
cd deploy && git pull && ./update.sh # Docker: copy the data, update, roll back on failure
diff --git a/electron/main.mjs b/electron/main.mjs
index 3c2acc4775..8645df64e9 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2950,7 +2950,7 @@ app.whenReady().then(async () => {
}
registerCuaIpc();
androidDevice.registerIpc(ipcMain);
- registerUpdaterIpc({ pageAllowed: updaterPageAllowed });
+ registerUpdaterIpc({ pageAllowed: updaterPageAllowed, serverPage: event => activePageOrigin(event), confirmRestart: async (version, server) => Boolean(mainWindow && !mainWindow.isDestroyed()) && (await dialog.showMessageBox(mainWindow, { type: "question", message: nativeT("native.update.forServer", { version, server }), detail: nativeT("native.update.forServerDetail"), buttons: [nativeT("native.update.restartNow"), nativeT("native.update.notNow")], defaultId: 0, cancelId: 1, noLink: true })).response === 0 });
desktopPrefs = nativeText.prefs;
updatesConsent = registerDesktopPrefs({ ipcMain, cloudAccount: () => cloudAccount, prefs: desktopPrefs, localConfig: jsonFile(path.join(desktopDataDir(), "config.json")).read, cloudOffered: () => cloudAccountRestored().then(cloudOffersReady),
frame: { made: () => windowFrameMade, restarts: process.platform === "win32", changed: () => void broadcastDesktopCapabilities() },
diff --git a/electron/preload.cjs b/electron/preload.cjs
index e3594dffd2..a74c68bf36 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -74,7 +74,7 @@ function railKeepsItsSize() {
if (typeof window !== "undefined") {
for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });
}
-const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame", "softwareRendering"]);
+const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame", "softwareRendering", "appUpdate"]);
/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */
const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];
function updaterOffered() {
@@ -428,6 +428,13 @@ const bridge = {
reset: () => ipcRenderer.invoke("credential-store:reset"),
},
+ // A server's page from the Server menu, once that server is newer than this app, asks for this app's own update from
+ // the person's click. It learns only what was done; main asks in a dialog of its own before anything restarts.
+ appUpdate: {
+ request: () => navigator.userActivation?.isActive === true
+ ? ipcRenderer.invoke("update:for-server-page") : Promise.reject(new Error("Choose Update app.")),
+ },
+
updater: {
check: () => ipcRenderer.invoke("update:check"),
install: () => isLocalPage || navigator.userActivation?.isActive === true
diff --git a/electron/updater.mjs b/electron/updater.mjs
index 5f0044e372..5000bb9889 100644
--- a/electron/updater.mjs
+++ b/electron/updater.mjs
@@ -124,7 +124,36 @@ export function sendUpdaterState() {
setState({});
}
-export function registerUpdaterIpc({ pageAllowed: allowed }) {
+/** How long a server's page's answer stands before it may ask again: one click never opens a second dialog. */
+export const SERVER_PAGE_ASK_COOLDOWN_MS = 10_000;
+let serverPageAsk = null;
+
+async function askForServerPage(confirmRestart, server) {
+ if (!updaterCoordinator) return "unavailable";
+ if (state.status !== "downloaded") await updaterCoordinator.check(true);
+ if (state.status === "downloaded") {
+ if (!(await confirmRestart(state.version ?? "", server))) return "later";
+ updaterCoordinator.install();
+ return "installing";
+ }
+ if (state.status === "downloading" || state.status === "preparing" || state.status === "available") return "downloading";
+ return state.status === "error" ? "failed" : "current";
+}
+
+/** What a server's page learns when it asks for this app's own update; never the updater's state. Asks at once share
+ * one answer, and that answer stands for SERVER_PAGE_ASK_COOLDOWN_MS. `server`: the asking page's address, for the dialog. */
+export function updateForServerPage(confirmRestart, server = "", now = Date.now) {
+ if (serverPageAsk && (!serverPageAsk.done || now() - serverPageAsk.done < SERVER_PAGE_ASK_COOLDOWN_MS)) return serverPageAsk.answer;
+ const ask = { done: 0, answer: null };
+ ask.answer = askForServerPage(confirmRestart, server).finally(() => { ask.done = now(); });
+ serverPageAsk = ask;
+ return ask.answer;
+}
+
+/** `serverPage`: the address of the page this app's window shows when it may ask for this app's update
+ * (`update:for-server-page`), a server from the Server menu newer than the app; null for any other sender. Nothing restarts
+ * until `confirmRestart`, this app's own dialog naming that address, says so. */
+export function registerUpdaterIpc({ pageAllowed: allowed, serverPage = () => null, confirmRestart = async () => false }) {
pageAllowed = allowed;
const guarded = (channel, handler) => (event) => {
if (!pageAllowed(event)) throw new Error(`${channel} is only available in this app's window`);
@@ -133,6 +162,11 @@ export function registerUpdaterIpc({ pageAllowed: allowed }) {
ipcMain.handle("update:get-state", guarded("update:get-state", view));
ipcMain.handle("update:check", guarded("update:check", () => updaterCoordinator?.check(true)));
ipcMain.handle("update:install", guarded("update:install", () => updaterCoordinator?.install()));
+ ipcMain.handle("update:for-server-page", (event) => {
+ const server = serverPage(event);
+ if (!server) throw new Error("update:for-server-page is only available to the page this app's window shows");
+ return updateForServerPage(confirmRestart, server);
+ });
ipcMain.handle("update:seen", guarded("update:seen", () => {
if (!launch?.updated) return;
updateSeen(quietRecord());
diff --git a/electron/updater.test.mjs b/electron/updater.test.mjs
index f8bbfe3dff..c248333383 100644
--- a/electron/updater.test.mjs
+++ b/electron/updater.test.mjs
@@ -38,7 +38,7 @@ function mainRule() {
const start = source.indexOf("function myCloud() {"), end = source.indexOf("const savedWorkspace = id =>", start);
expect(start).toBeGreaterThanOrEqual(0);
expect(end).toBeGreaterThan(start);
- expect(source.includes("registerUpdaterIpc({ pageAllowed: updaterPageAllowed });"), "main.mjs wires the updater to updaterPageAllowed").toBe(true);
+ expect(source.includes("registerUpdaterIpc({ pageAllowed: updaterPageAllowed, serverPage: event => activePageOrigin(event), confirmRestart: "), "main.mjs wires the updater to updaterPageAllowed").toBe(true);
const signInStart = source.indexOf("function ensureCloudAccount() {"), signInEnd = source.indexOf("\n}\n", signInStart) + 3;
expect(signInStart).toBeGreaterThanOrEqual(0);
const window = { isDestroyed: () => false, webContents: null };
@@ -91,10 +91,10 @@ function mainRule() {
context.cloudSignInRestored = true;
signIn.options.onState(state);
};
- return { context, window, show, offered, launching, signedIn, pageAllowed: vm.runInContext("updaterPageAllowed", context) };
+ return { context, window, show, offered, launching, signedIn, pageAllowed: vm.runInContext("updaterPageAllowed", context), serverPage: (event) => vm.runInContext("activePageOrigin", context)(event) ?? null };
}
-async function load(pageAllowed) {
+async function load(pageAllowed, serverPage = undefined, confirmRestart = undefined) {
vi.resetModules();
fixture.handlers.clear();
const autoUpdater = new EventEmitter();
@@ -111,7 +111,7 @@ async function load(pageAllowed) {
autoUpdater.quitAndInstall = vi.fn();
fixture.autoUpdater = autoUpdater;
const updater = await import("./updater.mjs");
- updater.registerUpdaterIpc({ pageAllowed });
+ updater.registerUpdaterIpc({ pageAllowed, ...(serverPage ? { serverPage, confirmRestart } : {}) });
return { updater, autoUpdater, handlers: fixture.handlers };
}
@@ -341,11 +341,12 @@ it("downloads an update by itself: the first check after launch starts it, and n
it("My Cloud's page reads and drives the update channels, and another server's page is refused", async () => {
const rule = mainRule();
const { handlers } = await load(rule.pageAllowed);
- expect([...handlers.keys()].sort()).toEqual(["update:check", "update:get-state", "update:install", "update:seen"]);
+ expect([...handlers.keys()].sort()).toEqual(["update:check", "update:for-server-page", "update:get-state", "update:install", "update:seen"]);
const cloud = page(CLOUD);
rule.show(cloud, "cloud");
- for (const channel of handlers.keys()) expect(() => handlers.get(channel)(cloud.event), channel).not.toThrow();
+ const channels = [...handlers.keys()].filter((channel) => channel !== "update:for-server-page");
+ for (const channel of channels) expect(() => handlers.get(channel)(cloud.event), channel).not.toThrow();
rule.context.cloudAccount = { homeTarget: () => null, state: () => ({ status: "unavailable", account: { id: "a1" } }), isOwnCloud: () => false };
rule.context.rememberedHome = { accountId: "a1", origin: CLOUD };
expect(() => handlers.get("update:get-state")(cloud.event)).not.toThrow();
@@ -354,19 +355,19 @@ it("My Cloud's page reads and drives the update channels, and another server's p
rule.context.cloudAccount = { homeTarget: () => ({ origin: CLOUD }), state: () => ({ status: "connected", account: { id: "a1" } }), isOwnCloud: () => false };
rule.context.desktopRemoteAccess = { endpoint: "https://companion.example.test" };
- for (const channel of handlers.keys()) expect(() => handlers.get(channel)(cloud.event), channel).toThrow(/only available/);
+ for (const channel of channels) expect(() => handlers.get(channel)(cloud.event), channel).toThrow(/only available/);
rule.context.desktopRemoteAccess = false;
const other = page(OTHER);
rule.show(other, "vps");
- for (const channel of handlers.keys()) expect(() => handlers.get(channel)(other.event), channel).toThrow(/only available/);
+ for (const channel of channels) expect(() => handlers.get(channel)(other.event), channel).toThrow(/only available/);
expect(() => handlers.get("update:get-state")({ sender: other.webContents, senderFrame: { url: `${CLOUD}/` } })).toThrow(/only available/);
rule.show(cloud, "cloud");
expect(() => handlers.get("update:get-state")({ sender: cloud.webContents, senderFrame: { url: `${CLOUD}/` } })).toThrow(/only available/);
const local = page(LOCAL);
rule.show(local);
- for (const channel of handlers.keys()) expect(() => handlers.get(channel)(local.event), channel).not.toThrow();
+ for (const channel of channels) expect(() => handlers.get(channel)(local.event), channel).not.toThrow();
});
it("sends update news only to a page allowed to read it", async () => {
@@ -423,3 +424,36 @@ it("sends updater progress to a reopened window without restarting the updater",
expect(autoUpdater.eventNames().reduce((count, name) => count + autoUpdater.listenerCount(name), 0)).toBe(listenerCount);
expect(vi.getTimerCount()).toBe(timerCount);
});
+
+it("a server's page the window shows may ask for the app's own update: it learns only what was done, and nothing restarts unless the person says so", async () => {
+ const rule = mainRule();
+ const other = page(OTHER);
+ rule.show(other, "vps");
+ expect(rule.serverPage(other.event)).toBe(OTHER);
+ expect(rule.serverPage({ sender: other.webContents, senderFrame: { url: `${CLOUD}/` } })).toBeNull();
+ expect(rule.serverPage({ sender: page(OTHER).webContents, senderFrame: { url: `${OTHER}/` } })).toBeNull();
+ const answers = [];
+ const confirmRestart = vi.fn(async (version) => { answers.push(version); return answers.length > 1; });
+ const { updater, autoUpdater, handlers } = await load(rule.pageAllowed, rule.serverPage, confirmRestart);
+ const ask = handlers.get("update:for-server-page");
+ await expect(Promise.resolve().then(() => ask({ sender: page(OTHER).webContents, senderFrame: { url: `${OTHER}/` } }))).rejects.toThrow(/only available/);
+ expect(await ask(other.event)).toBe("unavailable");
+ updater.attachUpdaterWindow(rule.window);
+ updater.startUpdater();
+ // Checked and downloaded at the page's request; the person said Not now. Five asks at once open one dialog, which
+ // names the asking server.
+ vi.advanceTimersByTime(updater.SERVER_PAGE_ASK_COOLDOWN_MS);
+ expect(await Promise.all([1, 2, 3, 4, 5].map(() => ask(other.event)))).toEqual(["later", "later", "later", "later", "later"]);
+ expect(confirmRestart).toHaveBeenCalledTimes(1);
+ expect(confirmRestart).toHaveBeenCalledWith("2.0.0", OTHER);
+ expect(await ask(other.event)).toBe("later");
+ expect(confirmRestart).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(updater.SERVER_PAGE_ASK_COOLDOWN_MS);
+ expect(autoUpdater.quitAndInstall).not.toHaveBeenCalled();
+ await settle();
+ // Not the updater's state: the page never hears it, only what its own request did.
+ expect(other.webContents.send).not.toHaveBeenCalled();
+ expect(await ask(other.event)).toBe("installing");
+ expect(confirmRestart).toHaveBeenLastCalledWith("2.0.0", OTHER);
+ expect(autoUpdater.quitAndInstall).toHaveBeenCalledTimes(1);
+});
diff --git a/scripts/server-installer.test.ts b/scripts/server-installer.test.ts
index 40024c88d9..93a102d80a 100644
--- a/scripts/server-installer.test.ts
+++ b/scripts/server-installer.test.ts
@@ -1,5 +1,5 @@
import { spawnSync } from "node:child_process";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
@@ -19,7 +19,7 @@ const BOX_PASSED = '{"box":"bwrap","total":31,"passed":31,"failed":[],"results":
const BOX_FAILED = '{"box":"bwrap","total":31,"passed":30,"failed":["config-hidden"],"results":[{"id":"config-hidden","ok":false}]}';
const FILES = "https://raw.githubusercontent.com/milind-soni/OpenMausBot";
const SOURCE = `${FILES}/v0.1.151`;
-const REAL_TOOLS = ["sed", "awk", "grep", "cat", "head", "tail", "tr", "sort", "cut", "mkdir", "mktemp", "chmod", "chown", "mv", "rm", "dirname", "sh", "install", "find"];
+const REAL_TOOLS = ["sed", "awk", "grep", "cat", "head", "tail", "tr", "sort", "cut", "mkdir", "mktemp", "chmod", "chown", "mv", "rm", "dirname", "sh", "stat", "install", "find"];
/** A server that passes every check: Ubuntu 24.04, x86-64, 4 cores, 8 GB, 80 GB free, Docker 27, free ports, a domain that points here. */
const HEALTHY = {
@@ -84,6 +84,7 @@ case "$*" in
for last; do :; done
case "$*" in
*deploy/box/prepare-host.sh*) printf '#!/bin/sh\\necho "prepare-host profiles=$MAUSBOT_PROFILES_DIR" >> "$FAKE_LOG"\\nexit "\${FAKE_PREPARE:-0}"\\n' > "$last" ;;
+ *deploy/update-runner.sh*) printf '#!/bin/sh\\necho "update-runner $*" >> "$FAKE_LOG"\\nexit "\${FAKE_RUNNER:-0}"\\n' > "$last" ;;
*) printf 'the repository file\\n' > "$last" ;;
esac ;;
*"get.docker.com -o "*) exit 22 ;;
@@ -319,6 +320,7 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
'docker image inspect -f {{index .Config.Labels "org.opencontainers.image.version"}} ghcr.io/milind-soni/openmausbot:v0.1.151',
"docker run --rm --network none --entrypoint id ghcr.io/milind-soni/openmausbot:v0.1.151 -u",
"docker run --rm --network none --entrypoint id ghcr.io/milind-soni/openmausbot:v0.1.151 -g",
+ 'docker image inspect -f {{index .Config.Labels "org.opencontainers.image.version"}} ghcr.io/milind-soni/openmausbot:v0.1.151',
"docker compose up -d --remove-orphans",
"docker compose exec -T omb node dist-server/bot-box/box-check.js --public=none",
]);
@@ -440,6 +442,20 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
expect(mode(first.install)).toBe(0o755);
expect(mode(join(first.install, "data"))).toBe(0o755);
expect(again.stdout).toContain(` note ${first.install} could be changed by others on this server; now only its owner can change it.`);
+ // A folder its owner made tighter keeps its mode; a link to the folder is judged by the folder, not the link.
+ chmodSync(first.install, 0o700);
+ const tight = run([], { umask: "000" }, { dir: first.dir });
+ expect(tight.status, tight.all).toBe(0);
+ expect(mode(first.install)).toBe(0o700);
+ expect(tight.stdout).not.toContain("could be changed by others");
+ chmodSync(first.install, 0o755);
+ const real = join(first.dir, "elsewhere");
+ renameSync(first.install, real);
+ symlinkSync(real, first.install);
+ const linked = run([], { umask: "000" }, { dir: first.dir });
+ expect(linked.status, linked.all).toBe(0);
+ expect(linked.stdout).not.toContain("could be changed by others");
+ expect(mode(real)).toBe(0o755);
});
it("--uninstall stops the server and keeps the data, saying where it is", () => {
@@ -594,6 +610,23 @@ describe.skipIf(!posix)("deploy/install.sh", () => {
expect(unpublished.stdout).toContain("To update later, run this command again.");
});
+ it("adds the Update server button with update-runner.sh, before the server starts, and says when it could not", () => {
+ const first = run(["--domain", "maus.example.com"]);
+ expect(first.calls.some((call) => call.includes(`${SOURCE}/deploy/update-runner.sh -o `))).toBe(true);
+ const ids = `${process.getuid?.()}:${process.getgid?.()}`;
+ const button = first.calls.findIndex((call) => call === `update-runner --install --dir ${first.install} --user ${ids} --no-restart`);
+ expect(button).toBeGreaterThan(-1);
+ expect(button).toBeLessThan(first.calls.indexOf("docker compose up -d --remove-orphans"));
+ expect(first.stdout).toContain(" note The app can update this server: Settings, Updates, Update server.");
+ const compose = readFileSync(join(first.install, "compose.yaml"), "utf8");
+ expect(compose).toContain(" - /var/lib/openmausbot-update/request:/run/omb-update/request\n - /var/lib/openmausbot-update/status:/run/omb-update/status:ro\n");
+ const refused = run(["--domain", "maus.example.com"], { env: { FAKE_RUNNER: "1" } });
+ expect(refused.status).toBe(0);
+ expect(refused.stdout).toContain(`Update it with: sudo ${refused.install}/update.sh`);
+ const removed = run(["--uninstall"], {}, { dir: first.dir });
+ expect(removed.calls).toContain(`update-runner --remove --dir ${first.install}`);
+ });
+
// update.sh moves an install from before Caddy had its own container, writing these two files as the installer does.
const UPDATE = join(ROOT, "deploy", "update.sh");
it.skipIf(!existsSync(UPDATE))("hands update.sh the very compose.yaml and Caddyfile it writes", () => {
diff --git a/scripts/testing/fake-compose-docker.mjs b/scripts/testing/fake-compose-docker.mjs
index 21495dd2fa..8975b0baa3 100644
--- a/scripts/testing/fake-compose-docker.mjs
+++ b/scripts/testing/fake-compose-docker.mjs
@@ -41,7 +41,7 @@ function composeUp() {
if (!wanted) fail(`pull access denied for ${composeImage()}`);
if (state.failUp === wanted.id) fail("Error response from daemon: driver failed programming external connectivity");
const crashes = wanted.behaviour === "crashes";
- state.containers.omb = { id: `omb-${++state.serial}`, image: wanted.id, status: crashes ? "restarting" : "running", restarts: crashes ? 5 : 0 };
+ state.containers.omb = { id: `omb-${++state.serial}`, image: wanted.id, status: crashes ? "restarting" : "running", restarts: crashes ? 5 : 0, started: `start-${state.serial}` };
state.containers.caddy = { id: `caddy-${state.serial}`, status: wanted.behaviour === "no-caddy" ? "exited" : "running" };
// A server that starts writes to its data, as a new version's migrations do.
if (!crashes) appendFileSync(join(volume(state.dataVolume), "started-by.txt"), `${wanted.version}\n`);
@@ -84,7 +84,11 @@ function inspect(format, target) {
if (format === "{{.Image}}") return out(omb.image);
if (format === "{{.State.Running}}") return out(String(omb.status === "running"));
if (format === "{{.State.Status}} {{.RestartCount}} {{.Image}}") return out(`${omb.status} ${omb.restarts} ${omb.image}`);
+ // Where /data is on the host: the volume's folder here (update-runner.sh reads its owner).
+ if (format.includes(".Mounts") && !format.includes(".Name")) return out(volume(state.dataVolume));
if (format.includes(".Mounts")) return out(state.dataVolume);
+ // A container's id and when it started: both stay the same across a run that stopped nothing.
+ if (format === "{{.Id}} {{.State.StartedAt}}") return out(`${omb.id} ${omb.started ?? "start-0"}`);
if (format.includes("com.docker.compose.project")) return out("deploy");
fail(`fake docker: unknown inspect format: ${format}`, 64);
}
diff --git a/scripts/testing/update-runner.test.ts b/scripts/testing/update-runner.test.ts
new file mode 100644
index 0000000000..fea10c3027
--- /dev/null
+++ b/scripts/testing/update-runner.test.ts
@@ -0,0 +1,568 @@
+// deploy/update-runner.sh, the Update server button's host side, against the stand-in for Docker that update.sh's own
+// test drives (fake-compose-docker.mjs): the server's request in, root's copy of update.sh run, the outcome out. The
+// requester is treated as hostile throughout: anything running as the server's user can leave the request.
+import { spawnSync } from "node:child_process";
+import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir, userInfo } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { parseRun, parseRunner } from "../../server/server-update.ts";
+
+const DEPLOY = join(import.meta.dirname, "..", "..", "deploy");
+const RUNNER = join(DEPLOY, "update-runner.sh");
+const FAKE = join(import.meta.dirname, "fake-compose-docker.mjs");
+const REPO = "ghcr.io/milind-soni/openmausbot";
+const posix = process.platform !== "win32";
+
+const id = (letter: string) => `sha256:${letter.repeat(64)}`;
+type Image = { id: string; refs: string[]; version: string; local: boolean; engine: boolean; serves?: string; behaviour?: string; lastWords?: string; label?: string };
+const OLD: Image = { id: id("a"), refs: [`${REPO}:latest`, `${REPO}@${id("1")}`], version: "0.1.150", local: true, engine: true };
+const NEW: Image = { id: id("b"), refs: [`${REPO}@${id("2")}`, `${REPO}:v0.1.151`], version: "0.1.151", local: false, engine: true };
+const NEXT: Image = { id: id("d"), refs: [`${REPO}@${id("4")}`, `${REPO}:v0.1.152`], version: "0.1.152", local: false, engine: true };
+const OLDER: Image = { id: id("c"), refs: [`${REPO}@${id("3")}`, `${REPO}:v0.1.100`], version: "0.1.100", local: false, engine: true };
+const EVIL = `${REPO}@${id("3")}`;
+const EARLIER_COPY = "deploy_data-before-update-20261101T000000Z";
+const RUNNER_COPY = "deploy_data-before-update-20261102T000000Z";
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+/** A checkout's deploy/ folder running `running`, with root's folder as `--install` leaves it. */
+function install(options: { stable?: Image; running?: Image; updater?: "real" | "recorder"; earlierCopy?: boolean; runnerCopy?: boolean; freeKb?: number } = {}) {
+ const running = options.running ?? OLD;
+ const stable = options.stable ?? NEW;
+ const root = mkdtempSync(join(tmpdir(), "omb-update-runner-"));
+ dirs.push(root);
+ const deploy = join(root, "deploy");
+ const state = join(root, "state");
+ const fake = join(root, "fake");
+ const bin = join(root, "bin");
+ const data = join(fake, "volumes", "deploy_data");
+ for (const dir of [bin, deploy, join(data, ".openmausbot"), join(state, "request"), join(state, "status")]) mkdirSync(dir, { recursive: true });
+ writeFileSync(join(data, ".openmausbot", "bots.json"), '[{"name":"Mira"}]');
+ writeFileSync(join(deploy, "docker-compose.yml"), "services: {}\n");
+ writeFileSync(join(deploy, ".env"), "DOMAIN=maus.example.test\n");
+ const argv = join(root, "update-sh-argv");
+ // A stand-in that says what a plain run would take, and notes every real run's arguments.
+ const recorder = `[ "\${3:-}" = --print-target ] && { echo "${NEW.refs[0]} 0.1.151"; exit 0; }\nprintf '%s\\n' "$#:$*:\${OMB_UPDATE_BY_RUNNER:-}" >> "${argv}"\n`;
+ // Root's copy and the install's own are the same file, as --install leaves them.
+ for (const where of [deploy, state]) {
+ if (options.updater === "recorder") writeFileSync(join(where, "update.sh"), recorder);
+ else copyFileSync(join(DEPLOY, "update.sh"), join(where, "update.sh"));
+ }
+ writeFileSync(join(bin, "docker"), `#!/bin/sh\nexec "${process.execPath}" "${FAKE}" "$@"\n`);
+ // The user's groups, a folder's group and the group list, as the test says: never the machine's own (a CI user may be in
+ // the docker group, a Mac's temporary folders belong to group wheel).
+ writeFileSync(join(bin, "id"), '#!/bin/sh\ncase "$1" in -nG) echo "${FAKE_GROUPS:-staff}" ;; *) exec /usr/bin/id "$@" ;; esac\n');
+ writeFileSync(join(bin, "getent"), '#!/bin/sh\ncase "$1" in\n group) [ -n "${FAKE_GETENT:-}" ] || exit 2; echo "$FAKE_GETENT" ;;\n passwd) [ -n "${FAKE_PASSWD:-}" ] || exit 2; printf "%s\\n" "$FAKE_PASSWD" ;;\n *) exit 2 ;;\nesac\n');
+ writeFileSync(join(bin, "stat"), `#!/bin/sh
+case "$*" in
+ *" %g "*) echo "\${FAKE_GID:-1000}"; exit 0 ;;
+ *"%U:%G"* | *"%Su:%Sg"*) for last; do :; done; echo "$(/usr/bin/stat -L -c %U "$last" 2>/dev/null || /usr/bin/stat -L -f %Su "$last"):\${FAKE_GROUP:-staff}"; exit 0 ;;
+ *" %G "* | *" %Sg "*) echo "\${FAKE_GROUP:-staff}"; exit 0 ;;
+esac
+exec /usr/bin/stat "$@"
+`);
+ for (const name of ["docker", "id", "getent", "stat"]) chmodSync(join(bin, name), 0o755);
+ const images = [running, stable, NEW, NEXT, OLDER].filter((image, at, all) => all.findIndex((other) => other.id === image.id) === at).map((image) => ({ ...image, local: image === running || image.local }));
+ const labels: Record<string, string[]> = {};
+ if (options.earlierCopy) {
+ mkdirSync(join(fake, "volumes", EARLIER_COPY), { recursive: true });
+ writeFileSync(join(fake, "volumes", EARLIER_COPY, "the-last-good-data.txt"), "good");
+ labels[EARLIER_COPY] = ["com.mausbot.role=update-backup", "com.mausbot.project=deploy", "com.mausbot.data=deploy_data", `com.mausbot.image=${running.id}`];
+ }
+ if (options.runnerCopy) {
+ mkdirSync(join(fake, "volumes", RUNNER_COPY), { recursive: true });
+ writeFileSync(join(fake, "volumes", RUNNER_COPY, "the-last-good-data.txt"), "good");
+ labels[RUNNER_COPY] = ["com.mausbot.role=update-backup", "com.mausbot.project=deploy", "com.mausbot.data=deploy_data", `com.mausbot.image=${running.id}`, "com.mausbot.by=runner"];
+ }
+ writeFileSync(join(fake, "state.json"), JSON.stringify({
+ serial: 1, composeReadsPin: true, defaultImage: `${REPO}:latest`, dataVolume: "deploy_data", images, volumeLabels: labels,
+ ...(options.freeKb === undefined ? {} : { freeKb: options.freeKb }),
+ containers: { omb: { id: "omb-1", image: running.id, status: "running", restarts: 0, started: "start-1" }, caddy: { id: "caddy-1", status: "running" } },
+ }));
+ const setStable = (image: Image) => writeFileSync(join(root, "stable.json"), JSON.stringify({ channel: "stable", version: image.version, image: image.refs.find((ref) => ref.includes("@sha256:")) }));
+ setStable(stable);
+ writeFileSync(join(state, "status", "runner"), `layout=compose\ndir=${deploy}\nheld=no\n`);
+ // The test's own user owns the checkout and cannot run Docker: trusted, as --install --trust-folder-owner leaves it.
+ writeFileSync(join(state, "trust"), `dir=${deploy}\n`);
+ writeFileSync(join(state, "status", "last"), "run=0\nstate=done\nresult=updated\nat=0\nran=0\n");
+ const request = join(state, "request", "request");
+ const policy = join(root, "policy.json");
+ const run = (env: Record<string, string> = {}) => spawnSync("sh", [RUNNER], {
+ encoding: "utf8", timeout: 60_000,
+ env: {
+ // The unit's own environment, as --install writes it, and nothing from the request.
+ PATH: `${bin}:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: root, FAKE_DOCKER_DIR: fake, OMB_INSTALL_DIR: deploy, OMB_UPDATE_STATE_DIR: state,
+ OMB_UPDATE_POLICY: policy, OMB_STABLE_URL: `file://${join(root, "stable.json")}`, OMB_NEWEST_URL: `file://${join(root, "newest.json")}`,
+ OMB_UPDATE_POLL_S: "0", OMB_UPDATE_WAIT_S: "120", OMB_UPDATE_ENGINE_WAIT_S: "1", OMB_RUNNER_QUIET_S: "0", OMB_RUNNER_IDLE_S: "0", ...env,
+ },
+ });
+ const fakeState = () => JSON.parse(readFileSync(join(fake, "state.json"), "utf8"));
+ const calls = () => (existsSync(join(fake, "calls.log")) ? readFileSync(join(fake, "calls.log"), "utf8").trim().split("\n") : []);
+ return {
+ root, deploy, state, fake, request, policy, run, setStable, calls, fakeState,
+ ask: (env: Record<string, string> = {}) => {
+ writeFileSync(request, "x\n");
+ return run(env);
+ },
+ last: () => parseRun(readFileSync(join(state, "status", "last"), "utf8")),
+ lastText: () => readFileSync(join(state, "status", "last"), "utf8"),
+ runnerInfo: () => parseRunner(readFileSync(join(state, "status", "runner"), "utf8")),
+ argv: () => (existsSync(argv) ? readFileSync(argv, "utf8").trim().split("\n") : []),
+ env: () => readFileSync(join(deploy, ".env"), "utf8"),
+ copies: () => Object.keys(fakeState().volumeLabels ?? {}).filter((name) => name.startsWith("deploy_data-before-update-")).sort(),
+ blocked: () => existsSync(join(state, "blocked")),
+ personRun: (env: Record<string, string> = {}) => spawnSync("bash", [join(deploy, "update.sh"), "--dir", deploy], {
+ encoding: "utf8", input: "", timeout: 60_000,
+ env: {
+ PATH: `${bin}:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: root, FAKE_DOCKER_DIR: fake, OMB_UPDATE_STATE_DIR: state, OMB_STABLE_URL: `file://${join(root, "stable.json")}`,
+ OMB_UPDATE_POLL_S: "0", OMB_UPDATE_WAIT_S: "120", OMB_UPDATE_ENGINE_WAIT_S: "1", ...env,
+ },
+ }),
+ };
+}
+
+/** What a server that wants more than "update now" might leave: flags, another image, an older version, a path. */
+const GREEDY = `--rollback\n--allow-older\n--version 0.1.100\n--image ${EVIL}\nimage=${EVIL}\nversion=0.1.100\n--dir /etc\n$(touch /tmp/omb-pwned)\n`;
+
+/** Root's tools without root: `id` says 0, `install` notes its owners and leaves them alone, `systemctl` notes what it is asked. */
+function rootTools(root: string) {
+ const fakes = join(root, "fakes");
+ mkdirSync(fakes);
+ const log = join(root, "root-tools.log");
+ writeFileSync(join(fakes, "id"), '#!/bin/sh\ncase "$1" in -nG) echo "${FAKE_GROUPS:-staff}" ;; *) echo 0 ;; esac\n');
+ writeFileSync(join(fakes, "install"), `#!/bin/sh
+echo "install $*" >> "${log}"
+args=""
+while [ $# -gt 0 ]; do case "$1" in -o|-g) shift ;; *) args="$args $1" ;; esac; shift; done
+# shellcheck disable=SC2086
+exec /usr/bin/install $args
+`);
+ writeFileSync(join(fakes, "systemctl"), `#!/bin/sh\necho "systemctl $*" >> "${log}"\n`);
+ for (const name of ["id", "install", "systemctl"]) chmodSync(join(fakes, name), 0o755);
+ return { fakes, log: () => readFileSync(log, "utf8").trim().split("\n") };
+}
+
+describe.skipIf(!posix)("deploy/update-runner.sh", () => {
+ it("is plain POSIX sh", () => {
+ expect(spawnSync("sh", ["-n", RUNNER]).status).toBe(0);
+ const dash = spawnSync("dash", ["-n", RUNNER]);
+ if (!dash.error) expect(dash.status).toBe(0);
+ });
+
+ it("does nothing without a request", () => {
+ const box = install();
+ expect(box.run().status).toBe(0);
+ // Only reads, to say again whether the running image is a released one.
+ expect(box.calls().filter((call) => !/^(compose ps -aq|inspect -f|image inspect -f)/.test(call))).toEqual([]);
+ expect(box.lastText()).toBe("run=0\nstate=done\nresult=updated\nat=0\nran=0\n");
+ expect(box.runnerInfo()).toMatchObject({ release: true });
+ });
+
+ it("takes a request, runs root's copy of update.sh (stable, copy first) and writes how it ended", () => {
+ const box = install();
+ writeFileSync(box.request, "8d0c6a4e-0000-4000-8000-000000000000\n");
+ const done = box.run();
+ expect(done.status, done.stdout + done.stderr).toBe(0);
+ expect(existsSync(box.request)).toBe(false);
+ expect(box.last()).toEqual({ run: 1, state: "done", result: "updated", at: expect.any(Number), version: "0.1.151" });
+ expect(box.fakeState().containers.omb).toMatchObject({ image: NEW.id, status: "running" });
+ expect(box.env()).toContain(`OMB_IMAGE=${NEW.refs[0]}`);
+ expect(box.calls().some((call) => call.includes("--entrypoint cp"))).toBe(true);
+ expect(done.stdout).toContain("Updated from 0.1.150 to 0.1.151.");
+ });
+
+ it("runs the same update whatever the request says: no flag, image, version or path in it reaches update.sh", () => {
+ const real = install();
+ writeFileSync(real.request, GREEDY);
+ expect(real.run().status).toBe(0);
+ expect(real.last()?.result).toBe("updated");
+ expect(real.fakeState().containers.omb.image).toBe(NEW.id);
+ expect(real.calls().filter((call) => call.includes(EVIL) || call.includes("0.1.100"))).toEqual([]);
+ expect(existsSync("/tmp/omb-pwned")).toBe(false);
+
+ const recorded = install({ updater: "recorder" });
+ writeFileSync(recorded.request, GREEDY);
+ recorded.run();
+ expect(recorded.argv()).toEqual([`2:--dir ${recorded.deploy}:1`]);
+ });
+
+ it("runs neither copy once the install's update.sh differs from root's (a git pull without --install), and says so", () => {
+ const box = install({ updater: "recorder" });
+ writeFileSync(join(box.deploy, "update.sh"), `touch "${join(box.root, "ran-the-folder-copy")}"\n`);
+ box.ask();
+ expect(box.last()).toMatchObject({ run: 1, result: "stale" });
+ expect(box.argv()).toEqual([]);
+ expect(existsSync(join(box.root, "ran-the-folder-copy"))).toBe(false);
+ // A link in its place is not followed, and not run either.
+ rmSync(join(box.deploy, "update.sh"));
+ symlinkSync(join(box.state, "update.sh"), join(box.deploy, "update.sh"));
+ box.ask();
+ expect(box.last()).toMatchObject({ run: 2, result: "no-updater" });
+ expect(box.argv()).toEqual([]);
+ });
+
+ it("removes a request that is a link or a folder without following it", () => {
+ const box = install({ updater: "recorder" });
+ const victim = join(box.root, "precious.txt");
+ writeFileSync(victim, "keep me");
+ symlinkSync(victim, box.request);
+ box.run();
+ expect(() => lstatSync(box.request)).toThrow();
+ expect(readFileSync(victim, "utf8")).toBe("keep me");
+ expect(box.argv()).toEqual([`2:--dir ${box.deploy}:1`]);
+
+ const folder = install({ updater: "recorder" });
+ mkdirSync(join(folder.request, "nested"), { recursive: true });
+ symlinkSync(victim, join(folder.request, "nested", "link"));
+ folder.run();
+ expect(existsSync(folder.request)).toBe(false);
+ expect(readFileSync(victim, "utf8")).toBe("keep me");
+ });
+
+ it("goes by the image's own label, never by the version the server says it runs", () => {
+ // Newer than stable, claiming to be very old: asked for from the app, it is not "updated" down onto its newer data.
+ const liar = install({ running: { ...NEXT, local: true, serves: "0.1.100" } });
+ liar.ask();
+ expect(liar.last()?.result).toBe("refused");
+ expect(liar.fakeState().containers.omb.image).toBe(NEXT.id);
+ expect(liar.copies()).toEqual([]);
+ // Telling the truth, it is newer than stable, and nothing changes either.
+ const newer = install({ running: { ...NEXT, local: true } });
+ newer.ask();
+ expect(newer.last()?.result).toBe("older");
+ expect(newer.fakeState().containers.omb.image).toBe(NEXT.id);
+ // A server that says it is newer than its image is not trusted for that either.
+ const boaster = install({ running: { ...OLD, serves: "0.1.160" } });
+ boaster.ask();
+ expect(boaster.last()?.result).toBe("refused");
+ });
+
+ it("keeps a person's own copy of the data when the server asked, and the runner's two newest copies", () => {
+ const box = install({ earlierCopy: true, runnerCopy: true });
+ // A server that damaged its own data, then asked as soon as a new stable version was out.
+ writeFileSync(join(box.fake, "volumes", "deploy_data", "the-last-good-data.txt"), "DAMAGED");
+ box.ask();
+ expect(box.last()?.result).toBe("updated");
+ const made = box.copies().filter((name) => name !== EARLIER_COPY && name !== RUNNER_COPY);
+ expect(made).toHaveLength(1);
+ expect(box.fakeState().volumeLabels[made[0]!]).toContain("com.mausbot.by=runner");
+ expect(readFileSync(join(box.fake, "volumes", made[0]!, "the-last-good-data.txt"), "utf8")).toBe("DAMAGED");
+ // The good copy made before it survives this update, and the person's own copy any number of them.
+ for (const kept of [RUNNER_COPY, EARLIER_COPY]) expect(readFileSync(join(box.fake, "volumes", kept, "the-last-good-data.txt"), "utf8"), kept).toBe("good");
+ // One more: now two newer runner copies exist, so the oldest of the runner's goes. The person's stays.
+ box.setStable(NEXT);
+ box.ask({ OMB_RUNNER_GAP_S: "0" });
+ expect(box.last()?.result).toBe("updated");
+ expect(box.copies()).not.toContain(RUNNER_COPY);
+ expect(box.copies()).toContain(EARLIER_COPY);
+ expect(box.copies().filter((name) => name !== EARLIER_COPY)).toHaveLength(2);
+ });
+
+ it("never tries a stable image again after it rolled back from it, until a person runs update.sh or another is out", () => {
+ const failing = { ...NEW, behaviour: "crashes", lastWords: "Error: cannot read the data" };
+ const box = install({ stable: failing });
+ box.ask({ OMB_RUNNER_GAP_S: "0" });
+ expect(box.last()?.result).toBe("rolled-back");
+ expect(box.copies()).toHaveLength(1);
+ const pulls = box.calls().filter((call) => call.startsWith("pull")).length;
+ for (let again = 0; again < 3; again += 1) {
+ box.ask({ OMB_RUNNER_GAP_S: "0" });
+ expect(box.last()).toMatchObject({ result: "not-retried", version: "0.1.151" });
+ }
+ // No more stops, copies or downloads: the server is left as the rollback left it.
+ expect(box.copies()).toHaveLength(1);
+ expect(box.calls().filter((call) => call.startsWith("pull")).length).toBe(pulls);
+ expect(box.fakeState().containers.omb.image).toBe(OLD.id);
+ // A person's own run lets the button try that version again.
+ expect(box.blocked()).toBe(true);
+ box.personRun();
+ expect(box.blocked()).toBe(false);
+ // Another stable image is tried at once.
+ const fresh = install({ stable: failing });
+ fresh.ask({ OMB_RUNNER_GAP_S: "0" });
+ fresh.setStable(NEXT);
+ fresh.ask({ OMB_RUNNER_GAP_S: "0" });
+ expect(fresh.last()?.result).toBe("updated");
+ expect(fresh.fakeState().containers.omb.image).toBe(NEXT.id);
+ expect(fresh.blocked()).toBe(false);
+ });
+
+ it("answers a repeated request with nothing to do from its own record, without asking GitHub or the registry", () => {
+ const box = install({ stable: OLD });
+ box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ const before = box.calls().filter((call) => call.startsWith("pull")).length;
+ for (let again = 0; again < 3; again += 1) box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ expect(box.last()).toMatchObject({ run: 4, result: "updated" });
+ expect(box.calls().filter((call) => call.startsWith("pull")).length).toBe(before);
+ });
+
+ it("says a build of main is not one the app updates, and runs nothing", () => {
+ const box = install({ running: { ...OLD, label: "main" } });
+ box.ask();
+ expect(box.last()).toMatchObject({ result: "unreleased" });
+ expect(box.runnerInfo()).toMatchObject({ release: false });
+ expect(box.calls().some((call) => call.startsWith("pull") || call.startsWith("compose stop"))).toBe(false);
+ });
+
+ it("lets a person's own run use links in the install's folder, as before", () => {
+ const box = install();
+ writeFileSync(join(box.root, "env-real"), "DOMAIN=maus.example.test\n");
+ rmSync(join(box.deploy, ".env"));
+ symlinkSync(join(box.root, "env-real"), join(box.deploy, ".env"));
+ const done = box.personRun();
+ expect(done.status, done.stdout + done.stderr).toBe(0);
+ expect(box.fakeState().containers.omb.image).toBe(NEW.id);
+ // The same link stops a run the server asked for.
+ const asked = install();
+ rmSync(join(asked.deploy, ".env"));
+ symlinkSync(join(box.root, "env-real"), join(asked.deploy, ".env"));
+ asked.ask();
+ expect(asked.last()?.result).toBe("refused");
+ expect(asked.fakeState().containers.omb.image).toBe(OLD.id);
+ });
+
+ it("runs nothing when the install's folder, or one above it, can be changed by others, and names that folder", () => {
+ const box = install({ updater: "recorder" });
+ const me = userInfo().username;
+ const unsafe = (env: Record<string, string> = {}) => {
+ box.ask(env);
+ const last = readFileSync(join(box.state, "status", "last"), "utf8");
+ return last.includes("result=unsafe") ? /^detail=(.*)$/m.exec(last)?.[1] ?? "" : null;
+ };
+ chmodSync(box.deploy, 0o775);
+ // Group-writable by a shared group: refused, and the folder named with its owner, group and mode.
+ expect(unsafe()).toBe(`${box.deploy} ${me}:staff 775`);
+ // By the owner's own private group (umask 002 on Ubuntu and Fedora), or by root's group: fine.
+ const passwd = `root:x:0:0::/root:/bin/sh\n${me}:x:1000:1000::/home/${me}:/bin/sh\nbob:x:1001:1001::/home/bob:/bin/sh`;
+ expect(unsafe({ FAKE_GROUP: me, FAKE_GETENT: `${me}:x:1000:`, FAKE_PASSWD: passwd })).toBeNull();
+ // Not when someone else has that group as their own, when the users can't be listed, or when it has no entry at all.
+ expect(unsafe({ FAKE_GROUP: me, FAKE_GETENT: `${me}:x:1000:`, FAKE_PASSWD: `${passwd}\neve:x:1002:1000::/home/eve:/bin/sh` })).toBe(`${box.deploy} ${me}:${me} 775`);
+ expect(unsafe({ FAKE_GROUP: me, FAKE_GETENT: `${me}:x:1000:` })).toBe(`${box.deploy} ${me}:${me} 775`);
+ expect(unsafe({ FAKE_GROUP: me, FAKE_PASSWD: passwd })).toBe(`${box.deploy} ${me}:${me} 775`);
+ expect(unsafe({ FAKE_GID: "0" })).toBeNull();
+ // A group of the owner's name with someone else in it is not private.
+ expect(unsafe({ FAKE_GROUP: me, FAKE_GETENT: `${me}:x:1000:${me},bob`, FAKE_PASSWD: passwd })).toBe(`${box.deploy} ${me}:${me} 775`);
+ // World-writable never, whatever the group.
+ chmodSync(box.deploy, 0o777);
+ expect(unsafe({ FAKE_GROUP: me, FAKE_GETENT: `${me}:x:1000:`, FAKE_PASSWD: passwd })).toBe(`${box.deploy} ${me}:${me} 777`);
+ chmodSync(box.deploy, 0o755);
+ // A folder above it, open to all without the sticky bit: that folder is the one named.
+ chmodSync(box.root, 0o777);
+ expect(unsafe()).toBe(`${box.root} ${me}:staff 777`);
+ chmodSync(box.root, 0o1777);
+ expect(unsafe()).toBeNull();
+ chmodSync(box.root, 0o700);
+ // An untrusted owner is checked at every run too, not only at --install; one in the docker group is fine.
+ rmSync(join(box.state, "trust"));
+ expect(unsafe()).toBe(`${box.deploy} ${me}:staff 755`);
+ expect(unsafe({ FAKE_GROUPS: "staff docker" })).toBeNull();
+ const ran = box.argv().length;
+ writeFileSync(join(box.state, "trust"), `dir=${box.deploy}\n`);
+ expect(unsafe()).toBeNull();
+ expect(box.argv()).toHaveLength(ran + 1);
+ });
+
+ it("says when there is no room for a copy of the data, apart from other refusals", () => {
+ const box = install({ freeKb: 1024 });
+ box.ask();
+ expect(box.last()?.result).toBe("no-room");
+ expect(box.fakeState().containers.omb.image).toBe(OLD.id);
+ });
+
+
+ it("checks a remembered answer again when the server knows of a newer version, asking only GitHub", () => {
+ const box = install({ stable: OLD });
+ box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ const pulls = () => box.calls().filter((call) => call.startsWith("pull")).length;
+ const before = pulls();
+ // Still the same stable image: the remembered answer stands, nothing is pulled.
+ writeFileSync(join(box.state, "request", "fresh"), "");
+ box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ expect(box.last()).toMatchObject({ result: "updated", version: "0.1.150" });
+ expect(pulls()).toBe(before);
+ expect(existsSync(join(box.state, "request", "fresh"))).toBe(false);
+ // A newer one is out: it is taken at once.
+ box.setStable(NEW);
+ box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ expect(box.last()?.result).toBe("updated");
+ expect(box.fakeState().containers.omb.image).toBe(OLD.id);
+ writeFileSync(join(box.state, "request", "fresh"), "");
+ box.ask({ OMB_RUNNER_IDLE_S: "300" });
+ expect(box.fakeState().containers.omb.image).toBe(NEW.id);
+ });
+
+ it("writes nothing through a .update that is a link", () => {
+ const box = install();
+ const elsewhere = join(box.root, "elsewhere");
+ mkdirSync(elsewhere, { mode: 0o755 });
+ symlinkSync(elsewhere, join(box.deploy, ".update"));
+ box.ask();
+ expect(box.last()?.result).toBe("refused");
+ expect(readdirSync(elsewhere)).toEqual([]);
+ expect(statSync(elsewhere).mode & 0o777).toBe(0o755);
+ expect(box.fakeState().containers.omb.image).toBe(OLD.id);
+ });
+
+ it("lets runs that change nothing pass freely, and keeps updates that change something four minutes apart", () => {
+ const box = install({ stable: OLD });
+ // A hostile requester's runs while there is nothing to update to: they stop nothing, and use up no gap.
+ for (let at = 1; at <= 3; at += 1) {
+ box.ask();
+ expect(box.last()).toMatchObject({ run: at, result: "updated" });
+ }
+ expect(box.fakeState().containers.omb.id).toBe("omb-1");
+ box.setStable(NEW);
+ box.ask();
+ expect(box.last()).toMatchObject({ run: 4, result: "updated" });
+ expect(box.fakeState().containers.omb.image).toBe(NEW.id);
+ // The run that changed something counts: the next one with something to change waits for the gap.
+ box.setStable(NEXT);
+ box.ask();
+ expect(box.last()).toMatchObject({ run: 5, result: "too-soon" });
+ expect(box.fakeState().containers.omb.image).toBe(NEW.id);
+ box.ask({ OMB_RUNNER_GAP_S: "0" });
+ expect(box.fakeState().containers.omb.image).toBe(NEXT.id);
+ });
+
+ it("spaces even cheap runs QUIET_S apart, waiting rather than refusing", () => {
+ const box = install({ updater: "recorder" });
+ box.ask({ OMB_RUNNER_QUIET_S: "2" });
+ const started = Date.now();
+ box.ask({ OMB_RUNNER_QUIET_S: "2", OMB_RUNNER_GAP_S: "0" });
+ expect(Date.now() - started).toBeGreaterThanOrEqual(900);
+ expect(box.argv()).toHaveLength(2);
+ });
+
+ it("puts the old version back when the new one is not healthy, and says so", () => {
+ const box = install({ stable: { ...NEW, behaviour: "crashes", lastWords: "Error: cannot read the data" } });
+ box.ask();
+ expect(box.last()?.result).toBe("rolled-back");
+ expect(box.fakeState().containers.omb).toMatchObject({ image: OLD.id, status: "running" });
+ });
+
+ it("does nothing while the owner's policy holds updates, and says the hold again whenever systemd runs it", () => {
+ const box = install({ updater: "recorder" });
+ writeFileSync(box.policy, '{ "jobs": ["status"], "updates" : "hold" }');
+ box.run();
+ expect(box.runnerInfo()).toMatchObject({ held: true });
+ box.ask();
+ expect(box.argv()).toEqual([]);
+ expect(box.last()).toMatchObject({ run: 1, result: "held" });
+ expect(existsSync(box.request)).toBe(false);
+ writeFileSync(box.policy, "{}");
+ box.run();
+ expect(box.runnerInfo()).toMatchObject({ held: false });
+ });
+
+ it("says when root's folder has no update.sh", () => {
+ const box = install({ updater: "recorder" });
+ rmSync(join(box.state, "update.sh"));
+ box.ask();
+ expect(box.last()).toMatchObject({ run: 1, result: "no-updater" });
+ });
+
+ it("--install makes root's folder with the right owners and modes, copies update.sh into it, and --remove takes it all away", () => {
+ const box = install();
+ rmSync(box.state, { recursive: true });
+ const tools = rootTools(box.root);
+ const sbin = join(box.root, "sbin");
+ const systemd = join(box.root, "systemd");
+ mkdirSync(systemd);
+ // The reviewer's attack: a temporary file planted as a link beside the override. Nothing is written through it.
+ const victim = join(box.root, "victim.txt");
+ writeFileSync(victim, "untouched");
+ symlinkSync(victim, join(box.deploy, "docker-compose.override.yml.tmp"));
+ const env = {
+ PATH: `${tools.fakes}:${join(box.root, "bin")}:/usr/bin:/bin:/usr/sbin:/sbin`, FAKE_DOCKER_DIR: box.fake, OMB_SBIN_DIR: sbin, OMB_SYSTEMD_DIR: systemd,
+ OMB_UPDATE_STATE_DIR: box.state, OMB_UPDATE_POLICY: box.policy, OMB_STABLE_URL: "file:///srv/stable.json", OMB_UPDATE_WAIT_S: "300; rm -rf /",
+ OMB_NEWEST_URL: "https://example.test/%2e%2e",
+ };
+ // Its folder is the test's user's, who cannot run Docker: refused unless asked, said why.
+ const refused = spawnSync("sh", [RUNNER, "--install", "--dir", box.deploy, "--no-restart"], { encoding: "utf8", env, timeout: 30_000 });
+ expect(refused.status).toBe(1);
+ expect(refused.stderr).toContain("who cannot run Docker. Whoever owns it can change what root runs");
+ expect(existsSync(box.state)).toBe(false);
+ chmodSync(box.deploy, 0o777);
+ const writable = spawnSync("sh", [RUNNER, "--install", "--dir", box.deploy, "--no-restart"], { encoding: "utf8", env: { ...env, FAKE_GROUPS: "staff docker" }, timeout: 30_000 });
+ expect(writable.status).toBe(1);
+ expect(writable.stderr).toContain(`${box.deploy} (${userInfo().username}:staff 777) can be changed by someone other than root and the owner of ${box.deploy}`);
+ chmodSync(box.deploy, 0o755);
+ const done = spawnSync("sh", [RUNNER, "--install", "--dir", box.deploy, "--no-restart"], { encoding: "utf8", env: { ...env, FAKE_GROUPS: "staff docker" }, timeout: 30_000 });
+ expect(done.status, done.stdout + done.stderr).toBe(0);
+ // The request folder's owner is the data's owner on the host, never what the container says.
+ const data = statSync(join(box.fake, "volumes", "deploy_data"));
+ const owner = `${data.uid} -g ${data.gid}`;
+ expect(tools.log()).toContain(`install -d -m 0755 -o 0 -g 0 ${box.state} ${join(box.state, "status")}`);
+ expect(tools.log()).toContain(`install -d -m 0700 -o ${owner} ${join(box.state, "request")}`);
+ expect(box.calls().some((call) => call.startsWith("compose exec"))).toBe(false);
+ const mode = (path: string) => statSync(path).mode & 0o777;
+ expect([mode(box.state), mode(join(box.state, "status")), mode(join(box.state, "request"))]).toEqual([0o755, 0o755, 0o700]);
+ for (const file of ["runner", "last"]) expect(mode(join(box.state, "status", file)), file).toBe(0o644);
+ expect(mode(join(box.state, "update.sh"))).toBe(0o755);
+ expect(readFileSync(join(box.state, "update.sh"), "utf8")).toBe(readFileSync(join(DEPLOY, "update.sh"), "utf8"));
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
+ expect(readFileSync(join(systemd, "openmausbot-update.path"), "utf8")).toContain(`PathExists=${box.state}/request/request\nPathChanged=${box.policy}\nPathChanged=${box.deploy}/.env\n`);
+ const service = readFileSync(join(systemd, "openmausbot-update.service"), "utf8");
+ expect(service).toContain(`ExecStart=${sbin}/openmausbot-update-runner`);
+ // Root's settings at the install, and only plain values: one that is not is left out, `%` included (systemd expands it).
+ expect(service).toContain(`Environment=HOME=/root OMB_INSTALL_DIR=${box.deploy} OMB_STABLE_URL=file:///srv/stable.json\n`);
+ expect(readFileSync(join(sbin, "openmausbot-update-runner"), "utf8")).toBe(readFileSync(RUNNER, "utf8"));
+ expect(tools.log()).toContain("systemctl enable --now openmausbot-update.path");
+ expect(box.runnerInfo()).toEqual({ layout: "compose", dir: box.deploy, held: false, release: true });
+ // One install per server: another folder is refused while this one has the button.
+ const other = join(box.root, "other");
+ mkdirSync(other);
+ writeFileSync(join(other, "docker-compose.yml"), "services: {}\n");
+ copyFileSync(join(DEPLOY, "update.sh"), join(other, "update.sh"));
+ const second = spawnSync("sh", [RUNNER, "--install", "--dir", other, "--user", "1000:1000", "--no-restart", "--trust-folder-owner"], { encoding: "utf8", env, timeout: 30_000 });
+ expect(second.status).toBe(1);
+ expect(second.stderr).toContain(`already updates ${box.deploy}: one install per server`);
+ const override = readFileSync(join(box.deploy, "docker-compose.override.yml"), "utf8");
+ expect(override).toContain(`- ${box.state}/request:/run/omb-update/request\n`);
+ expect(override).toContain(`- ${box.state}/status:/run/omb-update/status:ro\n`);
+ expect(readFileSync(join(box.deploy, "docker-compose.yml"), "utf8")).toBe("services: {}\n");
+
+ // --remove for another folder takes nothing away.
+ const elsewhere = spawnSync("sh", [RUNNER, "--remove", "--dir", other], { encoding: "utf8", env, timeout: 30_000 });
+ expect(elsewhere.status).toBe(1);
+ expect(elsewhere.stderr).toContain(`updates ${box.deploy}, not ${other}, so nothing was removed`);
+ expect(existsSync(join(box.state, "update.sh"))).toBe(true);
+ expect(existsSync(join(systemd, "openmausbot-update.path"))).toBe(true);
+ const removed = spawnSync("sh", [RUNNER, "--remove", "--dir", box.deploy], { encoding: "utf8", env, timeout: 30_000 });
+ expect(removed.status, removed.stdout + removed.stderr).toBe(0);
+ for (const gone of [join(systemd, "openmausbot-update.path"), join(systemd, "openmausbot-update.service"), join(sbin, "openmausbot-update-runner"),
+ join(box.deploy, "docker-compose.override.yml"), box.state]) expect(existsSync(gone), gone).toBe(false);
+ expect(existsSync(join(box.deploy, "update.sh"))).toBe(true);
+ });
+
+ it("--install never writes through a link, and leaves an override of the person's own alone", () => {
+ const box = install();
+ const tools = rootTools(box.root);
+ mkdirSync(join(box.root, "systemd"));
+ const env = {
+ PATH: `${tools.fakes}:/usr/bin:/bin:/usr/sbin:/sbin`, OMB_SBIN_DIR: join(box.root, "sbin"), OMB_SYSTEMD_DIR: join(box.root, "systemd"),
+ OMB_UPDATE_STATE_DIR: box.state, OMB_UPDATE_POLICY: box.policy,
+ };
+ const installRunner = () => spawnSync("sh", [RUNNER, "--install", "--dir", box.deploy, "--user", "1000:1000", "--no-restart", "--trust-folder-owner"], { encoding: "utf8", env, timeout: 30_000 });
+ const victim = join(box.root, "victim.txt");
+ writeFileSync(victim, "untouched");
+ symlinkSync(victim, join(box.deploy, "docker-compose.override.yml"));
+ const linked = installRunner();
+ expect(linked.status).toBe(1);
+ expect(linked.stderr).toContain("is a link, so it was left alone");
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
+
+ rmSync(join(box.deploy, "docker-compose.override.yml"));
+ writeFileSync(join(box.deploy, "docker-compose.override.yml"), "services:\n omb:\n environment:\n MINE: 1\n");
+ const mine = installRunner();
+ expect(mine.status).toBe(1);
+ expect(mine.stderr).toContain("is yours, so it was left alone");
+ expect(mine.stderr).toContain(`- ${box.state}/request:/run/omb-update/request`);
+ expect(readFileSync(join(box.deploy, "docker-compose.override.yml"), "utf8")).toContain("MINE: 1");
+ });
+});
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 9849484a5a..b70a4c39de 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -46,6 +46,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_OPENROUTER_DECIDER_KEY", "OMB_PERSON_FIRST_MS", "OMB_PHONE_RELAY", "OMB_PHONE_RELAY_URL", "OMB_PHONE_SECRET_PUBLIC_KEY", "OMB_PORT", "OMB_SERVES_TUNNEL", "OMB_POSTIZ_API_KEY",
"OMB_POSTIZ_CLOUD_URL", "OMB_PROCESS_ID", "OMB_PUBLIC_IPV4", "OMB_PUBLIC_URL", "OMB_QUOTA_SWITCH",
"OMB_REPLAY_TOOL_HISTORY", "OMB_ROOM_SESSIONS", "OMB_SAFETY_FLOOR", "OMB_SERVER_COMPILE_CACHE", "OMB_SERVER_NAME",
+ "OMB_SERVER_UPDATE_DIR",
"OMB_SESSION_IDLE_MIN_MS", "OMB_SESSION_IDLE_MS", "OMB_SESSION_MAX_DAYS", "OMB_SESSION_TTL_DAYS",
"OMB_SHARED_WORKSPACE_FULL_ACCESS", "OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_FROM",
"OMB_SIGNIN_SMTP_URL", "OMB_SKILLS_DIR", "OMB_SMOKE_BUNDLED_CUA", "OMB_SMOKE_CUA", "OMB_SMOKE_KEEP_OPEN",
diff --git a/server/index.ts b/server/index.ts
index bd7121190d..8f61cc09f1 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -592,7 +592,7 @@ import { createBotSkillsRoutes } from "./routes/bot-skills.ts";
import { createSkillShareRoutes } from "./routes/skill-share.ts";
import { createTeamContextRoutes } from "./routes/team-context.ts";
import { createAppSuggestions } from "./host/app-suggestions.ts"; import { createAppFindRoute, createAppSuggestionRoutes } from "./routes/app-suggestions.ts"; import { appPickAvailable } from "./decider/app-picks.ts"; import { managedConnectorUnavailableReason } from "../shared/connector-availability.ts"; import { createDeciderRoutes } from "./routes/decider.ts"; import { createCloudSendRoutes } from "./routes/cloud-send.ts"; import { claudeCodeSkillInputs } from "./setup-import.ts"; import { createCloudConnectionsHost } from "./cloud-connections-host.ts";
-import { createUpdateCheckRoutes, serverUpdateChecker } from "./routes/update-check.ts"; import { createSeatsRoutes } from "./routes/seats.ts"; import { createTimeZoneRoutes } from "./routes/time-zone.ts";
+import { createUpdateCheckRoutes, updateRouteDeps } from "./routes/update-check.ts"; import { createSeatsRoutes } from "./routes/seats.ts"; import { createTimeZoneRoutes } from "./routes/time-zone.ts";
import { createBrowserSiteRoutes } from "./routes/browser-sites.ts";
import { createInternalSignInRoutes } from "./routes/sign-in.ts";
import { createInternalMcpRoutes } from "./routes/internal-mcp.ts";
@@ -12203,7 +12203,7 @@ ROUTES.push(createBotMemoryRoutes({
broadcast({ kind: "config", ...configStatus() });
},
}));
-const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
+const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL || DESKTOP_MANAGED ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connectionsMoved: (language) => cloudConnections.moved(language), connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
ROUTES.push(teamPresence.routes, createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: () => composio.connectedServices(cfg), offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
diff --git a/server/routes/update-check.test.ts b/server/routes/update-check.test.ts
index 75409f6b43..9b06948694 100644
--- a/server/routes/update-check.test.ts
+++ b/server/routes/update-check.test.ts
@@ -3,7 +3,8 @@ import type { AddressInfo } from "node:net";
import { afterEach, describe, expect, it } from "vitest";
import { json, readBody } from "../harness/http.ts";
-import { requiredScope } from "../request-auth.ts";
+import { requiredScope, type RequestAuth } from "../request-auth.ts";
+import type { ServerUpdater } from "../server-update.ts";
import type { UpdateCheck } from "../update-check.ts";
import { dispatchRoutes } from "./table.ts";
import { createUpdateCheckRoutes } from "./update-check.ts";
@@ -13,13 +14,13 @@ afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
});
-async function serve(check: () => Promise<UpdateCheck>): Promise<string> {
- const routes = [createUpdateCheckRoutes({ check })];
+async function serve(check: () => Promise<UpdateCheck>, updater?: ServerUpdater, auth: RequestAuth = { kind: "loopback", scopes: ["admin"] }): Promise<string> {
+ const routes = [createUpdateCheckRoutes({ check, ...(updater ? { server: updater, actor: () => ({ kind: "loopback" as const }) } : {}) })];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
const handled = await dispatchRoutes(routes, {
req, res, url, path: url.pathname, method: req.method ?? "GET",
- auth: { kind: "loopback", scopes: ["admin"] }, json, readBody,
+ auth, json, readBody,
});
if (!handled) json(res, 404, { from: "inline routes" });
});
@@ -49,4 +50,24 @@ describe("update check route", () => {
expect(response.status).toBe(502);
expect(await response.json()).toEqual({ error: "Could not check for updates: GitHub answered 403" });
});
+
+ it("hands the Update server button only an admin's session; loopback and other methods are refused", async () => {
+ const asked: string[] = [];
+ const server: ServerUpdater = {
+ status: async () => { asked.push("status"); return { mode: "button", current: "0.1.150", available: true, activeTurns: 0 }; },
+ request: async () => { asked.push("request"); return { status: 202, body: { ok: true } }; },
+ };
+ const check = async (): Promise<UpdateCheck> => ({ current: "0.1.150", install: "docker", available: true });
+ const admin = { kind: "session", session: {}, via: "cookie", scopes: ["admin", "client"] } as unknown as RequestAuth;
+ const base = await serve(check, server, admin);
+ expect((await fetch(`${base}/api/updates/server`)).status).toBe(200);
+ expect((await fetch(`${base}/api/updates/server`, { method: "POST", body: '{"version":"0.0.1","image":"evil"}' })).status).toBe(202);
+ expect((await fetch(`${base}/api/updates/server`, { method: "DELETE" })).status).toBe(404);
+ expect(asked).toEqual(["status", "request"]);
+ const loopback = await serve(check, server);
+ const refused = await fetch(`${loopback}/api/updates/server`, { method: "POST" });
+ expect(refused.status).toBe(403);
+ expect(await refused.json()).toMatchObject({ code: "admin_only" });
+ expect(asked).toEqual(["status", "request"]);
+ });
});
diff --git a/server/routes/update-check.ts b/server/routes/update-check.ts
index 3acba2ce30..286a54a6b6 100644
--- a/server/routes/update-check.ts
+++ b/server/routes/update-check.ts
@@ -1,15 +1,37 @@
// GET /api/updates/check: whether a newer version exists, and how this install is updated. Read-only, so client sessions may ask.
+// GET and POST /api/updates/server: the Update server button, for an admin's session only (server/server-update.ts).
+import type { IncomingMessage } from "node:http";
+
+import type { AdminActor } from "../admin-activity.ts";
import { serverVersion } from "../environment.ts";
import { SERVER_ROOT } from "../proxy-paths.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { createServerUpdater, SERVER_UPDATE_DIR, SERVER_UPDATE_DIR_ENV, type ServerUpdater } from "../server-update.ts";
import { createUpdateChecker, installKind, updateChannel, type UpdateCheck } from "../update-check.ts";
import { PASS, type RouteHandler } from "./table.ts";
export interface UpdateCheckRouteDeps {
check(): Promise<UpdateCheck>;
+ server?: ServerUpdater;
+ actor?(auth: RequestAuth, req: IncomingMessage): AdminActor;
+}
+
+/** SECURITY: a person's admin session, never loopback: on a server, loopback is a bot's shell or a process beside it. This
+ * guards the button only. The request file it leaves is in a folder of the server's user, so until the bots' sandbox is
+ * on for self-hosted servers anything running as that user, a bot included, can leave it too; what that can cause is
+ * only the standard update (server/server-update.ts). */
+export function mayUpdateServer(auth: RequestAuth): boolean {
+ return auth.kind === "session" && auth.scopes.includes("admin");
}
export function createUpdateCheckRoutes(deps: UpdateCheckRouteDeps): RouteHandler {
- return async ({ res, path, method, json }) => {
+ return async ({ req, res, path, method, json, auth }) => {
+ if (path === "/api/updates/server" && deps.server && (method === "GET" || method === "POST")) {
+ if (!mayUpdateServer(auth)) return json(res, 403, { error: "Only an admin of this server, signed in, can update it.", code: "admin_only" });
+ if (method === "GET") return json(res, 200, await deps.server.status());
+ const done = await deps.server.request(deps.actor?.(auth, req) ?? { kind: "loopback" });
+ return json(res, done.status, done.body);
+ }
if (path !== "/api/updates/check" || method !== "GET") return PASS;
try {
return json(res, 200, await deps.check());
@@ -22,3 +44,19 @@ export function createUpdateCheckRoutes(deps: UpdateCheckRouteDeps): RouteHandle
export function serverUpdateChecker(where: { desktopManaged: boolean; managed: boolean }): () => Promise<UpdateCheck> {
return createUpdateChecker({ current: serverVersion(), install: installKind({ ...where, serverRoot: SERVER_ROOT }), channel: updateChannel() });
}
+
+/** Both routes' parts for this server: one shared check, and the button where the install has one. */
+export function updateRouteDeps(where: {
+ desktopManaged: boolean;
+ managed: boolean;
+ dataDir: string;
+ activeTurns(): number;
+ actor(auth: RequestAuth, req: IncomingMessage): AdminActor;
+}): UpdateCheckRouteDeps {
+ const install = installKind({ ...where, serverRoot: SERVER_ROOT });
+ const channel = updateChannel();
+ const check = createUpdateChecker({ current: serverVersion(), install, channel });
+ const dir = process.env[SERVER_UPDATE_DIR_ENV]?.trim() || (install === "docker" ? SERVER_UPDATE_DIR : undefined);
+ const server = createServerUpdater({ dir, dataDir: where.dataDir, install, version: serverVersion(), check, activeTurns: where.activeTurns, followsStable: channel === "stable" });
+ return { check, server, actor: where.actor };
+}
diff --git a/server/server-update.test.ts b/server/server-update.test.ts
new file mode 100644
index 0000000000..3caf00565c
--- /dev/null
+++ b/server/server-update.test.ts
@@ -0,0 +1,226 @@
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { flushAdminActivity, readAdminActivityRange } from "./admin-activity.ts";
+import type { RequestAuth } from "./request-auth.ts";
+import { requiredScope } from "./request-auth.ts";
+import { mayUpdateServer } from "./routes/update-check.ts";
+import {
+ createServerUpdater, parseRun, parseRunner, readHostFacts, REQUEST_GAP_MS, runOf, serverUpdateStatus, START_WAIT_MS,
+ type HostFacts, type PendingUpdate,
+} from "./server-update.ts";
+import type { UpdateCheck } from "./update-check.ts";
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const NOW = 1_800_000_000_000;
+const available: UpdateCheck = { current: "0.1.150", install: "docker", latest: "0.1.151", available: true, command: "git pull && ./update.sh" };
+const runner: HostFacts = { runner: { layout: "installer", dir: "/opt/openmausbot", held: false, release: true }, writable: true, last: { run: 3, state: "done", result: "updated", at: NOW - 86_400_000 } };
+
+/** The two folders the installer's compose.yaml gives the server, as the runner leaves them, and a data folder. */
+function host(options: { runnerFile?: string | null; last?: string; writable?: boolean } = {}) {
+ const root = mkdtempSync(join(tmpdir(), "omb-server-update-"));
+ dirs.push(root);
+ const dir = join(root, "omb-update");
+ const data = join(root, "data");
+ mkdirSync(join(dir, "request"), { recursive: true });
+ mkdirSync(join(dir, "status"), { recursive: true });
+ mkdirSync(data);
+ if (options.runnerFile !== null) writeFileSync(join(dir, "status", "runner"), options.runnerFile ?? "layout=installer\ndir=/opt/openmausbot\nheld=no\n");
+ writeFileSync(join(dir, "status", "last"), options.last ?? "run=3\nstate=done\nresult=updated\nat=1700000000\nran=1700000000\n");
+ if (options.writable === false) chmodSync(join(dir, "request"), 0o500);
+ const request = join(dir, "request", "request");
+ return { root, dir, data, request, finish: (text: string) => writeFileSync(join(dir, "status", "last"), text) };
+}
+
+function updater(box: ReturnType<typeof host>, options: { version?: string; check?: UpdateCheck; now?: () => number; turns?: number } = {}) {
+ return createServerUpdater({
+ dir: box.dir, dataDir: box.data, install: "docker", version: options.version ?? "0.1.150",
+ check: async () => options.check ?? available, activeTurns: () => options.turns ?? 0, now: options.now ?? (() => NOW),
+ });
+}
+
+const admin = { kind: "session", sessionId: "s1", label: "Laptop", email: "[email protected]" } as const;
+
+describe("what the host's runner wrote", () => {
+ it("reads only the fields it knows, in the shapes it expects", () => {
+ expect(parseRunner("layout=installer\ndir=/opt/openmausbot\nheld=no\nrelease=yes\n")).toEqual({ layout: "installer", dir: "/opt/openmausbot", held: false, release: true });
+ expect(parseRunner("layout=compose\ndir=/srv/OpenMausBot/deploy\nheld=yes\nrelease=no\n")).toEqual({ layout: "compose", dir: "/srv/OpenMausBot/deploy", held: true, release: false });
+ for (const bad of [null, "", "layout=podman\ndir=/opt/x", "layout=installer\ndir=relative", "layout=installer\ndir=/opt/x; rm -rf /"]) expect(parseRunner(bad), String(bad)).toBeNull();
+ expect(parseRun("run=4\nstate=running\nat=1700000000\nran=1700000000\n")).toEqual({ run: 4, state: "running", at: 1_700_000_000_000 });
+ expect(parseRun("run=4\nstate=done\nresult=rolled-back\nat=1700000000\n")).toEqual({ run: 4, state: "done", result: "rolled-back", at: 1_700_000_000_000 });
+ expect(parseRun("run=5\nstate=done\nresult=not-retried\nat=1\nversion=0.1.151\n")).toEqual({ run: 5, state: "done", result: "not-retried", at: 1000, version: "0.1.151" });
+ expect(parseRun("run=5\nstate=done\nresult=stale\nat=1\nversion=x;y\n")).toEqual({ run: 5, state: "done", result: "stale", at: 1000 });
+ expect(parseRun("run=6\nstate=done\nresult=unsafe\nat=1\ndetail=/opt root:staff 775\n")).toEqual({ run: 6, state: "done", result: "unsafe", at: 1000, detail: "/opt root:staff 775" });
+ expect(parseRun("run=6\nstate=done\nresult=unsafe\nat=1\ndetail=/opt $(x) 775\n")).toEqual({ run: 6, state: "done", result: "unsafe", at: 1000 });
+ expect(parseRun("run=7\nstate=done\nresult=no-room\nat=1\n")).toMatchObject({ result: "no-room" });
+ for (const bad of ["run=x\nstate=done\nresult=updated\nat=1", "run=1\nstate=done\nresult=whatever\nat=1", "run=1\nstate=done\nat=1", "run=1\nstate=odd\nat=1"]) expect(parseRun(bad), bad).toBeNull();
+ });
+
+ it("knows the runner is there only when its file is, and the request folder takes a file", () => {
+ const box = host();
+ expect(readHostFacts(box.dir)).toMatchObject({ runner: { layout: "installer" }, writable: true, last: { run: 3 } });
+ expect(readHostFacts(undefined)).toEqual({ runner: null, writable: false, last: null });
+ expect(readHostFacts(host({ runnerFile: null }).dir).runner).toBeNull();
+ // Folder modes are POSIX's; the server runs in a Linux container.
+ if (process.platform !== "win32" && process.getuid?.() !== 0) expect(readHostFacts(host({ writable: false }).dir).writable).toBe(false);
+ });
+});
+
+describe("the button's state", () => {
+ const status = (patch: Partial<Parameters<typeof serverUpdateStatus>[0]>) =>
+ serverUpdateStatus({ install: "docker", check: available, facts: runner, pending: null, version: "0.1.150", activeTurns: 2, now: NOW, ...patch });
+
+ it("offers the button only on a Docker install whose host has the runner, and says the commands it stands for", () => {
+ expect(status({})).toEqual({
+ mode: "button", current: "0.1.150", latest: "0.1.151", available: true, activeTurns: 2,
+ command: "cd /opt/openmausbot && sudo ./update.sh", rollback: "cd /opt/openmausbot && sudo ./update.sh --rollback",
+ logs: "cd /opt/openmausbot && sudo docker compose logs --tail 50 omb", setup: "cd /opt/openmausbot && sudo ./update-runner.sh --install",
+ });
+ expect(status({ facts: { ...runner, runner: { ...runner.runner!, held: true } } }).mode).toBe("held");
+ });
+
+ it("never offers the button for a build of main: it says so, with the command that moves it to stable", () => {
+ expect(status({ facts: { ...runner, runner: { ...runner.runner!, release: false } } })).toMatchObject({
+ mode: "command", why: "unreleased", command: "cd /opt/openmausbot && sudo ./update.sh",
+ });
+ });
+
+ it("shows the command, not the button, when the check follows every release, which update.sh does not take", () => {
+ const newest: UpdateCheck = { ...available, channel: "newest", latest: "0.1.152", command: "git pull && ./update.sh --version 0.1.152" };
+ expect(status({ check: newest, followsStable: false })).toMatchObject({ mode: "command", command: "git pull && ./update.sh --version 0.1.152" });
+ // Before a first version is made stable, the check and update.sh both take the newest release: the button stays.
+ expect(status({ check: { ...available, channel: "newest" }, followsStable: true }).mode).toBe("button");
+ });
+
+ it("shows the command to run instead wherever the button could not work", () => {
+ expect(status({ facts: { runner: null, writable: false, last: null } })).toMatchObject({ mode: "command", command: "git pull && ./update.sh" });
+ expect(status({ facts: { ...runner, writable: false } }).mode).toBe("command");
+ const npm: UpdateCheck = { ...available, install: "npm", command: "npm install -g [email protected]", restart: true };
+ expect(status({ install: "npm", check: npm })).toMatchObject({ mode: "command", command: "npm install -g [email protected]" });
+ // A runner's files somewhere else than a container are never the button: npm and Podman get their commands.
+ expect(status({ install: "podman", check: { ...available, install: "podman", command: undefined } })).toMatchObject({ mode: "command" });
+ });
+
+ it("never shows anything for this computer's app or a Cloud we run", () => {
+ expect(status({ install: "managed" })).toEqual({ mode: "none", current: "0.1.150", latest: "0.1.151", available: true, activeTurns: 2 });
+ expect(status({ install: "desktop" }).mode).toBe("none");
+ });
+
+ it("follows one request from asked to its outcome, by the runner's run number", () => {
+ const pending: PendingUpdate = { at: NOW, baseline: 3, from: "0.1.150" };
+ expect(runOf(pending, runner.last, "0.1.150", NOW + 1000)).toEqual({ outcome: "requested", from: "0.1.150", at: NOW });
+ expect(runOf(pending, { run: 4, state: "running", at: NOW + 2000 }, "0.1.150", NOW + 3000)?.outcome).toBe("running");
+ expect(runOf(pending, { run: 4, state: "done", result: "updated", at: NOW + 60_000 }, "0.1.151", NOW + 61_000)).toEqual({ outcome: "updated", from: "0.1.150", to: "0.1.151", at: NOW });
+ expect(runOf(pending, { run: 4, state: "done", result: "updated", at: NOW + 60_000 }, "0.1.150", NOW + 61_000)?.outcome).toBe("unchanged");
+ expect(runOf(pending, { run: 4, state: "done", result: "rolled-back", at: NOW + 60_000 }, "0.1.150", NOW + 61_000)).toMatchObject({ outcome: "rolled-back", to: "0.1.150" });
+ expect(runOf(pending, { run: 4, state: "done", result: "rollback-failed", at: NOW + 60_000 }, "0.1.150", NOW + 61_000)?.outcome).toBe("rollback-failed");
+ expect(runOf(pending, { run: 4, state: "done", result: "too-soon", at: NOW + 60_000 }, "0.1.150", NOW + 61_000)).toMatchObject({ outcome: "not-changed", reason: "too-soon" });
+ expect(runOf(pending, { run: 4, state: "done", result: "not-retried", at: NOW + 60_000, version: "0.1.151" }, "0.1.150", NOW + 61_000)).toMatchObject({ outcome: "not-changed", reason: "not-retried", target: "0.1.151" });
+ expect(runOf(pending, runner.last, "0.1.150", NOW + START_WAIT_MS + 1)?.outcome).toBe("not-started");
+ // A run cut off (a reboot) is not "updating" for ever; an old outcome is not shown for ever.
+ expect(runOf(pending, { run: 4, state: "running", at: NOW }, "0.1.150", NOW + 3 * 60 * 60_000)).toMatchObject({ outcome: "not-changed", reason: "failed" });
+ expect(runOf(pending, { run: 4, state: "done", result: "updated", at: NOW }, "0.1.151", NOW + 2 * 60 * 60_000)).toBeUndefined();
+ expect(runOf(null, runner.last, "0.1.150", NOW)).toBeUndefined();
+ });
+});
+
+describe("a request", () => {
+ it("leaves a file the host only needs to see, records it for after the restart, and logs who asked", async () => {
+ const box = host();
+ const done = await updater(box).request(admin);
+ expect(done.status).toBe(202);
+ expect((done.body.status as { run: unknown }).run).toEqual({ outcome: "requested", from: "0.1.150", at: NOW });
+ expect(readFileSync(box.request, "utf8")).toMatch(/^[0-9a-f-]{36}\n$/);
+ expect(JSON.parse(readFileSync(join(box.data, "server-update.json"), "utf8"))).toEqual({ at: NOW, baseline: 3, from: "0.1.150" });
+ await flushAdminActivity(box.data);
+ const rows = readAdminActivityRange(box.data, { from: new Date(Date.now() - 60_000), to: new Date(Date.now() + 60_000) });
+ expect(rows).toEqual([expect.objectContaining({ category: "config", action: "update.server", target: { kind: "server", name: "0.1.150 → 0.1.151" }, actor: admin })]);
+ });
+
+ it("asks the host to check its remembered answer again when that named an older version than this server's check", async () => {
+ const stale = host({ last: "run=3\nstate=done\nresult=updated\nat=1700000000\nran=0\nversion=0.1.150\n" });
+ expect((await updater(stale).request(admin)).status).toBe(202);
+ expect(existsSync(join(stale.dir, "request", "fresh"))).toBe(true);
+ const current = host({ last: "run=3\nstate=done\nresult=updated\nat=1700000000\nran=0\nversion=0.1.151\n" });
+ expect((await updater(current).request(admin)).status).toBe(202);
+ expect(existsSync(join(current.dir, "request", "fresh"))).toBe(false);
+ });
+
+ it("is one at a time: a second press while one runs is answered with the running one", async () => {
+ const box = host();
+ const one = updater(box);
+ const presses = await Promise.all([one.request(admin), one.request(admin)]);
+ expect(presses.map((press) => press.status).sort()).toEqual([202, 409]);
+ const again = await updater(box, { now: () => NOW + 1000 }).request(admin);
+ expect(again).toMatchObject({ status: 409, body: { code: "running", status: { run: { outcome: "requested" } } } });
+ box.finish("run=4\nstate=running\nat=1800000001\nran=1800000001\n");
+ expect(await updater(box, { now: () => NOW + 2000 }).request(admin)).toMatchObject({ status: 409, body: { code: "running" } });
+ });
+
+ it("is refused for five minutes after the last one, and when there is nothing to update to", async () => {
+ const box = host();
+ expect((await updater(box).request(admin)).status).toBe(202);
+ box.finish("run=4\nstate=done\nresult=refused\nat=1800000030\nran=1800000000\n");
+ rmSync(box.request, { force: true });
+ const soon = await updater(box, { now: () => NOW + 60_000 }).request(admin);
+ expect(soon).toMatchObject({ status: 429, body: { code: "too-soon", status: { retryAt: NOW + REQUEST_GAP_MS } } });
+ expect(existsSync(box.request)).toBe(false);
+ expect((await updater(box, { now: () => NOW + REQUEST_GAP_MS + 1 }).request(admin)).status).toBe(202);
+ const current = host();
+ expect(await updater(current, { check: { ...available, available: false, latest: "0.1.150" } }).request(admin)).toMatchObject({ status: 409, body: { code: "up-to-date" } });
+ expect(existsSync(current.request)).toBe(false);
+ });
+
+ it("is refused, with nothing written, where the button cannot work", async () => {
+ const none = host({ runnerFile: null });
+ expect(await updater(none).request(admin)).toMatchObject({ status: 409, body: { code: "unavailable", status: { mode: "command" } } });
+ const held = host({ runnerFile: "layout=installer\ndir=/opt/openmausbot\nheld=yes\n" });
+ expect(await updater(held).request(admin)).toMatchObject({ status: 409, body: { code: "unavailable", status: { mode: "held" } } });
+ for (const box of [none, held]) {
+ expect(existsSync(box.request)).toBe(false);
+ expect(readdirSync(box.data)).toEqual([]);
+ }
+ const managed = createServerUpdater({ dir: undefined, dataDir: host().data, install: "managed", version: "0.1.150", check: async () => available, activeTurns: () => 0 });
+ expect(await managed.request(admin)).toMatchObject({ status: 409, body: { status: { mode: "none" } } });
+ });
+
+ it("withdraws a request the host never took, so a runner switched on later does not act on it", async () => {
+ const box = host();
+ await updater(box).request(admin);
+ expect(existsSync(box.request)).toBe(true);
+ const status = await updater(box, { now: () => NOW + START_WAIT_MS + 1 }).status();
+ expect(status.run?.outcome).toBe("not-started");
+ expect(existsSync(box.request)).toBe(false);
+ });
+
+ it("reads the outcome after the restart, from what the runner wrote", async () => {
+ const box = host();
+ await updater(box).request(admin);
+ box.finish("run=4\nstate=done\nresult=updated\nat=1800000120\nran=1800000001\n");
+ expect((await updater(box, { version: "0.1.151", now: () => NOW + 130_000 }).status()).run).toEqual({ outcome: "updated", from: "0.1.150", to: "0.1.151", at: NOW });
+ box.finish("run=4\nstate=done\nresult=rolled-back\nat=1800000120\nran=1800000001\n");
+ expect((await updater(box, { now: () => NOW + 130_000 }).status()).run).toMatchObject({ outcome: "rolled-back", to: "0.1.150" });
+ });
+});
+
+describe("who may press it", () => {
+ const session = (scopes: string[]) => ({ kind: "session", session: {}, via: "cookie", scopes }) as unknown as RequestAuth;
+
+ it("an admin's session; never a member, a bot's shell or anything else on loopback", () => {
+ expect(mayUpdateServer(session(["admin", "client"]))).toBe(true);
+ expect(mayUpdateServer(session(["client"]))).toBe(false);
+ expect(mayUpdateServer({ kind: "loopback", scopes: ["admin", "client"] })).toBe(false);
+ expect(mayUpdateServer({ kind: "loopback", scopes: ["client"], trust: "service" })).toBe(false);
+ });
+
+ it("is an admin route for the central check: a member's session never reaches it", () => {
+ expect(requiredScope("GET", "/api/updates/server")).toBe("admin");
+ expect(requiredScope("POST", "/api/updates/server")).toBe("admin");
+ });
+});
diff --git a/server/server-update.ts b/server/server-update.ts
new file mode 100644
index 0000000000..d83ca7cc82
--- /dev/null
+++ b/server/server-update.ts
@@ -0,0 +1,245 @@
+// The server's half of the Update server button. A server in a container cannot replace its own image, so it only leaves
+// a file in the request folder its host gave it; root's deploy/update-runner.sh on the host sees the file, runs update.sh
+// as an owner would and writes how that ended into the status folder, which this container sees read-only.
+//
+// SECURITY: the runner never reads the request file. Whatever is written here, the host runs root's copy of `update.sh`
+// with no argument but the install's folder: the stable version, only when the running image's own label is older, a
+// copy of the data first, a rollback when the new version is not healthy. No version, image, URL, flag or path from a
+// client or from this server reaches the host. The route is an admin's only, but the folder is the server's user's:
+// until the bots' sandbox is on for self-hosted servers, a bot can leave the same file, and gets that same update.
+import { randomUUID } from "node:crypto";
+import { accessSync, constants, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import type { ServerUpdateOutcome, ServerUpdateReason, ServerUpdateRun, ServerUpdateStatus } from "../shared/server-update.ts";
+import { appendAdminAction, type AdminActor } from "./admin-activity.ts";
+import { isNewerVersion, updateCommand, type InstallKind, type UpdateCheck } from "./update-check.ts";
+
+/** Where a Docker install mounts the two folders (deploy/install.sh's compose.yaml, update-runner.sh's override):
+ * `request` (writable) and `status` (read-only). OMB_SERVER_UPDATE_DIR names another place. */
+export const SERVER_UPDATE_DIR = "/run/omb-update";
+export const SERVER_UPDATE_DIR_ENV = "OMB_SERVER_UPDATE_DIR";
+/** One request per five minutes; the runner on the host keeps its own, shorter gap. */
+export const REQUEST_GAP_MS = 5 * 60_000;
+/** A request the host has not taken by then is reported as never started, and may be made again. */
+export const START_WAIT_MS = 2 * 60_000;
+/** A run the host says is still going after this long was cut off (a reboot, a kill). */
+const RUNNING_FOR_MS = 2 * 60 * 60_000;
+/** How long the outcome of the last request is shown. */
+const SHOWN_FOR_MS = 60 * 60_000;
+const PENDING_FILE = "server-update.json";
+
+const REASONS: readonly ServerUpdateReason[] = ["busy", "refused", "older", "held", "too-soon", "no-updater", "failed", "not-retried", "stale", "unreleased", "unsafe", "no-room"];
+export type HostResult = "updated" | "rolled-back" | "rollback-failed" | ServerUpdateReason;
+const RESULTS: readonly HostResult[] = ["updated", "rolled-back", "rollback-failed", ...REASONS];
+
+/** `release`: the running image is labelled with a released version (false for a build of main). */
+export interface HostRunner { layout: "installer" | "compose"; dir: string; held: boolean; release: boolean }
+export interface HostRun { run: number; state: "running" | "done"; result?: HostResult; at: number; version?: string; detail?: string }
+export interface HostFacts {
+ runner: HostRunner | null;
+ /** This server can leave a file in the request folder. */
+ writable: boolean;
+ last: HostRun | null;
+}
+
+/** What this server asked for, kept in its data folder so the answer is known after the restart. */
+export interface PendingUpdate {
+ at: number;
+ /** The runner's run number when it was asked: a higher one is this request's. */
+ baseline: number;
+ from: string;
+}
+
+function fields(text: string | null): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const line of (text ?? "").slice(0, 4096).split("\n")) {
+ const match = /^([a-z]+)=([^\n]*)$/.exec(line.trim());
+ if (match && !out.has(match[1]!)) out.set(match[1]!, match[2]!);
+ }
+ return out;
+}
+
+function readText(path: string): string | null {
+ try { return readFileSync(path, "utf8"); } catch { return null; }
+}
+
+export function parseRunner(text: string | null): HostRunner | null {
+ const f = fields(text);
+ const layout = f.get("layout");
+ const dir = f.get("dir");
+ if ((layout !== "installer" && layout !== "compose") || !dir || !/^\/[A-Za-z0-9/._-]{0,200}$/.test(dir)) return null;
+ return { layout, dir, held: f.get("held") === "yes", release: f.get("release") !== "no" };
+}
+
+export function parseRun(text: string | null): HostRun | null {
+ const f = fields(text);
+ const run = Number(f.get("run"));
+ const at = Number(f.get("at"));
+ const state = f.get("state");
+ const result = f.get("result") as HostResult | undefined;
+ if (!/^\d{1,9}$/.test(f.get("run") ?? "") || !/^\d{1,12}$/.test(f.get("at") ?? "")) return null;
+ if (state !== "running" && state !== "done") return null;
+ if (state === "done" && !(result && RESULTS.includes(result))) return null;
+ const version = f.get("version");
+ const detail = f.get("detail");
+ return {
+ run, state, at: at * 1000, ...(state === "done" ? { result } : {}), ...(version && /^\d+\.\d+\.\d+$/.test(version) ? { version } : {}),
+ ...(detail && /^\/[A-Za-z0-9/._-]{0,200} [A-Za-z0-9._-]{1,64}:[A-Za-z0-9._-]{1,64} [0-7]{3,4}$/.test(detail) ? { detail } : {}),
+ };
+}
+
+export function readHostFacts(dir: string | undefined): HostFacts {
+ if (!dir) return { runner: null, writable: false, last: null };
+ let writable = false;
+ try {
+ accessSync(join(dir, "request"), constants.W_OK);
+ writable = true;
+ } catch {
+ }
+ return { runner: parseRunner(readText(join(dir, "status", "runner"))), writable, last: parseRun(readText(join(dir, "status", "last"))) };
+}
+
+export function readPending(dataDir: string): PendingUpdate | null {
+ try {
+ const raw = JSON.parse(readFileSync(join(dataDir, PENDING_FILE), "utf8")) as Partial<PendingUpdate>;
+ if (typeof raw.at !== "number" || typeof raw.baseline !== "number" || typeof raw.from !== "string") return null;
+ return { at: raw.at, baseline: raw.baseline, from: raw.from };
+ } catch {
+ return null;
+ }
+}
+
+function writePending(dataDir: string, pending: PendingUpdate): void {
+ mkdirSync(dataDir, { recursive: true });
+ const file = join(dataDir, PENDING_FILE);
+ writeFileSync(`${file}.tmp`, JSON.stringify(pending), { mode: 0o600 });
+ renameSync(`${file}.tmp`, file);
+}
+
+function outcomeOf(result: HostResult | undefined, from: string, version: string): { outcome: ServerUpdateOutcome; reason?: ServerUpdateReason } {
+ if (result === "updated") return { outcome: from === version ? "unchanged" : "updated" };
+ if (result === "rolled-back" || result === "rollback-failed") return { outcome: result };
+ return { outcome: "not-changed", reason: result ?? "failed" };
+}
+
+/** The last request and how it went, from what this server asked and what the host wrote since. */
+export function runOf(pending: PendingUpdate | null, last: HostRun | null, version: string, now: number): ServerUpdateRun | undefined {
+ if (!pending) return undefined;
+ const base = { from: pending.from, at: pending.at };
+ if (last && last.run > pending.baseline) {
+ if (last.state === "running") {
+ return now - last.at < RUNNING_FOR_MS ? { ...base, outcome: "running" } : { ...base, outcome: "not-changed", reason: "failed" };
+ }
+ if (now - last.at > SHOWN_FOR_MS) return undefined;
+ return { ...base, to: version, ...(last.version ? { target: last.version } : {}), ...(last.detail ? { detail: last.detail } : {}), ...outcomeOf(last.result, pending.from, version) };
+ }
+ if (now - pending.at < START_WAIT_MS) return { ...base, outcome: "requested" };
+ if (now - pending.at > SHOWN_FOR_MS) return undefined;
+ return { ...base, outcome: "not-started" };
+}
+
+export function serverUpdateStatus(input: {
+ install: InstallKind;
+ check: UpdateCheck | null;
+ facts: HostFacts;
+ pending: PendingUpdate | null;
+ version: string;
+ activeTurns: number;
+ now: number;
+ /** The update check follows the stable channel, as update.sh does; with OMB_UPDATE_CHANNEL=newest it does not. */
+ followsStable?: boolean;
+}): ServerUpdateStatus {
+ const { install, check, facts, pending, version, now } = input;
+ const base = { current: version, available: check?.available === true, ...(check?.latest ? { latest: check.latest } : {}), activeTurns: input.activeTurns };
+ if (install === "desktop" || install === "managed") return { ...base, mode: "none" };
+ const runner = install === "docker" && facts.writable ? facts.runner : null;
+ const run = runOf(pending, facts.last, version, now);
+ const retryAt = pending && now - pending.at < REQUEST_GAP_MS ? pending.at + REQUEST_GAP_MS : undefined;
+ const extra = { ...(run ? { run } : {}), ...(retryAt ? { retryAt } : {}) };
+ if (runner && !runner.release) {
+ return { ...base, ...extra, mode: "command", why: "unreleased", command: `cd ${runner.dir} && sudo ./update.sh` };
+ }
+ if (runner && input.followsStable !== false) {
+ const own = {
+ command: `cd ${runner.dir} && sudo ./update.sh`, rollback: `cd ${runner.dir} && sudo ./update.sh --rollback`,
+ logs: `cd ${runner.dir} && sudo docker compose logs --tail 50 omb`, setup: `cd ${runner.dir} && sudo ./update-runner.sh --install`,
+ };
+ return { ...base, ...own, ...extra, mode: runner.held ? "held" : "button" };
+ }
+ const command = check?.command ?? updateCommand(install)?.command;
+ return { ...base, ...extra, mode: "command", ...(command ? { command } : {}) };
+}
+
+export interface ServerUpdater {
+ status(): Promise<ServerUpdateStatus>;
+ /** One request, made for `actor`: the HTTP status to answer and its body. */
+ request(actor: AdminActor): Promise<{ status: number; body: Record<string, unknown> }>;
+}
+
+export function createServerUpdater(options: {
+ dir: string | undefined;
+ dataDir: string;
+ install: InstallKind;
+ version: string;
+ check(): Promise<UpdateCheck>;
+ activeTurns(): number;
+ followsStable?: boolean;
+ now?: () => number;
+}): ServerUpdater {
+ const now = options.now ?? Date.now;
+ const requestFile = options.dir ? join(options.dir, "request", "request") : null;
+ let queue: Promise<unknown> = Promise.resolve();
+
+ async function status(): Promise<ServerUpdateStatus> {
+ const check = await options.check().catch(() => null);
+ const facts = readHostFacts(options.dir);
+ const pending = readPending(options.dataDir);
+ const answer = serverUpdateStatus({ install: options.install, check, facts, pending, version: options.version, activeTurns: options.activeTurns(), now: now(), followsStable: options.followsStable });
+ // A request the host never took is withdrawn, so a runner switched on later does not act on an old press.
+ if (answer.run?.outcome === "not-started" && requestFile) rmSync(requestFile, { force: true, recursive: true });
+ return answer;
+ }
+
+ async function request(actor: AdminActor): Promise<{ status: number; body: Record<string, unknown> }> {
+ const current = await status();
+ if (current.mode !== "button" || !requestFile) {
+ return { status: 409, body: { error: "This server can't be updated from the app.", code: "unavailable", status: current } };
+ }
+ if (current.run?.outcome === "requested" || current.run?.outcome === "running") {
+ return { status: 409, body: { error: "This server is already updating.", code: "running", status: current } };
+ }
+ if (!current.available) return { status: 409, body: { error: "This server is up to date.", code: "up-to-date", status: current } };
+ if (current.retryAt) return { status: 429, body: { error: "Wait a few minutes before you ask again.", code: "too-soon", status: current } };
+ const last = readHostFacts(options.dir).last;
+ const pending: PendingUpdate = { at: now(), baseline: last?.run ?? 0, from: options.version };
+ writePending(options.dataDir, pending);
+ try {
+ // The host's last answer named an older stable version than this server's own check: it is checked, not reused.
+ if (last?.result === "updated" && last.version && current.latest && isNewerVersion(current.latest, last.version)) {
+ writeFileSync(join(options.dir!, "request", "fresh"), "", { mode: 0o600 });
+ }
+ rmSync(requestFile, { force: true, recursive: true });
+ writeFileSync(requestFile, `${randomUUID()}\n`, { mode: 0o600, flag: "wx" });
+ } catch {
+ rmSync(join(options.dataDir, PENDING_FILE), { force: true });
+ return { status: 500, body: { error: "The update could not be asked for: this server can't write its request.", code: "unwritable", status: await status() } };
+ }
+ appendAdminAction(options.dataDir, {
+ category: "config",
+ action: "update.server",
+ target: { kind: "server", name: `${options.version} → ${current.latest ?? "?"}` },
+ actor,
+ });
+ return { status: 202, body: { status: await status() } };
+ }
+
+ return {
+ status,
+ request: (actor) => {
+ const next = queue.then(() => request(actor));
+ queue = next.catch(() => {});
+ return next;
+ },
+ };
+}
diff --git a/shared/server-update.ts b/shared/server-update.ts
new file mode 100644
index 0000000000..7f587508fa
--- /dev/null
+++ b/shared/server-update.ts
@@ -0,0 +1,64 @@
+// GET and POST /api/updates/server: the Update server button in Settings → Updates, for the server's admins.
+
+/**
+ * `button`: this server can be updated from the app (a Docker Compose install with deploy/update-runner.sh on its host).
+ * `command`: it cannot, or the server follows every release (OMB_UPDATE_CHANNEL=newest), which update.sh does not take;
+ * `command` is what to run on the server instead.
+ * `held`: the host's own policy holds updates (`"updates": "hold"` in /etc/mausbot/policy.json).
+ * `none`: updated for its owner (this computer's app, or a Cloud we run): no button and no command.
+ */
+export type ServerUpdateMode = "button" | "command" | "held" | "none";
+
+/** How the last request went. `requested`: written, not yet taken by the host. `not-started`: the host never took it. */
+export type ServerUpdateOutcome =
+ | "requested"
+ | "running"
+ | "updated"
+ | "unchanged"
+ | "rolled-back"
+ | "rollback-failed"
+ | "not-changed"
+ | "not-started";
+
+/** Why an update changed nothing (`not-changed`), as the host's runner said it. */
+/** `not-retried`: the stable version rolled back on this server before, and is not tried again from the app. `stale`: a
+ * checkout's update.sh is newer than root's copy the button runs. `unreleased`: the server runs a build of main. `unsafe`:
+ * the install's folder, or one above it, can be changed by someone other than root and its owner. `no-room`: not enough
+ * free disk for a copy of the data. */
+export type ServerUpdateReason =
+ | "busy" | "refused" | "older" | "held" | "too-soon" | "no-updater" | "failed" | "not-retried" | "stale" | "unreleased" | "unsafe" | "no-room";
+
+export interface ServerUpdateRun {
+ outcome: ServerUpdateOutcome;
+ reason?: ServerUpdateReason;
+ /** The version that ran when the update was asked for, and the one that answers now. */
+ from: string;
+ to?: string;
+ /** The version the host's runner tried, when it says. */
+ target?: string;
+ /** For `unsafe`: the folder that failed, as "PATH user:group mode". */
+ detail?: string;
+ /** When it was asked for (ms since the epoch). */
+ at: number;
+}
+
+export interface ServerUpdateStatus {
+ mode: ServerUpdateMode;
+ current: string;
+ latest?: string;
+ available: boolean;
+ command?: string;
+ /** What puts the version from before the last update back, run on the server by hand. */
+ rollback?: string;
+ /** What shows the server's own log on the host, when it does not come back. */
+ logs?: string;
+ /** What refreshes the button's copy of update.sh on the host. */
+ setup?: string;
+ /** `unreleased`: the server runs a build of main, which the button does not update; `command` moves it to stable. */
+ why?: "unreleased";
+ /** Turns running now, which an update stops. */
+ activeTurns: number;
+ run?: ServerUpdateRun;
+ /** A new request is refused until then (ms since the epoch). */
+ retryAt?: number;
+}
diff --git a/src/components/ServerUpdateRow.tsx b/src/components/ServerUpdateRow.tsx
new file mode 100644
index 0000000000..942fc7f1ef
--- /dev/null
+++ b/src/components/ServerUpdateRow.tsx
@@ -0,0 +1,169 @@
+import { useCallback, useEffect, useState } from "react";
+
+import { unlessRefused } from "@/lib/admin-scope";
+import { openExternalLink } from "@/lib/app-links";
+import { t } from "@/lib/i18n";
+import { serverUpdateConfirmBody, serverUpdateView, type ServerUpdateCheck, type ServerUpdateStatus, type ServerUpdateView } from "@/lib/server-update";
+import { ApiError } from "@/state/api";
+import { api, useStore } from "@/state/store";
+import type { AppUpdateAnswer } from "@/types/ogb";
+import { ConfirmDialog } from "./ConfirmDialog";
+import { SettingRow } from "./SettingsPrimitives";
+
+const STATUS = "/api/updates/server";
+const POLL_MS = 4_000;
+
+/** This desktop app's version when the window shows a server from the Server menu that may ask for the app's update. */
+function askableAppVersion(): string | null {
+ const ogb = typeof window === "undefined" ? undefined : window.ogb;
+ return ogb?.app?.ownPage === false && ogb.appUpdate && ogb.app.version ? ogb.app.version : null;
+}
+
+const settled = (status: ServerUpdateStatus | null) => status?.run?.outcome !== "requested" && status?.run?.outcome !== "running";
+
+/** The check every session may read, the admin's button state, and the press. While the server restarts the page's
+ * connection drops; the store's own reconnect brings it back (`state.connected`), and only then is the server asked again. */
+export function useServerUpdate() {
+ const { state } = useStore();
+ const connected = state.connected !== false;
+ const [check, setCheck] = useState<ServerUpdateCheck | null>(null);
+ const [status, setStatus] = useState<ServerUpdateStatus | null>(null);
+ const [checking, setChecking] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [pressed, setPressed] = useState(false);
+ const [problem, setProblem] = useState<string | null>(null);
+ const [appAnswer, setAppAnswer] = useState<AppUpdateAnswer | null>(null);
+
+ const readStatus = useCallback(async () => {
+ const next = await unlessRefused(STATUS, () => api<ServerUpdateStatus>(STATUS, { timeoutMs: 20_000 }), null);
+ setStatus(next);
+ return next;
+ }, []);
+
+ const load = useCallback(async () => {
+ setChecking(true);
+ setFailed(false);
+ try {
+ const next = await api<ServerUpdateCheck>("/api/updates/check", { timeoutMs: 20_000 });
+ setCheck(next);
+ if (next.install !== "desktop" && next.install !== "managed") await readStatus().catch(() => null);
+ } catch {
+ setFailed(true);
+ } finally {
+ setChecking(false);
+ }
+ }, [readStatus]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const updating = pressed || !settled(status);
+ const [waitingSince, setWaitingSince] = useState<number | null>(null);
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!updating) return void setWaitingSince(null);
+ setWaitingSince((since) => since ?? Date.now());
+ const timer = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(timer);
+ }, [updating]);
+ useEffect(() => {
+ if (!updating || !connected) return;
+ let alive = true;
+ const ask = () => void readStatus().then((next) => {
+ if (alive && settled(next)) void load();
+ }).catch(() => {});
+ ask();
+ const timer = setInterval(ask, POLL_MS);
+ return () => {
+ alive = false;
+ clearInterval(timer);
+ };
+ }, [updating, connected, readStatus, load]);
+
+ const updateServer = useCallback(async () => {
+ setPressed(true);
+ setProblem(null);
+ try {
+ const answer = await api<{ status: ServerUpdateStatus }>(STATUS, { method: "POST", body: "{}", timeoutMs: 20_000 });
+ setStatus(answer.status);
+ } catch (error) {
+ if (error instanceof ApiError) {
+ const body = error.body as { status?: ServerUpdateStatus } | undefined;
+ if (body?.status) setStatus(body.status);
+ setProblem(error.status === 429 ? t("serverUpdate.reason.tooSoon") : error.status === 409 ? null : t("serverUpdate.failed"));
+ } else {
+ // No answer: the server may already be stopping for the update. Wait for it as if it had said so.
+ setStatus((current) => current && { ...current, run: { outcome: "requested", from: current.current, at: Date.now() } });
+ }
+ } finally {
+ setPressed(false);
+ }
+ }, []);
+
+ const updateApp = useCallback(async () => {
+ try {
+ setAppAnswer(await window.ogb!.appUpdate!.request());
+ } catch {
+ setAppAnswer("failed");
+ }
+ }, []);
+
+ const waitedMs = waitingSince === null ? 0 : Math.max(0, now - waitingSince);
+ const view: ServerUpdateView = serverUpdateView({ check, status, app: askableAppVersion(), checking, failed, pressed, appAnswer, waitedMs });
+ return { check, status, view: problem ? { ...view, note: problem, noteTone: "danger" as const } : view, load, readStatus, updateServer, updateApp };
+}
+
+const ACTION_LABEL = {
+ check: "settings.updates.check",
+ "update-server": "serverUpdate.updateServer",
+ "update-app": "serverUpdate.updateApp",
+ reload: "settings.simple.updates.reload",
+} as const;
+
+/** Settings → Updates on a server's page: one row for what is behind (the server, this app, or both) and the one action
+ * that fixes it. A server updated for its owner (this computer's app, a Cloud we run) gets no button. */
+export function ServerUpdateRow({ title }: { title: string }) {
+ const update = useServerUpdate();
+ const [confirming, setConfirming] = useState(false);
+ const { view, check, status } = update;
+ const press = () => {
+ if (view.action === "check") return void update.load();
+ if (view.action === "reload") return window.location.reload();
+ if (view.action === "update-app") return void update.updateApp();
+ if (view.action === "update-server") {
+ void update.readStatus().catch(() => null);
+ setConfirming(true);
+ }
+ };
+ const release = check?.available && check.releaseUrl && view.action !== "check" ? check.releaseUrl : null;
+ return (
+ <>
+ <SettingRow
+ title={title}
+ subtitle={[view.label, view.subtitle].filter(Boolean).join(" ")}
+ message={view.note ? <span className={view.noteTone === "danger" ? "text-danger" : "text-ink-secondary"}>{view.note}</span> : undefined}
+ >
+ <div className="flex items-center gap-2">
+ {release && (
+ <button type="button" className="ui-button" onClick={() => openExternalLink(release)}>{t("settings.simple.updates.seeRelease")}</button>
+ )}
+ {view.action && (
+ <button type="button" className="ui-button" disabled={view.busy} onClick={press}>{t(ACTION_LABEL[view.action])}</button>
+ )}
+ </div>
+ </SettingRow>
+ <ConfirmDialog
+ open={confirming}
+ title={t("serverUpdate.confirmTitle")}
+ body={serverUpdateConfirmBody(status?.activeTurns ?? 0)}
+ confirmLabel={t("serverUpdate.updateServer")}
+ onCancel={() => setConfirming(false)}
+ onConfirm={() => {
+ setConfirming(false);
+ void update.updateServer();
+ }}
+ />
+ </>
+ );
+}
diff --git a/src/components/SettingsModal.simple.test.ts b/src/components/SettingsModal.simple.test.ts
index e8c31f9be9..fd9c0bfba4 100644
--- a/src/components/SettingsModal.simple.test.ts
+++ b/src/components/SettingsModal.simple.test.ts
@@ -16,7 +16,6 @@ const fixture = vi.hoisted(() => ({
switches: [] as ComponentProps<typeof Switch>[],
ownerOrAdmin: null as boolean | null,
updater: null as import("@/lib/updater").UpdaterState | null,
- serverUpdate: null as ReturnType<typeof import("./SidebarProfileMenu").useServerUpdateItem>,
rail: null as { available: boolean; hidden: boolean } | null,
railHidden: [] as boolean[],
}));
@@ -70,10 +69,7 @@ vi.mock("./UpdatesConsent", async (importOriginal) => ({
...await importOriginal<typeof import("./UpdatesConsent")>(),
UpdatesConsentRow: marker("updatesConsent"),
}));
-vi.mock("./SidebarProfileMenu", async (importOriginal) => ({
- ...await importOriginal<typeof import("./SidebarProfileMenu")>(),
- useServerUpdateItem: () => fixture.serverUpdate,
-}));
+vi.mock("./ServerUpdateRow", () => ({ ServerUpdateRow: marker("serverUpdate") }));
vi.mock("@/lib/updater", async (importOriginal) => ({
...await importOriginal<typeof import("@/lib/updater")>(),
useUpdaterState: () => fixture.updater,
@@ -89,7 +85,6 @@ beforeEach(() => {
fixture.switches = [];
fixture.ownerOrAdmin = null;
fixture.updater = null;
- fixture.serverUpdate = null;
fixture.rail = null;
fixture.railHidden = [];
fixture.api.mockResolvedValue({});
@@ -245,14 +240,9 @@ describe("Settings in Simple mode", () => {
for (const shown of ["Check for updates", "MARKER:updatesConsent;", "Replay welcome tour", "Diagnostics"]) expect(placement(html, shown), shown).toBe("shown");
});
- it("checks the server's version from a browser", () => {
+ it("shows the server's own update row from a browser", () => {
vi.stubGlobal("window", {});
- const onSelect = vi.fn();
- fixture.serverUpdate = { phase: "up-to-date", pending: false, label: "Up to date", item: { key: "update", label: "Up to date", subtitle: "v1.2.3", icon: null, disabled: false, onSelect } };
- const html = open("updates");
- expect(html).toMatch(/>MausBot [^<]+<\/div>/);
- expect(html).toContain("Up to date v1.2.3");
- expect(placement(html, "Check for updates")).toBe("shown");
+ expect(placement(open("updates"), "MARKER:serverUpdate;")).toBe("shown");
});
it("opens the fold that holds a linked setting: API keys, Servers or this app as a client", () => {
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index c7ff0a8d60..1d4eeb3827 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -70,6 +70,7 @@ import { SIMPLE_ONLY } from "@/lib/simple-only";
import { Select } from "./Select";
import { SavedStepsRow } from "./SavedStepsRow";
import { BrowserProfilesRow, ColorUserBubblesRow, AdvancedModeRow, ExperimentalFeaturesRow, LanguageRow, NewBotEffortRow, PinnedCirclesRow, ReplayTourRow, RunCardRow, FollowUpRow, SendKeyRow, ShowThreadsRow, ToolCallsRow, UniversalPinsRow, UpdatesRow } from "./AppSettingsRows";
+import { ServerUpdateRow } from "./ServerUpdateRow";
import { SIMPLE_ADVANCED_ONLY, SIMPLE_MORE_LIMITS, SimpleAiPage, SimpleBillingPage, SimpleComputerPage, SimpleGeneralPage, SimpleLooksPage, SimpleMorePage, SimpleUpdatesPage, type Disclose, type SimpleDisclosureId } from "./SettingsSimplePages";
// labelKey, not a label: t() reads the active pack when called, so a label resolved at module scope would freeze the
@@ -390,7 +391,7 @@ function SettingsDialog() {
<PinnedPanelsSettings />
{!remoteActive && <ReplayTourRow />}
- <UpdatesRow />
+ {window.ogb?.updater ? <UpdatesRow /> : <ServerUpdateRow title={t("settings.updates.title")} />}
<DiagnosticsRow />
</>
);
diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsx
index 6b547a8c4f..37a83c48a4 100644
--- a/src/components/SettingsSimplePages.tsx
+++ b/src/components/SettingsSimplePages.tsx
@@ -35,7 +35,7 @@ import { ProfileSummaryRow } from "./ProfileSettings";
import { AwayEmailsSetting } from "./AwayEmailsSetting";
import { ImportSettings } from "./ImportSettings";
import { NotificationRows } from "./NotificationSettingsRows";
-import { useServerUpdateItem } from "./SidebarProfileMenu";
+import { ServerUpdateRow } from "./ServerUpdateRow";
import { AdvancedModeRow, BrowserProfilesRow, ColorUserBubblesRow, FollowUpRow, LanguageRow, ReplayTourRow, SendKeyRow, ToolCallsRow, UpdatesRow } from "./AppSettingsRows";
import { RoomTurnTimeoutSettings } from "./RoomTurnTimeoutSettings";
import { McpCallTimeoutSettings } from "./McpCallTimeoutSettings";
@@ -265,25 +265,11 @@ export function SimpleBillingPage({ has, disclose, cloudAccount }: { has: Has; d
const versionTitle = () => `${productName()} ${appVersion()}`;
-function ServerUpdatesRow() {
- const entry = useServerUpdateItem(true);
- if (!entry) return null;
- const status = entry.phase === "idle" ? undefined : [entry.label, entry.item.subtitle].filter(Boolean).join(" ");
- const action = entry.phase === "available" ? t("settings.simple.updates.seeRelease")
- : entry.phase === "reload" ? t("settings.simple.updates.reload")
- : entry.phase === "checking" ? t("common.checking") : t("settings.updates.check");
- return (
- <SettingRow title={versionTitle()} subtitle={status}>
- <button type="button" className="ui-button" disabled={entry.item.disabled} onClick={entry.item.onSelect}>{action}</button>
- </SettingRow>
- );
-}
-
export function SimpleUpdatesPage({ remoteActive }: { remoteActive: boolean }) {
return (
<SettingsGroup block="updates">
<SettingsRows>
- {window.ogb?.updater ? <UpdatesRow title={versionTitle()} /> : <ServerUpdatesRow />}
+ {window.ogb?.updater ? <UpdatesRow title={versionTitle()} /> : <ServerUpdateRow title={versionTitle()} />}
<UpdatesConsentRow />
{!remoteActive && <ReplayTourRow />}
<DiagnosticsRow simple />
diff --git a/src/lib/server-update.test.ts b/src/lib/server-update.test.ts
index 67f6b95cbc..70f37a0b2f 100644
--- a/src/lib/server-update.test.ts
+++ b/src/lib/server-update.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { setLocale } from "./i18n";
-import { serverCheckPhase, serverUpdateRow, type ServerUpdateCheck } from "./server-update";
+import { newerVersion, SERVER_UPDATE_DEADLINE_MS, serverCheckPhase, serverUpdateConfirmBody, serverUpdateRow, serverUpdateView, type ServerUpdateCheck, type ServerUpdateStatus } from "./server-update";
const check = (patch: Partial<ServerUpdateCheck> = {}): ServerUpdateCheck => ({
current: "0.1.92",
@@ -103,3 +103,122 @@ describe("the update row for another server the app shows", () => {
}
});
});
+
+describe("the Update server row", () => {
+ const behind = check({ current: "0.1.150", available: true, latest: "0.1.151", command: "git pull && ./update.sh" });
+ const button = (patch: Partial<ServerUpdateStatus> = {}): ServerUpdateStatus => ({
+ mode: "button", current: "0.1.150", latest: "0.1.151", available: true, activeTurns: 0,
+ command: "cd /opt/openmausbot && sudo ./update.sh", rollback: "cd /opt/openmausbot && sudo ./update.sh --rollback",
+ logs: "cd /opt/openmausbot && sudo docker compose logs --tail 50 omb", setup: "cd /opt/openmausbot && sudo ./update-runner.sh --install", ...patch,
+ });
+ const view = (input: Partial<Parameters<typeof serverUpdateView>[0]>) => serverUpdateView({ check: behind, status: button(), bundle: "0.1.150", app: null, ...input });
+
+ it("offers Update server to an admin of a server that can update itself", () => {
+ expect(view({})).toEqual({ label: "Version 0.1.151 is available for this server", action: "update-server", busy: false });
+ });
+
+ it("shows the command instead wherever the button could not work, and to a member", () => {
+ const command = { label: "Version 0.1.151 is available for this server", subtitle: "Update with: git pull && ./update.sh", action: null, busy: false };
+ expect(view({ status: button({ mode: "command", command: "git pull && ./update.sh", rollback: undefined }) })).toEqual(command);
+ expect(view({ status: null })).toEqual(command);
+ const npm = check({ install: "npm", available: true, latest: "0.1.151", command: "npm install -g [email protected]", restart: true });
+ expect(view({ check: npm, status: button({ mode: "command", command: npm.command }) }).subtitle).toBe("Update with: npm install -g [email protected], then restart the app");
+ expect(view({ status: button({ mode: "held" }) })).toMatchObject({ subtitle: "Updates are on hold on this server.", action: null });
+ });
+
+ it("says a build of main is not one the app updates, with the command that moves it to stable", () => {
+ expect(view({ status: button({ mode: "command", why: "unreleased", command: "cd /opt/openmausbot && sudo ./update.sh" }) })).toEqual({
+ label: "Version 0.1.151 is available for this server", action: null, busy: false,
+ subtitle: "This server runs a build of main, which the app doesn't update. It moves to the stable version once that is newer than the build; on the server run: cd /opt/openmausbot && sudo ./update.sh",
+ });
+ expect(JSON.stringify(view({ status: button({ mode: "command", why: "unreleased", command: "x" }) }))).not.toContain("--allow-older");
+ });
+
+ it("shows nothing to press for this computer's app or a Cloud we run", () => {
+ expect(view({ check: check({ install: "managed", available: false }), status: button({ mode: "none" }) })).toEqual({ label: "Kept up to date for you", action: null, busy: false });
+ expect(view({ check: check({ install: "desktop", available: false }) }).action).toBeNull();
+ });
+
+ it("says the server is updating while it is asked, runs, or the page has lost it", () => {
+ const updating = { label: "Updating the server…", subtitle: "It restarts and reconnects by itself. This takes a few minutes.", action: null, busy: true };
+ expect(view({ pressed: true })).toEqual(updating);
+ expect(view({ status: button({ run: { outcome: "requested", from: "0.1.150", at: 1 } }) })).toEqual(updating);
+ expect(view({ status: button({ run: { outcome: "running", from: "0.1.150", at: 1 } }) })).toEqual(updating);
+ });
+
+ it("after 15 minutes without the server, says it is not back and what to run on it", () => {
+ const running = button({ run: { outcome: "running", from: "0.1.150", at: 1 } });
+ expect(view({ status: running, waitedMs: SERVER_UPDATE_DEADLINE_MS - 1 }).label).toBe("Updating the server…");
+ expect(SERVER_UPDATE_DEADLINE_MS).toBe(15 * 60_000);
+ expect(view({ status: running, waitedMs: SERVER_UPDATE_DEADLINE_MS })).toEqual({
+ label: "The server isn't back yet", subtitle: "It has been updating for more than 15 minutes.", action: null, busy: true, noteTone: "danger",
+ note: "On the server, run: cd /opt/openmausbot && sudo docker compose logs --tail 50 omb To go back to the version before: cd /opt/openmausbot && sudo ./update.sh --rollback",
+ });
+ expect(view({ pressed: true, status: null, waitedMs: SERVER_UPDATE_DEADLINE_MS }).label).toBe("The server isn't back yet");
+ });
+
+ it("after the update, names the new version and asks this page to reload", () => {
+ const after = check({ current: "0.1.151", available: false, latest: "0.1.151" });
+ expect(view({ check: after, status: button({ current: "0.1.151", available: false, run: { outcome: "updated", from: "0.1.150", to: "0.1.151", at: 1 } }) })).toEqual({
+ label: "Reload for v0.1.151", subtitle: "This page is still running v0.1.150", action: "reload", busy: false, note: "The server is updated to v0.1.151.",
+ });
+ expect(view({ check: after, bundle: "0.1.151", status: button({ current: "0.1.151", available: false, run: { outcome: "updated", from: "0.1.150", to: "0.1.151", at: 1 } }) })).toMatchObject({
+ label: "You're up to date", note: "The server is updated to v0.1.151.",
+ });
+ });
+
+ it("says plainly when the server went back, and what to run when it could not", () => {
+ expect(view({ status: button({ run: { outcome: "rolled-back", from: "0.1.150", to: "0.1.150", at: 1 } }) })).toMatchObject({
+ action: "update-server", noteTone: "danger",
+ note: "The update didn't work, so the server went back to v0.1.150. Your data is as it was. The reason is in .update/update.log on the server.",
+ });
+ expect(view({ status: button({ run: { outcome: "rollback-failed", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The update failed, and the server couldn't go back by itself. On the server, run: cd /opt/openmausbot && sudo ./update.sh --rollback",
+ );
+ expect(view({ status: button({ run: { outcome: "not-changed", reason: "too-soon", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server wasn't changed. Updates were asked for too often. Try again in a few minutes.",
+ );
+ expect(view({ status: button({ run: { outcome: "not-changed", reason: "not-retried", target: "0.1.151", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server wasn't changed. The update to v0.1.151 didn't work on this server before, so the app won't try it again. To try it by hand, on the server run: cd /opt/openmausbot && sudo ./update.sh",
+ );
+ expect(view({ status: button({ setup: "cd /srv/deploy && sudo ./update-runner.sh --install", run: { outcome: "not-changed", reason: "stale", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server wasn't changed. The server's update.sh is newer than the copy the button uses. On the server, run: cd /srv/deploy && sudo ./update-runner.sh --install",
+ );
+ expect(view({ status: button({ run: { outcome: "not-changed", reason: "unsafe", detail: "/opt root:staff 775", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server wasn't changed. The button runs nothing, because someone other than root could change what it runs: /opt (root:staff, 775). Fix that, then on the server run: cd /opt/openmausbot && sudo ./update-runner.sh --install",
+ );
+ expect(view({ status: button({ run: { outcome: "not-changed", reason: "no-room", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server wasn't changed. The server needs free disk space for a copy of its data first. To see the copies earlier updates kept, on the server run: docker volume ls --filter label=com.mausbot.role=update-backup. To remove one: docker volume rm <name>",
+ );
+ expect(view({ status: button({ run: { outcome: "not-started", from: "0.1.150", at: 1 } }) }).note).toBe(
+ "The server didn't start the update. On the server, run: systemctl status openmausbot-update.path",
+ );
+ });
+
+ it("in the desktop app, offers the app's own update once the server is newer, and both when both are behind", () => {
+ const current = check({ current: "0.1.151", available: false, latest: "0.1.151" });
+ expect(view({ check: current, bundle: "0.1.151", app: "0.1.149", status: button({ available: false, current: "0.1.151" }) })).toEqual({
+ label: "This app is on v0.1.149, the server on v0.1.151", action: "update-app", busy: false,
+ });
+ expect(view({ app: "0.1.149" })).toEqual({ label: "This server can update to 0.1.151, and this app is behind too", action: "update-server", busy: false });
+ // An app as new as the server, or newer, is not behind: the skew rule never forces an update.
+ expect(view({ check: current, bundle: "0.1.151", app: "0.1.152", status: button({ available: false }) }).action).toBe("check");
+ expect(view({ check: current, bundle: "0.1.151", app: "0.1.149", status: button({ available: false }), appAnswer: "downloading" }).note).toBe(
+ "This app is getting its update. It installs when you restart the app.",
+ );
+ });
+
+ it("asks first, saying the server restarts, running work stops, and how much is running", () => {
+ const body = "The server restarts to update, so anything running on it stops. This takes a few minutes. If the new version doesn't work, the server goes back to this one by itself.";
+ expect(serverUpdateConfirmBody(0)).toBe(body);
+ expect(serverUpdateConfirmBody(1)).toBe(`${body} A bot is answering in 1 chat right now.`);
+ expect(serverUpdateConfirmBody(3)).toBe(`${body} Bots are answering in 3 chats right now.`);
+ });
+
+ it("compares released versions only", () => {
+ expect(newerVersion("0.1.151", "0.1.150")).toBe(true);
+ expect(newerVersion("0.2.0", "0.1.999")).toBe(true);
+ expect(newerVersion("0.1.150", "0.1.150")).toBe(false);
+ expect(newerVersion("dev", "0.1.150")).toBe(false);
+ });
+});
diff --git a/src/lib/server-update.ts b/src/lib/server-update.ts
index 23e751e66b..702661df15 100644
--- a/src/lib/server-update.ts
+++ b/src/lib/server-update.ts
@@ -1,6 +1,11 @@
+import type { ServerUpdateReason, ServerUpdateStatus } from "../../shared/server-update";
+import type { AppUpdateAnswer } from "@/types/ogb";
+import type { LocaleKey } from "@/locales";
import { appVersion } from "./app-links";
import { t } from "./i18n";
+export type { ServerUpdateStatus };
+
/** GET /api/updates/check (server/update-check.ts). */
export interface ServerUpdateCheck {
current: string;
@@ -56,3 +61,142 @@ export function serverUpdateRow(
}
return { label: t("sidebar.update.check") };
}
+
+/** X.Y.Z only; anything else is never newer. */
+export function newerVersion(a: string, b: string): boolean {
+ const parse = (value: string) => /^v?(\d+)\.(\d+)\.(\d+)$/.exec(value.trim())?.slice(1).map(Number);
+ const x = parse(a), y = parse(b);
+ if (!x || !y) return false;
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! > y[i]!;
+ return false;
+}
+
+/** An update that has not come back after this long is said to be stuck, with what to run on the server. */
+export const SERVER_UPDATE_DEADLINE_MS = 15 * 60_000;
+
+export type ServerUpdateAction = "check" | "update-server" | "update-app" | "reload" | null;
+
+/** The one row Settings → Updates shows for a self-hosted server: what is behind (the server, this app, or both) and the
+ * one action that fixes it, with the last update's outcome as `note`. */
+export interface ServerUpdateView {
+ label: string;
+ subtitle?: string;
+ note?: string;
+ noteTone?: "danger";
+ action: ServerUpdateAction;
+ busy: boolean;
+}
+
+const REASON_TEXT: Record<ServerUpdateReason, LocaleKey> = {
+ busy: "serverUpdate.reason.busy",
+ refused: "serverUpdate.reason.refused",
+ older: "serverUpdate.reason.older",
+ held: "serverUpdate.reason.held",
+ "too-soon": "serverUpdate.reason.tooSoon",
+ "no-updater": "serverUpdate.reason.noUpdater",
+ failed: "serverUpdate.reason.failed",
+ "not-retried": "serverUpdate.reason.notRetried",
+ stale: "serverUpdate.reason.stale",
+ unreleased: "serverUpdate.reason.unreleased",
+ unsafe: "serverUpdate.reason.unsafe",
+ "no-room": "serverUpdate.reason.noRoom",
+};
+
+/** The command each reason names, from what the server said. */
+function reasonText(reason: ServerUpdateReason, status: ServerUpdateStatus, run?: ServerUpdateStatus["run"]): string {
+ const command = reason === "stale" || reason === "unsafe" ? status.setup : status.command;
+ const [folder, owners, mode] = run?.detail?.split(" ") ?? [];
+ return t(REASON_TEXT[reason], {
+ version: run?.target ?? status.latest ?? "", command: command ?? "", folder: folder ? `${folder} (${owners}, ${mode})` : "",
+ list: "docker volume ls --filter label=com.mausbot.role=update-backup", remove: "docker volume rm <name>",
+ });
+}
+
+const APP_ANSWER_TEXT: Partial<Record<AppUpdateAnswer, LocaleKey>> = {
+ downloading: "serverUpdate.appDownloading",
+ current: "serverUpdate.appCurrent",
+ failed: "serverUpdate.appFailed",
+ unavailable: "serverUpdate.appUnavailable",
+};
+
+function runNote(status: ServerUpdateStatus | null): Pick<ServerUpdateView, "note" | "noteTone"> {
+ const run = status?.run;
+ switch (run?.outcome) {
+ case "updated": return { note: t("serverUpdate.updated", { version: run.to ?? status!.current }) };
+ case "unchanged": return { note: t("serverUpdate.unchanged") };
+ case "rolled-back": return { note: `${t("serverUpdate.rolledBack", { version: run.from })} ${t("serverUpdate.rolledBackDetail")}`, noteTone: "danger" };
+ case "rollback-failed": {
+ const detail = status!.rollback ? ` ${t("serverUpdate.runOnServer", { command: status!.rollback })}` : "";
+ return { note: `${t("serverUpdate.rollbackFailed")}${detail}`, noteTone: "danger" };
+ }
+ case "not-changed": return { note: `${t("serverUpdate.notChanged")} ${reasonText(run.reason ?? "failed", status!, run)}`, noteTone: "danger" };
+ case "not-started": return { note: `${t("serverUpdate.notStarted")} ${t("serverUpdate.runOnServer", { command: "systemctl status openmausbot-update.path" })}`, noteTone: "danger" };
+ default: return {};
+ }
+}
+
+export function serverUpdateView(input: {
+ check: ServerUpdateCheck | null;
+ /** The admin's view of the button; null for a member, or before it loads. */
+ status: ServerUpdateStatus | null;
+ /** The version of the page's own code. */
+ bundle?: string;
+ /** This desktop app's own version, when the page is another server's and the app can be asked for its update; null in
+ * a browser and on this computer. */
+ app?: string | null;
+ checking?: boolean;
+ failed?: boolean;
+ pressed?: boolean;
+ appAnswer?: AppUpdateAnswer | null;
+ /** How long this page has been waiting for the server to come back from an update. */
+ waitedMs?: number;
+}): ServerUpdateView {
+ const { check, status } = input;
+ const bundle = input.bundle ?? appVersion();
+ const outcome = status?.run?.outcome;
+ if (input.pressed || outcome === "requested" || outcome === "running") {
+ if ((input.waitedMs ?? 0) >= SERVER_UPDATE_DEADLINE_MS) {
+ const how = [
+ status?.logs ? t("serverUpdate.runOnServer", { command: status.logs }) : "",
+ status?.rollback ? t("serverUpdate.goBack", { command: status.rollback }) : "",
+ ].filter(Boolean).join(" ");
+ return { label: t("serverUpdate.notBack"), subtitle: t("serverUpdate.notBackDetail"), ...(how ? { note: how, noteTone: "danger" as const } : {}), action: null, busy: true };
+ }
+ return { label: t("serverUpdate.updating"), subtitle: t("serverUpdate.updatingDetail"), action: null, busy: true };
+ }
+ const note = runNote(status);
+ const appNote = input.appAnswer && APP_ANSWER_TEXT[input.appAnswer] ? { note: t(APP_ANSWER_TEXT[input.appAnswer]!) } : {};
+ const extra = { ...note, ...appNote };
+ if (input.checking) return { label: t("sidebar.update.checking"), action: null, busy: true, ...extra };
+ if (input.failed) return { label: t("sidebar.update.checkFailed"), action: "check", busy: false, ...extra };
+ if (!check) return { label: t("sidebar.update.check"), action: "check", busy: false, ...extra };
+ if (check.install === "desktop" || check.install === "managed") {
+ return { label: t(check.install === "desktop" ? "sidebar.update.howDesktop" : "sidebar.update.managed"), action: null, busy: false };
+ }
+ if (bundle !== "dev" && check.current !== bundle && !check.available) {
+ return { label: t("sidebar.update.reloadPage", { version: check.current }), subtitle: t("sidebar.update.pageVersion", { version: bundle }), action: "reload", busy: false, ...extra };
+ }
+ const appBehind = Boolean(input.app && newerVersion(check.current, input.app));
+ if (status?.why === "unreleased") {
+ const label = check.available && check.latest ? t("serverUpdate.available", { version: check.latest }) : `v${check.current}`;
+ return { label, subtitle: reasonText("unreleased", status), action: null, busy: false, ...extra };
+ }
+ if (check.available && check.latest) {
+ const label = t(appBehind ? "serverUpdate.availableBoth" : "serverUpdate.available", { version: check.latest });
+ if (status?.mode === "button") return { label, action: "update-server", busy: false, ...extra };
+ if (status?.mode === "held") return { label, subtitle: t("serverUpdate.reason.held"), action: null, busy: false, ...extra };
+ const how = check.restart ? "sidebar.update.howRestart" : "sidebar.update.how";
+ const command = status?.command ?? check.command;
+ return { label, ...(command ? { subtitle: t(how, { command }) } : {}), action: null, busy: false, ...extra };
+ }
+ if (appBehind && input.app) {
+ return { label: t("serverUpdate.appBehind", { appVersion: input.app, serverVersion: check.current }), action: "update-app", busy: false, ...extra };
+ }
+ return { label: t("sidebar.update.upToDate"), subtitle: `v${check.current}`, action: "check", busy: false, ...extra };
+}
+
+/** The confirm before Update server: the server restarts and running work stops, with how much is running now. */
+export function serverUpdateConfirmBody(activeTurns: number): string {
+ const busy = activeTurns > 0 ? t(activeTurns === 1 ? "serverUpdate.confirmBusy.one" : "serverUpdate.confirmBusy.other", { count: activeTurns }) : "";
+ return [t("serverUpdate.confirmBody"), busy].filter(Boolean).join(" ");
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index 3690fff9c8..0b8f8a5779 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -3476,5 +3476,49 @@
"phoneUpdate.open": "Telefon & Geräte öffnen",
"remote.devices.pairAgain": "Erneut koppeln",
"remote.devices.retired": "Dieses Telefon hat eine ältere MausBot-App. Aktualisieren Sie die App und öffnen Sie sie dann einmal im selben WLAN wie dieser Computer. Wenn es sich dann nicht wieder verbindet, koppeln Sie es hier erneut.",
- "remote.devices.retiredNotice": "Telefone erreichen diesen Computer jetzt über MausBot Relay, und die ältere sichere Verbindung wurde abgeschaltet. Ein Telefon mit einer älteren MausBot-App kann sich außerhalb Ihres WLANs nicht mehr verbinden. Aktualisieren Sie die MausBot-App auf diesem Telefon und öffnen Sie sie dann einmal im selben WLAN wie dieser Computer. Wenn es sich dann nicht wieder verbindet, koppeln Sie es hier erneut."
+ "remote.devices.retiredNotice": "Telefone erreichen diesen Computer jetzt über MausBot Relay, und die ältere sichere Verbindung wurde abgeschaltet. Ein Telefon mit einer älteren MausBot-App kann sich außerhalb Ihres WLANs nicht mehr verbinden. Aktualisieren Sie die MausBot-App auf diesem Telefon und öffnen Sie sie dann einmal im selben WLAN wie dieser Computer. Wenn es sich dann nicht wieder verbindet, koppeln Sie es hier erneut.",
+ "serverUpdate.available": "Version {version} ist für diesen Server verfügbar",
+ "serverUpdate.availableBoth": "Dieser Server kann auf {version} aktualisiert werden, und diese App ist auch nicht aktuell",
+ "serverUpdate.updateServer": "Server aktualisieren",
+ "serverUpdate.updating": "Server wird aktualisiert…",
+ "serverUpdate.updatingDetail": "Er startet neu und verbindet sich von selbst wieder. Das dauert ein paar Minuten.",
+ "serverUpdate.updated": "Der Server ist jetzt auf v{version}.",
+ "serverUpdate.unchanged": "Der Server war schon auf dem neuesten Stand.",
+ "serverUpdate.rolledBack": "Das Update hat nicht funktioniert, deshalb ist der Server wieder auf v{version}.",
+ "serverUpdate.rolledBackDetail": "Deine Daten sind wie vorher. Den Grund findest du in .update/update.log auf dem Server.",
+ "serverUpdate.rollbackFailed": "Das Update ist fehlgeschlagen, und der Server konnte nicht von selbst zurück.",
+ "serverUpdate.runOnServer": "Führe auf dem Server aus: {command}",
+ "serverUpdate.notChanged": "Der Server wurde nicht geändert.",
+ "serverUpdate.reason.busy": "Dort lief schon ein anderes Update.",
+ "serverUpdate.reason.refused": "Das Update konnte nicht starten, zum Beispiel weil der Download fehlschlug oder die Festplatte voll ist. Den Grund findest du in .update/update.log auf dem Server.",
+ "serverUpdate.reason.older": "Die stabile Version ist nicht neuer als die, die er gerade nutzt.",
+ "serverUpdate.reason.held": "Updates sind auf diesem Server angehalten.",
+ "serverUpdate.reason.tooSoon": "Updates wurden zu oft angefragt. Versuch es in ein paar Minuten noch einmal.",
+ "serverUpdate.reason.noUpdater": "update.sh fehlt auf dem Server.",
+ "serverUpdate.reason.failed": "Das Update hat vor dem Ende aufgehört. Den Grund findest du in .update/update.log auf dem Server.",
+ "serverUpdate.notStarted": "Der Server hat das Update nicht gestartet.",
+ "serverUpdate.appDownloading": "Diese App lädt ihr Update. Es wird installiert, wenn du die App neu startest.",
+ "serverUpdate.appCurrent": "Für diese App gibt es noch keine neuere Version.",
+ "serverUpdate.appFailed": "Diese App konnte ihr Update nicht laden. Versuch es noch einmal.",
+ "serverUpdate.appUnavailable": "Diese App kann sich hier nicht selbst aktualisieren. Lade die neue Version von der Website.",
+ "serverUpdate.appBehind": "Diese App ist auf v{appVersion}, der Server auf v{serverVersion}",
+ "serverUpdate.updateApp": "App aktualisieren",
+ "serverUpdate.confirmTitle": "Server aktualisieren?",
+ "serverUpdate.confirmBody": "Der Server startet für das Update neu, alles, was darauf läuft, wird also beendet. Das dauert ein paar Minuten. Wenn die neue Version nicht funktioniert, kehrt der Server von selbst zu dieser zurück.",
+ "serverUpdate.confirmBusy.one": "Gerade antwortet ein Bot in {count} Chat.",
+ "serverUpdate.confirmBusy.other": "Gerade antworten Bots in {count} Chats.",
+ "serverUpdate.failed": "Der Server konnte nicht um ein Update gebeten werden. Versuch es noch einmal.",
+ "activity.action.update.server": "Server-Update angefragt",
+ "native.update.forServer": "{server} bittet darum, diese App zu aktualisieren. Version {version} ist bereit. Jetzt neu starten, um sie zu installieren?",
+ "native.update.forServerDetail": "Bots auf diesem Computer halten an, während die App neu startet.",
+ "native.update.restartNow": "Jetzt neu starten",
+ "native.update.notNow": "Nicht jetzt",
+ "serverUpdate.notBack": "Der Server ist noch nicht zurück",
+ "serverUpdate.notBackDetail": "Das Update läuft schon über 15 Minuten.",
+ "serverUpdate.goBack": "Zurück zur Version davor: {command}",
+ "serverUpdate.reason.notRetried": "Das Update auf v{version} hat auf diesem Server schon einmal nicht funktioniert, deshalb versucht die App es nicht noch einmal. Um es von Hand zu versuchen, führe auf dem Server aus: {command}",
+ "serverUpdate.reason.stale": "Die update.sh des Servers ist neuer als die Kopie, die der Button nutzt. Führe auf dem Server aus: {command}",
+ "serverUpdate.reason.unreleased": "Dieser Server nutzt einen Build von main, den die App nicht aktualisiert. Er wechselt auf die stabile Version, sobald diese neuer ist als der Build; führe auf dem Server aus: {command}",
+ "serverUpdate.reason.unsafe": "Der Button führt nichts aus, weil jemand anderes als root ändern könnte, was er ausführt: {folder}. Behebe das und führe dann auf dem Server aus: {command}",
+ "serverUpdate.reason.noRoom": "Der Server braucht zuerst freien Speicherplatz für eine Kopie seiner Daten. Um die Kopien früherer Updates zu sehen, führe auf dem Server aus: {list}. Um eine zu entfernen: {remove}"
}
diff --git a/src/locales/en.json b/src/locales/en.json
index d29c2a987a..0813f3609e 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10208,5 +10208,49 @@
"phoneUpdate.body": "{phone} has an older version of the MausBot app, which can no longer connect to this computer away from your Wi-Fi. Update the app on that phone, then open it once on the same Wi-Fi as this computer. If that doesn't reconnect it, pair it again.",
"phoneUpdate.bodyMany": "{count} of your phones have an older version of the MausBot app, which can no longer connect to this computer away from your Wi-Fi. Update the app on each phone, then open it once on the same Wi-Fi as this computer. If that doesn't reconnect it, pair it again.",
"phoneUpdate.open": "Open Phone & devices",
- "remote.devices.pairAgain": "Pair again"
+ "remote.devices.pairAgain": "Pair again",
+ "serverUpdate.available": "Version {version} is available for this server",
+ "serverUpdate.availableBoth": "This server can update to {version}, and this app is behind too",
+ "serverUpdate.updateServer": "Update server",
+ "serverUpdate.updating": "Updating the server…",
+ "serverUpdate.updatingDetail": "It restarts and reconnects by itself. This takes a few minutes.",
+ "serverUpdate.updated": "The server is updated to v{version}.",
+ "serverUpdate.unchanged": "The server was already up to date.",
+ "serverUpdate.rolledBack": "The update didn't work, so the server went back to v{version}.",
+ "serverUpdate.rolledBackDetail": "Your data is as it was. The reason is in .update/update.log on the server.",
+ "serverUpdate.rollbackFailed": "The update failed, and the server couldn't go back by itself.",
+ "serverUpdate.runOnServer": "On the server, run: {command}",
+ "serverUpdate.notChanged": "The server wasn't changed.",
+ "serverUpdate.reason.busy": "Another update was already running on it.",
+ "serverUpdate.reason.refused": "The update couldn't start, for example because the download failed or the disk is full. The reason is in .update/update.log on the server.",
+ "serverUpdate.reason.older": "The stable version isn't newer than the one it runs.",
+ "serverUpdate.reason.held": "Updates are on hold on this server.",
+ "serverUpdate.reason.tooSoon": "Updates were asked for too often. Try again in a few minutes.",
+ "serverUpdate.reason.noUpdater": "update.sh is missing on the server.",
+ "serverUpdate.reason.failed": "The update stopped before it finished. The reason is in .update/update.log on the server.",
+ "serverUpdate.notStarted": "The server didn't start the update.",
+ "serverUpdate.appDownloading": "This app is getting its update. It installs when you restart the app.",
+ "serverUpdate.appCurrent": "There's no newer version of this app yet.",
+ "serverUpdate.appFailed": "This app couldn't get its update. Try again.",
+ "serverUpdate.appUnavailable": "This app can't update itself here. Download the new version from the website.",
+ "serverUpdate.appBehind": "This app is on v{appVersion}, the server on v{serverVersion}",
+ "serverUpdate.updateApp": "Update app",
+ "serverUpdate.confirmTitle": "Update the server?",
+ "serverUpdate.confirmBody": "The server restarts to update, so anything running on it stops. This takes a few minutes. If the new version doesn't work, the server goes back to this one by itself.",
+ "serverUpdate.confirmBusy.one": "A bot is answering in {count} chat right now.",
+ "serverUpdate.confirmBusy.other": "Bots are answering in {count} chats right now.",
+ "serverUpdate.failed": "Couldn't ask the server to update. Try again.",
+ "activity.action.update.server": "Asked the server to update",
+ "native.update.forServer": "{server} asks to update this app. Version {version} is ready. Restart now to install it?",
+ "native.update.forServerDetail": "Bots running on this computer stop while the app restarts.",
+ "native.update.restartNow": "Restart now",
+ "native.update.notNow": "Not now",
+ "serverUpdate.notBack": "The server isn't back yet",
+ "serverUpdate.notBackDetail": "It has been updating for more than 15 minutes.",
+ "serverUpdate.goBack": "To go back to the version before: {command}",
+ "serverUpdate.reason.notRetried": "The update to v{version} didn't work on this server before, so the app won't try it again. To try it by hand, on the server run: {command}",
+ "serverUpdate.reason.stale": "The server's update.sh is newer than the copy the button uses. On the server, run: {command}",
+ "serverUpdate.reason.unreleased": "This server runs a build of main, which the app doesn't update. It moves to the stable version once that is newer than the build; on the server run: {command}",
+ "serverUpdate.reason.unsafe": "The button runs nothing, because someone other than root could change what it runs: {folder}. Fix that, then on the server run: {command}",
+ "serverUpdate.reason.noRoom": "The server needs free disk space for a copy of its data first. To see the copies earlier updates kept, on the server run: {list}. To remove one: {remove}"
}
diff --git a/src/locales/es.json b/src/locales/es.json
index 7686f96830..7714beddbb 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -6089,5 +6089,49 @@
"phoneUpdate.open": "Abrir Teléfono y dispositivos",
"remote.devices.pairAgain": "Volver a vincular",
"remote.devices.retired": "Este teléfono tiene una versión anterior de la app MausBot. Actualiza la app y luego ábrela una vez en la misma red Wi-Fi que esta computadora. Si así no se vuelve a conectar, vuelve a vincularlo aquí.",
- "remote.devices.retiredNotice": "Ahora los teléfonos llegan a esta computadora a través de MausBot Relay, y el enlace seguro anterior se desactivó. Un teléfono con una versión anterior de la app MausBot ya no puede conectarse fuera de tu Wi-Fi. Actualiza la app MausBot en ese teléfono y luego ábrela una vez en la misma red Wi-Fi que esta computadora. Si así no se vuelve a conectar, vuelve a vincularlo aquí."
+ "remote.devices.retiredNotice": "Ahora los teléfonos llegan a esta computadora a través de MausBot Relay, y el enlace seguro anterior se desactivó. Un teléfono con una versión anterior de la app MausBot ya no puede conectarse fuera de tu Wi-Fi. Actualiza la app MausBot en ese teléfono y luego ábrela una vez en la misma red Wi-Fi que esta computadora. Si así no se vuelve a conectar, vuelve a vincularlo aquí.",
+ "serverUpdate.available": "La versión {version} está disponible para este servidor",
+ "serverUpdate.availableBoth": "Este servidor puede actualizarse a {version}, y esta app también está atrasada",
+ "serverUpdate.updateServer": "Actualizar servidor",
+ "serverUpdate.updating": "Actualizando el servidor…",
+ "serverUpdate.updatingDetail": "Se reinicia y se vuelve a conectar solo. Tarda unos minutos.",
+ "serverUpdate.updated": "El servidor se actualizó a la v{version}.",
+ "serverUpdate.unchanged": "El servidor ya estaba al día.",
+ "serverUpdate.rolledBack": "La actualización no funcionó, así que el servidor volvió a la v{version}.",
+ "serverUpdate.rolledBackDetail": "Tus datos están como estaban. El motivo está en .update/update.log en el servidor.",
+ "serverUpdate.rollbackFailed": "La actualización falló y el servidor no pudo volver atrás solo.",
+ "serverUpdate.runOnServer": "En el servidor, ejecuta: {command}",
+ "serverUpdate.notChanged": "El servidor no se cambió.",
+ "serverUpdate.reason.busy": "Ya había otra actualización en curso.",
+ "serverUpdate.reason.refused": "La actualización no pudo empezar, por ejemplo porque falló la descarga o el disco está lleno. El motivo está en .update/update.log en el servidor.",
+ "serverUpdate.reason.older": "La versión estable no es más nueva que la que usa.",
+ "serverUpdate.reason.held": "Las actualizaciones están en pausa en este servidor.",
+ "serverUpdate.reason.tooSoon": "Se pidieron actualizaciones demasiadas veces. Vuelve a intentarlo en unos minutos.",
+ "serverUpdate.reason.noUpdater": "Falta update.sh en el servidor.",
+ "serverUpdate.reason.failed": "La actualización se detuvo antes de terminar. El motivo está en .update/update.log en el servidor.",
+ "serverUpdate.notStarted": "El servidor no empezó la actualización.",
+ "serverUpdate.appDownloading": "Esta app está descargando su actualización. Se instala cuando reinicies la app.",
+ "serverUpdate.appCurrent": "Todavía no hay una versión más nueva de esta app.",
+ "serverUpdate.appFailed": "Esta app no pudo obtener su actualización. Vuelve a intentarlo.",
+ "serverUpdate.appUnavailable": "Esta app no puede actualizarse sola aquí. Descarga la nueva versión desde el sitio web.",
+ "serverUpdate.appBehind": "Esta app está en la v{appVersion} y el servidor en la v{serverVersion}",
+ "serverUpdate.updateApp": "Actualizar app",
+ "serverUpdate.confirmTitle": "¿Actualizar el servidor?",
+ "serverUpdate.confirmBody": "El servidor se reinicia para actualizarse, así que todo lo que esté en marcha se detiene. Tarda unos minutos. Si la nueva versión no funciona, el servidor vuelve solo a esta.",
+ "serverUpdate.confirmBusy.one": "Ahora mismo un bot está respondiendo en {count} chat.",
+ "serverUpdate.confirmBusy.other": "Ahora mismo hay bots respondiendo en {count} chats.",
+ "serverUpdate.failed": "No se pudo pedir al servidor que se actualice. Vuelve a intentarlo.",
+ "activity.action.update.server": "Pidió actualizar el servidor",
+ "native.update.forServer": "{server} pide actualizar esta app. La versión {version} está lista. ¿Reiniciar ahora para instalarla?",
+ "native.update.forServerDetail": "Los bots de este ordenador se detienen mientras la app se reinicia.",
+ "native.update.restartNow": "Reiniciar ahora",
+ "native.update.notNow": "Ahora no",
+ "serverUpdate.notBack": "El servidor aún no ha vuelto",
+ "serverUpdate.notBackDetail": "Lleva más de 15 minutos actualizándose.",
+ "serverUpdate.goBack": "Para volver a la versión anterior: {command}",
+ "serverUpdate.reason.notRetried": "La actualización a la v{version} ya falló en este servidor, así que la app no la volverá a intentar. Para intentarlo a mano, ejecuta en el servidor: {command}",
+ "serverUpdate.reason.stale": "El update.sh del servidor es más nuevo que la copia que usa el botón. En el servidor, ejecuta: {command}",
+ "serverUpdate.reason.unreleased": "Este servidor usa una compilación de main, que la app no actualiza. Pasa a la versión estable cuando esta sea más nueva que la compilación; en el servidor, ejecuta: {command}",
+ "serverUpdate.reason.unsafe": "El botón no ejecuta nada, porque alguien que no es root podría cambiar lo que ejecuta: {folder}. Corrígelo y luego, en el servidor, ejecuta: {command}",
+ "serverUpdate.reason.noRoom": "El servidor necesita primero espacio libre en disco para una copia de sus datos. Para ver las copias que guardaron actualizaciones anteriores, ejecuta en el servidor: {list}. Para quitar una: {remove}"
}
diff --git a/src/locales/fr.json b/src/locales/fr.json
index d57b53428b..e430fda9eb 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -3317,5 +3317,49 @@
"phoneUpdate.open": "Ouvrir Téléphone et appareils",
"remote.devices.pairAgain": "Appairer à nouveau",
"remote.devices.retired": "Ce téléphone a une ancienne version de l'app MausBot. Mettez l'app à jour, puis ouvrez-la une fois sur le même Wi-Fi que cet ordinateur. S'il ne se reconnecte pas, appairez-le à nouveau ici.",
- "remote.devices.retiredNotice": "Les téléphones rejoignent maintenant cet ordinateur via MausBot Relay, et l'ancien lien sécurisé a été désactivé. Un téléphone avec une ancienne version de l'app MausBot ne peut plus se connecter en dehors de votre Wi-Fi. Mettez à jour l'app MausBot sur ce téléphone, puis ouvrez-la une fois sur le même Wi-Fi que cet ordinateur. S'il ne se reconnecte pas, appairez-le à nouveau ici."
+ "remote.devices.retiredNotice": "Les téléphones rejoignent maintenant cet ordinateur via MausBot Relay, et l'ancien lien sécurisé a été désactivé. Un téléphone avec une ancienne version de l'app MausBot ne peut plus se connecter en dehors de votre Wi-Fi. Mettez à jour l'app MausBot sur ce téléphone, puis ouvrez-la une fois sur le même Wi-Fi que cet ordinateur. S'il ne se reconnecte pas, appairez-le à nouveau ici.",
+ "serverUpdate.available": "La version {version} est disponible pour ce serveur",
+ "serverUpdate.availableBoth": "Ce serveur peut passer à la version {version}, et cette app est aussi en retard",
+ "serverUpdate.updateServer": "Mettre à jour le serveur",
+ "serverUpdate.updating": "Mise à jour du serveur…",
+ "serverUpdate.updatingDetail": "Il redémarre et se reconnecte tout seul. Cela prend quelques minutes.",
+ "serverUpdate.updated": "Le serveur est passé à la v{version}.",
+ "serverUpdate.unchanged": "Le serveur était déjà à jour.",
+ "serverUpdate.rolledBack": "La mise à jour n'a pas marché, le serveur est donc revenu à la v{version}.",
+ "serverUpdate.rolledBackDetail": "Vos données sont comme avant. La raison est dans .update/update.log sur le serveur.",
+ "serverUpdate.rollbackFailed": "La mise à jour a échoué, et le serveur n'a pas pu revenir en arrière tout seul.",
+ "serverUpdate.runOnServer": "Sur le serveur, lancez : {command}",
+ "serverUpdate.notChanged": "Le serveur n'a pas été modifié.",
+ "serverUpdate.reason.busy": "Une autre mise à jour était déjà en cours.",
+ "serverUpdate.reason.refused": "La mise à jour n'a pas pu démarrer, par exemple parce que le téléchargement a échoué ou que le disque est plein. La raison est dans .update/update.log sur le serveur.",
+ "serverUpdate.reason.older": "La version stable n'est pas plus récente que celle qu'il utilise.",
+ "serverUpdate.reason.held": "Les mises à jour sont suspendues sur ce serveur.",
+ "serverUpdate.reason.tooSoon": "Trop de demandes de mise à jour. Réessayez dans quelques minutes.",
+ "serverUpdate.reason.noUpdater": "update.sh est absent du serveur.",
+ "serverUpdate.reason.failed": "La mise à jour s'est arrêtée avant la fin. La raison est dans .update/update.log sur le serveur.",
+ "serverUpdate.notStarted": "Le serveur n'a pas lancé la mise à jour.",
+ "serverUpdate.appDownloading": "Cette app télécharge sa mise à jour. Elle s'installe quand vous redémarrez l'app.",
+ "serverUpdate.appCurrent": "Il n'y a pas encore de version plus récente de cette app.",
+ "serverUpdate.appFailed": "Cette app n'a pas pu obtenir sa mise à jour. Réessayez.",
+ "serverUpdate.appUnavailable": "Cette app ne peut pas se mettre à jour seule ici. Téléchargez la nouvelle version sur le site.",
+ "serverUpdate.appBehind": "Cette app est en v{appVersion}, le serveur en v{serverVersion}",
+ "serverUpdate.updateApp": "Mettre à jour l'app",
+ "serverUpdate.confirmTitle": "Mettre à jour le serveur ?",
+ "serverUpdate.confirmBody": "Le serveur redémarre pour se mettre à jour : tout ce qui tourne dessus s'arrête. Cela prend quelques minutes. Si la nouvelle version ne marche pas, le serveur revient tout seul à celle-ci.",
+ "serverUpdate.confirmBusy.one": "Un bot répond en ce moment dans {count} chat.",
+ "serverUpdate.confirmBusy.other": "Des bots répondent en ce moment dans {count} chats.",
+ "serverUpdate.failed": "Impossible de demander la mise à jour au serveur. Réessayez.",
+ "activity.action.update.server": "A demandé la mise à jour du serveur",
+ "native.update.forServer": "{server} demande à mettre à jour cette app. La version {version} est prête. Redémarrer maintenant pour l'installer ?",
+ "native.update.forServerDetail": "Les bots de cet ordinateur s'arrêtent pendant que l'app redémarre.",
+ "native.update.restartNow": "Redémarrer maintenant",
+ "native.update.notNow": "Pas maintenant",
+ "serverUpdate.notBack": "Le serveur n'est pas encore revenu",
+ "serverUpdate.notBackDetail": "La mise à jour dure depuis plus de 15 minutes.",
+ "serverUpdate.goBack": "Pour revenir à la version d'avant : {command}",
+ "serverUpdate.reason.notRetried": "La mise à jour vers la v{version} n'a pas marché sur ce serveur, donc l'app ne la retentera pas. Pour essayer à la main, lancez sur le serveur : {command}",
+ "serverUpdate.reason.stale": "Le update.sh du serveur est plus récent que la copie qu'utilise le bouton. Sur le serveur, lancez : {command}",
+ "serverUpdate.reason.unreleased": "Ce serveur utilise une build de main, que l'app ne met pas à jour. Il passe à la version stable dès qu'elle est plus récente que la build ; sur le serveur, lancez : {command}",
+ "serverUpdate.reason.unsafe": "Le bouton n'exécute rien, car quelqu'un d'autre que root pourrait changer ce qu'il exécute : {folder}. Corrigez cela, puis sur le serveur lancez : {command}",
+ "serverUpdate.reason.noRoom": "Le serveur a d'abord besoin d'espace disque libre pour une copie de ses données. Pour voir les copies gardées par les mises à jour précédentes, lancez sur le serveur : {list}. Pour en supprimer une : {remove}"
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index c3daf643a2..1e84b66184 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -3169,5 +3169,49 @@
"phoneUpdate.open": "फ़ोन और डिवाइस खोलें",
"remote.devices.pairAgain": "फिर से पेयर करें",
"remote.devices.retired": "इस फ़ोन में MausBot ऐप का पुराना वर्शन है। ऐप अपडेट करें, फिर उसे इस कंप्यूटर वाले Wi-Fi पर एक बार खोलें। अगर इससे वह फिर से कनेक्ट नहीं होता, तो उसे यहाँ फिर से पेयर करें।",
- "remote.devices.retiredNotice": "अब फ़ोन MausBot Relay के ज़रिए इस कंप्यूटर तक पहुँचते हैं, और पुराना सुरक्षित लिंक बंद कर दिया गया है। MausBot ऐप के पुराने वर्शन वाला फ़ोन अब आपके Wi-Fi से बाहर कनेक्ट नहीं हो सकता। उस फ़ोन पर MausBot ऐप अपडेट करें, फिर उसे इस कंप्यूटर वाले Wi-Fi पर एक बार खोलें। अगर इससे वह फिर से कनेक्ट नहीं होता, तो उसे यहाँ फिर से पेयर करें।"
+ "remote.devices.retiredNotice": "अब फ़ोन MausBot Relay के ज़रिए इस कंप्यूटर तक पहुँचते हैं, और पुराना सुरक्षित लिंक बंद कर दिया गया है। MausBot ऐप के पुराने वर्शन वाला फ़ोन अब आपके Wi-Fi से बाहर कनेक्ट नहीं हो सकता। उस फ़ोन पर MausBot ऐप अपडेट करें, फिर उसे इस कंप्यूटर वाले Wi-Fi पर एक बार खोलें। अगर इससे वह फिर से कनेक्ट नहीं होता, तो उसे यहाँ फिर से पेयर करें।",
+ "serverUpdate.available": "इस सर्वर के लिए वर्ज़न {version} उपलब्ध है",
+ "serverUpdate.availableBoth": "यह सर्वर {version} पर अपडेट हो सकता है, और यह ऐप भी पीछे है",
+ "serverUpdate.updateServer": "सर्वर अपडेट करें",
+ "serverUpdate.updating": "सर्वर अपडेट हो रहा है…",
+ "serverUpdate.updatingDetail": "यह अपने आप रीस्टार्ट होकर फिर से जुड़ जाएगा। इसमें कुछ मिनट लगते हैं।",
+ "serverUpdate.updated": "सर्वर v{version} पर अपडेट हो गया है।",
+ "serverUpdate.unchanged": "सर्वर पहले से अपडेटेड था।",
+ "serverUpdate.rolledBack": "अपडेट काम नहीं किया, इसलिए सर्वर v{version} पर वापस चला गया।",
+ "serverUpdate.rolledBackDetail": "आपका डेटा पहले जैसा है। वजह सर्वर पर .update/update.log में है।",
+ "serverUpdate.rollbackFailed": "अपडेट नहीं हो पाया, और सर्वर अपने आप वापस नहीं जा सका।",
+ "serverUpdate.runOnServer": "सर्वर पर चलाएँ: {command}",
+ "serverUpdate.notChanged": "सर्वर में कोई बदलाव नहीं हुआ।",
+ "serverUpdate.reason.busy": "उस पर पहले से एक और अपडेट चल रहा था।",
+ "serverUpdate.reason.refused": "अपडेट शुरू नहीं हो सका, जैसे डाउनलोड फ़ेल हो गया या डिस्क भरी है। वजह सर्वर पर .update/update.log में है।",
+ "serverUpdate.reason.older": "स्टेबल वर्ज़न उस वर्ज़न से नया नहीं है जो यह चला रहा है।",
+ "serverUpdate.reason.held": "इस सर्वर पर अपडेट रोके गए हैं।",
+ "serverUpdate.reason.tooSoon": "अपडेट बहुत बार माँगे गए। कुछ मिनट बाद फिर से कोशिश करें।",
+ "serverUpdate.reason.noUpdater": "सर्वर पर update.sh नहीं है।",
+ "serverUpdate.reason.failed": "अपडेट पूरा होने से पहले रुक गया। वजह सर्वर पर .update/update.log में है।",
+ "serverUpdate.notStarted": "सर्वर ने अपडेट शुरू नहीं किया।",
+ "serverUpdate.appDownloading": "यह ऐप अपना अपडेट ले रहा है। ऐप रीस्टार्ट करने पर यह इंस्टॉल हो जाएगा।",
+ "serverUpdate.appCurrent": "इस ऐप का कोई नया वर्ज़न अभी नहीं है।",
+ "serverUpdate.appFailed": "यह ऐप अपना अपडेट नहीं ले सका। फिर से कोशिश करें।",
+ "serverUpdate.appUnavailable": "यह ऐप यहाँ खुद अपडेट नहीं हो सकता। नया वर्ज़न वेबसाइट से डाउनलोड करें।",
+ "serverUpdate.appBehind": "यह ऐप v{appVersion} पर है, सर्वर v{serverVersion} पर",
+ "serverUpdate.updateApp": "ऐप अपडेट करें",
+ "serverUpdate.confirmTitle": "सर्वर अपडेट करें?",
+ "serverUpdate.confirmBody": "अपडेट के लिए सर्वर रीस्टार्ट होगा, इसलिए उस पर जो कुछ चल रहा है वह रुक जाएगा। इसमें कुछ मिनट लगते हैं। अगर नया वर्ज़न काम नहीं करता, तो सर्वर अपने आप इसी पर लौट आएगा।",
+ "serverUpdate.confirmBusy.one": "अभी {count} चैट में एक बॉट जवाब दे रहा है।",
+ "serverUpdate.confirmBusy.other": "अभी {count} चैट में बॉट जवाब दे रहे हैं।",
+ "serverUpdate.failed": "सर्वर से अपडेट करने को नहीं कहा जा सका। फिर से कोशिश करें।",
+ "activity.action.update.server": "सर्वर अपडेट करने को कहा",
+ "native.update.forServer": "{server} इस ऐप को अपडेट करने को कह रहा है। वर्ज़न {version} तैयार है। इंस्टॉल करने के लिए अभी रीस्टार्ट करें?",
+ "native.update.forServerDetail": "ऐप रीस्टार्ट होने तक इस कंप्यूटर पर चल रहे बॉट रुक जाएँगे।",
+ "native.update.restartNow": "अभी रीस्टार्ट करें",
+ "native.update.notNow": "अभी नहीं",
+ "serverUpdate.notBack": "सर्वर अभी तक वापस नहीं आया",
+ "serverUpdate.notBackDetail": "यह 15 मिनट से ज़्यादा समय से अपडेट हो रहा है।",
+ "serverUpdate.goBack": "पिछले वर्ज़न पर लौटने के लिए: {command}",
+ "serverUpdate.reason.notRetried": "v{version} पर अपडेट इस सर्वर पर पहले काम नहीं किया, इसलिए ऐप इसे दोबारा नहीं आज़माएगा। हाथ से आज़माने के लिए सर्वर पर चलाएँ: {command}",
+ "serverUpdate.reason.stale": "सर्वर का update.sh बटन वाली कॉपी से नया है। सर्वर पर चलाएँ: {command}",
+ "serverUpdate.reason.unreleased": "यह सर्वर main का बिल्ड चला रहा है, जिसे ऐप अपडेट नहीं करता। स्टेबल वर्ज़न इस बिल्ड से नया होते ही यह उस पर चला जाता है; सर्वर पर चलाएँ: {command}",
+ "serverUpdate.reason.unsafe": "बटन कुछ नहीं चलाता, क्योंकि root के अलावा कोई और बदल सकता है कि यह क्या चलाए: {folder}। इसे ठीक करें, फिर सर्वर पर चलाएँ: {command}",
+ "serverUpdate.reason.noRoom": "सर्वर को पहले अपने डेटा की कॉपी के लिए खाली डिस्क जगह चाहिए। पिछले अपडेट की रखी कॉपियाँ देखने के लिए सर्वर पर चलाएँ: {list}। किसी एक को हटाने के लिए: {remove}"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index bf57085371..b70d88104a 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -6710,5 +6710,49 @@
"phoneUpdate.open": "Apri Telefono e dispositivi",
"remote.devices.pairAgain": "Abbina di nuovo",
"remote.devices.retired": "Questo telefono ha una versione precedente dell'app MausBot. Aggiorna l'app, poi aprila una volta sulla stessa Wi-Fi di questo computer. Se non si ricollega, abbinalo di nuovo qui.",
- "remote.devices.retiredNotice": "Ora i telefoni raggiungono questo computer tramite MausBot Relay, e il vecchio collegamento sicuro è stato disattivato. Un telefono con una versione precedente dell'app MausBot non può più collegarsi fuori dalla tua Wi-Fi. Aggiorna l'app MausBot su quel telefono, poi aprila una volta sulla stessa Wi-Fi di questo computer. Se non si ricollega, abbinalo di nuovo qui."
+ "remote.devices.retiredNotice": "Ora i telefoni raggiungono questo computer tramite MausBot Relay, e il vecchio collegamento sicuro è stato disattivato. Un telefono con una versione precedente dell'app MausBot non può più collegarsi fuori dalla tua Wi-Fi. Aggiorna l'app MausBot su quel telefono, poi aprila una volta sulla stessa Wi-Fi di questo computer. Se non si ricollega, abbinalo di nuovo qui.",
+ "serverUpdate.available": "La versione {version} è disponibile per questo server",
+ "serverUpdate.availableBoth": "Questo server può passare alla {version}, e anche questa app è indietro",
+ "serverUpdate.updateServer": "Aggiorna server",
+ "serverUpdate.updating": "Aggiornamento del server…",
+ "serverUpdate.updatingDetail": "Si riavvia e si ricollega da solo. Ci vuole qualche minuto.",
+ "serverUpdate.updated": "Il server è aggiornato alla v{version}.",
+ "serverUpdate.unchanged": "Il server era già aggiornato.",
+ "serverUpdate.rolledBack": "L'aggiornamento non ha funzionato, quindi il server è tornato alla v{version}.",
+ "serverUpdate.rolledBackDetail": "I tuoi dati sono come prima. Il motivo è in .update/update.log sul server.",
+ "serverUpdate.rollbackFailed": "L'aggiornamento non è riuscito e il server non è riuscito a tornare indietro da solo.",
+ "serverUpdate.runOnServer": "Sul server, esegui: {command}",
+ "serverUpdate.notChanged": "Il server non è stato modificato.",
+ "serverUpdate.reason.busy": "Era già in corso un altro aggiornamento.",
+ "serverUpdate.reason.refused": "L'aggiornamento non è potuto partire, per esempio perché il download non è riuscito o il disco è pieno. Il motivo è in .update/update.log sul server.",
+ "serverUpdate.reason.older": "La versione stabile non è più recente di quella che usa.",
+ "serverUpdate.reason.held": "Gli aggiornamenti sono sospesi su questo server.",
+ "serverUpdate.reason.tooSoon": "Gli aggiornamenti sono stati chiesti troppo spesso. Riprova tra qualche minuto.",
+ "serverUpdate.reason.noUpdater": "Sul server manca update.sh.",
+ "serverUpdate.reason.failed": "L'aggiornamento si è fermato prima di finire. Il motivo è in .update/update.log sul server.",
+ "serverUpdate.notStarted": "Il server non ha avviato l'aggiornamento.",
+ "serverUpdate.appDownloading": "Questa app sta scaricando il suo aggiornamento. Si installa quando riavvii l'app.",
+ "serverUpdate.appCurrent": "Non c'è ancora una versione più recente di questa app.",
+ "serverUpdate.appFailed": "Questa app non è riuscita a ottenere l'aggiornamento. Riprova.",
+ "serverUpdate.appUnavailable": "Questa app non può aggiornarsi da sola qui. Scarica la nuova versione dal sito.",
+ "serverUpdate.appBehind": "Questa app è alla v{appVersion}, il server alla v{serverVersion}",
+ "serverUpdate.updateApp": "Aggiorna app",
+ "serverUpdate.confirmTitle": "Aggiornare il server?",
+ "serverUpdate.confirmBody": "Il server si riavvia per aggiornarsi, quindi tutto ciò che è in esecuzione si ferma. Ci vuole qualche minuto. Se la nuova versione non funziona, il server torna da solo a questa.",
+ "serverUpdate.confirmBusy.one": "In questo momento un bot sta rispondendo in {count} chat.",
+ "serverUpdate.confirmBusy.other": "In questo momento dei bot stanno rispondendo in {count} chat.",
+ "serverUpdate.failed": "Non è stato possibile chiedere al server di aggiornarsi. Riprova.",
+ "activity.action.update.server": "Ha chiesto di aggiornare il server",
+ "native.update.forServer": "{server} chiede di aggiornare questa app. La versione {version} è pronta. Riavviare ora per installarla?",
+ "native.update.forServerDetail": "I bot su questo computer si fermano mentre l'app si riavvia.",
+ "native.update.restartNow": "Riavvia ora",
+ "native.update.notNow": "Non ora",
+ "serverUpdate.notBack": "Il server non è ancora tornato",
+ "serverUpdate.notBackDetail": "Si sta aggiornando da più di 15 minuti.",
+ "serverUpdate.goBack": "Per tornare alla versione precedente: {command}",
+ "serverUpdate.reason.notRetried": "L'aggiornamento alla v{version} non ha già funzionato su questo server, quindi l'app non lo riproverà. Per provarlo a mano, sul server esegui: {command}",
+ "serverUpdate.reason.stale": "L'update.sh del server è più recente della copia usata dal pulsante. Sul server, esegui: {command}",
+ "serverUpdate.reason.unreleased": "Questo server usa una build di main, che l'app non aggiorna. Passa alla versione stabile appena è più recente della build; sul server esegui: {command}",
+ "serverUpdate.reason.unsafe": "Il pulsante non esegue nulla, perché qualcuno che non è root potrebbe cambiare ciò che esegue: {folder}. Correggi, poi sul server esegui: {command}",
+ "serverUpdate.reason.noRoom": "Il server ha prima bisogno di spazio libero su disco per una copia dei suoi dati. Per vedere le copie tenute dagli aggiornamenti precedenti, sul server esegui: {list}. Per rimuoverne una: {remove}"
}
diff --git a/src/locales/ja.json b/src/locales/ja.json
index b2d00c67f4..1223e48494 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -7760,5 +7760,49 @@
"phoneUpdate.open": "スマホとデバイスを開く",
"remote.devices.pairAgain": "もう一度ペアリング",
"remote.devices.retired": "このスマホの MausBot アプリは古いバージョンです。アプリを更新してから、このコンピューターと同じ Wi-Fi で一度開いてください。それでも再接続しない場合は、ここでもう一度ペアリングしてください。",
- "remote.devices.retiredNotice": "スマホは MausBot Relay を通じてこのコンピューターに接続するようになり、以前の安全なリンクは停止されました。古いバージョンの MausBot アプリのスマホは、Wi-Fi の外から接続できなくなりました。そのスマホで MausBot アプリを更新してから、このコンピューターと同じ Wi-Fi で一度開いてください。それでも再接続しない場合は、ここでもう一度ペアリングしてください。"
+ "remote.devices.retiredNotice": "スマホは MausBot Relay を通じてこのコンピューターに接続するようになり、以前の安全なリンクは停止されました。古いバージョンの MausBot アプリのスマホは、Wi-Fi の外から接続できなくなりました。そのスマホで MausBot アプリを更新してから、このコンピューターと同じ Wi-Fi で一度開いてください。それでも再接続しない場合は、ここでもう一度ペアリングしてください。",
+ "serverUpdate.available": "このサーバーのバージョン {version} が利用できます",
+ "serverUpdate.availableBoth": "このサーバーは {version} に更新できます。このアプリも古くなっています",
+ "serverUpdate.updateServer": "サーバーを更新",
+ "serverUpdate.updating": "サーバーを更新しています…",
+ "serverUpdate.updatingDetail": "自動で再起動して再接続します。数分かかります。",
+ "serverUpdate.updated": "サーバーを v{version} に更新しました。",
+ "serverUpdate.unchanged": "サーバーはすでに最新でした。",
+ "serverUpdate.rolledBack": "更新がうまくいかなかったため、サーバーは v{version} に戻りました。",
+ "serverUpdate.rolledBackDetail": "データは元のままです。理由はサーバーの .update/update.log にあります。",
+ "serverUpdate.rollbackFailed": "更新に失敗し、サーバーは自動で元に戻せませんでした。",
+ "serverUpdate.runOnServer": "サーバーで実行してください:{command}",
+ "serverUpdate.notChanged": "サーバーは変更されていません。",
+ "serverUpdate.reason.busy": "別の更新がすでに実行中でした。",
+ "serverUpdate.reason.refused": "ダウンロードの失敗やディスクの空き不足などで、更新を始められませんでした。理由はサーバーの .update/update.log にあります。",
+ "serverUpdate.reason.older": "安定版は、いま動いているバージョンより新しくありません。",
+ "serverUpdate.reason.held": "このサーバーでは更新が保留されています。",
+ "serverUpdate.reason.tooSoon": "更新の依頼が多すぎます。数分後にもう一度お試しください。",
+ "serverUpdate.reason.noUpdater": "サーバーに update.sh がありません。",
+ "serverUpdate.reason.failed": "更新は完了する前に止まりました。理由はサーバーの .update/update.log にあります。",
+ "serverUpdate.notStarted": "サーバーは更新を始めませんでした。",
+ "serverUpdate.appDownloading": "このアプリは更新をダウンロード中です。アプリを再起動するとインストールされます。",
+ "serverUpdate.appCurrent": "このアプリの新しいバージョンはまだありません。",
+ "serverUpdate.appFailed": "このアプリは更新を取得できませんでした。もう一度お試しください。",
+ "serverUpdate.appUnavailable": "このアプリはここでは自動更新できません。新しいバージョンをウェブサイトからダウンロードしてください。",
+ "serverUpdate.appBehind": "このアプリは v{appVersion}、サーバーは v{serverVersion} です",
+ "serverUpdate.updateApp": "アプリを更新",
+ "serverUpdate.confirmTitle": "サーバーを更新しますか?",
+ "serverUpdate.confirmBody": "更新のためサーバーが再起動するので、実行中の処理は止まります。数分かかります。新しいバージョンが動かない場合、サーバーは自動でこのバージョンに戻ります。",
+ "serverUpdate.confirmBusy.one": "いま {count} 件のチャットでボットが応答中です。",
+ "serverUpdate.confirmBusy.other": "いま {count} 件のチャットでボットが応答中です。",
+ "serverUpdate.failed": "サーバーに更新を依頼できませんでした。もう一度お試しください。",
+ "activity.action.update.server": "サーバーの更新を依頼しました",
+ "native.update.forServer": "{server} がこのアプリの更新を求めています。バージョン {version} の準備ができました。今すぐ再起動してインストールしますか?",
+ "native.update.forServerDetail": "アプリの再起動中は、このコンピューターで動いているボットが止まります。",
+ "native.update.restartNow": "今すぐ再起動",
+ "native.update.notNow": "後で",
+ "serverUpdate.notBack": "サーバーはまだ戻っていません",
+ "serverUpdate.notBackDetail": "更新が始まってから 15 分以上たっています。",
+ "serverUpdate.goBack": "前のバージョンに戻すには:{command}",
+ "serverUpdate.reason.notRetried": "v{version} への更新はこのサーバーで以前うまくいかなかったため、アプリからは再試行しません。手動で試すには、サーバーで実行してください:{command}",
+ "serverUpdate.reason.stale": "サーバーの update.sh が、ボタンが使うコピーより新しくなっています。サーバーで実行してください:{command}",
+ "serverUpdate.reason.unreleased": "このサーバーは main のビルドで動いており、アプリからは更新しません。安定版がこのビルドより新しくなれば移行します。サーバーで実行してください:{command}",
+ "serverUpdate.reason.unsafe": "root 以外の人がボタンの実行内容を変更できるため、ボタンは何も実行しません:{folder}。修正してから、サーバーで実行してください:{command}",
+ "serverUpdate.reason.noRoom": "サーバーには、まずデータのコピー用の空きディスク容量が必要です。以前の更新で残したコピーを見るには、サーバーで実行してください:{list}。削除するには:{remove}"
}
diff --git a/src/locales/ko.json b/src/locales/ko.json
index c2af1b0dfa..01bb1c88f9 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -7429,5 +7429,49 @@
"phoneUpdate.open": "휴대폰 및 기기 열기",
"remote.devices.pairAgain": "다시 페어링",
"remote.devices.retired": "이 휴대폰의 MausBot 앱은 이전 버전입니다. 앱을 업데이트한 다음, 이 컴퓨터와 같은 Wi-Fi에서 한 번 여세요. 그래도 다시 연결되지 않으면 여기에서 다시 페어링하세요.",
- "remote.devices.retiredNotice": "이제 휴대폰은 MausBot Relay를 통해 이 컴퓨터에 연결되며, 이전의 보안 링크는 꺼졌습니다. 이전 버전의 MausBot 앱이 있는 휴대폰은 이제 Wi-Fi 밖에서 연결할 수 없습니다. 그 휴대폰에서 MausBot 앱을 업데이트한 다음, 이 컴퓨터와 같은 Wi-Fi에서 한 번 여세요. 그래도 다시 연결되지 않으면 여기에서 다시 페어링하세요."
+ "remote.devices.retiredNotice": "이제 휴대폰은 MausBot Relay를 통해 이 컴퓨터에 연결되며, 이전의 보안 링크는 꺼졌습니다. 이전 버전의 MausBot 앱이 있는 휴대폰은 이제 Wi-Fi 밖에서 연결할 수 없습니다. 그 휴대폰에서 MausBot 앱을 업데이트한 다음, 이 컴퓨터와 같은 Wi-Fi에서 한 번 여세요. 그래도 다시 연결되지 않으면 여기에서 다시 페어링하세요.",
+ "serverUpdate.available": "이 서버에 버전 {version}을(를) 쓸 수 있어요",
+ "serverUpdate.availableBoth": "이 서버를 {version}(으)로 업데이트할 수 있고, 이 앱도 예전 버전이에요",
+ "serverUpdate.updateServer": "서버 업데이트",
+ "serverUpdate.updating": "서버를 업데이트하는 중…",
+ "serverUpdate.updatingDetail": "알아서 다시 시작하고 다시 연결돼요. 몇 분 걸려요.",
+ "serverUpdate.updated": "서버를 v{version}(으)로 업데이트했어요.",
+ "serverUpdate.unchanged": "서버가 이미 최신 버전이었어요.",
+ "serverUpdate.rolledBack": "업데이트가 제대로 되지 않아 서버가 v{version}(으)로 돌아갔어요.",
+ "serverUpdate.rolledBackDetail": "데이터는 그대로예요. 이유는 서버의 .update/update.log에 있어요.",
+ "serverUpdate.rollbackFailed": "업데이트에 실패했고, 서버가 스스로 되돌아가지 못했어요.",
+ "serverUpdate.runOnServer": "서버에서 실행하세요: {command}",
+ "serverUpdate.notChanged": "서버는 바뀌지 않았어요.",
+ "serverUpdate.reason.busy": "다른 업데이트가 이미 진행 중이었어요.",
+ "serverUpdate.reason.refused": "다운로드 실패나 디스크 부족 같은 이유로 업데이트를 시작하지 못했어요. 이유는 서버의 .update/update.log에 있어요.",
+ "serverUpdate.reason.older": "안정 버전이 지금 실행 중인 버전보다 새롭지 않아요.",
+ "serverUpdate.reason.held": "이 서버는 업데이트가 보류되어 있어요.",
+ "serverUpdate.reason.tooSoon": "업데이트 요청이 너무 잦았어요. 몇 분 뒤에 다시 시도하세요.",
+ "serverUpdate.reason.noUpdater": "서버에 update.sh가 없어요.",
+ "serverUpdate.reason.failed": "업데이트가 끝나기 전에 멈췄어요. 이유는 서버의 .update/update.log에 있어요.",
+ "serverUpdate.notStarted": "서버가 업데이트를 시작하지 않았어요.",
+ "serverUpdate.appDownloading": "이 앱이 업데이트를 받는 중이에요. 앱을 다시 시작하면 설치돼요.",
+ "serverUpdate.appCurrent": "이 앱의 새 버전은 아직 없어요.",
+ "serverUpdate.appFailed": "이 앱이 업데이트를 받지 못했어요. 다시 시도하세요.",
+ "serverUpdate.appUnavailable": "이 앱은 여기서 스스로 업데이트할 수 없어요. 웹사이트에서 새 버전을 내려받으세요.",
+ "serverUpdate.appBehind": "이 앱은 v{appVersion}, 서버는 v{serverVersion}이에요",
+ "serverUpdate.updateApp": "앱 업데이트",
+ "serverUpdate.confirmTitle": "서버를 업데이트할까요?",
+ "serverUpdate.confirmBody": "업데이트하려면 서버가 다시 시작되므로 실행 중인 작업이 멈춰요. 몇 분 걸려요. 새 버전이 제대로 동작하지 않으면 서버가 알아서 이 버전으로 돌아와요.",
+ "serverUpdate.confirmBusy.one": "지금 {count}개 채팅에서 봇이 답하고 있어요.",
+ "serverUpdate.confirmBusy.other": "지금 {count}개 채팅에서 봇이 답하고 있어요.",
+ "serverUpdate.failed": "서버에 업데이트를 요청하지 못했어요. 다시 시도하세요.",
+ "activity.action.update.server": "서버 업데이트 요청",
+ "native.update.forServer": "{server}에서 이 앱의 업데이트를 요청해요. 버전 {version}이(가) 준비됐어요. 지금 다시 시작해서 설치할까요?",
+ "native.update.forServerDetail": "앱이 다시 시작되는 동안 이 컴퓨터에서 실행 중인 봇이 멈춰요.",
+ "native.update.restartNow": "지금 다시 시작",
+ "native.update.notNow": "나중에",
+ "serverUpdate.notBack": "서버가 아직 돌아오지 않았어요",
+ "serverUpdate.notBackDetail": "업데이트가 15분 넘게 이어지고 있어요.",
+ "serverUpdate.goBack": "이전 버전으로 돌아가려면: {command}",
+ "serverUpdate.reason.notRetried": "v{version}(으)로의 업데이트가 이 서버에서 이전에 실패해서 앱이 다시 시도하지 않아요. 직접 시도하려면 서버에서 실행하세요: {command}",
+ "serverUpdate.reason.stale": "서버의 update.sh가 버튼이 쓰는 사본보다 새로워요. 서버에서 실행하세요: {command}",
+ "serverUpdate.reason.unreleased": "이 서버는 main 빌드로 실행 중이라 앱이 업데이트하지 않아요. 안정 버전이 이 빌드보다 새로워지면 그 버전으로 옮겨가요. 서버에서 실행하세요: {command}",
+ "serverUpdate.reason.unsafe": "root가 아닌 사람이 버튼이 실행하는 내용을 바꿀 수 있어서 아무것도 실행하지 않아요: {folder}. 고친 다음 서버에서 실행하세요: {command}",
+ "serverUpdate.reason.noRoom": "서버에 먼저 데이터 사본을 둘 빈 디스크 공간이 필요해요. 이전 업데이트가 남긴 사본을 보려면 서버에서 실행하세요: {list}. 하나를 지우려면: {remove}"
}
diff --git a/src/locales/pl.json b/src/locales/pl.json
index f35801a4f7..e133e292df 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -6848,5 +6848,49 @@
"phoneUpdate.open": "Otwórz Telefon i urządzenia",
"remote.devices.pairAgain": "Sparuj ponownie",
"remote.devices.retired": "Ten telefon ma starszą wersję aplikacji MausBot. Zaktualizuj aplikację, a potem otwórz ją raz w tej samej sieci Wi-Fi co ten komputer. Jeśli to nie przywróci połączenia, sparuj go tutaj ponownie.",
- "remote.devices.retiredNotice": "Telefony łączą się teraz z tym komputerem przez MausBot Relay, a starsze bezpieczne połączenie zostało wyłączone. Telefon ze starszą wersją aplikacji MausBot nie może już łączyć się poza Twoją siecią Wi-Fi. Zaktualizuj aplikację MausBot na tym telefonie, a potem otwórz ją raz w tej samej sieci Wi-Fi co ten komputer. Jeśli to nie przywróci połączenia, sparuj go tutaj ponownie."
+ "remote.devices.retiredNotice": "Telefony łączą się teraz z tym komputerem przez MausBot Relay, a starsze bezpieczne połączenie zostało wyłączone. Telefon ze starszą wersją aplikacji MausBot nie może już łączyć się poza Twoją siecią Wi-Fi. Zaktualizuj aplikację MausBot na tym telefonie, a potem otwórz ją raz w tej samej sieci Wi-Fi co ten komputer. Jeśli to nie przywróci połączenia, sparuj go tutaj ponownie.",
+ "serverUpdate.available": "Wersja {version} jest dostępna dla tego serwera",
+ "serverUpdate.availableBoth": "Ten serwer można zaktualizować do {version}, a ta aplikacja też jest nieaktualna",
+ "serverUpdate.updateServer": "Zaktualizuj serwer",
+ "serverUpdate.updating": "Aktualizowanie serwera…",
+ "serverUpdate.updatingDetail": "Uruchomi się ponownie i sam połączy. To potrwa kilka minut.",
+ "serverUpdate.updated": "Serwer zaktualizowano do v{version}.",
+ "serverUpdate.unchanged": "Serwer był już aktualny.",
+ "serverUpdate.rolledBack": "Aktualizacja się nie udała, więc serwer wrócił do v{version}.",
+ "serverUpdate.rolledBackDetail": "Dane są takie jak przedtem. Przyczynę znajdziesz w .update/update.log na serwerze.",
+ "serverUpdate.rollbackFailed": "Aktualizacja się nie powiodła, a serwer nie wrócił sam do poprzedniej wersji.",
+ "serverUpdate.runOnServer": "Na serwerze uruchom: {command}",
+ "serverUpdate.notChanged": "Serwer nie został zmieniony.",
+ "serverUpdate.reason.busy": "Trwała już inna aktualizacja.",
+ "serverUpdate.reason.refused": "Aktualizacja nie mogła się zacząć, np. pobieranie się nie udało albo dysk jest pełny. Przyczynę znajdziesz w .update/update.log na serwerze.",
+ "serverUpdate.reason.older": "Wersja stabilna nie jest nowsza niż ta, której używa.",
+ "serverUpdate.reason.held": "Aktualizacje są wstrzymane na tym serwerze.",
+ "serverUpdate.reason.tooSoon": "Za często proszono o aktualizację. Spróbuj ponownie za kilka minut.",
+ "serverUpdate.reason.noUpdater": "Na serwerze brakuje update.sh.",
+ "serverUpdate.reason.failed": "Aktualizacja zatrzymała się przed końcem. Przyczynę znajdziesz w .update/update.log na serwerze.",
+ "serverUpdate.notStarted": "Serwer nie rozpoczął aktualizacji.",
+ "serverUpdate.appDownloading": "Ta aplikacja pobiera aktualizację. Zainstaluje się po ponownym uruchomieniu aplikacji.",
+ "serverUpdate.appCurrent": "Nowszej wersji tej aplikacji jeszcze nie ma.",
+ "serverUpdate.appFailed": "Ta aplikacja nie mogła pobrać aktualizacji. Spróbuj ponownie.",
+ "serverUpdate.appUnavailable": "Ta aplikacja nie może się tu sama zaktualizować. Pobierz nową wersję ze strony.",
+ "serverUpdate.appBehind": "Ta aplikacja ma v{appVersion}, a serwer v{serverVersion}",
+ "serverUpdate.updateApp": "Zaktualizuj aplikację",
+ "serverUpdate.confirmTitle": "Zaktualizować serwer?",
+ "serverUpdate.confirmBody": "Serwer uruchomi się ponownie, żeby się zaktualizować, więc wszystko, co na nim działa, się zatrzyma. To potrwa kilka minut. Jeśli nowa wersja nie zadziała, serwer sam wróci do tej.",
+ "serverUpdate.confirmBusy.one": "Bot odpowiada teraz w {count} czacie.",
+ "serverUpdate.confirmBusy.other": "Boty odpowiadają teraz w czatach: {count}.",
+ "serverUpdate.failed": "Nie udało się poprosić serwera o aktualizację. Spróbuj ponownie.",
+ "activity.action.update.server": "Poproszono o aktualizację serwera",
+ "native.update.forServer": "{server} prosi o aktualizację tej aplikacji. Wersja {version} jest gotowa. Uruchomić ponownie teraz, żeby ją zainstalować?",
+ "native.update.forServerDetail": "Boty działające na tym komputerze zatrzymają się na czas ponownego uruchomienia aplikacji.",
+ "native.update.restartNow": "Uruchom ponownie teraz",
+ "native.update.notNow": "Nie teraz",
+ "serverUpdate.notBack": "Serwer jeszcze nie wrócił",
+ "serverUpdate.notBackDetail": "Aktualizacja trwa już ponad 15 minut.",
+ "serverUpdate.goBack": "Aby wrócić do poprzedniej wersji: {command}",
+ "serverUpdate.reason.notRetried": "Aktualizacja do v{version} nie udała się już na tym serwerze, więc aplikacja nie spróbuje ponownie. Aby spróbować ręcznie, uruchom na serwerze: {command}",
+ "serverUpdate.reason.stale": "update.sh na serwerze jest nowszy niż kopia, której używa przycisk. Na serwerze uruchom: {command}",
+ "serverUpdate.reason.unreleased": "Ten serwer działa na buildzie main, którego aplikacja nie aktualizuje. Przejdzie na wersję stabilną, gdy będzie ona nowsza niż build; na serwerze uruchom: {command}",
+ "serverUpdate.reason.unsafe": "Przycisk niczego nie uruchamia, bo ktoś inny niż root mógłby zmienić to, co uruchamia: {folder}. Popraw to, a potem na serwerze uruchom: {command}",
+ "serverUpdate.reason.noRoom": "Serwer potrzebuje najpierw wolnego miejsca na dysku na kopię swoich danych. Aby zobaczyć kopie zachowane przez wcześniejsze aktualizacje, uruchom na serwerze: {list}. Aby usunąć jedną: {remove}"
}
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 450a691063..ed1eddc158 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10208,5 +10208,49 @@
"phoneUpdate.body": "{phone} tem uma versão mais antiga do app MausBot, que não consegue mais se conectar a este computador fora do seu Wi-Fi. Atualize o app nesse celular e depois abra-o uma vez no mesmo Wi-Fi deste computador. Se ele não reconectar, pareie de novo.",
"phoneUpdate.bodyMany": "{count} dos seus celulares têm uma versão mais antiga do app MausBot, que não consegue mais se conectar a este computador fora do seu Wi-Fi. Atualize o app em cada celular e depois abra-o uma vez no mesmo Wi-Fi deste computador. Se ele não reconectar, pareie de novo.",
"phoneUpdate.open": "Abrir Celular e dispositivos",
- "remote.devices.pairAgain": "Parear de novo"
+ "remote.devices.pairAgain": "Parear de novo",
+ "serverUpdate.available": "A versão {version} está disponível para este servidor",
+ "serverUpdate.availableBoth": "Este servidor pode ser atualizado para a {version}, e este app também está desatualizado",
+ "serverUpdate.updateServer": "Atualizar servidor",
+ "serverUpdate.updating": "Atualizando o servidor…",
+ "serverUpdate.updatingDetail": "Ele reinicia e se reconecta sozinho. Isso leva alguns minutos.",
+ "serverUpdate.updated": "O servidor foi atualizado para a v{version}.",
+ "serverUpdate.unchanged": "O servidor já estava atualizado.",
+ "serverUpdate.rolledBack": "A atualização não funcionou, então o servidor voltou para a v{version}.",
+ "serverUpdate.rolledBackDetail": "Seus dados estão como antes. O motivo está em .update/update.log no servidor.",
+ "serverUpdate.rollbackFailed": "A atualização falhou, e o servidor não conseguiu voltar sozinho.",
+ "serverUpdate.runOnServer": "No servidor, execute: {command}",
+ "serverUpdate.notChanged": "O servidor não foi alterado.",
+ "serverUpdate.reason.busy": "Outra atualização já estava em andamento.",
+ "serverUpdate.reason.refused": "A atualização não pôde começar, por exemplo porque o download falhou ou o disco está cheio. O motivo está em .update/update.log no servidor.",
+ "serverUpdate.reason.older": "A versão estável não é mais nova que a que ele usa.",
+ "serverUpdate.reason.held": "As atualizações estão suspensas neste servidor.",
+ "serverUpdate.reason.tooSoon": "Atualizações foram pedidas vezes demais. Tente de novo em alguns minutos.",
+ "serverUpdate.reason.noUpdater": "O update.sh não está no servidor.",
+ "serverUpdate.reason.failed": "A atualização parou antes de terminar. O motivo está em .update/update.log no servidor.",
+ "serverUpdate.notStarted": "O servidor não começou a atualização.",
+ "serverUpdate.appDownloading": "Este app está baixando a atualização. Ela é instalada quando você reiniciar o app.",
+ "serverUpdate.appCurrent": "Ainda não há uma versão mais nova deste app.",
+ "serverUpdate.appFailed": "Este app não conseguiu obter a atualização. Tente de novo.",
+ "serverUpdate.appUnavailable": "Este app não consegue se atualizar sozinho aqui. Baixe a nova versão no site.",
+ "serverUpdate.appBehind": "Este app está na v{appVersion}, e o servidor na v{serverVersion}",
+ "serverUpdate.updateApp": "Atualizar app",
+ "serverUpdate.confirmTitle": "Atualizar o servidor?",
+ "serverUpdate.confirmBody": "O servidor reinicia para atualizar, então tudo que estiver rodando nele para. Isso leva alguns minutos. Se a nova versão não funcionar, o servidor volta sozinho para esta.",
+ "serverUpdate.confirmBusy.one": "Agora mesmo um bot está respondendo em {count} chat.",
+ "serverUpdate.confirmBusy.other": "Agora mesmo há bots respondendo em {count} chats.",
+ "serverUpdate.failed": "Não foi possível pedir ao servidor para atualizar. Tente de novo.",
+ "activity.action.update.server": "Pediu para atualizar o servidor",
+ "native.update.forServer": "{server} pede para atualizar este app. A versão {version} está pronta. Reiniciar agora para instalar?",
+ "native.update.forServerDetail": "Os bots deste computador param enquanto o app reinicia.",
+ "native.update.restartNow": "Reiniciar agora",
+ "native.update.notNow": "Agora não",
+ "serverUpdate.notBack": "O servidor ainda não voltou",
+ "serverUpdate.notBackDetail": "A atualização já dura mais de 15 minutos.",
+ "serverUpdate.goBack": "Para voltar à versão anterior: {command}",
+ "serverUpdate.reason.notRetried": "A atualização para a v{version} já falhou neste servidor, então o app não vai tentar de novo. Para tentar à mão, execute no servidor: {command}",
+ "serverUpdate.reason.stale": "O update.sh do servidor é mais novo que a cópia que o botão usa. No servidor, execute: {command}",
+ "serverUpdate.reason.unreleased": "Este servidor roda um build da main, que o app não atualiza. Ele passa para a versão estável assim que ela for mais nova que o build; no servidor, execute: {command}",
+ "serverUpdate.reason.unsafe": "O botão não executa nada, porque alguém que não é o root poderia mudar o que ele executa: {folder}. Corrija isso e depois, no servidor, execute: {command}",
+ "serverUpdate.reason.noRoom": "O servidor precisa primeiro de espaço livre em disco para uma cópia dos dados. Para ver as cópias que atualizações anteriores guardaram, execute no servidor: {list}. Para remover uma: {remove}"
}
diff --git a/src/locales/ru.json b/src/locales/ru.json
index dca15b11aa..c94399f9cd 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -6910,5 +6910,49 @@
"phoneUpdate.open": "Открыть «Телефон и устройства»",
"remote.devices.pairAgain": "Сопрячь заново",
"remote.devices.retired": "На этом телефоне старая версия приложения MausBot. Обновите приложение, затем один раз откройте его в той же Wi-Fi, что и этот компьютер. Если подключение не восстановится, сопрягите его здесь заново.",
- "remote.devices.retiredNotice": "Теперь телефоны подключаются к этому компьютеру через MausBot Relay, а старая защищённая ссылка отключена. Телефон со старой версией приложения MausBot больше не может подключаться вне вашей Wi-Fi. Обновите приложение MausBot на этом телефоне, затем один раз откройте его в той же Wi-Fi, что и этот компьютер. Если подключение не восстановится, сопрягите его здесь заново."
+ "remote.devices.retiredNotice": "Теперь телефоны подключаются к этому компьютеру через MausBot Relay, а старая защищённая ссылка отключена. Телефон со старой версией приложения MausBot больше не может подключаться вне вашей Wi-Fi. Обновите приложение MausBot на этом телефоне, затем один раз откройте его в той же Wi-Fi, что и этот компьютер. Если подключение не восстановится, сопрягите его здесь заново.",
+ "serverUpdate.available": "Для этого сервера доступна версия {version}",
+ "serverUpdate.availableBoth": "Этот сервер можно обновить до {version}, и это приложение тоже устарело",
+ "serverUpdate.updateServer": "Обновить сервер",
+ "serverUpdate.updating": "Сервер обновляется…",
+ "serverUpdate.updatingDetail": "Он перезапустится и подключится сам. Это займёт несколько минут.",
+ "serverUpdate.updated": "Сервер обновлён до v{version}.",
+ "serverUpdate.unchanged": "На сервере уже была последняя версия.",
+ "serverUpdate.rolledBack": "Обновление не сработало, поэтому сервер вернулся на v{version}.",
+ "serverUpdate.rolledBackDetail": "Ваши данные остались прежними. Причина — в .update/update.log на сервере.",
+ "serverUpdate.rollbackFailed": "Обновление не удалось, и сервер не смог сам вернуться назад.",
+ "serverUpdate.runOnServer": "На сервере выполните: {command}",
+ "serverUpdate.notChanged": "Сервер не изменился.",
+ "serverUpdate.reason.busy": "Там уже шло другое обновление.",
+ "serverUpdate.reason.refused": "Обновление не смогло начаться: например, не удалась загрузка или диск заполнен. Причина — в .update/update.log на сервере.",
+ "serverUpdate.reason.older": "Стабильная версия не новее той, что на нём работает.",
+ "serverUpdate.reason.held": "Обновления на этом сервере приостановлены.",
+ "serverUpdate.reason.tooSoon": "Обновление запрашивали слишком часто. Попробуйте через несколько минут.",
+ "serverUpdate.reason.noUpdater": "На сервере нет update.sh.",
+ "serverUpdate.reason.failed": "Обновление остановилось, не закончившись. Причина — в .update/update.log на сервере.",
+ "serverUpdate.notStarted": "Сервер не начал обновление.",
+ "serverUpdate.appDownloading": "Приложение загружает обновление. Оно установится, когда вы перезапустите приложение.",
+ "serverUpdate.appCurrent": "Новой версии этого приложения пока нет.",
+ "serverUpdate.appFailed": "Приложению не удалось получить обновление. Попробуйте ещё раз.",
+ "serverUpdate.appUnavailable": "Здесь приложение не может обновиться само. Скачайте новую версию с сайта.",
+ "serverUpdate.appBehind": "У приложения v{appVersion}, у сервера v{serverVersion}",
+ "serverUpdate.updateApp": "Обновить приложение",
+ "serverUpdate.confirmTitle": "Обновить сервер?",
+ "serverUpdate.confirmBody": "Для обновления сервер перезапустится, поэтому всё, что на нём работает, остановится. Это займёт несколько минут. Если новая версия не заработает, сервер сам вернётся к этой.",
+ "serverUpdate.confirmBusy.one": "Сейчас бот отвечает в {count} чате.",
+ "serverUpdate.confirmBusy.other": "Сейчас боты отвечают в чатах: {count}.",
+ "serverUpdate.failed": "Не удалось попросить сервер обновиться. Попробуйте ещё раз.",
+ "activity.action.update.server": "Запросил обновление сервера",
+ "native.update.forServer": "{server} просит обновить это приложение. Версия {version} готова. Перезапустить сейчас, чтобы установить её?",
+ "native.update.forServerDetail": "Боты на этом компьютере остановятся, пока приложение перезапускается.",
+ "native.update.restartNow": "Перезапустить",
+ "native.update.notNow": "Не сейчас",
+ "serverUpdate.notBack": "Сервер ещё не вернулся",
+ "serverUpdate.notBackDetail": "Обновление идёт уже больше 15 минут.",
+ "serverUpdate.goBack": "Чтобы вернуть прежнюю версию: {command}",
+ "serverUpdate.reason.notRetried": "Обновление до v{version} уже не сработало на этом сервере, поэтому приложение не будет пробовать снова. Чтобы попробовать вручную, выполните на сервере: {command}",
+ "serverUpdate.reason.stale": "update.sh на сервере новее копии, которую использует кнопка. На сервере выполните: {command}",
+ "serverUpdate.reason.unreleased": "Этот сервер работает на сборке main, которую приложение не обновляет. Он перейдёт на стабильную версию, когда она станет новее сборки; на сервере выполните: {command}",
+ "serverUpdate.reason.unsafe": "Кнопка ничего не запускает, потому что кто-то кроме root мог бы изменить то, что она запускает: {folder}. Исправьте это, затем на сервере выполните: {command}",
+ "serverUpdate.reason.noRoom": "Серверу сначала нужно свободное место на диске для копии данных. Чтобы увидеть копии, оставленные прошлыми обновлениями, выполните на сервере: {list}. Чтобы удалить одну: {remove}"
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 923dc96a55..6b66805035 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5589,5 +5589,49 @@
"phoneUpdate.open": "Telefon ve cihazlar'ı aç",
"remote.devices.pairAgain": "Yeniden eşleştir",
"remote.devices.retired": "Bu telefonda MausBot uygulamasının eski bir sürümü var. Uygulamayı güncelleyin, ardından bu bilgisayarla aynı Wi-Fi ağındayken bir kez açın. Yeniden bağlanmazsa burada yeniden eşleştirin.",
- "remote.devices.retiredNotice": "Telefonlar artık bu bilgisayara MausBot Relay üzerinden ulaşıyor ve eski güvenli bağlantı kapatıldı. MausBot uygulamasının eski bir sürümüne sahip bir telefon artık Wi-Fi ağınızın dışından bağlanamıyor. O telefonda MausBot uygulamasını güncelleyin, ardından bu bilgisayarla aynı Wi-Fi ağındayken bir kez açın. Yeniden bağlanmazsa burada yeniden eşleştirin."
+ "remote.devices.retiredNotice": "Telefonlar artık bu bilgisayara MausBot Relay üzerinden ulaşıyor ve eski güvenli bağlantı kapatıldı. MausBot uygulamasının eski bir sürümüne sahip bir telefon artık Wi-Fi ağınızın dışından bağlanamıyor. O telefonda MausBot uygulamasını güncelleyin, ardından bu bilgisayarla aynı Wi-Fi ağındayken bir kez açın. Yeniden bağlanmazsa burada yeniden eşleştirin.",
+ "serverUpdate.available": "Bu sunucu için {version} sürümü hazır",
+ "serverUpdate.availableBoth": "Bu sunucu {version} sürümüne güncellenebilir, bu uygulama da geride",
+ "serverUpdate.updateServer": "Sunucuyu güncelle",
+ "serverUpdate.updating": "Sunucu güncelleniyor…",
+ "serverUpdate.updatingDetail": "Kendiliğinden yeniden başlar ve yeniden bağlanır. Bu birkaç dakika sürer.",
+ "serverUpdate.updated": "Sunucu v{version} sürümüne güncellendi.",
+ "serverUpdate.unchanged": "Sunucu zaten günceldi.",
+ "serverUpdate.rolledBack": "Güncelleme işe yaramadı, bu yüzden sunucu v{version} sürümüne geri döndü.",
+ "serverUpdate.rolledBackDetail": "Verileriniz olduğu gibi. Nedeni sunucudaki .update/update.log dosyasında.",
+ "serverUpdate.rollbackFailed": "Güncelleme başarısız oldu ve sunucu kendi kendine geri dönemedi.",
+ "serverUpdate.runOnServer": "Sunucuda şunu çalıştırın: {command}",
+ "serverUpdate.notChanged": "Sunucu değiştirilmedi.",
+ "serverUpdate.reason.busy": "Üzerinde zaten başka bir güncelleme çalışıyordu.",
+ "serverUpdate.reason.refused": "Güncelleme başlayamadı; örneğin indirme başarısız oldu ya da disk dolu. Nedeni sunucudaki .update/update.log dosyasında.",
+ "serverUpdate.reason.older": "Kararlı sürüm, çalıştırdığı sürümden daha yeni değil.",
+ "serverUpdate.reason.held": "Bu sunucuda güncellemeler beklemede.",
+ "serverUpdate.reason.tooSoon": "Güncelleme çok sık istendi. Birkaç dakika sonra yeniden deneyin.",
+ "serverUpdate.reason.noUpdater": "Sunucuda update.sh yok.",
+ "serverUpdate.reason.failed": "Güncelleme bitmeden durdu. Nedeni sunucudaki .update/update.log dosyasında.",
+ "serverUpdate.notStarted": "Sunucu güncellemeyi başlatmadı.",
+ "serverUpdate.appDownloading": "Bu uygulama güncellemesini indiriyor. Uygulamayı yeniden başlattığınızda yüklenir.",
+ "serverUpdate.appCurrent": "Bu uygulamanın henüz daha yeni bir sürümü yok.",
+ "serverUpdate.appFailed": "Bu uygulama güncellemesini alamadı. Yeniden deneyin.",
+ "serverUpdate.appUnavailable": "Bu uygulama burada kendini güncelleyemiyor. Yeni sürümü web sitesinden indirin.",
+ "serverUpdate.appBehind": "Bu uygulama v{appVersion}, sunucu v{serverVersion} sürümünde",
+ "serverUpdate.updateApp": "Uygulamayı güncelle",
+ "serverUpdate.confirmTitle": "Sunucu güncellensin mi?",
+ "serverUpdate.confirmBody": "Sunucu güncellemek için yeniden başlar, bu yüzden üzerinde çalışan her şey durur. Bu birkaç dakika sürer. Yeni sürüm çalışmazsa sunucu kendiliğinden bu sürüme döner.",
+ "serverUpdate.confirmBusy.one": "Şu anda {count} sohbette bir bot yanıt veriyor.",
+ "serverUpdate.confirmBusy.other": "Şu anda {count} sohbette botlar yanıt veriyor.",
+ "serverUpdate.failed": "Sunucudan güncellenmesi istenemedi. Yeniden deneyin.",
+ "activity.action.update.server": "Sunucu güncellemesi istendi",
+ "native.update.forServer": "{server} bu uygulamanın güncellenmesini istiyor. {version} sürümü hazır. Yüklemek için şimdi yeniden başlatılsın mı?",
+ "native.update.forServerDetail": "Uygulama yeniden başlarken bu bilgisayardaki botlar durur.",
+ "native.update.restartNow": "Şimdi yeniden başlat",
+ "native.update.notNow": "Şimdi değil",
+ "serverUpdate.notBack": "Sunucu henüz geri gelmedi",
+ "serverUpdate.notBackDetail": "Güncelleme 15 dakikadan uzun süredir devam ediyor.",
+ "serverUpdate.goBack": "Önceki sürüme dönmek için: {command}",
+ "serverUpdate.reason.notRetried": "v{version} sürümüne güncelleme bu sunucuda daha önce işe yaramadı, bu yüzden uygulama yeniden denemeyecek. Elle denemek için sunucuda şunu çalıştırın: {command}",
+ "serverUpdate.reason.stale": "Sunucudaki update.sh, düğmenin kullandığı kopyadan daha yeni. Sunucuda şunu çalıştırın: {command}",
+ "serverUpdate.reason.unreleased": "Bu sunucu main dalının bir derlemesini çalıştırıyor; uygulama bunu güncellemez. Kararlı sürüm bu derlemeden yeni olduğunda ona geçer; sunucuda şunu çalıştırın: {command}",
+ "serverUpdate.reason.unsafe": "Düğme hiçbir şey çalıştırmıyor, çünkü root dışında biri çalıştırdığı şeyi değiştirebilir: {folder}. Bunu düzeltin, ardından sunucuda şunu çalıştırın: {command}",
+ "serverUpdate.reason.noRoom": "Sunucunun önce verilerinin bir kopyası için boş disk alanına ihtiyacı var. Önceki güncellemelerin sakladığı kopyaları görmek için sunucuda şunu çalıştırın: {list}. Birini silmek için: {remove}"
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index 3bcf7403af..c5deb81980 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -3607,5 +3607,49 @@
"phoneUpdate.open": "Відкрити «Телефон і пристрої»",
"remote.devices.pairAgain": "Прив'язати знову",
"remote.devices.retired": "На цьому телефоні стара версія застосунку MausBot. Оновіть застосунок, потім один раз відкрийте його в тій самій Wi-Fi, що й цей комп'ютер. Якщо з'єднання не відновиться, прив'яжіть його тут знову.",
- "remote.devices.retiredNotice": "Тепер телефони під'єднуються до цього комп'ютера через MausBot Relay, а старе захищене з'єднання вимкнено. Телефон зі старою версією застосунку MausBot більше не може під'єднуватися поза вашою Wi-Fi. Оновіть застосунок MausBot на цьому телефоні, потім один раз відкрийте його в тій самій Wi-Fi, що й цей комп'ютер. Якщо з'єднання не відновиться, прив'яжіть його тут знову."
+ "remote.devices.retiredNotice": "Тепер телефони під'єднуються до цього комп'ютера через MausBot Relay, а старе захищене з'єднання вимкнено. Телефон зі старою версією застосунку MausBot більше не може під'єднуватися поза вашою Wi-Fi. Оновіть застосунок MausBot на цьому телефоні, потім один раз відкрийте його в тій самій Wi-Fi, що й цей комп'ютер. Якщо з'єднання не відновиться, прив'яжіть його тут знову.",
+ "serverUpdate.available": "Для цього сервера доступна версія {version}",
+ "serverUpdate.availableBoth": "Цей сервер можна оновити до {version}, і цей застосунок теж застарів",
+ "serverUpdate.updateServer": "Оновити сервер",
+ "serverUpdate.updating": "Сервер оновлюється…",
+ "serverUpdate.updatingDetail": "Він перезапуститься й підключиться сам. Це займе кілька хвилин.",
+ "serverUpdate.updated": "Сервер оновлено до v{version}.",
+ "serverUpdate.unchanged": "На сервері вже була актуальна версія.",
+ "serverUpdate.rolledBack": "Оновлення не спрацювало, тому сервер повернувся до v{version}.",
+ "serverUpdate.rolledBackDetail": "Ваші дані такі, як були. Причина — у .update/update.log на сервері.",
+ "serverUpdate.rollbackFailed": "Оновлення не вдалося, і сервер не зміг сам повернутися назад.",
+ "serverUpdate.runOnServer": "На сервері виконайте: {command}",
+ "serverUpdate.notChanged": "Сервер не змінився.",
+ "serverUpdate.reason.busy": "Там уже йшло інше оновлення.",
+ "serverUpdate.reason.refused": "Оновлення не змогло почитися: наприклад, не вдалося завантаження або диск заповнений. Причина — у .update/update.log на сервері.",
+ "serverUpdate.reason.older": "Стабільна версія не новіша за ту, що на ньому працює.",
+ "serverUpdate.reason.held": "Оновлення на цьому сервері призупинено.",
+ "serverUpdate.reason.tooSoon": "Оновлення запитували надто часто. Спробуйте за кілька хвилин.",
+ "serverUpdate.reason.noUpdater": "На сервері немає update.sh.",
+ "serverUpdate.reason.failed": "Оновлення зупинилося, не завершившись. Причина — у .update/update.log на сервері.",
+ "serverUpdate.notStarted": "Сервер не почав оновлення.",
+ "serverUpdate.appDownloading": "Застосунок завантажує оновлення. Воно встановиться, коли ви перезапустите застосунок.",
+ "serverUpdate.appCurrent": "Нової версії цього застосунку поки немає.",
+ "serverUpdate.appFailed": "Застосунку не вдалося отримати оновлення. Спробуйте ще раз.",
+ "serverUpdate.appUnavailable": "Тут застосунок не може оновитися сам. Завантажте нову версію з сайту.",
+ "serverUpdate.appBehind": "У застосунку v{appVersion}, у сервера v{serverVersion}",
+ "serverUpdate.updateApp": "Оновити застосунок",
+ "serverUpdate.confirmTitle": "Оновити сервер?",
+ "serverUpdate.confirmBody": "Для оновлення сервер перезапуститься, тож усе, що на ньому працює, зупиниться. Це займе кілька хвилин. Якщо нова версія не запрацює, сервер сам повернеться до цієї.",
+ "serverUpdate.confirmBusy.one": "Зараз бот відповідає в {count} чаті.",
+ "serverUpdate.confirmBusy.other": "Зараз боти відповідають у чатах: {count}.",
+ "serverUpdate.failed": "Не вдалося попросити сервер оновитися. Спробуйте ще раз.",
+ "activity.action.update.server": "Запит на оновлення сервера",
+ "native.update.forServer": "{server} просить оновити цей застосунок. Версія {version} готова. Перезапустити зараз, щоб її встановити?",
+ "native.update.forServerDetail": "Боти на цьому комп'ютері зупиняться, поки застосунок перезапускається.",
+ "native.update.restartNow": "Перезапустити",
+ "native.update.notNow": "Не зараз",
+ "serverUpdate.notBack": "Сервер ще не повернувся",
+ "serverUpdate.notBackDetail": "Оновлення триває вже понад 15 хвилин.",
+ "serverUpdate.goBack": "Щоб повернути попередню версію: {command}",
+ "serverUpdate.reason.notRetried": "Оновлення до v{version} уже не спрацювало на цьому сервері, тож застосунок не пробуватиме знову. Щоб спробувати вручну, виконайте на сервері: {command}",
+ "serverUpdate.reason.stale": "update.sh на сервері новіший за копію, яку використовує кнопка. На сервері виконайте: {command}",
+ "serverUpdate.reason.unreleased": "Цей сервер працює на збірці main, яку застосунок не оновлює. Він перейде на стабільну версію, щойно вона стане новішою за збірку; на сервері виконайте: {command}",
+ "serverUpdate.reason.unsafe": "Кнопка нічого не запускає, бо хтось, крім root, міг би змінити те, що вона запускає: {folder}. Виправте це, потім на сервері виконайте: {command}",
+ "serverUpdate.reason.noRoom": "Серверу спершу потрібне вільне місце на диску для копії даних. Щоб побачити копії, які залишили попередні оновлення, виконайте на сервері: {list}. Щоб видалити одну: {remove}"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index dcc02f61ea..511084bd98 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5589,5 +5589,49 @@
"phoneUpdate.open": "Mở Điện thoại và thiết bị",
"remote.devices.pairAgain": "Ghép nối lại",
"remote.devices.retired": "Điện thoại này đang dùng phiên bản cũ của ứng dụng MausBot. Hãy cập nhật ứng dụng, rồi mở nó một lần khi ở cùng Wi-Fi với máy tính này. Nếu vẫn không kết nối lại, hãy ghép nối lại tại đây.",
- "remote.devices.retiredNotice": "Giờ điện thoại kết nối với máy tính này qua MausBot Relay, và liên kết bảo mật cũ đã bị tắt. Điện thoại dùng phiên bản cũ của ứng dụng MausBot không thể kết nối khi ở ngoài Wi-Fi của bạn nữa. Hãy cập nhật ứng dụng MausBot trên điện thoại đó, rồi mở nó một lần khi ở cùng Wi-Fi với máy tính này. Nếu vẫn không kết nối lại, hãy ghép nối lại tại đây."
+ "remote.devices.retiredNotice": "Giờ điện thoại kết nối với máy tính này qua MausBot Relay, và liên kết bảo mật cũ đã bị tắt. Điện thoại dùng phiên bản cũ của ứng dụng MausBot không thể kết nối khi ở ngoài Wi-Fi của bạn nữa. Hãy cập nhật ứng dụng MausBot trên điện thoại đó, rồi mở nó một lần khi ở cùng Wi-Fi với máy tính này. Nếu vẫn không kết nối lại, hãy ghép nối lại tại đây.",
+ "serverUpdate.available": "Đã có phiên bản {version} cho máy chủ này",
+ "serverUpdate.availableBoth": "Máy chủ này có thể cập nhật lên {version}, và ứng dụng này cũng đã cũ",
+ "serverUpdate.updateServer": "Cập nhật máy chủ",
+ "serverUpdate.updating": "Đang cập nhật máy chủ…",
+ "serverUpdate.updatingDetail": "Máy chủ sẽ tự khởi động lại và kết nối lại. Việc này mất vài phút.",
+ "serverUpdate.updated": "Máy chủ đã được cập nhật lên v{version}.",
+ "serverUpdate.unchanged": "Máy chủ đã ở phiên bản mới nhất.",
+ "serverUpdate.rolledBack": "Bản cập nhật không chạy được nên máy chủ đã quay về v{version}.",
+ "serverUpdate.rolledBackDetail": "Dữ liệu của bạn vẫn như cũ. Lý do nằm trong .update/update.log trên máy chủ.",
+ "serverUpdate.rollbackFailed": "Cập nhật thất bại và máy chủ không tự quay lại được.",
+ "serverUpdate.runOnServer": "Trên máy chủ, chạy: {command}",
+ "serverUpdate.notChanged": "Máy chủ không thay đổi.",
+ "serverUpdate.reason.busy": "Đã có một bản cập nhật khác đang chạy.",
+ "serverUpdate.reason.refused": "Không thể bắt đầu cập nhật, ví dụ do tải xuống thất bại hoặc ổ đĩa đã đầy. Lý do nằm trong .update/update.log trên máy chủ.",
+ "serverUpdate.reason.older": "Phiên bản ổn định không mới hơn phiên bản đang chạy.",
+ "serverUpdate.reason.held": "Cập nhật đang bị tạm dừng trên máy chủ này.",
+ "serverUpdate.reason.tooSoon": "Yêu cầu cập nhật quá thường xuyên. Hãy thử lại sau vài phút.",
+ "serverUpdate.reason.noUpdater": "Máy chủ không có update.sh.",
+ "serverUpdate.reason.failed": "Bản cập nhật đã dừng trước khi xong. Lý do nằm trong .update/update.log trên máy chủ.",
+ "serverUpdate.notStarted": "Máy chủ chưa bắt đầu cập nhật.",
+ "serverUpdate.appDownloading": "Ứng dụng đang tải bản cập nhật. Bản cập nhật sẽ được cài khi bạn khởi động lại ứng dụng.",
+ "serverUpdate.appCurrent": "Chưa có phiên bản mới hơn của ứng dụng này.",
+ "serverUpdate.appFailed": "Ứng dụng không lấy được bản cập nhật. Hãy thử lại.",
+ "serverUpdate.appUnavailable": "Ứng dụng không thể tự cập nhật ở đây. Hãy tải phiên bản mới từ trang web.",
+ "serverUpdate.appBehind": "Ứng dụng này đang ở v{appVersion}, máy chủ ở v{serverVersion}",
+ "serverUpdate.updateApp": "Cập nhật ứng dụng",
+ "serverUpdate.confirmTitle": "Cập nhật máy chủ?",
+ "serverUpdate.confirmBody": "Máy chủ sẽ khởi động lại để cập nhật, nên mọi thứ đang chạy trên đó sẽ dừng. Việc này mất vài phút. Nếu phiên bản mới không chạy được, máy chủ sẽ tự quay về phiên bản này.",
+ "serverUpdate.confirmBusy.one": "Một bot đang trả lời trong {count} cuộc trò chuyện.",
+ "serverUpdate.confirmBusy.other": "Các bot đang trả lời trong {count} cuộc trò chuyện.",
+ "serverUpdate.failed": "Không thể yêu cầu máy chủ cập nhật. Hãy thử lại.",
+ "activity.action.update.server": "Đã yêu cầu cập nhật máy chủ",
+ "native.update.forServer": "{server} yêu cầu cập nhật ứng dụng này. Phiên bản {version} đã sẵn sàng. Khởi động lại ngay để cài đặt?",
+ "native.update.forServerDetail": "Các bot đang chạy trên máy tính này sẽ dừng trong lúc ứng dụng khởi động lại.",
+ "native.update.restartNow": "Khởi động lại ngay",
+ "native.update.notNow": "Để sau",
+ "serverUpdate.notBack": "Máy chủ vẫn chưa quay lại",
+ "serverUpdate.notBackDetail": "Việc cập nhật đã kéo dài hơn 15 phút.",
+ "serverUpdate.goBack": "Để quay về phiên bản trước: {command}",
+ "serverUpdate.reason.notRetried": "Bản cập nhật lên v{version} đã không chạy được trên máy chủ này, nên ứng dụng sẽ không thử lại. Để tự thử, chạy trên máy chủ: {command}",
+ "serverUpdate.reason.stale": "update.sh trên máy chủ mới hơn bản sao mà nút đang dùng. Trên máy chủ, chạy: {command}",
+ "serverUpdate.reason.unreleased": "Máy chủ này đang chạy bản dựng từ main, ứng dụng không cập nhật bản này. Máy chủ chuyển sang phiên bản ổn định khi phiên bản đó mới hơn bản dựng; trên máy chủ, chạy: {command}",
+ "serverUpdate.reason.unsafe": "Nút không chạy gì, vì người khác ngoài root có thể thay đổi những gì nút chạy: {folder}. Hãy sửa, rồi trên máy chủ chạy: {command}",
+ "serverUpdate.reason.noRoom": "Máy chủ cần dung lượng đĩa trống cho một bản sao dữ liệu trước. Để xem các bản sao mà những lần cập nhật trước giữ lại, chạy trên máy chủ: {list}. Để xóa một bản: {remove}"
}
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index c5d6bce7c7..cceeb19de3 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -9965,5 +9965,49 @@
"phoneUpdate.open": "開啟「手機和裝置」",
"remote.devices.pairAgain": "重新配對",
"remote.devices.retired": "這支手機上的 MausBot 應用程式是舊版本。請更新應用程式,然後在與這台電腦相同的 Wi-Fi 下開啟一次。如果仍無法重新連線,請在這裡重新配對。",
- "remote.devices.retiredNotice": "手機現在透過 MausBot Relay 連線到這台電腦,舊的安全連結已經關閉。使用舊版 MausBot 應用程式的手機,離開你的 Wi-Fi 後已無法連線。請在那支手機上更新 MausBot 應用程式,然後在與這台電腦相同的 Wi-Fi 下開啟一次。如果仍無法重新連線,請在這裡重新配對。"
+ "remote.devices.retiredNotice": "手機現在透過 MausBot Relay 連線到這台電腦,舊的安全連結已經關閉。使用舊版 MausBot 應用程式的手機,離開你的 Wi-Fi 後已無法連線。請在那支手機上更新 MausBot 應用程式,然後在與這台電腦相同的 Wi-Fi 下開啟一次。如果仍無法重新連線,請在這裡重新配對。",
+ "serverUpdate.available": "此伺服器有可用的版本 {version}",
+ "serverUpdate.availableBoth": "此伺服器可更新到 {version},此應用程式也不是最新版本",
+ "serverUpdate.updateServer": "更新伺服器",
+ "serverUpdate.updating": "正在更新伺服器…",
+ "serverUpdate.updatingDetail": "它會自動重新啟動並重新連線,需要幾分鐘。",
+ "serverUpdate.updated": "伺服器已更新到 v{version}。",
+ "serverUpdate.unchanged": "伺服器已經是最新版本。",
+ "serverUpdate.rolledBack": "更新沒有成功,伺服器已回到 v{version}。",
+ "serverUpdate.rolledBackDetail": "你的資料保持原樣。原因見伺服器上的 .update/update.log。",
+ "serverUpdate.rollbackFailed": "更新失敗,伺服器也沒能自行回復。",
+ "serverUpdate.runOnServer": "請在伺服器上執行:{command}",
+ "serverUpdate.notChanged": "伺服器沒有變更。",
+ "serverUpdate.reason.busy": "伺服器上已有另一個更新在進行。",
+ "serverUpdate.reason.refused": "更新無法開始,例如下載失敗或磁碟已滿。原因見伺服器上的 .update/update.log。",
+ "serverUpdate.reason.older": "穩定版並不比它正在執行的版本新。",
+ "serverUpdate.reason.held": "此伺服器的更新已暫停。",
+ "serverUpdate.reason.tooSoon": "更新請求過於頻繁。請幾分鐘後再試。",
+ "serverUpdate.reason.noUpdater": "伺服器上缺少 update.sh。",
+ "serverUpdate.reason.failed": "更新在完成前停止了。原因見伺服器上的 .update/update.log。",
+ "serverUpdate.notStarted": "伺服器沒有開始更新。",
+ "serverUpdate.appDownloading": "此應用程式正在取得更新,重新啟動應用程式後即會安裝。",
+ "serverUpdate.appCurrent": "此應用程式暫時沒有更新的版本。",
+ "serverUpdate.appFailed": "此應用程式無法取得更新。請重試。",
+ "serverUpdate.appUnavailable": "此應用程式無法在這裡自行更新。請從網站下載新版本。",
+ "serverUpdate.appBehind": "此應用程式為 v{appVersion},伺服器為 v{serverVersion}",
+ "serverUpdate.updateApp": "更新應用程式",
+ "serverUpdate.confirmTitle": "要更新伺服器嗎?",
+ "serverUpdate.confirmBody": "伺服器會重新啟動以完成更新,所以上面正在執行的一切都會停止。這需要幾分鐘。如果新版本無法正常運作,伺服器會自動回到目前版本。",
+ "serverUpdate.confirmBusy.one": "目前有 {count} 個聊天中的機器人正在回覆。",
+ "serverUpdate.confirmBusy.other": "目前有 {count} 個聊天中的機器人正在回覆。",
+ "serverUpdate.failed": "無法請求伺服器更新。請重試。",
+ "activity.action.update.server": "請求更新伺服器",
+ "native.update.forServer": "{server} 請求更新此應用程式。版本 {version} 已就緒。現在重新啟動以安裝嗎?",
+ "native.update.forServerDetail": "應用程式重新啟動期間,這台電腦上執行的機器人會停止。",
+ "native.update.restartNow": "立即重新啟動",
+ "native.update.notNow": "稍後再說",
+ "serverUpdate.notBack": "伺服器尚未恢復",
+ "serverUpdate.notBackDetail": "更新已持續超過 15 分鐘。",
+ "serverUpdate.goBack": "要回到之前的版本:{command}",
+ "serverUpdate.reason.notRetried": "更新到 v{version} 之前在此伺服器上沒有成功,所以應用程式不會再試。要手動嘗試,請在伺服器上執行:{command}",
+ "serverUpdate.reason.stale": "伺服器上的 update.sh 比按鈕使用的副本更新。請在伺服器上執行:{command}",
+ "serverUpdate.reason.unreleased": "此伺服器執行的是 main 的建置版本,應用程式不會更新它。穩定版比該建置新時,它就會切換到穩定版;請在伺服器上執行:{command}",
+ "serverUpdate.reason.unsafe": "按鈕不會執行任何操作,因為 root 以外的人可以更改它執行的內容:{folder}。請修正後在伺服器上執行:{command}",
+ "serverUpdate.reason.noRoom": "伺服器需要先有可用磁碟空間來存放資料副本。要查看之前的更新保留的副本,請在伺服器上執行:{list}。要刪除一個:{remove}"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 8c3a2a6b30..6e2e01413a 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -7648,5 +7648,49 @@
"phoneUpdate.open": "打开“手机和设备”",
"remote.devices.pairAgain": "重新配对",
"remote.devices.retired": "这部手机上的 MausBot 应用是旧版本。请更新应用,然后在与这台电脑相同的 Wi-Fi 下打开一次。如果仍无法重新连接,请在这里重新配对。",
- "remote.devices.retiredNotice": "手机现在通过 MausBot Relay 连接到这台电脑,旧的安全链接已经关闭。使用旧版 MausBot 应用的手机,离开你的 Wi-Fi 后已无法连接。请在那部手机上更新 MausBot 应用,然后在与这台电脑相同的 Wi-Fi 下打开一次。如果仍无法重新连接,请在这里重新配对。"
+ "remote.devices.retiredNotice": "手机现在通过 MausBot Relay 连接到这台电脑,旧的安全链接已经关闭。使用旧版 MausBot 应用的手机,离开你的 Wi-Fi 后已无法连接。请在那部手机上更新 MausBot 应用,然后在与这台电脑相同的 Wi-Fi 下打开一次。如果仍无法重新连接,请在这里重新配对。",
+ "serverUpdate.available": "此服务器有可用的版本 {version}",
+ "serverUpdate.availableBoth": "此服务器可更新到 {version},此应用也不是最新版本",
+ "serverUpdate.updateServer": "更新服务器",
+ "serverUpdate.updating": "正在更新服务器…",
+ "serverUpdate.updatingDetail": "它会自动重启并重新连接,需要几分钟。",
+ "serverUpdate.updated": "服务器已更新到 v{version}。",
+ "serverUpdate.unchanged": "服务器已经是最新版本。",
+ "serverUpdate.rolledBack": "更新没有成功,服务器已回到 v{version}。",
+ "serverUpdate.rolledBackDetail": "你的数据保持原样。原因见服务器上的 .update/update.log。",
+ "serverUpdate.rollbackFailed": "更新失败,服务器也没能自行回退。",
+ "serverUpdate.runOnServer": "请在服务器上运行:{command}",
+ "serverUpdate.notChanged": "服务器没有变化。",
+ "serverUpdate.reason.busy": "服务器上已有另一个更新在进行。",
+ "serverUpdate.reason.refused": "更新无法开始,例如下载失败或磁盘已满。原因见服务器上的 .update/update.log。",
+ "serverUpdate.reason.older": "稳定版并不比它正在运行的版本新。",
+ "serverUpdate.reason.held": "此服务器的更新已暂停。",
+ "serverUpdate.reason.tooSoon": "更新请求过于频繁。请几分钟后再试。",
+ "serverUpdate.reason.noUpdater": "服务器上缺少 update.sh。",
+ "serverUpdate.reason.failed": "更新在完成前停止了。原因见服务器上的 .update/update.log。",
+ "serverUpdate.notStarted": "服务器没有开始更新。",
+ "serverUpdate.appDownloading": "此应用正在获取更新,重启应用后即会安装。",
+ "serverUpdate.appCurrent": "此应用暂时没有更新的版本。",
+ "serverUpdate.appFailed": "此应用无法获取更新。请重试。",
+ "serverUpdate.appUnavailable": "此应用无法在这里自行更新。请从网站下载新版本。",
+ "serverUpdate.appBehind": "此应用为 v{appVersion},服务器为 v{serverVersion}",
+ "serverUpdate.updateApp": "更新应用",
+ "serverUpdate.confirmTitle": "要更新服务器吗?",
+ "serverUpdate.confirmBody": "服务器会重启以完成更新,所以上面正在运行的一切都会停止。这需要几分钟。如果新版本无法正常工作,服务器会自动回到当前版本。",
+ "serverUpdate.confirmBusy.one": "目前有 {count} 个聊天中的机器人正在回复。",
+ "serverUpdate.confirmBusy.other": "目前有 {count} 个聊天中的机器人正在回复。",
+ "serverUpdate.failed": "无法请求服务器更新。请重试。",
+ "activity.action.update.server": "请求更新服务器",
+ "native.update.forServer": "{server} 请求更新此应用。版本 {version} 已就绪。现在重启以安装吗?",
+ "native.update.forServerDetail": "应用重启期间,这台电脑上运行的机器人会停止。",
+ "native.update.restartNow": "立即重启",
+ "native.update.notNow": "以后再说",
+ "serverUpdate.notBack": "服务器尚未恢复",
+ "serverUpdate.notBackDetail": "更新已持续超过 15 分钟。",
+ "serverUpdate.goBack": "要回到之前的版本:{command}",
+ "serverUpdate.reason.notRetried": "更新到 v{version} 之前在此服务器上没有成功,所以应用不会再试。要手动尝试,请在服务器上运行:{command}",
+ "serverUpdate.reason.stale": "服务器上的 update.sh 比按钮使用的副本更新。请在服务器上运行:{command}",
+ "serverUpdate.reason.unreleased": "此服务器运行的是 main 的构建版本,应用不会更新它。稳定版比该构建新时,它就会切换到稳定版;请在服务器上运行:{command}",
+ "serverUpdate.reason.unsafe": "按钮不会执行任何操作,因为 root 以外的人可以更改它执行的内容:{folder}。请修正后在服务器上运行:{command}",
+ "serverUpdate.reason.noRoom": "服务器需要先有空闲磁盘空间来存放数据副本。要查看之前的更新保留的副本,请在服务器上运行:{list}。要删除一个:{remove}"
}
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index ee4832ee86..d59c0174d9 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -472,6 +472,11 @@ const __APP_VERSION__: string;
seen?(): Promise<void>;
onState(cb: (s: UpdaterState) => void): () => void;
};
+ /** On a server's page from the Server menu: asks for this app's own update, from the person's click. The page
+ * learns only what was done; the app asks in its own dialog before it restarts. Absent in older desktop builds. */
+ appUpdate?: {
+ request(): Promise<AppUpdateAnswer>;
+ };
};
}
}
@@ -489,6 +494,9 @@ export interface LinuxLocalControlStatus {
warnings?: Array<{ label: string; status: string; message: string; detail?: string }>;
}
+/** What asking for this app's update from a server's page did (electron/updater.mjs `updateForServerPage`). */
+export type AppUpdateAnswer = "installing" | "later" | "downloading" | "current" | "failed" | "unavailable";
+
export interface UpdaterState {
status:
| "idle"