Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Connector: a customer-run mode for a server its owner installed
milind-soni81d3683a51b1
diff --git a/apps/docs/content/docs/self-hosting/connected-servers.mdx b/apps/docs/content/docs/self-hosting/connected-servers.mdxindex 88758da060..a43c1962fd 100644--- a/apps/docs/content/docs/self-hosting/connected-servers.mdx+++ b/apps/docs/content/docs/self-hosting/connected-servers.mdx@@ -5,10 +5,12 @@ icon: ShieldCheck---<Callout title="Connected mode is not on sale yet">- A standalone server, the default, has no connector and nothing on this page applies to it. This page describes the connector's code as it is in the [public repository](https://github.com/milind-soni/OpenMausBot/tree/main/connector), so you can check every line against it. Items marked **planned** do not exist yet.+ A standalone server, the default, has no connector and nothing on this page applies to it. This page describes the connector's code as it is in the [public repository](https://github.com/milind-soni/OpenMausBot/tree/main/connector), so you can check every line against it. No released connector or server contains this mode yet. Items marked **planned** do not exist yet.</Callout>-A connected server is a server of yours that MausBot's control plane (the Admin) manages for you: it starts the MausBot server (the home) there, updates it and watches its health. The part that does this on your server is the **connector**.+A connected server is a MausBot server you installed and run yourself, which MausBot's control plane (the Admin) may start, stop, update and back up for you, and whose health it watches. The part that does this on your server is the **connector**. On a server you run it works in **customer-run mode**, and that mode is what this page describes.++The whole list of what the Admin may run, ask and learn in this mode is one file: [`connector/src/customer-run.ts`](https://github.com/milind-soni/OpenMausBot/blob/main/connector/src/customer-run.ts). The connector enforces it on your server. It does not depend on the Admin behaving.## The connector@@ -16,78 +18,114 @@ A connected server is a server of yours that MausBot's control plane (the Admin)- It only calls out: one HTTPS request to enrol, then one WebSocket to the Admin. It opens no port.- It makes its own Ed25519 key at enrolment. The private key stays on your server. It pins the Admin's signing keys.- It runs with every Linux capability dropped, a read-only file system and no new privileges.-- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: the home's container, its data volume and copies of it, short helper containers, and the connector's own replacement. It runs images from `ghcr.io/milind-soni/` only, pinned by digest.+- It is given Docker's socket, which is root on the server in the hands of any program. What the connector does with it is fixed in its code: it starts and stops the two containers of your install, runs one fixed read inside your server's container (below), runs short helper containers that copy your data folder to and from a Docker volume on the same server, and replaces itself. It never makes a second MausBot and never changes your `.env` or your Compose file.+- The mode is chosen on your server when it enrols, kept in the connector's own state, and told to the Admin. The Admin cannot change it.++## It connects the server you installed++The connector attaches to the MausBot the [server installer](/docs/self-hosting/deploy-vps) made in `/opt/openmausbot`: the same containers, the same `data` folder, the same settings. Nothing is reinstalled and no data moves. Two limits:-## What MausBot can do: eleven jobs+- It attaches only to that layout: Docker Compose, the published image, the data in a folder beside the Compose file. A server built from source, or run without Docker, cannot be connected yet.+- A connector started the other way (the mode MausBot uses on servers it operates itself) refuses to enrol on a machine where your MausBot already runs, so there are never two.-Every job is signed by the Admin for your server alone and is refused 15 minutes after it was signed. A job of any other kind, or with any other argument, is refused. There is no shell, no command the Admin chooses, and no reading of a file by its path.+## What MausBot can do: nine jobs++Every job is signed by the Admin for your server alone and is refused 15 minutes after it was signed. A job of any other kind, or with any other argument, is refused on your server and the refusal is written to your log. There is no shell, no command the Admin chooses, and no reading of a file by its path.| Job | What it does on your server ||---|---|-| `start` | Starts the home on a named image with the settings the Admin sends (names beginning `OMB_` only) |-| `stop`, `restart` | Stops or restarts the home |-| `update` | Pulls a new image, copies the data, swaps the container and rolls both back if the new version is not healthy |-| `status` | Reads the home's state, the connector's version and the list of copies |-| `backup` | Copies the data to a volume on your server; three are kept |-| `restore` | Puts one of those copies back |-| `export-disk` | **Uploads an archive of the whole data directory to MausBot.** Used to move a Cloud off your server |-| `import-disk` | Replaces the data directory with an archive from an HTTPS address. Used to move a Cloud onto your server |+| `start`, `stop`, `restart` | Starts or stops your server's containers, with your settings. A `start` that names an image or a setting is refused |+| `update` | Hands one image, MausBot's server image pinned by digest, to your server's own updater: `update.sh` in `/opt/openmausbot`, the command you run by hand. It copies the data aside, starts the new version, checks it, and puts the old version and the copy back when the check fails |+| `status` | Reads the server's state, the two versions and the list of backups |+| `backup` | Copies the data folder to a Docker volume on your server; three are kept |+| `restore` | Puts one of those copies back, after a safety copy of what is there || `host-health` | Reads the server's size, load and checks (below) |-| `self-update` | Replaces the connector with a newer one from the same registry |+| `self-update` | Replaces the connector with a newer one from the same registry, pinned by digest |++Three things to know:++- **Not on the list, so refused:** `export-disk` (uploads an archive of the data to MausBot) and `import-disk` (replaces the data with an archive from elsewhere). They exist in the connector for servers MausBot operates itself.+- **`update` needs your updater.** It works only when `update.sh` is in `/opt/openmausbot` and the connector's installer has set up the small systemd unit that runs it. Without either, the job is refused and nothing changes. The server installer does not put `update.sh` there yet: **planned**.+- **`self-update` can change these rules**, because a new connector is new code. The new image comes only from MausBot's registry and its source is public, but images are not signed yet. To keep the connector you read, leave `self-update` out of your policy's job list (below).Until your team's Owner accepts the server in MausBot, it answers only `status` and `host-health`.-## What else MausBot can do: requests to the home+## What else MausBot can ask: four requests++On the same connection the Admin can send HTTP requests. In customer-run mode none of them reaches your server: the connector answers these four itself, and refuses every other path, every other method, and any request that carries a body.++| Request | Answer |+|---|---|+| `GET /v1/health` | The server's state, and whether it answers |+| `GET /v1/version` | The server's version and the connector's |+| `GET /v1/seats` | How many people can sign in: a number |+| `GET /v1/update` | Whether an update is running, and the images before and after the last one |++There is no pairing: the Admin cannot open a sign-in on your server, as a member or as anyone. A pairing request, and a request for the team summary, are refused and logged like any other.-On the same connection the Admin can send HTTP requests to the home. The connector passes each one to the home on the server's loopback and nowhere else, one request per stream, with no protocol upgrade. The home treats them as requests from outside: without a member's session it acts only on those signed with its own secret. The signed ones read its health and its team summary (below), and one of them, a **pairing**, opens a sign-in for a named member of your team: it is how the MausBot dashboard signs a person in to your server. A session opened this way can do what that member can do.+## Signing in does not go through MausBot-Jobs are not limited to reading: `export-disk` and a pairing both reach what people wrote. They are here so you can see them, log them and refuse them.+People sign in to your server with your server's own sign-in: a pairing code you make on the server, or a code emailed to an address on your sign-in list. Neither passes through the connector or the Admin.-## Your log and your rules+- **Pairing codes** work with MausBot unreachable.+- **Emailed codes** are sent through MausBot's account service unless you set your own mail server (`OMB_SIGNIN_SMTP_URL`). With your own mail server they also work with MausBot unreachable.+- Sessions already open keep working either way.-- **The audit log.** Every job, each of its steps, its result and every request to the home is one line in `/var/log/mausbot/audit.jsonl` on your server, owned by root. A pairing's line names the member and the device. Each line carries the hash of the line before it, so a removed or changed line shows. A job that would change something is refused when the log cannot be written.+## Your log, your rules, your switch++- **The audit log.** Every job, each of its steps, its result, every request and every refusal is one line in `/var/log/mausbot/audit.jsonl` on your server, owned by root. Each line carries the hash of the line before it, so a removed or changed line shows. A job that would change something is refused when the log cannot be written. A failed job's full reason is here; only its code leaves the server.```shdocker exec mausbot-connector mausbot-connector audit --tail 50docker exec mausbot-connector mausbot-connector audit --verify```-- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, lists the job kinds MausBot may run and can hold updates. The connector reads it before every job and never writes it.+- **Pause.** One command makes the connector refuse every job and every request from MausBot, the connector's own update included, and log each one. The server keeps running, people keep signing in, and the heartbeat below still goes out, saying that you paused. A switch in Settings is **planned**.++ ```sh+ docker exec mausbot-connector mausbot-connector pause+ docker exec mausbot-connector mausbot-connector resume+ ```++- **Your policy.** `/etc/mausbot/policy.json`, which only root on your server can write, narrows the nine jobs further and can hold updates. The connector reads it before every job and never writes it.```json{ "jobs": ["status", "host-health", "update", "backup"], "updates": "hold" }```- `"jobs": []` refuses every job. Two things the policy does not cover: the connector's own `self-update` is always accepted, and requests to the home are not jobs.--- **Cutting MausBot off.** `docker stop mausbot-connector` ends the connection. The home keeps running and the sessions it already gave out keep working. While the connector is stopped, MausBot's dashboard cannot open a new sign-in, and nothing restarts the home if it stops. A pause switch in MausBot itself is **planned**.+- **Cutting MausBot off.** `docker stop mausbot-connector` ends the connection and the heartbeat. Your server, its sign-in and its bots are not affected.## What the connector sends| When | What ||---|---|-| Once, at enrolment | The one-time code, the connector's public key, and the server's facts: operating system, kernel, architecture, CPU count, memory, free disk, Docker version, whether AppArmor and user namespaces are on |-| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and the result of each server check; the home's state, image and version, and its sandbox self-check as a count and check names; the connector's version and image |-| After each job | The result: the home's state and image, the name and time of a copy, or a byte count and checksum. A failure is a fixed code and a sentence that never carries a secret |-| During `export-disk` only | The archive of the data directory |+| Once, at enrolment | The one-time code, the connector's public key, the mode, and the server's facts: operating system, kernel, architecture, CPU count, memory, free disk, Docker version, whether AppArmor and user namespaces are on |+| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and each server check as an id and a pass or fail; the server's state, image and version; the connector's version and image; the mode; whether you paused; the seat count |+| After each job | The result: the server's state, image and version, or the id and time of a backup. A failure is a fixed code and a fixed sentence |++The seat count is the number of people who can sign in: the addresses on your sign-in list, plus any other address that has signed in. It is a number. No address, name or role is sent.-The connector reads no chat, file, key or name to build any of this, apart from the archive.+To build this the connector reads three things from your server, on the server's own loopback: that it answers, its version, and its seat count. It keeps one field from each answer and drops the rest. It reads no chat, file, key, name or address, and it sends no line of any log.-## What the home sends+## What your server itself still sends-A connected home runs the image our own Clouds run, so it also talks to MausBot itself. Read from the server's code:+Your server is a standalone MausBot, and a standalone MausBot talks to MausBot in a few cases of its own. Connecting it does not add to them and does not remove them:-- **At each start:** a signed note that it started, with the time.-- **When the Admin asks for health:** versions, start time, counts of turns started and failed, each routine's random id and last status, which engines are installed and signed in, which connected apps are on, sandbox and memory figures, counts such as emails sorted and replies drafted, and incidents as fixed codes. No message text, bot name, title, address or key.-- **On a team's server, when the Admin asks for the team summary** (MausBot's Team admin pages show it)**:** the names of connected apps and MCP servers, the account email each engine is signed in with, and the email addresses of the members who connected each app.-- **Only when a person does it:** a page a bot publishes is uploaded; a report someone sends to the developers carries their message, the bot's name and recent log lines, with secrets removed.-- **Only if your plan includes them:** included AI credit, voice and research send that traffic through MausBot's hosts. With your own keys it goes to the provider directly.-- **Connected apps:** a home registers with MausBot's connected-apps broker at start, and app traffic passes through it while apps are used.+- **Emailed sign-in codes**, unless you use your own mail server: the address being signed in goes to MausBot's account service.+- **A report to the developers**, only when a person writes a message that tags `@devs`: it carries that message, the bot's name and recent log lines, with secrets removed. While such a report is open, the server asks for its status once an hour.+- **An update check**, only when a person opens it in the app: it asks GitHub for the latest release.- **In the browser:** [usage analytics](/docs/security/analytics), which each person can turn off.+It does not send what a server MausBot operates sends: no health report to the Admin, no team summary with members' addresses, no registration with MausBot's connected-apps broker, no traffic through MausBot's AI, voice or research hosts.++Traffic to the AI providers, engines and apps you set up is between your server and them, and is not on this page.+## Planned-- A seat count in what the server reports. No seat or member count is sent today.-- A connected mode in which nothing a person wrote can leave: today `export-disk`, pairing, the Team admin summary and reports to the developers are the exceptions above.-- Connecting a server that was installed standalone, keeping its data. Today the connector starts a separate home with its own data.+- The server installer putting `update.sh` in place, so `update` works without a manual step.+- Backups to storage of yours outside the server (a bucket). Today a backup is a Docker volume on the same server.+- A pause switch in Settings.+- Signed connector images.+- Seats and plan features delivered to the server as a signed document. Today the seat count is only reported.+- Connecting a server built from source or run without Docker.- A published list of the network addresses a connected server needs.diff --git a/connector/Dockerfile b/connector/Dockerfileindex 66ea6564eb..00bd7fa026 100644--- a/connector/Dockerfile+++ b/connector/Dockerfile@@ -10,6 +10,7 @@ RUN apt-get update \WORKDIR /appCOPY package.json ./package.jsonCOPY profiles ./profiles+COPY host ./hostCOPY install.sh ./install.shCOPY src ./srcRUN printf '#!/bin/sh\nexec node --disable-warning=ExperimentalWarning /app/src/main.ts "$@"\n' > /usr/local/bin/mausbot-connector \diff --git a/connector/host/mausbot-update-runner.sh b/connector/host/mausbot-update-runner.shnew file mode 100755index 0000000000..db02ebfefd--- /dev/null+++ b/connector/host/mausbot-update-runner.sh@@ -0,0 +1,34 @@+#!/bin/sh+# Runs on a customer-run server, as root, outside every container: systemd starts it when the MausBot connector leaves+# an update request (mausbot-update.path watches for the file). It hands the request to the server's own updater,+# update.sh in the install's folder, the same command its owner runs by hand, and writes down how that ended.+#+# The request is two lines, `id=<job id>` and `image=<image>`. The image must be MausBot's server image pinned by+# digest; anything else is refused here, whatever the connector wrote. Nothing else in the request is read.+set -u++DIR="${MAUSBOT_UPDATE_DIR:-/var/lib/mausbot/update}"+INSTALL_DIR="${MAUSBOT_INSTALL_DIR:-/opt/openmausbot}"+REQUEST="$DIR/request"++[ -f "$REQUEST" ] || exit 0+id=$(sed -n 's/^id=//p' "$REQUEST" | head -n 1)+image=$(sed -n 's/^image=//p' "$REQUEST" | head -n 1)+rm -f "$REQUEST"+printf '%s' "$id" | grep -Eqx '[A-Za-z0-9_-]{1,64}' || exit 0++answer() { # the updater's exit code, for the connector to read+ printf 'id=%s\ncode=%s\n' "$id" "$1" >"$DIR/result.tmp" && mv "$DIR/result.tmp" "$DIR/result"+}++if ! printf '%s' "$image" | grep -Eqx 'ghcr\.io/milind-soni/openmausbot@sha256:[0-9a-f]{64}'; then+ answer 4+ exit 0+fi+if [ ! -f "$INSTALL_DIR/update.sh" ]; then+ answer 127+ exit 0+fi+code=0+bash "$INSTALL_DIR/update.sh" --dir "$INSTALL_DIR" --image "$image" >>"$DIR/runner.log" 2>&1 || code=$?+answer "$code"diff --git a/connector/install.sh b/connector/install.shindex 2070ab6cc0..3b25df2c26 100644--- a/connector/install.sh+++ b/connector/install.sh@@ -3,6 +3,11 @@# connector and connects it to MausBot with the one-time code MausBot shows. Running it again repairs the install.## curl -fsSL https://cloud.openmausbot.com/install.sh | sudo sh -s -- <code>+#+# On a server where you already installed MausBot yourself (deploy/install.sh, in /opt/openmausbot) it connects that+# MausBot instead of starting another: the connector then runs in customer-run mode, where MausBot may only start,+# stop, update and back up your server and learns only its versions, health and seat count (connector/src/customer-run.ts).+## curl -fsSL https://cloud.openmausbot.com/install.sh | sudo sh -s -- uninstall (keeps your data)# curl -fsSL https://cloud.openmausbot.com/install.sh | sudo sh -s -- uninstall --delete-data (deletes it too)#@@ -24,6 +29,13 @@ DATA_VOLUME=mausbot-dataSTATE_VOLUME=mausbot-connectorSNAPSHOT_VOLUME=mausbot-snapshotROLE_LABEL=com.mausbot.role+INSTALL_DIR="${MAUSBOT_INSTALL_DIR:-/opt/openmausbot}"+UPDATE_DIR="${MAUSBOT_UPDATE_DIR:-/var/lib/mausbot/update}"+SBIN_DIR="${MAUSBOT_SBIN_DIR:-/usr/local/sbin}"+SYSTEMD_DIR="${MAUSBOT_SYSTEMD_DIR:-/etc/systemd/system}"+UPDATE_RUNNER=mausbot-update-runner+UPDATE_UNIT=mausbot-update+MODE=operatedMIN_DOCKER=24MIN_CPUS=2MIN_MEMORY_MB=3500@@ -232,9 +244,66 @@ install_profiles() {fi}+# A MausBot its owner installed is here: the connector attaches to it and never starts a second one.+own_server_here() {+ [ -f "$INSTALL_DIR/compose.yaml" ]+}++# The server's own updater: update.sh in the install's folder, started by systemd when the connector asks. The+# connector's container can only leave the request; the update itself runs here, on the server, as its owner's does.+install_updater() {+ install -d -m 0700 "$UPDATE_DIR"+ rm -f "$UPDATE_DIR/runner"+ if ! command -v systemctl >/dev/null 2>&1 || [ ! -d "$SYSTEMD_DIR" ]; then+ note "note: this server has no systemd, so MausBot cannot update it for you. Update it yourself with: $INSTALL_DIR/update.sh"+ return+ fi+ install -d -m 0755 "$SBIN_DIR"+ docker run --rm --network none --entrypoint cat "$CONNECTOR_IMAGE" "/app/host/$UPDATE_RUNNER.sh" >"$SBIN_DIR/$UPDATE_RUNNER.tmp" ||+ fail "The updater could not be read from the connector's image. Run this command again."+ chmod 0755 "$SBIN_DIR/$UPDATE_RUNNER.tmp"+ mv "$SBIN_DIR/$UPDATE_RUNNER.tmp" "$SBIN_DIR/$UPDATE_RUNNER"+ cat >"$SYSTEMD_DIR/$UPDATE_UNIT.path" <<UNIT+[Unit]+Description=Runs MausBot's updater when the MausBot connector asks for an update++[Path]+PathExists=$UPDATE_DIR/request++[Install]+WantedBy=multi-user.target+UNIT+ cat >"$SYSTEMD_DIR/$UPDATE_UNIT.service" <<UNIT+[Unit]+Description=MausBot's updater ($INSTALL_DIR/update.sh), for an update the MausBot connector asked for++[Service]+Type=oneshot+Environment=MAUSBOT_UPDATE_DIR=$UPDATE_DIR MAUSBOT_INSTALL_DIR=$INSTALL_DIR+ExecStart=$SBIN_DIR/$UPDATE_RUNNER+UNIT+ systemctl daemon-reload >/dev/null 2>&1 || true+ if systemctl enable --now "$UPDATE_UNIT.path" >/dev/null 2>&1; then+ echo 1 >"$UPDATE_DIR/runner"+ else+ note "note: the updater could not be switched on, so MausBot cannot update this server for you. Update it yourself with: $INSTALL_DIR/update.sh"+ fi+ if [ ! -f "$INSTALL_DIR/update.sh" ]; then+ note "note: there is no update.sh in $INSTALL_DIR yet. Until it is there, MausBot's updates are refused and nothing is changed."+ fi+}++remove_updater() {+ if command -v systemctl >/dev/null 2>&1; then systemctl disable --now "$UPDATE_UNIT.path" >/dev/null 2>&1 || true; fi+ rm -f "$SYSTEMD_DIR/$UPDATE_UNIT.path" "$SYSTEMD_DIR/$UPDATE_UNIT.service" "$SBIN_DIR/$UPDATE_RUNNER"+ if command -v systemctl >/dev/null 2>&1; then systemctl daemon-reload >/dev/null 2>&1 || true; fi+ rm -rf "$UPDATE_DIR"+}+start_connector() {say "Starting the MausBot connector..."docker volume create "$STATE_VOLUME" >/dev/null+ install -d -m 0755 "$ETC_DIR"# The audit log: every job MausBot runs here, root's, for you to read (mausbot-connector audit).install -d -m 0750 "$AUDIT_DIR"docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || true@@ -245,6 +314,9 @@ start_connector() {'' | *[!0-9]*) ;;*) set -- "$@" -e "MAUSBOT_UPDATE_WAIT_S=$MAUSBOT_UPDATE_WAIT_S" ;;esac+ if [ "$MODE" = customer-run ]; then+ set -- "$@" -e MAUSBOT_MODE=customer-run -v "$UPDATE_DIR:/var/lib/mausbot/update"+ fidocker run -d --name "$CONNECTOR" --restart unless-stopped --network host \--security-opt no-new-privileges=true --cap-drop ALL --read-only --tmpfs /tmp \-v /var/run/docker.sock:/var/run/docker.sock -v "$STATE_VOLUME:/state" -v "$ETC_DIR:/etc/mausbot:ro" -v "$AUDIT_DIR:/var/log/mausbot" \@@ -292,6 +364,7 @@ install_connector() {for arg in "$@"; docase "$arg" in--install-docker) MAUSBOT_INSTALL_DOCKER=1 ;;+ --customer-run) MODE=customer-run ;;-*) fail "Unknown option $arg. Usage: $(command_line '<code>')" ;;*) code=$arg ;;esac@@ -301,10 +374,31 @@ install_connector() {esacneed_root "${code:-<code>}"need_settings+ if own_server_here; then+ MODE=customer-run+ elif [ "$MODE" = customer-run ]; then+ fail "MausBot isn't installed in $INSTALL_DIR yet. Install it first with the server's install command, then run this again to connect it."+ fisay "Checking this server..."check_oscheck_archcheck_docker+ if [ "$MODE" = customer-run ]; then+ note "MausBot is already installed in $INSTALL_DIR: connecting that server, as it is"+ check_resources+ check_network+ check_clock+ pull_connector+ install_updater+ start_connector+ connect "$code"+ say ""+ say "Connected. Your server shows up in MausBot in a minute, for your team's Owner to accept."+ say "You run this server: MausBot can start, stop, update and back it up, and sees its versions, health and seat count."+ say " What it was asked to do: sudo docker exec $CONNECTOR mausbot-connector audit"+ say " Pause remote management: sudo docker exec $CONNECTOR mausbot-connector pause"+ return+ ficheck_apparmorcheck_usernscheck_resources@@ -330,6 +424,26 @@ uninstall() {doneneed_root uninstallcommand -v docker >/dev/null 2>&1 || fail "Docker isn't installed here, so MausBot isn't either."+ if own_server_here; then+ say "Disconnecting this server from MausBot..."+ docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || true+ for container in $(docker ps -aq --filter "label=$ROLE_LABEL=helper" 2>/dev/null); do+ docker rm -f "$container" >/dev/null 2>&1 || true+ done+ remove_updater+ docker volume rm "$STATE_VOLUME" >/dev/null 2>&1 || true+ if [ "$delete" = yes ]; then+ for volume in "$SNAPSHOT_VOLUME" $(docker volume ls -q --filter "label=$ROLE_LABEL=backup" 2>/dev/null); do+ docker volume rm "$volume" >/dev/null 2>&1 || true+ done+ rm -rf "$AUDIT_DIR"+ say "This server is disconnected. The backups MausBot made and the audit log are deleted."+ else+ say "This server is disconnected. The backups MausBot made are kept as Docker volumes, and the audit log in $AUDIT_DIR."+ fi+ say "Your MausBot in $INSTALL_DIR and its data were not touched, and it keeps running."+ return+ fisay "Stopping MausBot on this server..."docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || truedocker stop -t 30 "$HOME_CONTAINER" >/dev/null 2>&1 || truediff --git a/connector/src/adopted-home.ts b/connector/src/adopted-home.tsnew file mode 100644index 0000000000..e02a0a0081--- /dev/null+++ b/connector/src/adopted-home.ts@@ -0,0 +1,509 @@+// The home on a customer-run server: the MausBot server its owner installed with Docker Compose (deploy/install.sh:+// project `openmausbot`, service `omb`, Caddy in front, the data in a folder beside the Compose file). The connector+// attaches to it and never makes a second one: it starts and stops those containers, copies that folder, and hands an+// update to the server's own updater. It never writes the owner's settings and never picks the home's image itself.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, parseHomeReads, type HomeFacts } from "./customer-run.ts";+import type { ContainerInfo, Docker, Mount } from "./docker.ts";+import { JobFailure } from "./failure.ts";+import { backupId, helperSpec } from "./home.ts";+import { errorText, type Log } from "./log.ts";+import type { CopyInfo, HomeHealth, HomeReport, HomeState, JobError, JobReply, JobResults, ServerMode } from "./protocol.ts";+import { BACKUPS_KEPT, HOME_STOP_TIMEOUT_S, LABELS, NAMES } from "./settings.ts";+import type { HomeRecord, Operation, StateStore } from "./state.ts";++export const COMPOSE_PROJECT = "openmausbot";+const SERVICE = "omb";+const FRONT = "caddy";+const PROJECT_LABEL = "com.docker.compose.project";+const SERVICE_LABEL = "com.docker.compose.service";+const HOME_REPOSITORY = "ghcr.io/milind-soni/openmausbot";+const COPY_CAPS = ["CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER", "FSETID"];+const READ_CAPS = ["DAC_READ_SEARCH"];+const DELETE_CAPS = ["DAC_OVERRIDE", "DAC_READ_SEARCH"];++/** The request the connector leaves for the server's updater, and the answer it reads: `key=value` lines. */+export const UPDATE_FILES = { runner: "runner", request: "request", result: "result" } as const;+/** deploy/update.sh's exit codes, and 127 when the server has no update.sh. */+const UPDATE_EXIT = { done: 0, rolledBack: 1, rollbackFailed: 2, busy: 3, notStarted: 4, missing: 127 } as const;++const lastLine = (text: string) => text.trim().split("\n").pop()?.slice(0, 300) ?? "";+const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10;++export interface Install {+ container: ContainerInfo;+ /** The folder on the server that the home mounts at /data. */+ dataDir: string;+}++/** The Compose install on this server, or the plain sentence that says why the connector cannot attach to one. */+export async function findInstall(docker: Docker): Promise<{ ok: true; install: Install } | { ok: false; why: string }> {+ const [found] = await docker.listContainers({ [PROJECT_LABEL]: COMPOSE_PROJECT, [SERVICE_LABEL]: SERVICE });+ const container = found ? await docker.containerInspect(found.Id) : null;+ if (!container) return { ok: false, why: "MausBot is not installed on this server yet. Install it first with the server's install command, then connect it." };+ const image = container.Config.Image;+ if (!image.startsWith(`${HOME_REPOSITORY}:`) && !image.startsWith(`${HOME_REPOSITORY}@`)) {+ return { ok: false, why: "The MausBot on this server was built here, not downloaded from MausBot's registry, so MausBot cannot update it. Move it to the published image first: ./update.sh --replace-local-build" };+ }+ const data = (container.Mounts ?? []).find((mount) => mount.Destination === "/data");+ if (!data || data.Type !== "bind") return { ok: false, why: "The MausBot on this server does not keep its data in a folder beside its Compose file, so it is not one the server installer made. Install it with the server's install command, then connect it." };+ return { ok: true, install: { container, dataDir: data.Source } };+}++/** True when a MausBot server its owner installed runs here: an `operated` connector must not start a second home beside it. */+export async function standaloneServerPresent(docker: Docker): Promise<boolean> {+ return (await docker.listContainers({ [PROJECT_LABEL]: COMPOSE_PROJECT, [SERVICE_LABEL]: SERVICE })).length > 0;+}++/**+ * Why this server cannot be enrolled in `mode`, in a sentence for the person at the terminal, or null. An `operated`+ * connector makes its own home, so it is refused where a MausBot its owner installed already runs: that would be two.+ */+export async function enrolmentRefusal(mode: ServerMode, docker: Docker): Promise<string | null> {+ if (mode === "customer-run") {+ const found = await findInstall(docker);+ return found.ok ? null : found.why;+ }+ return (await standaloneServerPresent(docker))+ ? "MausBot already runs on this server, installed by its owner. Connecting it this way would start a second MausBot beside it. Run the install command again and it connects the one that is here, keeping its data."+ : null;+}++export interface AdoptedHomeOptions {+ docker: Docker;+ state: StateStore;+ log: Log;+ /** Free bytes where Docker keeps its volumes, so where a backup goes. */+ diskFree: () => number;+ /** The folder shared with the server's updater (mausbot-update-runner.sh), as the connector sees it. */+ updateDir: string;+ onStep?: (step: { id: string; type: Operation["type"]; step: string; detail?: Record<string, unknown> }) => void;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+ startWindowMs?: number;+ updateDeadlineMs?: number;+ pollMs?: number;+}++export class AdoptedHome {+ private readonly docker: Docker;+ private readonly state: StateStore;+ private readonly log: Log;+ private readonly options: AdoptedHomeOptions;+ private readonly now: () => number;+ private readonly sleep: (ms: number) => Promise<void>;+ private readonly startWindowMs: number;+ private readonly updateDeadlineMs: number;+ private readonly pollMs: number;+ private lastHealth: HomeHealth | null = null;+ private lastSeats: number | null = null;+ private chain: Promise<unknown> = Promise.resolve();+ private active = 0;++ constructor(options: AdoptedHomeOptions) {+ this.options = options;+ this.docker = options.docker;+ this.state = options.state;+ this.log = options.log;+ this.now = options.now ?? Date.now;+ this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ this.startWindowMs = options.startWindowMs ?? 10 * 60_000;+ this.updateDeadlineMs = options.updateDeadlineMs ?? 90 * 60_000;+ this.pollMs = options.pollMs ?? 2_000;+ }++ get busy(): boolean {+ return this.active > 0;+ }++ /** How many people can sign in, as the home last said; null when it does not say. */+ get seats(): number | null {+ return this.lastSeats;+ }++ get previousImage(): string | null {+ return this.state.home().previousImage;+ }++ exclusive<T>(work: () => Promise<T>): Promise<T> {+ const run = this.chain.then(async () => {+ this.active += 1;+ try { return await work(); } finally { this.active -= 1; }+ });+ this.chain = run.catch(() => {});+ return run;+ }++ /** Docker restarts the home itself (Compose's `restart: unless-stopped`), so there is nothing to keep running here. */+ async supervise(): Promise<void> {}++ async report(): Promise<HomeReport> {+ const record = this.state.home();+ const container = await this.container(SERVICE);+ let state: HomeState;+ if (record.operation?.type === "update") state = "updating";+ else if (record.operation?.type === "restore") state = "restoring";+ else if (!container) state = "absent";+ else if (container.State.Running) state = this.lastHealth?.ok ? "running" : "starting";+ else state = record.desired === "running" ? "crashed" : "stopped";+ return { state, image: container ? await this.imageOf(container) : record.image, health: this.lastHealth };+ }++ async refreshHealth(): Promise<HomeHealth | null> {+ const container = await this.container(SERVICE);+ if (!container?.State.Running) {+ this.lastHealth = null;+ return null;+ }+ const facts = await this.read(container);+ this.lastSeats = facts.seats;+ this.lastHealth = { ok: facts.answers, version: facts.version, image: await this.imageOf(container), box: null, at: this.now() };+ return this.lastHealth;+ }++ async copies(): Promise<{ backups: CopyInfo[]; snapshot: CopyInfo | null }> {+ const backups = (await this.docker.listVolumes({ [LABELS.role]: "backup" }))+ .filter((volume) => volume.Name.startsWith(NAMES.backupPrefix))+ .map((volume) => copyInfo(volume.Name.slice(NAMES.backupPrefix.length), "backup", volume.Labels))+ .sort((a, b) => b.createdAt - a.createdAt);+ const snapshot = await this.docker.volumeInspect(NAMES.snapshotVolume);+ return { backups, snapshot: snapshot ? copyInfo("snapshot", "snapshot", snapshot.Labels) : null };+ }++ start(): Promise<JobResults["start"]> {+ return this.exclusive(async () => {+ await this.install();+ this.state.saveHome({ ...this.state.home(), desired: "running" });+ await this.bringUp();+ return { home: await this.report() };+ });+ }++ stop(): Promise<JobResults["stop"]> {+ return this.exclusive(async () => {+ await this.install();+ this.state.saveHome({ ...this.state.home(), desired: "stopped" });+ await this.takeDown();+ return { home: await this.report() };+ });+ }++ restart(): Promise<JobResults["restart"]> {+ return this.exclusive(async () => {+ await this.install();+ this.state.saveHome({ ...this.state.home(), desired: "running" });+ await this.takeDown();+ await this.bringUp();+ return { home: await this.report() };+ });+ }++ /**+ * Leaves the image for the server's own updater and waits for its verdict. The updater is deploy/update.sh, the+ * command the owner runs by hand: it copies the data aside, pins the image in the owner's .env, starts it, checks+ * it, and puts the old image and the copy back when the check fails.+ */+ update(jobId: string, image: string): Promise<JobResults["update"]> {+ return this.exclusive(async () => {+ if (!CUSTOMER_HOME_IMAGE.test(image)) throw new JobFailure("image_refused", `${image} is not MausBot's server image pinned by digest. Nothing was changed.`);+ const { container } = await this.install();+ const previous = await this.imageOf(container);+ const dir = this.options.updateDir;+ if (!existsSync(join(dir, UPDATE_FILES.runner))) {+ throw new JobFailure("update_unavailable", "This server has no updater for MausBot to hand an update to. Run the connector's install command again to add it; until then, update with ./update.sh on the server.");+ }+ const wasRunning = container.State.Running;+ this.begin({ jobId, type: "update", phase: "request", previousImage: previous, nextImage: image, target: null, dataAtRisk: false, wasRunning });+ rmSync(join(dir, UPDATE_FILES.result), { force: true });+ const request = join(dir, UPDATE_FILES.request);+ writeFileSync(`${request}.tmp`, `id=${jobId}\nimage=${image}\n`, { mode: 0o600 });+ renameSync(`${request}.tmp`, request);+ this.phase({ phase: "wait" });+ const code = await this.updaterVerdict(jobId, this.now() + this.updateDeadlineMs);+ this.lastHealth = null;+ if (code !== UPDATE_EXIT.done) {+ this.finish({});+ await this.refreshHealth().catch(() => null);+ throw updateFailure(code, previous);+ }+ this.finish({ image, previousImage: previous, desired: "running" });+ await this.refreshHealth().catch(() => null);+ this.log(`the server's updater moved the home from ${previous ?? "its image"} to ${image}`);+ return { home: await this.report(), previousImage: previous, snapshot: null };+ });+ }++ backup(jobId: string): Promise<JobResults["backup"]> {+ return this.exclusive(async () => {+ const { container, dataDir } = await this.install();+ const helper = this.helperImage(container);+ await this.ensureRoomForCopy(helper, dataDir);+ const image = await this.imageOf(container);+ const wasRunning = container.State.Running;+ const id = backupId(this.now());+ const target = `${NAMES.backupPrefix}${id}`;+ this.begin({ jobId, type: "backup", phase: "stop", previousImage: image, nextImage: null, target, dataAtRisk: false, wasRunning });+ try {+ await this.takeDown();+ this.phase({ phase: "copy" });+ await this.copy(helper, this.dataMount(dataDir, "/from", true), { Type: "volume", Source: target, Target: "/to" }, "backup", image);+ } finally {+ if (wasRunning) await this.bringUp().catch((error) => this.log(`could not start the home again: ${errorText(error)}`));+ this.finish({});+ }+ const { backups } = await this.copies();+ for (const old of backups.slice(BACKUPS_KEPT)) await this.docker.removeVolume(`${NAMES.backupPrefix}${old.id}`);+ return { backup: backups.find((entry) => entry.id === id) ?? { id, kind: "backup", createdAt: this.now(), image } };+ });+ }++ restore(jobId: string, id: string): Promise<JobResults["restore"]> {+ return this.exclusive(async () => {+ const { container, dataDir } = await this.install();+ const helper = this.helperImage(container);+ const source = `${NAMES.backupPrefix}${id}`;+ const volume = await this.docker.volumeInspect(source);+ if (!volume || volume.Labels?.[LABELS.role] !== "backup") throw new JobFailure("not_found", `There is no backup ${id} on this server.`);+ await this.ensureRoomForCopy(helper, dataDir);+ const image = await this.imageOf(container);+ const wasRunning = container.State.Running;+ this.begin({ jobId, type: "restore", phase: "stop", previousImage: image, nextImage: null, target: source, dataAtRisk: false, wasRunning });+ await this.takeDown();+ this.phase({ phase: "snapshot" });+ try {+ await this.copy(helper, this.dataMount(dataDir, "/from", true), { Type: "volume", Source: NAMES.snapshotVolume, Target: "/to" }, "snapshot", image);+ } catch (error) {+ this.finish({});+ if (wasRunning) await this.bringUp().catch(() => {});+ throw error;+ }+ this.phase({ phase: "copy", dataAtRisk: true });+ try {+ await this.overwrite(helper, { Type: "volume", Source: source, Target: "/from", ReadOnly: true }, this.dataMount(dataDir, "/to", false));+ } catch (error) {+ await this.putBackSnapshot(helper, dataDir);+ this.finish({});+ if (wasRunning) await this.bringUp().catch(() => {});+ throw new JobFailure("docker", `Restoring backup ${id} failed (${errorText(error)}); the data is as it was.`);+ }+ this.phase({ phase: "start", dataAtRisk: false });+ this.state.saveHome({ ...this.state.home(), desired: "running" });+ try {+ await this.bringUp();+ } catch (error) {+ throw new JobFailure("unhealthy", `Backup ${id} is back, but the home did not become healthy (${errorText(error)}).`);+ } finally {+ this.finish({});+ }+ return { home: await this.report(), backupId: id };+ });+ }++ /** At start: a job the connector was in the middle of is finished safely, and its result is for the Admin. */+ recover(): Promise<JobReply | null> {+ return this.exclusive(async () => {+ const op = this.state.home().operation;+ if (!op) return null;+ this.log(`the connector restarted during ${op.type} (${op.phase}); finishing it safely`);+ if (op.type === "update") return this.recoverUpdate(op);+ const found = await findInstall(this.docker);+ let outcome = "nothing was changed";+ if (found.ok) {+ const { container, dataDir } = found.install;+ if (op.dataAtRisk) {+ await this.takeDown();+ await this.putBackSnapshot(this.helperImage(container), dataDir);+ outcome = "the data was put back as it was before";+ }+ if (op.type === "backup" && op.target) await this.docker.removeVolume(op.target).catch(() => {});+ if (op.wasRunning) {+ await this.bringUp().catch((error) => this.log(`could not start the home: ${errorText(error)}`));+ outcome += ", and the home was started again";+ }+ }+ this.finish({});+ return { id: op.jobId, ok: false, error: { code: "interrupted", message: `The connector restarted during this ${op.type}; ${outcome}.` } };+ });+ }++ private async recoverUpdate(op: Operation): Promise<JobReply> {+ const code = await this.updaterVerdict(op.jobId, this.now() + 60_000);+ if (code === UPDATE_EXIT.done && op.nextImage) {+ this.finish({ image: op.nextImage, previousImage: op.previousImage, desired: "running" });+ await this.refreshHealth().catch(() => null);+ return { id: op.jobId, ok: true, result: { home: await this.report(), previousImage: op.previousImage, snapshot: null } } as JobReply;+ }+ this.finish({});+ const error: JobError = code === null+ ? { code: "interrupted", message: "The connector restarted during this update. The server's own updater finishes or undoes it by itself; ask for the status to see which version runs." }+ : updateFailure(code, op.previousImage).toJobError();+ return { id: op.jobId, ok: false, error };+ }++ /** The updater's exit code for request `jobId`, or null when it has not answered by `deadline`. */+ private async updaterVerdict(jobId: string, deadline: number): Promise<number | null> {+ const file = join(this.options.updateDir, UPDATE_FILES.result);+ for (;;) {+ let text = "";+ try { text = readFileSync(file, "utf8"); } catch { text = ""; }+ const code = /^code=(\d{1,3})$/m.exec(text)?.[1];+ if (code !== undefined && /^id=(.*)$/m.exec(text)?.[1] === jobId) return Number(code);+ if (this.now() >= deadline) return null;+ await this.sleep(this.pollMs);+ }+ }++ private async container(service: string): Promise<ContainerInfo | null> {+ const [found] = await this.docker.listContainers({ [PROJECT_LABEL]: COMPOSE_PROJECT, [SERVICE_LABEL]: service });+ return found ? this.docker.containerInspect(found.Id) : null;+ }++ private async install(): Promise<Install> {+ const found = await findInstall(this.docker);+ if (!found.ok) throw new JobFailure("no_home", found.why);+ return found.install;+ }++ /** The image the home runs, by digest when Docker knows the digest it was pulled by. */+ private async imageOf(container: ContainerInfo): Promise<string | null> {+ const named = container.Config.Image;+ if (CUSTOMER_HOME_IMAGE.test(named)) return named;+ const digests = (await this.docker.imageInspect(container.Image ?? named).catch(() => null))?.RepoDigests ?? [];+ return digests.find((digest) => CUSTOMER_HOME_IMAGE.test(digest)) ?? named;+ }++ /** The helpers run from the image the home itself runs, so no other image is ever needed for a copy. */+ private helperImage(container: ContainerInfo): string {+ return container.Image ?? container.Config.Image;+ }++ private async read(container: ContainerInfo): Promise<HomeFacts> {+ try {+ return parseHomeReads((await this.docker.exec(container.Id, [...HOME_READS_COMMAND], 30_000)).output);+ } catch {+ return { answers: false, version: null, seats: null };+ }+ }++ /** Caddy shares the home's network, so it stops first and starts only once the home is up again. */+ private async takeDown(): Promise<void> {+ const front = await this.container(FRONT);+ if (front) await this.docker.stopContainer(front.Id, 10);+ const home = await this.container(SERVICE);+ if (home) await this.docker.stopContainer(home.Id, HOME_STOP_TIMEOUT_S);+ this.lastHealth = null;+ }++ private async bringUp(): Promise<void> {+ const home = await this.container(SERVICE);+ if (!home) throw new JobFailure("no_home", "MausBot's container is gone from this server. Run the server's install command again to repair it.");+ const wasRunning = home.State.Running;+ try {+ await this.docker.startContainer(home.Id);+ } catch (error) {+ throw new JobFailure("docker", `Docker could not start the home (${errorText(error)}).`);+ }+ const deadline = this.now() + this.startWindowMs;+ for (;;) {+ const now = await this.docker.containerInspect(home.Id);+ if (!now?.State.Running && !now?.State.Restarting) throw new JobFailure("unhealthy", `The home stopped as it started (exit ${now?.State.ExitCode ?? "unknown"}).`);+ if ((await this.refreshHealth())?.ok) break;+ if (this.now() >= deadline) throw new JobFailure("unhealthy", `The home did not answer within ${Math.round(this.startWindowMs / 60_000)} minutes.`);+ await this.sleep(this.pollMs);+ }+ const front = await this.container(FRONT);+ if (!front) return;+ // A Caddy that kept running while the home restarted is still in the old home's network.+ if (front.State.Running && !wasRunning) await this.docker.stopContainer(front.Id, 10);+ await this.docker.startContainer(front.Id).catch((error) => this.log(`could not start Caddy again: ${errorText(error)}`));+ }++ private dataMount(dataDir: string, target: string, readOnly: boolean): Mount {+ return { Type: "bind", Source: dataDir, Target: target, ...(readOnly ? { ReadOnly: true } : {}) };+ }++ private async helper(image: string, mounts: Mount[], command: string[], caps: string[]): Promise<{ code: number; output: string }> {+ const name = `mausbot-helper-${randomBytes(4).toString("hex")}`;+ await this.docker.createContainer(name, helperSpec(image, mounts, command, caps));+ try {+ await this.docker.startContainer(name);+ const code = await this.docker.waitContainer(name, 6 * 60 * 60_000);+ return { code, output: await this.docker.logs(name, 50) };+ } finally {+ await this.docker.removeContainer(name).catch(() => {});+ }+ }++ private async ensureRoomForCopy(image: string, dataDir: string): Promise<void> {+ const measured = await this.helper(image, [this.dataMount(dataDir, "/data", true)], ["du", "-sk", "/data"], READ_CAPS);+ const used = Number(/^(\d+)/.exec(measured.output.trim())?.[1] ?? NaN) * 1024;+ if (!Number.isFinite(used)) return;+ const free = this.options.diskFree();+ const needed = used * 1.1 + 1e9;+ if (free < needed) throw new JobFailure("disk_full", `There is not enough free disk for a copy of the data: it needs about ${gb(needed)} GB and ${gb(free)} GB are free. Free some space or add a disk.`);+ }++ private async copy(helper: string, from: Mount, to: Mount, kind: "backup" | "snapshot", image: string | null): Promise<void> {+ await this.docker.removeVolume(to.Source);+ await this.docker.createVolume(to.Source, { [LABELS.role]: kind, [LABELS.created]: String(this.now()), ...(image ? { [LABELS.image]: image } : {}) });+ const copied = await this.helper(helper, [from, to], ["cp", "-a", "/from/.", "/to/"], COPY_CAPS);+ if (copied.code !== 0) {+ await this.docker.removeVolume(to.Source);+ throw new JobFailure("docker", `Copying the data failed (${lastLine(copied.output)}); nothing was changed.`);+ }+ }++ private async overwrite(helper: string, from: Mount, to: Mount): Promise<void> {+ const wiped = await this.helper(helper, [to], ["find", "/to", "-mindepth", "1", "-delete"], DELETE_CAPS);+ if (wiped.code !== 0) throw new Error(`clearing the data failed (${lastLine(wiped.output)})`);+ const copied = await this.helper(helper, [from, to], ["cp", "-a", "/from/.", "/to/"], COPY_CAPS);+ if (copied.code !== 0) throw new Error(`copying the data back failed (${lastLine(copied.output)})`);+ }++ private async putBackSnapshot(helper: string, dataDir: string): Promise<void> {+ if (!(await this.docker.volumeInspect(NAMES.snapshotVolume))) throw new JobFailure("rollback_failed", "The safety copy of the data is missing; the data was left as it is.");+ await this.overwrite(helper, { Type: "volume", Source: NAMES.snapshotVolume, Target: "/from", ReadOnly: true }, this.dataMount(dataDir, "/to", false));+ }++ private begin(op: Omit<Operation, "startedAt">): void {+ this.state.saveHome({ ...this.state.home(), operation: { ...op, startedAt: this.now() } });+ this.step(op.phase, op.nextImage ? { image: op.nextImage, from: op.previousImage } : undefined);+ }++ private phase(patch: Partial<Operation>): void {+ const record = this.state.home();+ if (!record.operation) return;+ this.state.saveHome({ ...record, operation: { ...record.operation, ...patch } });+ if (patch.phase && patch.phase !== record.operation.phase) this.step(patch.phase);+ }++ private step(step: string, detail?: Record<string, unknown>): void {+ const op = this.state.home().operation;+ if (op) this.options.onStep?.({ id: op.jobId, type: op.type, step, ...(detail ? { detail } : {}) });+ }++ private finish(patch: Partial<HomeRecord>): void {+ this.state.saveHome({ ...this.state.home(), ...patch, operation: null });+ }+}++function updateFailure(code: number | null, previous: string | null): JobFailure {+ const log = "The updater's own account is in .update/update.log in the install's folder.";+ switch (code) {+ case UPDATE_EXIT.rolledBack: return new JobFailure("update_rolled_back", `The new version did not become healthy. The previous version and its data are back. ${log}`, previous ?? undefined);+ case UPDATE_EXIT.rollbackFailed: return new JobFailure("rollback_failed", `The update failed and the previous version did not come back healthy either. ${log}`, previous ?? undefined);+ case UPDATE_EXIT.busy: return new JobFailure("busy", "Another update is already running on this server.");+ case UPDATE_EXIT.notStarted: return new JobFailure("update_not_started", `The server's updater did not start the update, and nothing was changed. ${log}`);+ case UPDATE_EXIT.missing: return new JobFailure("update_unavailable", "This server has no update.sh in its install folder, so MausBot cannot update it. Add deploy/update.sh there, or update by hand.");+ case null: return new JobFailure("interrupted", "The server's updater did not answer in time. It finishes or undoes an update by itself; ask for the status to see which version runs.");+ default: return new JobFailure("docker", `The server's updater stopped with code ${code}. ${log}`);+ }+}++function copyInfo(id: string, kind: CopyInfo["kind"], labels: Record<string, string> | null): CopyInfo {+ const created = Number(labels?.[LABELS.created]);+ return { id, kind, createdAt: Number.isFinite(created) ? created : 0, image: labels?.[LABELS.image] ?? null };+}diff --git a/connector/src/agent.ts b/connector/src/agent.tsindex 86e6bbea94..9c2c23cfb2 100644--- a/connector/src/agent.ts+++ b/connector/src/agent.ts@@ -4,13 +4,14 @@// arrive as yamux streams.import { randomBytes } from "node:crypto";+import { checkCustomerRunJob } from "./customer-run.ts";import { errorText, type Log } from "./log.ts";import { MuxSession, type MuxStream } from "./mux.ts";import {BOX_HEADER, CHANNEL_DEAD_MS, CHANNEL_PING_MS, CHANNEL_PROTOCOL, CLOSE_KEY_COPIED, CLOSE_PROTOCOL, CLOSE_REPLACED, CLOSE_SILENT,CLOSE_UNAUTHORIZED, CONNECT_PATH, HANDSHAKE_MS, HEARTBEAT_INTERVAL_MS, TRANSFER_SCHEME, TRANSFER_TOKEN_MS, authText, checkConfig, checkHello, checkJob,checkJobPayload, checkNonce, type Auth, type BoxState, type ConfigPayload, type Heartbeat, type Job, type JobAck, type JobErrorCode, type JobReply,- type JobType, type TransferPayload,+ type JobType, type ServerMode, type TransferPayload,} from "./protocol.ts";import { b64u, seal, signText, unseal } from "./signed.ts";import type { AgentRecord, ConfigRecord, StatusRecord } from "./state.ts";@@ -67,6 +68,10 @@ export interface AgentOptions {stream?: (stream: MuxStream, accept: () => void) => void;/** A job refused before it ran; for the audit log. */refused?: (refusal: Refusal) => void;+ /** Absent: `operated`. */+ mode?: ServerMode;+ /** What a reply becomes before it leaves the server (customer-run: customer-run.ts `reducedReply`). */+ outgoing?: (reply: JobReply) => JobReply;status?: (patch: Partial<StatusRecord>) => void;now?: () => number;random?: () => number;@@ -172,7 +177,8 @@ export class Agent {}/** A reply to send now and on each new connection, until the Admin acknowledges it. */- reply(reply: JobReply): void {+ reply(made: JobReply): void {+ const reply = this.options.outgoing ? this.options.outgoing(made) : made;this.replies.set(reply.id, reply);while (this.replies.size > KEPT_REPLIES) this.replies.delete(this.replies.keys().next().value as string);const text = JSON.stringify(reply);@@ -399,9 +405,10 @@ export class Agent {const claimed = typeof opened.payload.job === "object" && opened.payload.job !== null ? opened.payload.job as { id?: unknown; type?: unknown } : {};const id = typeof claimed.id === "string" ? claimed.id.slice(0, 64) : undefined;if (!payload.ok) return this.refuse({ code: payload.code, message: payload.message, id, type: typeof claimed.type === "string" ? claimed.type.slice(0, 32) : undefined }, true);- const checked = checkJob(payload.job);+ const checked = this.options.mode === "customer-run" ? checkCustomerRunJob(payload.job) : checkJob(payload.job);if (!checked.ok) {- if (checked.id) this.reply({ id: checked.id, ok: false, error: { code: checked.code, message: checked.message } });+ if (checked.code === "refused_by_mode") this.refuse({ code: checked.code, message: checked.message, id: checked.id ?? undefined, type: typeof claimed.type === "string" ? claimed.type.slice(0, 32) : undefined }, true);+ else if (checked.id) this.reply({ id: checked.id, ok: false, error: { code: checked.code, message: checked.message } });else this.options.log(`ignored a job without a valid id: ${checked.message}`);return;}diff --git a/connector/src/audit.ts b/connector/src/audit.tsindex 892e75ef11..ce627fb22f 100644--- a/connector/src/audit.ts+++ b/connector/src/audit.ts@@ -6,19 +6,25 @@ import { createHash } from "node:crypto";import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync } from "node:fs";import { dirname } from "node:path";-import type { Job, JobError, JobErrorCode, JobType } from "./protocol.ts";+import type { Job, JobError, JobErrorCode, JobType, ServerMode } from "./protocol.ts";/** Who asked: the Admin over the connector's connection, or root on this server through `mausbot-connector job`. */export type AuditSource = "admin" | "local";export type AuditEvent =- | { event: "connector"; what: "started" | "enrolled"; version: string; image: string | null; boxId?: string }+ | { event: "connector"; what: "started" | "enrolled"; version: string; image: string | null; boxId?: string; mode?: ServerMode }+ /** The server's admin paused or resumed remote management (`mausbot-connector pause`, `resume`). */+ | { event: "management"; what: "paused" | "resumed"; by: "local" }| { event: "refused"; by: "admin"; code: JobErrorCode; why: string; id?: string; type?: string }| { event: "job"; by: AuditSource; id: string; type: JobType; args: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: true; detail?: Record<string, unknown> }| { event: "result"; by: AuditSource; id: string; type: JobType; ok: false; error: JobError }| { event: "step"; id: string; type: JobType; step: string; detail?: Record<string, unknown> }- | { event: "request"; by: "admin"; method: string; path: string; status: number; member?: { email: string; role: string; device: string | null } };+ | {+ event: "request"; by: "admin"; method: string; path: string; status: number; member?: { email: string; role: string; device: string | null };+ /** A customer-run server refused it: it is not on that mode's list, or remote management is paused. */+ refused?: "mode" | "paused";+ };export type AuditLine = AuditEvent & { seq: number; at: string; prev: string };diff --git a/connector/src/customer-run-requests.ts b/connector/src/customer-run-requests.tsnew file mode 100644index 0000000000..6e45211f47--- /dev/null+++ b/connector/src/customer-run-requests.ts@@ -0,0 +1,44 @@+// The Admin's requests on a customer-run server. None reaches the home: the connector answers the four listed in+// customer-run.ts from facts it already reports, and refuses the rest. Each one, answered or refused, is a line in the+// audit log.+import type { Duplex } from "node:stream";++import type { AuditEvent } from "./audit.ts";+import { answerCustomerRunRequest, customerRunRequest, type ServerFacts } from "./customer-run.ts";+import { RequestGate, type RequestHead } from "./home-requests.ts";++const WORDS: Record<number, string> = { 200: "OK", 400: "Bad Request", 403: "Forbidden", 503: "Service Unavailable" };++function response(status: number, body: Record<string, unknown>): string {+ const text = JSON.stringify(body);+ return `HTTP/1.1 ${status} ${WORDS[status]}\r\ncontent-type: application/json\r\ncontent-length: ${Buffer.byteLength(text)}\r\nconnection: close\r\n\r\n${text}`;+}++export interface CustomerRunRequestOptions {+ facts: () => Promise<ServerFacts>;+ paused: () => boolean;+ record: (event: AuditEvent) => void;+}++export function serveCustomerRunRequest(stream: Duplex, accept: () => void, options: CustomerRunRequestOptions): void {+ let answered = false;+ const answer = (head: RequestHead | null, status: number, body: Record<string, unknown>, refused?: "mode" | "paused") => {+ if (answered) return;+ answered = true;+ options.record({ event: "request", by: "admin", method: head?.method ?? "INVALID", path: head?.target.split("?")[0]!.slice(0, 200) ?? "", status, ...(refused ? { refused } : {}) });+ if (!stream.destroyed) stream.end(response(status, body));+ };+ const gate = new RequestGate((head) => {+ if (options.paused()) return answer(head, 403, { error: "paused" }, "paused");+ const request = head.length === 0 ? customerRunRequest(head.method, head.target) : null;+ if (!request) return answer(head, 403, { error: "refused_by_mode" }, "mode");+ options.facts().then(+ (facts) => answer(head, 200, answerCustomerRunRequest(request, facts)),+ () => answer(head, 503, { error: "unavailable" }),+ );+ }, () => {});+ gate.on("error", () => answer(null, 400, { error: "invalid_request" }, "mode"));+ gate.resume();+ accept();+ stream.pipe(gate);+}diff --git a/connector/src/customer-run.ts b/connector/src/customer-run.tsnew file mode 100644index 0000000000..ef2c7e78ce--- /dev/null+++ b/connector/src/customer-run.ts@@ -0,0 +1,242 @@+// A customer-run server: everything MausBot's control plane (the Admin) may run on it, ask of it and learn from it.+// This one file is the whole list, for a security reviewer to read. The connector enforces it on the server itself,+// whatever the Admin sends: a job, a request or a reported field that is not written here does not exist in this mode.+//+// Security invariant: nothing in this file passes through text a person wrote. Every string that leaves is either a+// constant below, an enumerated code, or matches one of the patterns below (a version, an image reference, an id).+import {+ checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeReport, type HomeState, type HostHealth,+ type Job, type JobError, type JobErrorCode, type JobReply, type JobType,+} from "./protocol.ts";++// 1. JOBS. The only kinds the Admin may run. Not here, so refused: `export-disk` (uploads the data to MausBot) and+// `import-disk` (replaces the data with an archive from elsewhere).++export const CUSTOMER_RUN_JOBS = ["start", "stop", "restart", "update", "self-update", "status", "host-health", "backup", "restore"] as const satisfies readonly JobType[];++/**+ * What each job may carry.+ * - `start`, `stop`, `restart`: nothing. They start and stop the server its owner installed, with the owner's settings;+ * a `start` that names an image or settings is refused.+ * - `update`: the image to move to, MausBot's own server image pinned by digest. The server's own updater does it.+ * - `self-update`: the connector's next image, pinned by digest.+ * - `backup`: nothing. Copies the data to a Docker volume on this server. `restore`: the id of one of those copies.+ * - `status`, `host-health`: nothing. They read.+ */+export const CUSTOMER_HOME_IMAGE = /^ghcr\.io\/milind-soni\/openmausbot@sha256:[0-9a-f]{64}$/;++const isCustomerRunJob = (type: unknown): type is (typeof CUSTOMER_RUN_JOBS)[number] => (CUSTOMER_RUN_JOBS as readonly unknown[]).includes(type);++/** Why this server refuses a job of `type`, or null when the kind is on the list. */+export function customerRunRefusal(type: string): string | null {+ return isCustomerRunJob(type) ? null : `This server is run by its owner, and ${JSON.stringify(type.slice(0, 32))} is not a job MausBot may run on it.`;+}++type CheckedJob = { ok: true; job: Job } | { ok: false; id: string | null; code: "invalid_job" | "unknown_job" | "invalid_args" | "refused_by_mode"; message: string };++/** A whole job message for a customer-run server: a listed kind with exactly that kind's arguments. */+export function checkCustomerRunJob(message: unknown): CheckedJob {+ const fields = typeof message === "object" && message !== null && !Array.isArray(message) ? message as Record<string, unknown> : {};+ const { id, type } = fields;+ if (typeof type === "string" && !isCustomerRunJob(type)) {+ const known = typeof id === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(id) ? id : null;+ return { ok: false, id: known, code: "refused_by_mode", message: customerRunRefusal(type)! };+ }+ if (type !== "start" && type !== "update") return checkJob(message);+ const args = fields.args === undefined ? {} : fields.args;+ const shape = checkJob({ id, type: "stop", args: {} });+ if (!shape.ok) return shape;+ if (typeof args !== "object" || args === null || Array.isArray(args)) return { ok: false, id: shape.job.id, code: "invalid_args", message: "args must be an object" };+ const keys = Object.keys(args);+ if (type === "start") {+ return keys.length === 0+ ? { ok: true, job: { id: shape.job.id, type, args: {} } as unknown as Job }+ : { ok: false, id: shape.job.id, code: "refused_by_mode", message: "This server is run by its owner: MausBot may start it, but not choose its image or its settings." };+ }+ const image = (args as Record<string, unknown>).image;+ if (keys.length !== 1 || typeof image !== "string" || !CUSTOMER_HOME_IMAGE.test(image)) {+ return { ok: false, id: shape.job.id, code: "invalid_args", message: "image must be ghcr.io/milind-soni/openmausbot@sha256:<digest>" };+ }+ return { ok: true, job: { id: shape.job.id, type, args: { image } } };+}++// 2. REQUESTS. The Admin can also open streams that carry one HTTP request each. On a customer-run server none of them+// reaches the home: the connector answers these four itself, from the facts in section 3, and refuses every other+// method and path, and any request with a body. There is no pairing, so the Admin cannot open a sign-in.++export const CUSTOMER_RUN_REQUESTS = {+ /** `{ state, ok }`: the home's state, and whether it answers. */+ "GET /v1/health": "health",+ /** `{ home, connector }`: the two versions. */+ "GET /v1/version": "version",+ /** `{ seats }`: how many people can sign in. A number, or null when the home does not say. */+ "GET /v1/seats": "seats",+ /** `{ state, image, previousImage }`: whether an update is running, and the images before and after the last one. */+ "GET /v1/update": "update",+} as const;++export type CustomerRunRequest = (typeof CUSTOMER_RUN_REQUESTS)[keyof typeof CUSTOMER_RUN_REQUESTS];++export function customerRunRequest(method: string, target: string): CustomerRunRequest | null {+ const known = CUSTOMER_RUN_REQUESTS as Record<string, CustomerRunRequest>;+ const key = `${method} ${target}`;+ return Object.hasOwn(known, key) ? known[key]! : null;+}++/** What the connector knows of the server to answer with: all of it is in the heartbeat too. */+export interface ServerFacts {+ home: HomeReport;+ connector: ConnectorIdentity;+ seats: number | null;+ previousImage: string | null;+}++export function answerCustomerRunRequest(request: CustomerRunRequest, facts: ServerFacts): Record<string, unknown> {+ const home = reducedHome(facts.home);+ switch (request) {+ case "health": return { state: home.state, ok: home.health?.ok === true };+ case "version": return { home: home.health?.version ?? null, connector: versionOrNull(facts.connector.version) };+ case "seats": return { seats: seatsOrNull(facts.seats) };+ case "update": return { state: home.state, image: home.image, previousImage: imageOrNull(facts.previousImage) };+ }+}++// 3. WHAT THE CONNECTOR READS FROM THE HOME. Three GETs on the home's own loopback, with no body, and from each answer+// one field: that it answers as MausBot, its version, and its seat count. Every other field of those answers (the+// server's name among them) is dropped here and never kept.++export const HOME_READS = ["/api/health", "/.well-known/openmausbot/environment", "/api/seats"] as const;+const RECORD_END = "\u001e";+/** Run inside the home's container: curl comes with the image, and the home listens on its own loopback only. */+export const HOME_READS_COMMAND = [+ "sh", "-c",+ `for path in ${HOME_READS.join(" ")}; do curl -s --max-time 5 "http://127.0.0.1:\${OMB_PORT:-8799}$path" || true; printf '\\n\\036\\n'; done`,+] as const;++export interface HomeFacts {+ answers: boolean;+ version: string | null;+ seats: number | null;+}++const parsed = (text: string | undefined): Record<string, unknown> => {+ try {+ const value: unknown = JSON.parse(text ?? "");+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {};+ } catch {+ return {};+ }+};++export function parseHomeReads(output: string): HomeFacts {+ const [health, environment, seats] = output.split(RECORD_END);+ return { answers: parsed(health).app === "openmausbot", version: versionOrNull(parsed(environment).version), seats: seatsOrNull(parsed(seats).seats) };+}++// 4. WHAT LEAVES THE SERVER. The heartbeat (every 30 seconds) and each job's reply, rebuilt here field by field. A+// field that is not copied below is not sent. No name, no address, no file name, no log line.++const VERSION = /^v?\d{1,5}\.\d{1,5}\.\d{1,5}(?:-[0-9A-Za-z.]{1,32})?$/;+const IMAGE = /^ghcr\.io\/milind-soni\/(?:openmausbot|mausbot-connector)(?:@sha256:[0-9a-f]{64}|:[0-9A-Za-z][0-9A-Za-z._-]{0,63})$/;+/** An operating system, kernel or Docker version as the machine names itself: letters, digits and version punctuation. */+const MACHINE = /^[0-9A-Za-z][0-9A-Za-z ._:+~()/#-]{0,79}$/;+const COPY_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;+const CHECK_IDS: readonly CheckId[] = ["arch", "docker", "rootless", "apparmor", "profiles", "userns", "box", "disk", "memory", "clock"];+const HOME_STATES: readonly HomeState[] = ["absent", "stopped", "starting", "running", "crashed", "updating", "restoring"];++const versionOrNull = (value: unknown) => (typeof value === "string" && VERSION.test(value) ? value : null);+const imageOrNull = (value: unknown) => (typeof value === "string" && IMAGE.test(value) ? value : null);+const machine = (value: unknown) => (typeof value === "string" && MACHINE.test(value) ? value : "unknown");+const count = (value: unknown, max = 1e15) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max ? value : 0);+const seatsOrNull = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1_000_000 ? value : null);++function reducedHost(host: HostHealth): HostHealth {+ return {+ os: machine(host.os), kernel: machine(host.kernel), arch: machine(host.arch), docker: machine(host.docker),+ cpus: count(host.cpus), memMb: count(host.memMb), diskGb: count(host.diskGb), diskTotalGb: count(host.diskTotalGb), memAvailableMb: count(host.memAvailableMb),+ load1: count(host.load1), uptimeS: count(host.uptimeS),+ apparmor: host.apparmor === true, userns: host.userns === true,+ clockSkewS: typeof host.clockSkewS === "number" && Number.isFinite(host.clockSkewS) ? host.clockSkewS : null,+ // The check's id and verdict. The sentence that tells the owner how to fix it stays on the server (`probe`).+ checks: (host.checks ?? []).filter((check) => CHECK_IDS.includes(check.id)).map((check) => ({ id: check.id, ok: check.ok === true, ...(check.warning ? { warning: true } : {}) })),+ };+}++function reducedHome(home: HomeReport): HomeReport {+ const health = home.health;+ return {+ state: HOME_STATES.includes(home.state) ? home.state : "absent",+ image: imageOrNull(home.image),+ health: health ? { ok: health.ok === true, version: versionOrNull(health.version), image: imageOrNull(health.image), box: null, at: count(health.at) } : null,+ };+}++const reducedConnector = (connector: ConnectorIdentity): ConnectorIdentity => ({ version: versionOrNull(connector.version) ?? "0.0.0", protocol: connector.protocol, image: imageOrNull(connector.image) });++const reducedCopy = (copy: CopyInfo): CopyInfo => ({+ id: COPY_ID.test(copy.id) ? copy.id : "unknown", kind: copy.kind === "snapshot" ? "snapshot" : "backup", createdAt: count(copy.createdAt), image: imageOrNull(copy.image),+});++export function reducedHeartbeat(facts: { host: HostHealth; home: HomeReport; connector: ConnectorIdentity; paused: boolean; seats: number | null }): Heartbeat {+ return {+ heartbeat: {+ host: reducedHost(facts.host), home: reducedHome(facts.home), connector: reducedConnector(facts.connector),+ mode: "customer-run", paused: facts.paused === true, seats: seatsOrNull(facts.seats),+ },+ };+}++/** A failed job's reply names its code; this sentence goes with it. What Docker or the home said stays in the audit log. */+const FAILURES: Record<JobErrorCode, string> = {+ invalid_job: "The job was malformed.",+ unknown_job: "The connector does not know this kind of job.",+ invalid_args: "The job's arguments were not the ones this kind of job takes.",+ busy: "Too many jobs are waiting on this server, or its updater is already running.",+ interrupted: "The job was interrupted and finished safely.",+ audit_unavailable: "The audit log on the server cannot be written, so nothing was done.",+ refused_by_policy: "The server's policy file does not allow this job.",+ refused_by_mode: "This server is run by its owner, and this is not a job MausBot may run on it.",+ paused: "The server's admin has paused remote management.",+ image_refused: "The image was refused. Nothing was changed.",+ no_home: "MausBot is not installed on this server.",+ docker: "Docker on the server could not do this.",+ pull_failed: "The image could not be downloaded. Nothing was changed.",+ unhealthy: "The server did not become healthy.",+ update_rolled_back: "The new version did not become healthy. The previous version and its data are back.",+ rollback_failed: "The update failed and the previous version did not come back healthy either.",+ update_unavailable: "The server's own updater is not installed, so MausBot cannot update it.",+ update_not_started: "The server's own updater did not start the update. Nothing was changed.",+ not_found: "There is no such backup on this server.",+ disk_full: "There is not enough free disk on the server for a safety copy of the data.",+ port_in_use: "A port the server needs is used by another program.",+ box_unavailable: "The bot box's security profiles are not installed on this server.",+ transfer_failed: "A transfer failed.",+ self_update_failed: "The connector could not replace itself and was not changed.",+ unsigned_job: "The job was not signed by MausBot.",+ wrong_box: "The job was signed for another server.",+ expired_job: "The job's signature was too old.",+ pending_box: "The team's Owner has not accepted this server in MausBot yet.",+};+const AUDIT_HINT = " The server's admin can read the reason with: mausbot-connector audit";++function reducedError(error: JobError): JobError {+ const code: JobErrorCode = Object.hasOwn(FAILURES, error.code) ? error.code : "docker";+ const image = imageOrNull(error.image);+ return { code, message: `${FAILURES[code]}${AUDIT_HINT}`, ...(image ? { image } : {}) };+}++/** A job's reply as it leaves a customer-run server: the fields below, and nothing else the job produced. */+export function reducedReply(reply: JobReply): JobReply {+ if (!reply.ok) return { id: reply.id, ok: false, error: reducedError(reply.error) };+ const result = reply.result as Record<string, unknown>;+ const out: Record<string, unknown> = {};+ if (result.home) out.home = reducedHome(result.home as HomeReport);+ if (result.host) out.host = reducedHost(result.host as HostHealth);+ if (result.connector) out.connector = reducedConnector(result.connector as ConnectorIdentity);+ if (Array.isArray(result.backups)) out.backups = (result.backups as CopyInfo[]).map(reducedCopy);+ if (result.backup) out.backup = reducedCopy(result.backup as CopyInfo);+ if ("snapshot" in result) out.snapshot = result.snapshot ? reducedCopy(result.snapshot as CopyInfo) : null;+ if ("previousImage" in result) out.previousImage = imageOrNull(result.previousImage);+ if (typeof result.backupId === "string" && COPY_ID.test(result.backupId)) out.backupId = result.backupId;+ return { id: reply.id, ok: true, result: out } as JobReply;+}diff --git a/connector/src/docker.ts b/connector/src/docker.tsindex 6f387f4db5..c1271ab376 100644--- a/connector/src/docker.ts+++ b/connector/src/docker.ts@@ -27,6 +27,8 @@ export interface ImageInfo {export interface ContainerInfo {Id: string;Name: string;+ /** The id of the image the container was made from. */+ Image?: string;Created: string;Config: { Image: string; Env: string[] | null; Labels: Record<string, string> | null; Cmd: string[] | null; Entrypoint: string[] | null };HostConfig: Record<string, unknown>;@@ -110,6 +112,8 @@ export interface Docker {/** Waits for the container to exit and returns its exit code. */waitContainer(name: string, timeoutMs: number): Promise<number>;logs(name: string, tail: number): Promise<string>;+ /** Runs `command` in the running container `name` as its own user, without a terminal or input; its exit code and output. */+ exec(name: string, command: string[], timeoutMs: number): Promise<{ code: number; output: string }>;volumeInspect(name: string): Promise<VolumeInfo | null>;createVolume(name: string, labels: Record<string, string>): Promise<void>;removeVolume(name: string): Promise<void>;@@ -337,6 +341,16 @@ export class SocketDocker implements Docker {return response.status === 200 ? demuxLogs(response.body) : "";}+ async exec(name: string, command: string[], timeoutMs: number): Promise<{ code: number; output: string }> {+ const created = await this.json<{ Id: string }>("POST", `/containers/${encodeURIComponent(name)}/exec`, { body: { Cmd: command, AttachStdout: true, AttachStderr: true, Tty: false }, ok: [201] });+ const id = created!.Id;+ // Without a terminal Docker frames the output like a log stream, and ends the answer when the command exits.+ const response = await this.call("POST", `/exec/${id}/start`, { body: { Detach: false, Tty: false }, timeoutMs });+ if (response.status !== 200) throw new DockerError(response.status, `Docker could not run a command in ${name}`);+ const state = await this.json<{ ExitCode: number | null }>("GET", `/exec/${id}/json`);+ return { code: state?.ExitCode ?? -1, output: demuxLogs(response.body) };+ }+async volumeInspect(name: string): Promise<VolumeInfo | null> {return this.json<VolumeInfo>("GET", `/volumes/${encodeURIComponent(name)}`, { missing: true });}diff --git a/connector/src/enroll.ts b/connector/src/enroll.tsindex 64137036de..dbb8bacc6a 100644--- a/connector/src/enroll.ts+++ b/connector/src/enroll.ts@@ -1,7 +1,7 @@// Trades the one-time code for this server's place in the team: a key made here, whose public half the Admin keeps, and// the Admin's own keys, which the connector pins. Once, over HTTPS.import { errorText } from "./log.ts";-import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type EnrollRequest, type HostFacts } from "./protocol.ts";+import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type EnrollRequest, type HostFacts, type ServerMode } from "./protocol.ts";import { generateKeyPair } from "./signed.ts";import type { AgentRecord } from "./state.ts";@@ -27,6 +27,8 @@ export async function enroll(options: {code: string;host: HostFacts;connector: ConnectorIdentity;+ /** Absent: `operated`. */+ mode?: ServerMode;fetch?: typeof fetch;now?: () => number;timeoutMs?: number;@@ -34,7 +36,8 @@ export async function enroll(options: {const code = checkEnrollCode(options.code.trim());if (!code.ok) throw new Error(code.message);const key = generateKeyPair();- const request: EnrollRequest = { code: code.value, publicKey: key.publicKey, host: options.host, connector: options.connector };+ const customerRun = options.mode === "customer-run";+ const request: EnrollRequest = { code: code.value, publicKey: key.publicKey, host: options.host, connector: options.connector, ...(customerRun ? { mode: "customer-run" } : {}) };let response: Response;try {response = await (options.fetch ?? fetch)(`${options.admin}${ENROLL_PATH}`, {@@ -55,5 +58,5 @@ export async function enroll(options: {const checked = checkEnrollResponse(body);if (!checked.ok) throw new Error(`MausBot's answer could not be used (${checked.message}). Try the install command again.`);const { boxId, teamId, adminKeys } = checked.value;- return { version: 2, admin: options.admin, boxId, teamId, publicKey: key.publicKey, privateKey: key.privateKey, adminKeys, enrolledAt: (options.now ?? Date.now)() };+ return { version: 2, admin: options.admin, boxId, teamId, publicKey: key.publicKey, privateKey: key.privateKey, adminKeys, enrolledAt: (options.now ?? Date.now)(), ...(customerRun ? { mode: "customer-run" } : {}) };}diff --git a/connector/src/jobs.ts b/connector/src/jobs.tsindex 28c461d3d5..7960ba4a9e 100644--- a/connector/src/jobs.ts+++ b/connector/src/jobs.ts@@ -1,18 +1,23 @@// Each job type of the protocol, and nothing else: what runs for a job is fixed here, and its arguments were checked// (protocol.ts checkJob) before it got here.+import type { AdoptedHome } from "./adopted-home.ts";import { auditArgs, type AuditEvent, type AuditLog, type AuditSource } from "./audit.ts";+import { customerRunRefusal } from "./customer-run.ts";import { asJobError } from "./failure.ts";import type { Home } from "./home.ts";import { errorText, type Log } from "./log.ts";import { policyRefusal, readPolicy } from "./policy.ts";-import type { ConnectorIdentity, HostHealth, Job, JobArgs, JobReply, JobResults, JobType } from "./protocol.ts";+import type { ConnectorIdentity, HostHealth, Job, JobArgs, JobReply, JobResults, JobType, ServerMode } from "./protocol.ts";/** Jobs that change the home, its data or the connector; they wait for each other. */const CHANGES: ReadonlySet<JobType> = new Set(["start", "stop", "restart", "update", "backup", "restore", "export-disk", "import-disk", "self-update"]);const MAX_WAITING = 8;export interface RunnerDeps {- home: Home;+ /** On a server MausBot operates: the home the connector makes and keeps running. */+ home?: Home;+ /** On a customer-run server: the home its owner installed. Every job goes to it, and `home` is never used. */+ adopted?: AdoptedHome;hostHealth: () => Promise<HostHealth>;identity: () => ConnectorIdentity;/** The Admin's origin, and the `Authorization` a transfer for a job sends it. */@@ -26,29 +31,59 @@ export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | nuconst run = async (job: Job): Promise<JobReply | null> => {const ok = <T extends JobType>(result: JobResults[T]): JobReply => ({ id: job.id, ok: true, result });try {+ const adopted = deps.adopted;+ if (adopted) {+ switch (job.type) {+ case "start":+ return ok(await adopted.start());+ case "stop":+ return ok(await adopted.stop());+ case "restart":+ return ok(await adopted.restart());+ case "update":+ return ok(await adopted.update(job.id, (job.args as JobArgs["update"]).image));+ case "backup":+ return ok(await adopted.backup(job.id));+ case "restore":+ return ok(await adopted.restore(job.id, (job.args as JobArgs["restore"]).backupId));+ case "status": {+ await adopted.refreshHealth();+ const { backups, snapshot } = await adopted.copies();+ return ok({ home: await adopted.report(), connector: deps.identity(), backups, snapshot });+ }+ case "host-health":+ return ok({ host: await deps.hostHealth() });+ case "self-update":+ return await deps.selfUpdate(job as Job<"self-update">);+ default:+ return { id: job.id, ok: false, error: { code: "refused_by_mode", message: customerRunRefusal(job.type) ?? "This server is run by its owner." } };+ }+ }+ const home = deps.home;+ if (!home) return { id: job.id, ok: false, error: { code: "no_home", message: "This connector was started without a home to run." } };switch (job.type) {case "start": {const { image, env } = job.args as JobArgs["start"];- return ok(await deps.home.start(job.id, image, env));+ return ok(await home.start(job.id, image, env));}case "stop":- return ok(await deps.home.stop());+ return ok(await home.stop());case "restart":- return ok(await deps.home.restart());+ return ok(await home.restart());case "update":- return ok(await deps.home.update(job.id, (job.args as JobArgs["update"]).image));+ return ok(await home.update(job.id, (job.args as JobArgs["update"]).image));case "backup":- return ok(await deps.home.backup(job.id));+ return ok(await home.backup(job.id));case "restore":- return ok(await deps.home.restore(job.id, (job.args as JobArgs["restore"]).backupId));+ return ok(await home.restore(job.id, (job.args as JobArgs["restore"]).backupId));case "export-disk":- return ok(await deps.home.exportDisk(job.id, deps.admin()));+ return ok(await home.exportDisk(job.id, deps.admin()));case "import-disk":- return ok(await deps.home.importDisk(job.id, (job.args as JobArgs["import-disk"]).url, deps.admin()));+ return ok(await home.importDisk(job.id, (job.args as JobArgs["import-disk"]).url, deps.admin()));case "status": {- await deps.home.refreshHealth();- const { backups, snapshot } = await deps.home.copies();- return ok({ home: await deps.home.report(), connector: deps.identity(), backups, snapshot });+ await home.refreshHealth();+ const { backups, snapshot } = await home.copies();+ return ok({ home: await home.report(), connector: deps.identity(), backups, snapshot });}case "host-health":return ok({ host: await deps.hostHealth() });@@ -82,7 +117,18 @@ export interface Desk {submit(job: Job, by: AuditSource): Promise<JobReply | null>;}-export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audit: AuditLog; log: Log; policyFile?: string }): Desk {+export interface DeskDeps {+ run: (job: Job) => Promise<JobReply | null>;+ audit: AuditLog;+ log: Log;+ policyFile?: string;+ /** Absent: `operated`. On a customer-run server a job outside that mode's list is refused, whoever sent it. */+ mode?: ServerMode;+ /** The server's admin has paused remote management: every job from MausBot is refused until they resume it. */+ paused?: () => boolean;+}++export function jobDesk(deps: DeskDeps): Desk {const record = (event: AuditEvent): boolean => {try {deps.audit.append(event);@@ -97,12 +143,16 @@ export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audif (!record({ event: "job", by, id: job.id, type: job.type, args: auditArgs(job) }) && !READS.has(job.type)) {return { id: job.id, ok: false, error: { code: "audit_unavailable", message: `The audit log at ${deps.audit.file} cannot be written, so nothing was done. Run the install command again to repair it.` } };}- const refusal = by === "admin" && deps.policyFile ? policyRefusal(job, readPolicy(deps.policyFile), deps.policyFile) : null;- if (refusal) {- const refused: JobReply = { id: job.id, ok: false, error: { code: "refused_by_policy", message: refusal } };+ const refuse = (code: "refused_by_mode" | "paused" | "refused_by_policy", message: string): JobReply => {+ const refused: JobReply = { id: job.id, ok: false, error: { code, message } };record(resultEvent(by, job.type, refused));return refused;- }+ };+ const outsideMode = deps.mode === "customer-run" ? customerRunRefusal(job.type) : null;+ if (outsideMode) return refuse("refused_by_mode", outsideMode);+ if (by === "admin" && deps.paused?.()) return refuse("paused", "This server's admin has paused remote management. They resume it with: mausbot-connector resume");+ const refusal = by === "admin" && deps.policyFile ? policyRefusal(job, readPolicy(deps.policyFile), deps.policyFile, deps.mode) : null;+ if (refusal) return refuse("refused_by_policy", refusal);const reply = await deps.run(job);if (reply) record(resultEvent(by, job.type, reply));return reply;diff --git a/connector/src/local.ts b/connector/src/local.tsindex 52f11e26ea..19a32f4dc3 100644--- a/connector/src/local.ts+++ b/connector/src/local.ts@@ -7,7 +7,8 @@ import { createConnection, createServer, type Server } from "node:net";import type { Desk } from "./jobs.ts";import { errorText, type Log } from "./log.ts";-import { checkJob, type JobReply } from "./protocol.ts";+import { checkCustomerRunJob } from "./customer-run.ts";+import { checkJob, type JobReply, type ServerMode } from "./protocol.ts";const MAX_REQUEST_BYTES = 64 * 1024;@@ -16,7 +17,7 @@ export function localJobId(): string {}/** Answers one JSON line `{type, args}` per connection with the job's reply, as one JSON line. */-export function serveLocalJobs(socketPath: string, desk: Desk, log: Log): Promise<Server> {+export function serveLocalJobs(socketPath: string, desk: Desk, log: Log, mode: ServerMode = "operated"): Promise<Server> {rmSync(socketPath, { force: true });const server = createServer((socket) => {let text = "";@@ -36,7 +37,8 @@ export function serveLocalJobs(socketPath: string, desk: Desk, log: Log): Promislet request: unknown;try { request = JSON.parse(text.slice(0, end)); } catch { request = null; }const fields = typeof request === "object" && request !== null && !Array.isArray(request) ? request as Record<string, unknown> : {};- const checked = checkJob({ id: localJobId(), type: fields.type, args: fields.args });+ const message = { id: localJobId(), type: fields.type, args: fields.args };+ const checked = mode === "customer-run" ? checkCustomerRunJob(message) : checkJob(message);if (!checked.ok) {answer({ ok: false, error: { code: checked.code, message: checked.message } });return;diff --git a/connector/src/main.ts b/connector/src/main.tsindex 472a715e04..882d5667be 100644--- a/connector/src/main.ts+++ b/connector/src/main.ts@@ -1,13 +1,16 @@// mausbot-connector: `run` (the service), `enroll` (the code on stdin), `status`, `probe`, `job` (one job from root on this-// server), `audit` (the audit log, checked), `version`.+// server), `audit` (the audit log, checked), `pause` and `resume` (remote management, by the server's admin), `version`.import { existsSync, readFileSync, statfsSync } from "node:fs";import { join } from "node:path";import { createConnection } from "node:net";import type { Duplex } from "node:stream";+import { AdoptedHome, enrolmentRefusal } from "./adopted-home.ts";import { Agent, savedConfig, transferAuthorization } from "./agent.ts";import { AuditLog, verifyAudit } from "./audit.ts";+import { serveCustomerRunRequest } from "./customer-run-requests.ts";+import { reducedHeartbeat, reducedReply } from "./customer-run.ts";import { SocketDocker, dockerApiProblem, type DockerInfo } from "./docker.ts";import { adminOrigin, enroll } from "./enroll.ts";import { readHealth } from "./home-health.ts";@@ -18,7 +21,7 @@ import { jobDesk, jobRunner, resultEvent } from "./jobs.ts";import { sendLocalJob, serveLocalJobs } from "./local.ts";import { POLICY_FILE } from "./policy.ts";import { errorText, log, registerSecret } from "./log.ts";-import { PROTOCOL_VERSION, type ConnectorIdentity, type Heartbeat, type HostHealth } from "./protocol.ts";+import { PROTOCOL_VERSION, type CheckId, type ConnectorIdentity, type Heartbeat, type HostHealth, type ServerMode } from "./protocol.ts";import { SELF_UPDATE_DEADLINE_MS, SelfUpdater, ownContainer } from "./self-update.ts";import { AUDIT_FILE, CONNECTOR_VERSION, HOME_PORT, PATHS, SECCOMP_FILE, envSeconds } from "./settings.ts";import { StateStore, type AgentRecord } from "./state.ts";@@ -46,6 +49,14 @@ const auditLog = () => new AuditLog(join(PATHS.audit, AUDIT_FILE));const identity = (): ConnectorIdentity => ({ version: CONNECTOR_VERSION, protocol: PROTOCOL_VERSION, image: process.env.MAUSBOT_CONNECTOR_IMAGE || null });const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+/** The stricter of what the server was enrolled as and what install.sh started this container as. */+function serverMode(record: AgentRecord | null): ServerMode {+ return record?.mode === "customer-run" || process.env.MAUSBOT_MODE === "customer-run" ? "customer-run" : "operated";+}++/** The bot box's profiles belong to a home the connector makes; a home its owner installed is not given them. */+const OPERATED_ONLY_CHECKS: ReadonlySet<CheckId> = new Set(["apparmor", "profiles", "box"]);+function seccomp(): string {const text = reader.installedSeccomp();if (!text) throw new Error(`The bot box's seccomp profile is missing from ${PATHS.hostConfig}. Run the install command again to repair it.`);@@ -53,7 +64,7 @@ function seccomp(): string {}/** What the host reports, with Docker's info read again at most every five minutes and the box probed every six hours. */-function hostReporter(docker: SocketDocker, admin: () => string | null) {+function hostReporter(docker: SocketDocker, admin: () => string | null, mode: ServerMode) {let info: { at: number; value: DockerInfo } | null = null;let box: { at: number; value: BoxProbeResult | null } | null = null;let clock: { at: number; skew: number | null } | null = null;@@ -63,7 +74,7 @@ function hostReporter(docker: SocketDocker, admin: () => string | null) {};const probe = async (fresh: boolean) => {const image = process.env.MAUSBOT_CONNECTOR_IMAGE;- if (!image) return null;+ if (!image || mode === "customer-run") return null;if (fresh || !box || Date.now() - box.at > 6 * 60 * 60_000) {let value: BoxProbeResult | null;try { value = await probeBox(docker, image, seccomp()); } catch (error) { value = { ok: false, fix: errorText(error) }; }@@ -92,7 +103,8 @@ function hostReporter(docker: SocketDocker, admin: () => string | null) {info: dockerInfo,async health(fresh: boolean): Promise<HostHealth> {const [value, boxed, skewed] = await Promise.all([dockerInfo(fresh), probe(fresh), skew(fresh)]);- return hostHealth(value, reader, { clockSkewS: skewed, box: boxed });+ const health = hostHealth(value, reader, { clockSkewS: skewed, box: boxed });+ return mode === "customer-run" ? { ...health, checks: health.checks.filter((check) => !OPERATED_ONLY_CHECKS.has(check.id)) } : health;},};}@@ -123,11 +135,17 @@ async function run(): Promise<void> {}registerSecret(record.privateKey);let current: AgentRecord = record;- if (enrolledNow) note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, boxId: record.boxId });+ const mode = serverMode(record);+ if (enrolledNow) note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, boxId: record.boxId, mode });+ if (mode === "customer-run") log("this server is run by its owner: MausBot may only do what connector/src/customer-run.ts lists");const kept = savedConfig(state.adminConfig(), current);if (kept) log(`going by MausBot's schedule and policy kept on this server (version ${kept.version}) until MausBot answers`);- const host = hostReporter(docker, () => current.admin);- const home = new Home({+ const host = hostReporter(docker, () => current.admin, mode);+ const adopted = mode === "customer-run" ? new AdoptedHome({+ docker, state, log, diskFree: () => reader.disk().free, updateDir: PATHS.update,+ onStep: ({ id, type, step, detail }) => note({ event: "step", id, type, step, ...(detail ? { detail } : {}) }),+ }) : null;+ const home = adopted ?? new Home({docker, state, log, readHealth, seccomp, transfer: httpTransfer,diskFree: () => reader.disk().free,updateWindowMs: envSeconds("MAUSBOT_UPDATE_WAIT_S", 600, 60, 3600) * 1000,@@ -136,17 +154,18 @@ async function run(): Promise<void> {const updater = new SelfUpdater({ docker, state, log, instance, identity });const heartbeat = async (): Promise<Heartbeat> => {await home.refreshHealth().catch(() => null);- return { heartbeat: { host: await host.health(false), home: await home.report(), connector: identity() } };+ const facts = { host: await host.health(false), home: await home.report(), connector: identity() };+ return adopted ? reducedHeartbeat({ ...facts, paused: state.paused(), seats: adopted.seats }) : { heartbeat: facts };};let agent: Agent;const runner = jobRunner({- home,+ ...(adopted ? { adopted } : { home: home as Home }),hostHealth: () => host.health(true),identity,admin: () => ({ origin: current.admin, authorization: (jobId) => transferAuthorization(current, jobId) }),selfUpdate: (job) => home.exclusive(() => updater.run(job, { pause: () => agent.stop(), resume: () => agent.start() })),});- const desk = jobDesk({ run: runner, audit, log, policyFile: join(PATHS.hostConfig, POLICY_FILE) });+ const desk = jobDesk({ run: runner, audit, log, policyFile: join(PATHS.hostConfig, POLICY_FILE), mode, paused: () => mode === "customer-run" && state.paused() });const connectHome = () => new Promise<Duplex>((resolve, reject) => {const socket = createConnection({ host: "127.0.0.1", port: HOME_PORT });socket.once("connect", () => resolve(socket));@@ -162,7 +181,17 @@ async function run(): Promise<void> {},config: { saved: () => state.adminConfig(), save: (config) => state.saveAdminConfig(config) },onConfig: (config) => log(`MausBot's schedule and policy (version ${config.version}) are kept on this server`),- stream: (stream, accept) => serveRequest(stream, accept, { connectHome, record: note }),+ stream: (stream, accept) => (adopted+ ? serveCustomerRunRequest(stream, accept, {+ paused: () => state.paused(), record: note,+ facts: async () => {+ await adopted.refreshHealth().catch(() => null);+ return { home: await adopted.report(), connector: identity(), seats: adopted.seats, previousImage: adopted.previousImage };+ },+ })+ : serveRequest(stream, accept, { connectHome, record: note })),+ mode,+ ...(adopted ? { outgoing: reducedReply } : {}),refused: (refusal) => note({ event: "refused", by: "admin", code: refusal.code, why: refusal.message, ...(refusal.id ? { id: refusal.id } : {}), ...(refusal.type ? { type: refusal.type } : {}) }),});agent = makeAgent();@@ -197,11 +226,16 @@ async function run(): Promise<void> {agent.reply(role.reply);}agent.start();- await serveLocalJobs(PATHS.jobs, desk, log).catch((error) => log(`jobs from this server are off: ${errorText(error)}`));+ await serveLocalJobs(PATHS.jobs, desk, log, mode).catch((error) => log(`jobs from this server are off: ${errorText(error)}`));setInterval(() => {home.supervise().catch((error) => log(`supervising the home failed: ${errorText(error)}`));const latest = state.agent();+ if (latest && serverMode(latest) !== mode) {+ log("this server was connected again in another mode; the connector restarts to take it up");+ agent.stop();+ process.exit(0);+ }if (latest && latest.publicKey !== current.publicKey) {log("this server was connected again with a new code; reconnecting");registerSecret(latest.privateKey);@@ -231,7 +265,10 @@ async function enrollCommand(): Promise<void> {const code = (await readStdin()).trim();const state = new StateStore(PATHS.state);const docker = new SocketDocker(PATHS.docker);- const record = await enroll({ admin, code, host: hostFacts(await docker.info(), reader), connector: identity() });+ const mode = serverMode(null);+ const refusal = await enrolmentRefusal(mode, docker);+ if (refusal) throw new Error(refusal);+ const record = await enroll({ admin, code, host: hostFacts(await docker.info(), reader), connector: identity(), mode });state.saveAgent(record);// Connected again only once the service has connected with this token.state.saveStatus({ connected: false, unauthorized: false, lastError: null });@@ -244,7 +281,7 @@ function statusCommand(): void {const status = state.status();const home = state.home();console.log(JSON.stringify({- enrolled: Boolean(record), admin: record?.admin ?? null, boxId: record?.boxId ?? null, teamId: record?.teamId ?? null,+ enrolled: Boolean(record), mode: serverMode(record), paused: state.paused(), admin: record?.admin ?? null, boxId: record?.boxId ?? null, teamId: record?.teamId ?? null,connected: status.connected, accepted: status.boxState === "accepted", unauthorized: status.unauthorized,lastConnectedAt: status.lastConnectedAt, lastHeartbeatAt: status.lastHeartbeatAt, config: state.adminConfig()?.version ?? null,lastError: status.lastError, home: { desired: home.desired, image: home.image, operation: home.operation?.type ?? null },@@ -302,6 +339,21 @@ function auditCommand(): void {for (const line of audit.tail(Number.isInteger(count) && count > 0 ? count : 50)) console.log(line);}+/** `pause` and `resume`: the server's admin stops and allows MausBot's jobs and requests. The running connector reads it before each one. */+function pauseCommand(paused: boolean): void {+ const state = new StateStore(PATHS.state);+ if (serverMode(state.agent()) !== "customer-run") {+ throw new Error("MausBot runs this server, so there is no remote management to pause here. To cut the connection: docker stop mausbot-connector");+ }+ if (state.paused() !== paused) {+ state.savePause(paused);+ auditLog().append({ event: "management", what: paused ? "paused" : "resumed", by: "local" });+ }+ console.log(paused+ ? "Remote management is paused: this server refuses every job and request from MausBot, and logs each one. It still reports its health. To allow them again: mausbot-connector resume"+ : "Remote management is on again: MausBot may run the jobs this server allows.");+}+const commands: Record<string, () => Promise<void> | void> = {run,enroll: enrollCommand,@@ -309,12 +361,14 @@ const commands: Record<string, () => Promise<void> | void> = {probe: probeCommand,job: jobCommand,audit: auditCommand,+ pause: () => pauseCommand(true),+ resume: () => pauseCommand(false),version: () => console.log(CONNECTOR_VERSION),};const command = commands[process.argv[2] ?? "run"];if (!command) {- console.error("usage: mausbot-connector run | enroll | status | probe [--json] | job <type> [args] | audit [--tail N | --verify] | version");+ console.error("usage: mausbot-connector run | enroll | status | probe [--json] | job <type> [args] | audit [--tail N | --verify] | pause | resume | version");process.exitCode = 2;} else {Promise.resolve().then(command).catch((error) => {diff --git a/connector/src/policy.ts b/connector/src/policy.tsindex c9d64d57e6..7ef86770cf 100644--- a/connector/src/policy.ts+++ b/connector/src/policy.ts@@ -6,9 +6,11 @@//// `jobs`: the only kinds MausBot may run here (absent: all of them). `updates: "hold"`: MausBot's home updates wait.// A self-update of the connector is always accepted, so a held or locked-down server never strands an old connector.+// On a customer-run server the owner's list covers it too: a new connector could carry other rules, so the owner may+// keep the one they read.import { readFileSync } from "node:fs";-import { JOB_TYPES, type Job, type JobType } from "./protocol.ts";+import { JOB_TYPES, type Job, type JobType, type ServerMode } from "./protocol.ts";export const POLICY_FILE = "policy.json";@@ -44,9 +46,9 @@ export function readPolicy(file: string): ReturnType<typeof parsePolicy> {return parsePolicy(text);}-/** Why the server's policy refuses `job` from MausBot, or null. A self-update is never refused. */-export function policyRefusal(job: Job, read: ReturnType<typeof parsePolicy>, file: string): string | null {- if (job.type === "self-update") return null;+/** Why the server's policy refuses `job` from MausBot, or null. On a server MausBot operates a self-update is never refused. */+export function policyRefusal(job: Job, read: ReturnType<typeof parsePolicy>, file: string, mode: ServerMode = "operated"): string | null {+ if (job.type === "self-update" && (mode !== "customer-run" || !read.ok || !read.policy.jobs)) return null;if (!read.ok) return READS.has(job.type) ? null : `This server's policy ${file} cannot be used (${read.problem}), so MausBot changes nothing here until it is fixed.`;if (read.policy.jobs && !read.policy.jobs.includes(job.type)) return `This server's policy ${file} does not let MausBot run ${job.type} jobs.`;if (job.type === "update" && read.policy.updates === "hold") return `This server's policy ${file} holds updates.`;diff --git a/connector/src/protocol.ts b/connector/src/protocol.tsindex 27198145ab..33ce681586 100644--- a/connector/src/protocol.ts+++ b/connector/src/protocol.ts@@ -13,6 +13,14 @@export const PROTOCOL_VERSION = 2;+/**+ * Who runs the server. `operated`: MausBot does (a Team Cloud on a server we manage), and the connector does whatever+ * the Admin signs. `customer-run`: its owner does; the connector then runs only the jobs, answers only the requests and+ * reports only the fields listed in customer-run.ts, whatever the Admin sends. The mode is chosen on the server when+ * it enrols and kept there; the Admin is told it (`EnrollRequest.mode`, `Heartbeat`) and can never change it.+ */+export type ServerMode = "operated" | "customer-run";+/** `POST {admin}{ENROLL_PATH}` with an `EnrollRequest`; answers an `EnrollResponse`. The code is single use. */export const ENROLL_PATH = "/api/cloud/box/v1/enroll";/** `GET {admin}{CONNECT_PATH}`, upgraded to a WebSocket with subprotocol `CHANNEL_PROTOCOL` and header `x-omb-box`. */@@ -133,7 +141,17 @@ export interface CopyInfo {/** Connector → Admin, every `HEARTBEAT_INTERVAL_MS` and once right after connecting. */export interface Heartbeat {- heartbeat: { host: HostHealth; home: HomeReport; connector: ConnectorIdentity };+ heartbeat: {+ host: HostHealth;+ home: HomeReport;+ connector: ConnectorIdentity;+ /** Only from a customer-run server; absent means `operated`. */+ mode?: "customer-run";+ /** Customer-run only: the server's admin has paused remote management, so every job and request is refused. */+ paused?: boolean;+ /** Customer-run only: how many people can sign in to the home; null when the home does not say. Never who. */+ seats?: number | null;+ };}export interface JobArgs {@@ -183,7 +201,9 @@ export type JobErrorCode =| "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable" | "refused_by_policy" | "image_refused"| "no_home" | "docker" | "pull_failed" | "unhealthy" | "update_rolled_back" | "rollback_failed"| "not_found" | "disk_full" | "port_in_use" | "box_unavailable" | "transfer_failed" | "self_update_failed"- | "unsigned_job" | "wrong_box" | "expired_job" | "pending_box";+ | "unsigned_job" | "wrong_box" | "expired_job" | "pending_box"+ /** A customer-run server only: the job is not on its list, its admin has paused remote management, or its own updater is missing or declined. */+ | "refused_by_mode" | "paused" | "update_unavailable" | "update_not_started";/** `message` is plain words for the Admin's log and alerts; it never carries a secret. */export interface JobError {@@ -210,6 +230,12 @@ export interface EnrollRequest {publicKey: string;host: HostFacts;connector: ConnectorIdentity;+ /**+ * Sent only by a customer-run server, so an `operated` enrolment is the same request as before this field existed.+ * The Admin keeps it with the box: such a box refuses `export-disk`, `import-disk`, a `start` that carries an image+ * or settings, every request to the home outside its list, and reports only the reduced heartbeat.+ */+ mode?: "customer-run";}/**diff --git a/connector/src/settings.ts b/connector/src/settings.tsindex 69da410fa0..2922d3590b 100644--- a/connector/src/settings.ts+++ b/connector/src/settings.ts@@ -37,6 +37,8 @@ export const PATHS = {audit: process.env.MAUSBOT_AUDIT_DIR || "/var/log/mausbot",/** In the container's own /tmp: `mausbot-connector job` reaches the running connector here. */jobs: process.env.MAUSBOT_JOBS_SOCKET || "/tmp/mausbot-jobs.sock",+ /** /var/lib/mausbot/update on the host, on a customer-run server only: where an update is handed to the server's own updater. */+ update: process.env.MAUSBOT_UPDATE_DIR || "/var/lib/mausbot/update",} as const;export const AUDIT_FILE = "audit.jsonl";diff --git a/connector/src/state.ts b/connector/src/state.tsindex 978116d60a..feaec0df1a 100644--- a/connector/src/state.ts+++ b/connector/src/state.ts@@ -4,6 +4,7 @@import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";+import type { ServerMode } from "./protocol.ts";import { HOME_SECRET_ENV, HOME_SECRETS_DIR, HOME_SECRETS_FILE } from "./settings.ts";export interface AgentRecord {@@ -17,6 +18,14 @@ export interface AgentRecord {/** The Admin's signing keys by id, pinned at enrolment; only a hello signed by one of them replaces them. */adminKeys: Record<string, string>;enrolledAt: number;+ /** Who runs this server (protocol.ts `ServerMode`), set when it enrolled; absent on a record made before modes: `operated`. */+ mode?: ServerMode;+}++/** The server's admin paused remote management (`mausbot-connector pause`): every job and request from MausBot is refused. */+export interface PauseRecord {+ paused: boolean;+ at: number;}/** The Admin's newest signed config this box verified (protocol.ts `ConfigPayload`), kept as signed. */@@ -82,6 +91,7 @@ const FILES = {selfUpdate: "self-update.json",count: "connect-count.json",config: "admin-config.json",+ pause: "pause.json",} as const;export class StateStore {@@ -184,6 +194,15 @@ export class StateStore {this.write(FILES.status, { ...this.status(), ...patch });}+ /** Read from the disk each time: `mausbot-connector pause` is another process. */+ paused(): boolean {+ return this.read<PauseRecord>(FILES.pause)?.paused === true;+ }++ savePause(paused: boolean, now = Date.now()): void {+ this.write(FILES.pause, { paused, at: now } satisfies PauseRecord);+ }+selfUpdate(): SelfUpdateRecord | null {return this.read<SelfUpdateRecord>(FILES.selfUpdate);}diff --git a/connector/test/customer-run.test.ts b/connector/test/customer-run.test.tsnew file mode 100644index 0000000000..f4db6b196d--- /dev/null+++ b/connector/test/customer-run.test.ts@@ -0,0 +1,542 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { AdoptedHome, UPDATE_FILES, enrolmentRefusal, findInstall, standaloneServerPresent } from "../src/adopted-home.ts";+import { Agent, type Refusal } from "../src/agent.ts";+import { AuditLog, type AuditEvent, type AuditLine } from "../src/audit.ts";+import { serveCustomerRunRequest } from "../src/customer-run-requests.ts";+import {+ CUSTOMER_RUN_JOBS, CUSTOMER_RUN_REQUESTS, HOME_READS, HOME_READS_COMMAND, checkCustomerRunJob, customerRunRefusal, parseHomeReads, reducedHeartbeat, reducedReply,+} from "../src/customer-run.ts";+import { enroll } from "../src/enroll.ts";+import { jobDesk, jobRunner } from "../src/jobs.ts";+import { parsePolicy, policyRefusal } from "../src/policy.ts";+import { JOB_TYPES, checkJob, type HostFacts, type HostHealth, type Job, type JobReply, type JobType } from "../src/protocol.ts";+import { StateStore, type AgentRecord } from "../src/state.ts";+import { FakeAdmin } from "./fake-admin.ts";+import { FakeDocker } from "./fake-docker.ts";++const digest = (letter: string) => `ghcr.io/milind-soni/openmausbot@sha256:${letter.repeat(64)}`;+const CLOUD_HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"c".repeat(64)}`;+const CONNECTOR = `ghcr.io/milind-soni/mausbot-connector@sha256:${"1".repeat(64)}`;+const RUNNING = "ghcr.io/milind-soni/openmausbot:v0.1.151";+const NEXT = digest("b");+const EMAIL = "[email protected]";+const WRITTEN = "Quarterly numbers for Project Nightingale";+const SERVER_NAME = "Lovelace Analytical Engines";+const host: HostFacts = { os: "Ubuntu 24.04.3 LTS", kernel: "6.8.0-1021-azure", arch: "x86_64", cpus: 4, memMb: 16_000, diskGb: 120, docker: "28.0.4", apparmor: true, userns: true };+const health: HostHealth = {+ ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0,+ checks: [{ id: "disk", ok: true, warning: true, fix: `Your server's disk is 90% full, ${EMAIL} said so.` }, { id: "clock", ok: true }],+};+const identity = { version: "1.0.0", protocol: 2 as const, image: CONNECTOR };++const cleanups: (() => Promise<void> | void)[] = [];+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();+});++async function until(check: () => boolean, ms = 5_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!check()) {+ if (Date.now() > deadline) throw new Error("timed out");+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}++/** A server its owner installed with deploy/install.sh: the Compose project, its data folder, and a home that answers on its own loopback. */+function server(options: { image?: string; seats?: number | null } = {}) {+ const dir = mkdtempSync(join(tmpdir(), "omb-customer-run-"));+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));+ const dataDir = join(dir, "opt-openmausbot", "data");+ const updateDir = join(dir, "update");+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(updateDir);+ const state = new StateStore(join(dir, "state"));+ const docker = new FakeDocker(state.dir);+ let clock = 1_800_000_000_000;+ docker.now = () => clock;+ const image = options.image ?? RUNNING;+ for (const ref of [image, NEXT, "caddy:2"]) {+ docker.publish(ref, null);+ docker.images.set(ref, {});+ }+ const compose = (service: string) => ({ "com.docker.compose.project": "openmausbot", "com.docker.compose.service": service });+ const home = { answers: true, seats: options.seats === undefined ? 7 : options.seats, execs: [] as string[][] };+ docker.onExec = (_container, command) => {+ home.execs.push(command);+ if (!home.answers) return { code: 0, output: "\n\u001e\n\n\u001e\n\n\u001e\n" };+ return {+ code: 0,+ output: [+ JSON.stringify({ app: "openmausbot", pid: 41, owner: EMAIL }),+ JSON.stringify({ environmentId: "env-1", label: SERVER_NAME, version: "0.1.151", admin: EMAIL }),+ home.seats === null ? JSON.stringify({ error: "Not found" }) : JSON.stringify({ seats: home.seats, people: [EMAIL] }),+ ].map((answer) => `${answer}\n\u001e\n`).join(""),+ };+ };+ const steps: string[] = [];+ const lines: string[] = [];+ const adopted = new AdoptedHome({+ docker, state, log: (line) => lines.push(line), diskFree: () => 500e9, updateDir,+ now: () => clock, sleep: async (ms) => { clock += ms; }, startWindowMs: 60_000, updateDeadlineMs: 120_000, pollMs: 2_000,+ onStep: ({ id, step }) => steps.push(`${id} ${step}`),+ });+ const install = async () => {+ await docker.createContainer("openmausbot-omb-1", { Image: image, Labels: compose("omb"), HostConfig: { Mounts: [{ Type: "bind", Source: dataDir, Target: "/data" }] } });+ await docker.createContainer("openmausbot-caddy-1", { Image: "caddy:2", Labels: compose("caddy"), HostConfig: { NetworkMode: "container:omb" } });+ await docker.startContainer("openmausbot-omb-1");+ await docker.startContainer("openmausbot-caddy-1");+ docker.folder(dataDir).files.set("chats.json", WRITTEN);+ docker.calls.length = 0;+ };+ return { dir, dataDir, updateDir, state, docker, adopted, home, steps, lines, install, image };+}++function desk(fixture: ReturnType<typeof server>, options: { mode?: "customer-run" | "operated"; paused?: () => boolean } = {}) {+ const ran: Job[] = [];+ const audit = new AuditLog(join(fixture.dir, "audit.jsonl"));+ const run = jobRunner({+ adopted: fixture.adopted, hostHealth: async () => health, identity: () => identity,+ admin: () => ({ origin: "https://cloud.example.test", authorization: () => "Box token" }),+ selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: identity } }),+ });+ const made = jobDesk({ run: async (job) => { ran.push(job); return run(job); }, audit, log: () => {}, mode: options.mode ?? "customer-run", paused: options.paused });+ const lines = () => audit.tail(100).map((line) => JSON.parse(line) as AuditLine);+ return { desk: made, ran, lines };+}++describe("a customer-run server: the jobs MausBot may run", () => {+ it("lists nine kinds, and neither of the two that move the data", () => {+ expect([...CUSTOMER_RUN_JOBS].sort()).toEqual(["backup", "host-health", "restart", "restore", "self-update", "start", "status", "stop", "update"]);+ expect(JOB_TYPES.filter((type) => customerRunRefusal(type) !== null)).toEqual(["export-disk", "import-disk"]);+ });++ it("refuses export-disk, import-disk and any kind it does not list as the job arrives, while the operated check still takes them", () => {+ const moved: [JobType, Record<string, unknown>][] = [["export-disk", {}], ["import-disk", { url: "https://storage.example.test/disk.tar.gz" }]];+ for (const [type, args] of moved) {+ expect(checkJob({ id: "j1", type, args })).toMatchObject({ ok: true });+ expect(checkCustomerRunJob({ id: "j1", type, args })).toEqual({+ ok: false, id: "j1", code: "refused_by_mode", message: `This server is run by its owner, and "${type}" is not a job MausBot may run on it.`,+ });+ }+ expect(checkCustomerRunJob({ id: "j2", type: "shell", args: { command: "cat /data" } })).toMatchObject({ ok: false, code: "refused_by_mode" });+ });++ it("refuses a start that names an image or settings, and an update to anything but MausBot's server image by digest", () => {+ const env = { OMB_CLOUD_ROLE: "team", OMB_CLOUD_MACHINE_ID: "m", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_PUBLIC_URL: "https://acme.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: "s".repeat(40) };+ expect(checkJob({ id: "s1", type: "start", args: { image: CLOUD_HOME, env } })).toMatchObject({ ok: true });+ expect(checkCustomerRunJob({ id: "s1", type: "start", args: { image: CLOUD_HOME, env } })).toMatchObject({ ok: false, id: "s1", code: "refused_by_mode" });+ expect(checkCustomerRunJob({ id: "s2", type: "start" })).toEqual({ ok: true, job: { id: "s2", type: "start", args: {} } });+ expect(checkCustomerRunJob({ id: "u1", type: "update", args: { image: NEXT } })).toEqual({ ok: true, job: { id: "u1", type: "update", args: { image: NEXT } } });+ for (const image of [CLOUD_HOME, RUNNING, "ghcr.io/someone-else/openmausbot@sha256:" + "a".repeat(64)]) {+ expect(checkCustomerRunJob({ id: "u2", type: "update", args: { image } }), image).toMatchObject({ ok: false, code: "invalid_args" });+ }+ expect(checkCustomerRunJob({ id: "u3", type: "update", args: { image: NEXT, env } })).toMatchObject({ ok: false, code: "invalid_args" });+ expect(checkCustomerRunJob({ id: "bad id", type: "start" })).toMatchObject({ ok: false, id: null, code: "invalid_job" });+ expect(checkCustomerRunJob({ id: "r1", type: "restore", args: { backupId: "../etc" } })).toMatchObject({ ok: false, code: "invalid_args" });+ });++ it("refuses them again at the desk, whoever sent them, runs nothing, and writes both the job and the refusal to the audit log", async () => {+ const fixture = server();+ await fixture.install();+ const { desk: made, ran, lines } = desk(fixture);+ for (const by of ["admin", "local"] as const) {+ for (const type of ["export-disk", "import-disk"] as const) {+ const reply = await made.submit({ id: `${by}-${type}`, type, args: type === "import-disk" ? { url: "https://storage.example.test/disk.tar.gz" } : {} } as Job, by);+ expect(reply).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });+ }+ }+ expect(ran).toEqual([]);+ expect(fixture.docker.calls).toEqual([]);+ expect(lines().map((line) => `${line.event} ${(line as { id?: string }).id}`)).toEqual([+ "job admin-export-disk", "result admin-export-disk", "job admin-import-disk", "result admin-import-disk",+ "job local-export-disk", "result local-export-disk", "job local-import-disk", "result local-import-disk",+ ]);+ const operated = desk(fixture, { mode: "operated" });+ await operated.desk.submit({ id: "x", type: "export-disk", args: {} }, "admin");+ expect(operated.ran.map((job) => job.type)).toEqual(["export-disk"]);+ });++ it("has no way to run them even past both checks: the home it attached to refuses the kind", async () => {+ const fixture = server();+ await fixture.install();+ const run = jobRunner({+ adopted: fixture.adopted, hostHealth: async () => health, identity: () => identity,+ admin: () => ({ origin: "https://cloud.example.test", authorization: () => "Box token" }),+ selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: identity } }),+ });+ expect(await run({ id: "e", type: "export-disk", args: {} })).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });+ expect(await run({ id: "i", type: "import-disk", args: { url: "https://storage.example.test/disk.tar.gz" } })).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });+ expect(fixture.docker.calls).toEqual([]);+ });+});++describe("a customer-run server: pausing remote management", () => {+ it("refuses every job from MausBot while paused, the connector's own update too, logs each, and still runs the admin's own", async () => {+ const fixture = server();+ await fixture.install();+ let paused = true;+ const { desk: made, ran, lines } = desk(fixture, { paused: () => paused });+ for (const type of ["status", "stop", "self-update"] as const) {+ const job = { id: `p-${type}`, type, args: type === "self-update" ? { image: CONNECTOR } : {} } as Job;+ expect(await made.submit(job, "admin")).toMatchObject({ ok: false, error: { code: "paused" } });+ }+ expect(ran).toEqual([]);+ expect(lines().filter((line) => line.event === "result").map((line) => (line as { error?: { code: string } }).error?.code)).toEqual(["paused", "paused", "paused"]);+ expect(await made.submit({ id: "mine", type: "status", args: {} }, "local")).toMatchObject({ ok: true });+ paused = false;+ expect(await made.submit({ id: "after", type: "status", args: {} }, "admin")).toMatchObject({ ok: true });+ });++ it("lets the owner's policy file keep the connector they read: its job list covers the connector's own update here, and only here", () => {+ const update = { id: "c1", type: "self-update", args: { image: CONNECTOR } } as Job;+ const listed = parsePolicy('{"jobs":["status","host-health"]}');+ expect(policyRefusal(update, listed, "/etc/mausbot/policy.json", "customer-run")).toBe("This server's policy /etc/mausbot/policy.json does not let MausBot run self-update jobs.");+ expect(policyRefusal(update, listed, "/etc/mausbot/policy.json")).toBeNull();+ expect(policyRefusal(update, parsePolicy(null), "/etc/mausbot/policy.json", "customer-run")).toBeNull();+ expect(policyRefusal(update, parsePolicy('{"jobs":["self-update"]}'), "/etc/mausbot/policy.json", "customer-run")).toBeNull();+ });++ it("is kept on the server's disk, where the running connector reads it before each job", () => {+ const { state } = server();+ expect(state.paused()).toBe(false);+ state.savePause(true);+ expect(new StateStore(state.dir).paused()).toBe(true);+ state.savePause(false);+ expect(state.paused()).toBe(false);+ });+});++describe("a customer-run server: what leaves it", () => {+ const TOLD = /^(?:v?\d+\.\d+\.\d+|ghcr\.io\/milind-soni\/[a-z-]+[@:][\w.:-]+|Ubuntu 24\.04\.3 LTS|6\.8\.0-1021-azure|x86_64|28\.0\.4|customer-run|running|stopped|starting|updating|absent|[a-z]+|\d{8}-\d{6}-[0-9a-f]{4})$/;+ const strings = (value: unknown, out: string[] = []): string[] => {+ if (typeof value === "string") out.push(value);+ else if (Array.isArray(value)) for (const item of value) strings(item, out);+ else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) strings(item, out);+ return out;+ };++ it("reads three fields from the home and drops everything else it answered", () => {+ const fixture = server();+ expect(HOME_READS).toEqual(["/api/health", "/.well-known/openmausbot/environment", "/api/seats"]);+ const facts = parseHomeReads(fixture.docker.onExec!({} as never, []).output);+ expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7 });+ expect(parseHomeReads("not json\n\u001e\n{\"version\":\"<script>\"}\n\u001e\n{\"seats\":\"seven\"}\n\u001e\n")).toEqual({ answers: false, version: null, seats: null });+ expect(parseHomeReads("")).toEqual({ answers: false, version: null, seats: null });+ });++ it("sends a heartbeat of versions, states, counts and the seat count, with no address, name or sentence in it", async () => {+ const fixture = server();+ await fixture.install();+ await fixture.adopted.refreshHealth();+ expect(fixture.home.execs).toEqual([[...HOME_READS_COMMAND]]);+ const beat = reducedHeartbeat({ host: health, home: await fixture.adopted.report(), connector: identity, paused: false, seats: fixture.adopted.seats });+ const sent = JSON.stringify(beat);+ for (const secret of [EMAIL, "@customer", "lovelace", SERVER_NAME, "Lovelace", WRITTEN, "said so", "env-1"]) expect(sent, secret).not.toContain(secret);+ expect(beat.heartbeat).toEqual({+ host: { ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0, checks: [{ id: "disk", ok: true, warning: true }, { id: "clock", ok: true }] },+ home: { state: "running", image: RUNNING, health: { ok: true, version: "0.1.151", image: RUNNING, box: null, at: 1_800_000_000_000 } },+ connector: identity, mode: "customer-run", paused: false, seats: 7,+ });+ for (const text of strings(beat)) expect(text, text).toMatch(TOLD);+ });++ it("replaces anything that is not a version, an image or a machine's own name before it is sent", () => {+ const beat = reducedHeartbeat({+ host: { ...health, os: `Ubuntu (${EMAIL})`, kernel: "6.8.0\nBcc: someone", checks: [{ id: "notes" as never, ok: false, fix: WRITTEN }] },+ home: { state: WRITTEN as never, image: `registry.example/${EMAIL}`, health: { ok: true, version: WRITTEN, image: null, box: { box: EMAIL, checks: WRITTEN, failed: [EMAIL] }, at: 1 } },+ connector: { version: WRITTEN, protocol: 2, image: EMAIL }, paused: true, seats: 7.5,+ });+ expect(beat.heartbeat).toMatchObject({+ host: { os: "unknown", kernel: "unknown", checks: [] }, home: { state: "absent", image: null, health: { version: null, box: null } },+ connector: { version: "0.0.0", image: null }, paused: true, seats: null,+ });+ expect(JSON.stringify(beat)).not.toMatch(/@|Nightingale|Bcc/);+ });++ it("answers a failed job with its code and a fixed sentence: what Docker or the home said stays in the audit log", () => {+ const failed = reducedReply({ id: "j", ok: false, error: { code: "unhealthy", message: `The home stopped: startup failed: could not open ${EMAIL}'s chat "${WRITTEN}"`, image: RUNNING } });+ expect(failed).toEqual({ id: "j", ok: false, error: { code: "unhealthy", message: "The server did not become healthy. The server's admin can read the reason with: mausbot-connector audit", image: RUNNING } });+ const odd = reducedReply({ id: "j", ok: false, error: { code: WRITTEN as never, message: EMAIL, image: EMAIL } });+ expect(odd).toMatchObject({ error: { code: "docker" } });+ expect(JSON.stringify([failed, odd])).not.toMatch(/@|Nightingale/);+ });++ it("answers a job that worked with the fields it lists and nothing else the job produced", () => {+ const reply = reducedReply({+ id: "s", ok: true,+ result: {+ home: { state: "running", image: RUNNING, health: null, owner: EMAIL }, connector: identity, backups: [{ id: "20261028-104512-3fa9", kind: "backup", createdAt: 5, image: RUNNING, note: WRITTEN }],+ snapshot: null, members: [EMAIL], bytes: 12, sha256: "0".repeat(64),+ },+ } as unknown as JobReply);+ expect(reply).toEqual({+ id: "s", ok: true,+ result: { home: { state: "running", image: RUNNING, health: null }, connector: identity, backups: [{ id: "20261028-104512-3fa9", kind: "backup", createdAt: 5, image: RUNNING }], snapshot: null },+ });+ });+});++describe("a customer-run server: the home its owner installed", () => {+ it("attaches to the Compose install, and says in plain words why it cannot when there is none or it was built here", async () => {+ const fixture = server();+ expect(await standaloneServerPresent(fixture.docker)).toBe(false);+ expect(await findInstall(fixture.docker)).toEqual({ ok: false, why: "MausBot is not installed on this server yet. Install it first with the server's install command, then connect it." });+ await fixture.install();+ expect(await standaloneServerPresent(fixture.docker)).toBe(true);+ expect(await findInstall(fixture.docker)).toMatchObject({ ok: true, install: { dataDir: fixture.dataDir } });+ const built = server({ image: "deploy-omb" });+ await built.install();+ expect(await findInstall(built.docker)).toMatchObject({ ok: false, why: expect.stringContaining("was built here") });+ });++ it("will not be enrolled as a server MausBot runs where its owner's MausBot is already installed: that would start a second one", async () => {+ const fixture = server();+ expect(await enrolmentRefusal("operated", fixture.docker)).toBeNull();+ expect(await enrolmentRefusal("customer-run", fixture.docker)).toContain("MausBot is not installed on this server yet.");+ await fixture.install();+ expect(await enrolmentRefusal("operated", fixture.docker)).toBe(+ "MausBot already runs on this server, installed by its owner. Connecting it this way would start a second MausBot beside it. Run the install command again and it connects the one that is here, keeping its data.",+ );+ expect(await enrolmentRefusal("customer-run", fixture.docker)).toBeNull();+ });++ it("stops Caddy before the home and starts it after the home answers, and never makes, removes or renames a container", async () => {+ const fixture = server();+ await fixture.install();+ expect(await fixture.adopted.stop()).toEqual({ home: { state: "stopped", image: RUNNING, health: null } });+ expect(fixture.docker.calls).toEqual(["stop openmausbot-caddy-1", "stop openmausbot-omb-1"]);+ fixture.docker.calls.length = 0;+ expect(await fixture.adopted.start()).toMatchObject({ home: { state: "running", health: { ok: true, version: "0.1.151" } } });+ expect(fixture.docker.calls).toEqual(["start openmausbot-omb-1", "exec openmausbot-omb-1", "start openmausbot-caddy-1"]);+ fixture.docker.calls.length = 0;+ await fixture.adopted.restart();+ expect(fixture.docker.calls.filter((call) => /^(create|rm|rename|pull|rmi) /.test(call))).toEqual([]);+ expect(fixture.docker.container("mausbot-home")).toBeNull();+ expect(fixture.docker.volumes.has("mausbot-data")).toBe(false);+ });++ it("says the home did not answer when it does not, within the wait", async () => {+ const fixture = server();+ await fixture.install();+ await fixture.adopted.stop();+ fixture.home.answers = false;+ await expect(fixture.adopted.start()).rejects.toMatchObject({ code: "unhealthy", message: "The home did not answer within 1 minutes." });+ expect((await fixture.adopted.report()).state).toBe("starting");+ });++ it("backs the data folder up to a volume on the same server and puts a backup back, with a safety copy first", async () => {+ const fixture = server();+ await fixture.install();+ const { backup } = await fixture.adopted.backup("b1");+ expect(fixture.docker.files(`mausbot-backup-${backup.id}`)).toEqual({ "chats.json": WRITTEN });+ expect(fixture.docker.container("openmausbot-omb-1")?.status).toBe("running");+ fixture.docker.folder(fixture.dataDir).files.set("chats.json", "changed since");+ fixture.docker.folder(fixture.dataDir).files.set("new.json", "made since");+ expect(await fixture.adopted.restore("r1", backup.id)).toMatchObject({ backupId: backup.id, home: { state: "running" } });+ expect(Object.fromEntries(fixture.docker.folder(fixture.dataDir).files)).toEqual({ "chats.json": WRITTEN });+ expect(fixture.docker.files("mausbot-snapshot")).toEqual({ "chats.json": "changed since", "new.json": "made since" });+ expect(fixture.steps).toEqual(["b1 stop", "b1 copy", "r1 stop", "r1 snapshot", "r1 copy", "r1 start"]);+ expect(fixture.state.home().operation).toBeNull();+ await expect(fixture.adopted.restore("r2", "20200101-000000-aaaa")).rejects.toMatchObject({ code: "not_found" });+ });++ it("puts the data back as it was when the connector restarts in the middle of a restore", async () => {+ const fixture = server();+ await fixture.install();+ const { backup } = await fixture.adopted.backup("b1");+ const before = { "chats.json": "the newest chats" };+ fixture.docker.folder(fixture.dataDir).files.set("chats.json", before["chats.json"]);+ await fixture.docker.createVolume("mausbot-snapshot", { "com.mausbot.role": "snapshot" });+ fixture.docker.volume("mausbot-snapshot").files.set("chats.json", before["chats.json"]);+ fixture.docker.folder(fixture.dataDir).files.clear();+ fixture.state.saveHome({ ...fixture.state.home(), operation: { jobId: "r9", type: "restore", phase: "copy", previousImage: RUNNING, nextImage: null, target: `mausbot-backup-${backup.id}`, dataAtRisk: true, wasRunning: true, startedAt: 1 } });+ expect(await fixture.adopted.recover()).toEqual({ id: "r9", ok: false, error: { code: "interrupted", message: "The connector restarted during this restore; the data was put back as it was before, and the home was started again." } });+ expect(Object.fromEntries(fixture.docker.folder(fixture.dataDir).files)).toEqual(before);+ expect(fixture.docker.container("openmausbot-omb-1")?.status).toBe("running");+ });+});++describe("a customer-run server: updates go to the server's own updater", () => {+ /** Stands in for mausbot-update-runner.sh: reads the request the connector left and answers with update.sh's exit code. */+ const updater = (fixture: ReturnType<typeof server>, code: number, seen: string[] = []) => {+ writeFileSync(join(fixture.updateDir, UPDATE_FILES.runner), "1\n");+ const sleep = (fixture.adopted as unknown as { sleep: (ms: number) => Promise<void> }).sleep;+ (fixture.adopted as unknown as { sleep: (ms: number) => Promise<void> }).sleep = async (ms) => {+ const request = join(fixture.updateDir, UPDATE_FILES.request);+ if (existsSync(request)) {+ const text = readFileSync(request, "utf8");+ seen.push(text);+ rmSync(request);+ writeFileSync(join(fixture.updateDir, UPDATE_FILES.result), `id=${/^id=(.*)$/m.exec(text)![1]}\ncode=${code}\n`);+ }+ await sleep(ms);+ };+ return seen;+ };++ it("leaves the image for the updater, touches no container itself, and reports the new image once the updater is done", async () => {+ const fixture = server();+ await fixture.install();+ const seen = updater(fixture, 0);+ const result = await fixture.adopted.update("u1", NEXT);+ expect(seen).toEqual([`id=u1\nimage=${NEXT}\n`]);+ expect(result).toMatchObject({ previousImage: RUNNING, snapshot: null, home: { state: "running" } });+ expect(fixture.docker.calls.filter((call) => !call.startsWith("exec "))).toEqual([]);+ expect(fixture.state.home()).toMatchObject({ image: NEXT, previousImage: RUNNING, operation: null });+ expect(fixture.steps).toEqual(["u1 request", "u1 wait"]);+ });++ it("maps each way the updater ends to a code, and refuses when the server has no updater or the image is not MausBot's", async () => {+ for (const [code, expected] of [[1, "update_rolled_back"], [2, "rollback_failed"], [3, "busy"], [4, "update_not_started"], [127, "update_unavailable"], [9, "docker"]] as const) {+ const fixture = server();+ await fixture.install();+ updater(fixture, code);+ await expect(fixture.adopted.update("u1", NEXT), String(code)).rejects.toMatchObject({ code: expected });+ expect(fixture.state.home().operation).toBeNull();+ }+ const bare = server();+ await bare.install();+ await expect(bare.adopted.update("u2", NEXT)).rejects.toMatchObject({ code: "update_unavailable" });+ await expect(bare.adopted.update("u3", CLOUD_HOME)).rejects.toMatchObject({ code: "image_refused" });+ expect(existsSync(join(bare.updateDir, UPDATE_FILES.request))).toBe(false);+ });++ it("says so when the updater never answers, and takes its late verdict after a restart", async () => {+ const fixture = server();+ await fixture.install();+ writeFileSync(join(fixture.updateDir, UPDATE_FILES.runner), "1\n");+ await expect(fixture.adopted.update("u1", NEXT)).rejects.toMatchObject({ code: "interrupted" });+ fixture.state.saveHome({ ...fixture.state.home(), operation: { jobId: "u7", type: "update", phase: "wait", previousImage: RUNNING, nextImage: NEXT, target: null, dataAtRisk: false, wasRunning: true, startedAt: 1 } });+ writeFileSync(join(fixture.updateDir, UPDATE_FILES.result), "id=u7\ncode=0\n");+ expect(await fixture.adopted.recover()).toMatchObject({ id: "u7", ok: true, result: { previousImage: RUNNING } });+ });+});++describe("a customer-run server: MausBot's requests", () => {+ async function connected(options: { paused?: () => boolean } = {}) {+ const admin = new FakeAdmin();+ await admin.listen();+ cleanups.push(() => admin.close());+ const record: AgentRecord = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector: identity, mode: "customer-run" });+ admin.boxes.get(record.boxId)!.state = "accepted";+ const audits: AuditEvent[] = [];+ const refusals: Refusal[] = [];+ const handled: Job[] = [];+ let count = 0;+ const agent = new Agent({+ identity: () => record, log: () => {}, heartbeatMs: 100, random: () => 0, nextCount: () => ++count, mode: "customer-run", outgoing: reducedReply,+ heartbeat: async () => reducedHeartbeat({ host: health, home: { state: "running", image: RUNNING, health: null }, connector: identity, paused: false, seats: 7 }),+ handle: async (job) => {+ handled.push(job);+ return { id: job.id, ok: false, error: { code: "docker", message: `Docker said: ${EMAIL}` } };+ },+ stream: (stream, accept) => serveCustomerRunRequest(stream, accept, {+ paused: options.paused ?? (() => false), record: (event) => audits.push(event),+ facts: async () => ({ home: { state: "running", image: RUNNING, health: { ok: true, version: "0.1.151", image: RUNNING, box: null, at: 1 } }, connector: identity, seats: 7, previousImage: null }),+ }),+ refused: (refusal) => refusals.push(refusal),+ });+ cleanups.push(() => agent.stop());+ agent.start();+ await until(() => agent.connected);+ return { admin, record, audits, refusals, handled };+ }+ const bodyOf = (answer: { body: string }) => JSON.parse(answer.body) as unknown;++ it("tells MausBot its mode when it enrols and in every heartbeat, and an operated server's enrolment is unchanged", async () => {+ const { admin, record } = await connected();+ expect(admin.boxes.get(record.boxId)!.enroll.mode).toBe("customer-run");+ expect(record.mode).toBe("customer-run");+ await until(() => admin.heartbeats.length >= 1);+ expect(admin.heartbeats[0]).toMatchObject({ mode: "customer-run", paused: false, seats: 7 });+ const operated = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector: identity });+ expect(Object.keys(admin.boxes.get(operated.boxId)!.enroll).sort()).toEqual(["code", "connector", "host", "publicKey"]);+ expect("mode" in operated).toBe(false);+ });++ it("answers the four requests on its list itself, with numbers and versions only", async () => {+ const { admin, audits } = await connected();+ expect(Object.keys(CUSTOMER_RUN_REQUESTS)).toEqual(["GET /v1/health", "GET /v1/version", "GET /v1/seats", "GET /v1/update"]);+ expect(bodyOf(await admin.fetch("/v1/health"))).toEqual({ state: "running", ok: true });+ expect(bodyOf(await admin.fetch("/v1/version"))).toEqual({ home: "0.1.151", connector: "1.0.0" });+ expect(bodyOf(await admin.fetch("/v1/seats"))).toEqual({ seats: 7 });+ expect(bodyOf(await admin.fetch("/v1/update"))).toEqual({ state: "running", image: RUNNING, previousImage: null });+ expect(audits).toEqual(["/v1/health", "/v1/version", "/v1/seats", "/v1/update"].map((path) => ({ event: "request", by: "admin", method: "GET", path, status: 200 })));+ });++ it("refuses a pairing, the team summary, the home's own routes and anything with a body, and logs each refusal", async () => {+ const { admin, audits } = await connected();+ const pairing = JSON.stringify({ label: "MausBot dashboard", member: { email: EMAIL, role: "admin" } });+ const refused: [string, string, string?][] = [+ ["POST", "/api/cloud/pairing", pairing], ["GET", "/api/cloud/team/admin"], ["GET", "/api/cloud/health"], ["GET", "/api/health"], ["GET", "/api/seats"],+ ["GET", "/api/bots"], ["GET", "/v1/seats?who=1"], ["POST", "/v1/seats", "{}"], ["GET", "/v1/seats", "{}"], ["DELETE", "/v1/health"], ["GET", "/"],+ ];+ for (const [method, path, body] of refused) {+ const answer = await admin.fetch(path, { method, ...(body ? { body, headers: { "content-type": "application/json" } } : {}) });+ expect(answer.status, `${method} ${path}`).toBe(403);+ expect(bodyOf(answer)).toEqual({ error: "refused_by_mode" });+ }+ expect(audits).toHaveLength(refused.length);+ expect(audits.every((event) => event.event === "request" && event.status === 403 && event.refused === "mode")).toBe(true);+ expect(JSON.stringify(audits)).not.toContain(EMAIL);+ });++ it("refuses even the listed requests while remote management is paused", async () => {+ const { admin, audits } = await connected({ paused: () => true });+ const answer = await admin.fetch("/v1/seats");+ expect(answer.status).toBe(403);+ expect(bodyOf(answer)).toEqual({ error: "paused" });+ expect(audits).toEqual([{ event: "request", by: "admin", method: "GET", path: "/v1/seats", status: 403, refused: "paused" }]);+ });++ it("refuses a signed export-disk before it reaches the desk, logs the refusal, and sends back only codes and fixed sentences", async () => {+ const { admin, record, refusals, handled } = await connected();+ admin.send({ job: admin.signJob(record.boxId, { id: "x1", type: "export-disk", args: {} }) });+ expect(await admin.replyTo("x1", 5_000)).toEqual({+ id: "x1", ok: false, error: { code: "refused_by_mode", message: "This server is run by its owner, and this is not a job MausBot may run on it. The server's admin can read the reason with: mausbot-connector audit" },+ });+ admin.send({ job: admin.signJob(record.boxId, { id: "x2", type: "import-disk", args: { url: "https://storage.example.test/d.tar.gz" } }) });+ expect(await admin.replyTo("x2", 5_000)).toMatchObject({ ok: false, error: { code: "refused_by_mode" } });+ expect(handled).toEqual([]);+ expect(refusals.map((refusal) => `${refusal.code} ${refusal.id} ${refusal.type}`)).toEqual(["refused_by_mode x1 export-disk", "refused_by_mode x2 import-disk"]);+ admin.send({ job: admin.signJob(record.boxId, { id: "x3", type: "stop", args: {} }) });+ const failed = await admin.replyTo("x3", 5_000);+ expect(failed).toMatchObject({ ok: false, error: { code: "docker" } });+ expect(JSON.stringify(failed)).not.toContain("@");+ expect(handled.map((job) => job.type)).toEqual(["stop"]);+ });++ it("leaves a server MausBot runs as it was: export-disk reaches the desk, and replies and heartbeats pass as made", async () => {+ const admin = new FakeAdmin();+ await admin.listen();+ cleanups.push(() => admin.close());+ const record = await enroll({ admin: admin.origin, code: admin.mintCode(), host, connector: identity });+ admin.boxes.get(record.boxId)!.state = "accepted";+ const handled: Job[] = [];+ const refusals: Refusal[] = [];+ let count = 0;+ const beat = { heartbeat: { host: health, home: { state: "running" as const, image: CLOUD_HOME, health: null }, connector: identity } };+ const agent = new Agent({+ identity: () => record, log: () => {}, heartbeatMs: 100, random: () => 0, nextCount: () => ++count, heartbeat: async () => beat,+ handle: async (job) => {+ handled.push(job);+ return { id: job.id, ok: false, error: { code: "transfer_failed", message: `The data could not be sent to MausBot (${WRITTEN}).` } };+ },+ refused: (refusal) => refusals.push(refusal),+ });+ cleanups.push(() => agent.stop());+ agent.start();+ await until(() => agent.connected);+ admin.send({ job: admin.signJob(record.boxId, { id: "x1", type: "export-disk", args: {} }) });+ expect(await admin.replyTo("x1", 5_000)).toEqual({ id: "x1", ok: false, error: { code: "transfer_failed", message: `The data could not be sent to MausBot (${WRITTEN}).` } });+ expect(handled.map((job) => job.type)).toEqual(["export-disk"]);+ expect(refusals).toEqual([]);+ await until(() => admin.heartbeats.length >= 1);+ expect(admin.heartbeats[0]).toEqual(beat.heartbeat);+ expect(Object.keys(admin.heartbeats[0]!).sort()).toEqual(["connector", "home", "host"]);+ });+});diff --git a/connector/test/fake-docker.ts b/connector/test/fake-docker.tsindex 112b43f9be..ae6360b98f 100644--- a/connector/test/fake-docker.ts+++ b/connector/test/fake-docker.ts@@ -41,6 +41,10 @@ export class FakeDocker implements Docker {failCopy = false;/** What the box probe prints and its exit code. */probe = { code: 0, output: "" };+ /** What a command run inside a container prints: lets a test act as the home's own loopback. */+ onExec: ((container: FakeContainer, command: string[]) => { code: number; output: string }) | null = null;+ /** Folders on the host that containers bind-mount, by path. */+ readonly folders = new Map<string, FakeVolume>();/** Run when a home container starts: lets a test act as the home (write files, crash). */onHomeStart: ((container: FakeContainer) => void) | null = null;/** Run when a connector container starts: lets a test act as the new connector. */@@ -195,6 +199,19 @@ export class FakeDocker implements Docker {return this.container(name)?.logs ?? "";}+ async exec(name: string, command: string[]): Promise<{ code: number; output: string }> {+ const container = this.container(name);+ if (!container || container.status !== "running") throw new DockerError(409, `Container ${name} is not running`);+ this.calls.push(`exec ${container.name}`);+ return this.onExec?.(container, command) ?? { code: 127, output: "" };+ }++ folder(path: string): FakeVolume {+ let folder = this.folders.get(path);+ if (!folder) this.folders.set(path, folder = { labels: {}, files: new Map() });+ return folder;+ }+async volumeInspect(name: string): Promise<VolumeInfo | null> {if (name === "mausbot-connector") return { Name: name, Labels: {}, Mountpoint: this.stateDir };const volume = this.volumes.get(name);@@ -228,7 +245,7 @@ export class FakeDocker implements Docker {const mounted = (target: string) => {const mount = (container.spec.HostConfig.Mounts ?? []).find((entry) => entry.Target === target);if (!mount) throw new Error(`helper has nothing mounted at ${target}`);- return { volume: this.volume(mount.Source), readOnly: Boolean(mount.ReadOnly) };+ return { volume: mount.Type === "bind" ? this.folder(mount.Source) : this.volume(mount.Source), readOnly: Boolean(mount.ReadOnly) };};const writable = (target: string) => {const found = mounted(target);diff --git a/connector/test/install-script.test.ts b/connector/test/install-script.test.tsindex d737c2da99..a3e14be1a6 100644--- a/connector/test/install-script.test.ts+++ b/connector/test/install-script.test.ts@@ -15,7 +15,7 @@ afterEach(() => {});/** Runs install.sh with stand-ins for docker, id and apparmor_parser that record what they were asked to do. */-function run(args: string[], options: { uid?: number; env?: Record<string, string> } = {}) {+function run(args: string[], options: { uid?: number; env?: Record<string, string>; ownServer?: boolean } = {}) {const dir = mkdtempSync(join(tmpdir(), "omb-install-"));dirs.push(dir);const bin = join(dir, "bin");@@ -41,17 +41,28 @@ esac`);writeFileSync(join(audit, "audit.jsonl"), "{}\n");writeFileSync(join(etc, SECCOMP_FILE), "{}");writeFileSync(join(apparmor, APPARMOR_PROFILE), "profile");+ const install = join(dir, "opt-openmausbot");+ const update = join(dir, "update");+ const sbin = join(dir, "sbin");+ const systemd = join(dir, "systemd");+ for (const made of [install, join(install, "data"), update, sbin, systemd]) mkdirSync(made);+ if (options.ownServer) {+ writeFileSync(join(install, "compose.yaml"), "name: openmausbot\n");+ writeFileSync(join(install, "data", "chats.json"), "theirs");+ for (const file of [join(update, "runner"), join(sbin, "mausbot-update-runner"), join(systemd, "mausbot-update.path"), join(systemd, "mausbot-update.service")]) writeFileSync(file, "1\n");+ }const result = spawnSync("sh", [SCRIPT, ...args], {encoding: "utf8",env: {PATH: `${bin}:/usr/bin:/bin`, MAUSBOT_ETC_DIR: etc, MAUSBOT_APPARMOR_DIR: apparmor, MAUSBOT_AUDIT_DIR: audit,+ MAUSBOT_INSTALL_DIR: install, MAUSBOT_UPDATE_DIR: update, MAUSBOT_SBIN_DIR: sbin, MAUSBOT_SYSTEMD_DIR: systemd,MAUSBOT_ADMIN_URL: "https://cloud.example.test", MAUSBOT_CONNECTOR_IMAGE: `ghcr.io/milind-soni/mausbot-connector@sha256:${"1".repeat(64)}`,...options.env,},timeout: 30_000,});const calls = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : [];- return { ...result, calls, etc, apparmor, audit };+ return { ...result, calls, etc, apparmor, audit, install, update, sbin, systemd };}describe("install.sh", () => {@@ -129,4 +140,31 @@ describe("install.sh", () => {expect(odd.stderr).toContain("That code doesn't look right. Copy the install command from MausBot again.");expect(odd.calls).toEqual([]);});++ it("starts a customer-run connector with its mode and the updater's folder, and only where MausBot is already installed", () => {+ expect(script).toContain('set -- "$@" -e MAUSBOT_MODE=customer-run -v "$UPDATE_DIR:/var/lib/mausbot/update"');+ expect(PATHS.update).toBe("/var/lib/mausbot/update");+ expect(script).toContain('INSTALL_DIR="${MAUSBOT_INSTALL_DIR:-/opt/openmausbot}"');+ expect(script).toContain("PathExists=$UPDATE_DIR/request");+ expect(script).toContain("ExecStart=$SBIN_DIR/$UPDATE_RUNNER");+ });++ it.skipIf(!posix)("refuses --customer-run where MausBot is not installed, before touching a thing", () => {+ const refused = run(["--customer-run", "MB-1A2B-3C4D"]);+ expect(refused.status).toBe(1);+ expect(refused.stderr).toContain(`MausBot isn't installed in ${refused.install} yet. Install it first with the server's install command, then run this again to connect it.`);+ expect(refused.calls).toEqual([]);+ });++ it.skipIf(!posix)("disconnecting a server its owner installed removes the connector and the updater, and leaves that MausBot and its data alone", () => {+ const result = run(["uninstall", "--delete-data"], { ownServer: true });+ expect(result.status, result.stderr).toBe(0);+ expect(result.calls).toContain(`docker rm -f ${NAMES.connector} ${NAMES.connectorNext}`);+ expect(result.calls.filter((call) => /mausbot-home|mausbot-data|openmausbot|compose/.test(call))).toEqual([]);+ expect(readFileSync(join(result.install, "data", "chats.json"), "utf8")).toBe("theirs");+ expect(existsSync(join(result.install, "compose.yaml"))).toBe(true);+ for (const gone of [result.update, join(result.sbin, "mausbot-update-runner"), join(result.systemd, "mausbot-update.path"), join(result.systemd, "mausbot-update.service")]) expect(existsSync(gone), gone).toBe(false);+ expect(result.stdout).toContain(`Your MausBot in ${result.install} and its data were not touched, and it keeps running.`);+ expect(existsSync(join(result.apparmor, APPARMOR_PROFILE))).toBe(true);+ });});diff --git a/connector/test/update-runner.test.ts b/connector/test/update-runner.test.tsnew file mode 100644index 0000000000..9a1f3caa30--- /dev/null+++ b/connector/test/update-runner.test.ts@@ -0,0 +1,73 @@+import { spawnSync } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { UPDATE_FILES } from "../src/adopted-home.ts";+import { CUSTOMER_HOME_IMAGE } from "../src/customer-run.ts";++const SCRIPT = join(import.meta.dirname, "..", "host", "mausbot-update-runner.sh");+const IMAGE = `ghcr.io/milind-soni/openmausbot@sha256:${"b".repeat(64)}`;+const posix = process.platform !== "win32";+const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/** Runs the runner on a request, beside an update.sh that records how it was called and exits with `exit`. */+function run(request: string | null, options: { exit?: number; updater?: boolean } = {}) {+ const dir = mkdtempSync(join(tmpdir(), "omb-update-runner-"));+ dirs.push(dir);+ const update = join(dir, "update");+ const install = join(dir, "opt-openmausbot");+ mkdirSync(update);+ mkdirSync(install);+ const called = join(dir, "called");+ if (options.updater !== false) {+ writeFileSync(join(install, "update.sh"), `printf '%s\\n' "$*" >> "${called}"\nexit ${options.exit ?? 0}\n`);+ chmodSync(join(install, "update.sh"), 0o755);+ }+ if (request !== null) writeFileSync(join(update, UPDATE_FILES.request), request);+ const result = spawnSync("sh", [SCRIPT], { encoding: "utf8", env: { PATH: "/usr/bin:/bin", MAUSBOT_UPDATE_DIR: update, MAUSBOT_INSTALL_DIR: install }, timeout: 30_000 });+ const answer = existsSync(join(update, UPDATE_FILES.result)) ? readFileSync(join(update, UPDATE_FILES.result), "utf8") : null;+ return { result, answer, calls: existsSync(called) ? readFileSync(called, "utf8").trim().split("\n") : [], install, pending: existsSync(join(update, UPDATE_FILES.request)) };+}++describe.skipIf(!posix)("mausbot-update-runner.sh", () => {+ it("is plain POSIX sh and accepts the image the connector accepts", () => {+ expect(spawnSync("sh", ["-n", SCRIPT]).status).toBe(0);+ expect(readFileSync(SCRIPT, "utf8")).toContain("'ghcr\\.io/milind-soni/openmausbot@sha256:[0-9a-f]{64}'");+ expect(CUSTOMER_HOME_IMAGE.source).toBe("^ghcr\\.io\\/milind-soni\\/openmausbot@sha256:[0-9a-f]{64}$");+ });++ it("hands a request to the install's own update.sh with the image, and writes down how it ended", () => {+ const done = run(`id=u1\nimage=${IMAGE}\n`);+ expect(done.result.status).toBe(0);+ expect(done.calls).toEqual([`--dir ${done.install} --image ${IMAGE}`]);+ expect(done.answer).toBe("id=u1\ncode=0\n");+ expect(done.pending).toBe(false);+ expect(run(`id=u2\nimage=${IMAGE}\n`, { exit: 1 }).answer).toBe("id=u2\ncode=1\n");+ expect(run(`id=u3\nimage=${IMAGE}\n`, { exit: 2 }).answer).toBe("id=u3\ncode=2\n");+ });++ it("runs nothing for an image that is not MausBot's server image by digest, whatever the request says", () => {+ for (const image of ["ghcr.io/milind-soni/openmausbot:latest", "ghcr.io/someone/openmausbot@sha256:" + "b".repeat(64), `${IMAGE} --replace-local-build`, `${IMAGE};reboot`, ""]) {+ const refused = run(`id=u1\nimage=${image}\n`);+ expect(refused.calls, image).toEqual([]);+ expect(refused.answer, image).toBe("id=u1\ncode=4\n");+ }+ const odd = run(`id=u1;reboot\nimage=${IMAGE}\n`);+ expect(odd.calls).toEqual([]);+ expect(odd.answer).toBeNull();+ expect(odd.pending).toBe(false);+ });++ it("answers 127 when the install has no update.sh, and does nothing without a request", () => {+ expect(run(`id=u1\nimage=${IMAGE}\n`, { updater: false }).answer).toBe("id=u1\ncode=127\n");+ const idle = run(null);+ expect(idle.result.status).toBe(0);+ expect(idle.answer).toBeNull();+ expect(idle.calls).toEqual([]);+ });+});diff --git a/docs/design/self-hosted-design.md b/docs/design/self-hosted-design.mdindex 112abd4175..66ddbdf64e 100644--- a/docs/design/self-hosted-design.md+++ b/docs/design/self-hosted-design.md@@ -22,9 +22,13 @@ A standalone server becomes connected by enrolling the connector. No reinstall,- **Home**: the server image our own Clouds run (`ghcr.io/milind-soni/openmausbot`). This repository.- **Connector** (`connector/`): enrols with a one-time code, holds its own Ed25519 key, keeps one outbound WebSocket- and runs only a fixed job list: `start`, `stop`, `restart`, `update`, `status`, `backup`, `restore`, `export-disk`,- `import-disk`, `host-health`, `self-update`. No shell, no command of its own choosing, no read of a file by path. In- this repository, so customers can read what it can do.+ and runs only a fixed job list. No shell, no command of its own choosing, no read of a file by path. In this+ repository, so customers can read what it can do. It has two modes, chosen on the server when it enrols:+ - `customer-run`, for a server its owner installed: nine jobs (`start`, `stop`, `restart`, `update`, `status`,+ `backup`, `restore`, `host-health`, `self-update`), four requests it answers itself, and a reduced report. The+ whole list is `connector/src/customer-run.ts`. This is the mode of the Business self-hosted plan.+ - `operated`, for a server we run a Team Cloud on: those jobs plus `export-disk` and `import-disk`, a `start` that+ carries the image and the settings, and the Admin's signed requests to the home, pairing among them.- **Installer**: one script with a preflight. This repository.- **Paid-only features** (SSO, seat checks): `enterprise/` in this repository, under its source-available licence.- **Control plane**: our Admin, in a private repository: enrolment, entitlements, update scheduling, health, billing,@@ -46,7 +50,7 @@ A standalone server becomes connected by enrolling the connector. No reinstall,The published lists of principles 5 and 6 are the docs page[What a connected server shares](../../apps/docs/content/docs/self-hosting/connected-servers.mdx). It describes the-code as it is, including where the code does not meet these two principles yet.+`customer-run` mode as the code is, including what is still planned.## Updates@@ -91,49 +95,102 @@ Ubuntu 22.04 and 24.04, x86-64, Docker. arm64 after it is tested.The Coolify hosted-workspace path (never proven on a real install). `fleet` stays but is not the business offering.+## The customer-run mode++Decided: the server installer brings MausBot; the connector attaches to that install and the Admin never starts it.++- **Chosen on the server.** `connector/install.sh` picks `customer-run` when `/opt/openmausbot/compose.yaml` exists+ and starts the connector with `MAUSBOT_MODE=customer-run`; the enrolment writes the mode into the connector's state.+ The stricter of the two always wins, and nothing the Admin sends changes it. A connector started in `operated` mode+ refuses to enrol where the owner's MausBot already runs.+- **Enforced on the server, three times over for jobs.** A job outside the list is refused as it arrives+ (`checkCustomerRunJob`), again at the desk every job passes through (`jobDesk`), and the home the connector attached+ to has no code path for it (`AdoptedHome`). Each refusal is a line in the audit log.+- **Requests never reach the home.** The connector answers the four listed requests itself from the facts it already+ reports (`customer-run-requests.ts`). Everything else is answered 403 and logged.+- **The report is rebuilt, not filtered.** `reducedHeartbeat` and `reducedReply` copy named fields; every string is an+ enumerated code or matches a pattern (a version, an image reference, a machine's own name for itself). A failed job+ sends its code and a fixed sentence; the reason stays in the audit log.+- **Adoption.** `AdoptedHome` finds the Compose project `openmausbot` (service `omb`, Caddy in front, `/data` bound+ to a folder). `start`, `stop` and `restart` start and stop those containers. `backup` and `restore` copy that folder+ to and from Docker volumes on the same server with helpers run from the home's own image.+- **Update: the server's own updater.** The connector never recreates the owner's containers and never writes the+ owner's `.env`. It leaves `id` and `image` in `/var/lib/mausbot/update/request`; a systemd path unit on the host runs+ `mausbot-update-runner`, which checks the image again and runs `/opt/openmausbot/update.sh --image <digest>`; the+ connector reads the exit code. So a connected update and a hand-run update are the same code, with the same copy,+ health check, rollback and journal. Chosen over driving Compose from inside the connector (which would need the+ install folder writable in a container and a Compose binary in the image) and over recreating containers through+ Docker's API (which would drift from the Compose file).+- **Seat count.** The home answers `GET /api/seats` with a number, to an admin session or its own loopback. The+ connector reads it with one fixed command run inside the home's container, together with `/api/health` and the+ version.+- **Pause.** `mausbot-connector pause` writes a file in the connector's state; the running connector reads it before+ every job and request.++### What the Admin must know++Backward compatible: a field is only ever added, and only by a customer-run server.++| Where | Field | Meaning |+|---|---|---|+| `EnrollRequest` (`POST /api/cloud/box/v1/enroll`) | `mode: "customer-run"` | Present only for a customer-run server; absent means `operated`, exactly the request sent before. Store it with the box |+| `Heartbeat.heartbeat` | `mode: "customer-run"`, `paused: boolean`, `seats: number \| null` | Present only for a customer-run server. `host`, `home` and `connector` keep their shape; `host.checks[]` carries `id`, `ok` and `warning` without `fix`; `home.health.box` is always null |+| `JobErrorCode` | `refused_by_mode`, `paused`, `update_unavailable`, `update_not_started` | Only from a customer-run server. Its error `message` is a fixed sentence per code |++For a customer-run box the Admin should: send `start` with no arguments; send `update` with+`ghcr.io/milind-soni/openmausbot@sha256:…` (the server image, not the Cloud home image); never send `export-disk`,+`import-disk` or a request other than `GET /v1/health`, `/v1/version`, `/v1/seats`, `/v1/update`; send+`schedule.image: null` in the signed config (a Cloud home image there is accepted, any other is ignored with the whole+config); and sign people in by sending them to the server's own address, never by pairing.+## Status against the code-Read at commit `542f8e55f`. "Built" means the code is in this repository; it does not mean a customer can buy it.+Read at the commit that adds the customer-run mode. "Built" means the code is in this repository; it does not mean a customer can buy it.### Built-- The connector: enrolment with a one-time code, its own Ed25519 key, pinned Admin keys, one outbound WebSocket, the- eleven jobs above, each signed for one server and refused 15 minutes after signing (`connector/src/protocol.ts`,+- The connector: enrolment with a one-time code, its own Ed25519 key, pinned Admin keys, one outbound WebSocket, a+ fixed job list, each job signed for one server and refused 15 minutes after signing (`connector/src/protocol.ts`,`agent.ts`, `jobs.ts`).+- The customer-run mode described above: the job and request lists, the reduced report with a seat count, the mode in+ the enrolment handshake, pause, and attaching to an installer-made server (`customer-run.ts`,+ `customer-run-requests.ts`, `adopted-home.ts`, `host/mausbot-update-runner.sh`, `server/routes/seats.ts`).- A server the team's Owner has not accepted answers only `status` and `host-health` (`agent.ts`).- The audit log on the customer's server, `/var/log/mausbot/audit.jsonl`: one line per job, step, result and Adminrequest, each carrying the hash of the line before it. A job that changes something is refused when it cannot belogged (`audit.ts`, `jobs.ts`).- The owner's policy file, `/etc/mausbot/policy.json`: the job kinds we may run, and a hold on updates (`policy.ts`).-- `update` with a safety copy of the data and a rollback of image and data when the new version does not report- healthy (`home.ts`).+- On an operated server, `update` with a safety copy of the data and a rollback of image and data when the new+ version does not report healthy (`home.ts`).- The connector's own installer with a preflight, `connector/install.sh`, which the Admin is to serve with its addressand the connector's image digest filled in.- The offline licence check for paid features (`enterprise/server/license.ts`).### Different from this document-- **Job list.** An earlier draft listed nine jobs. The code has eleven: `export-disk` uploads a gzip archive of the- whole data directory to the Admin, and `import-disk` replaces the data directory with an archive from an HTTPS- address. They move a Cloud between our servers and a customer's. `export-disk` sends everything people wrote, so- principle 6 does not hold while a server's policy allows it.-- **Requests to the home.** Besides jobs, the Admin opens streams on the same connection, each carrying one HTTP- request for the home (`home-requests.ts`). The home answers only requests signed with its own secret, among them- `POST /api/cloud/pairing`, which opens a sign-in for a named member. Each request is in the audit log. The policy- file does not cover them. They are not on the job list of principle 5.-- **Which image.** The connector starts `ghcr.io/milind-soni/openmausbot-cloud-home` by digest, with the Cloud- settings the Admin sends, on its own data volume (`mausbot-data`). The standalone install runs- `ghcr.io/milind-soni/openmausbot` on its own data. Enrolling the connector on a standalone server therefore does- not connect that server: it prepares a second home beside it. "No reinstall, no data move" is planned.-- **What leaves the server.** A connected home reports more than version, health and job results; the docs page above- lists it. The connector does not send a seat count.-- **Sign-in during our outage.** The MausBot dashboard signs a person in to a connected home through a pairing the- Admin sends, so that way in stops while we are down or the connector is stopped. Sessions the home already issued- keep working. Principle 2 for sign-in is planned.-- **Pausing remote management.** Today that is the policy file (`"jobs": []` refuses every job but the connector's own- update) or stopping the connector. A switch in the product is planned.+- **Updates on a connected server need `update.sh` in place.** The connector hands an update to+ `/opt/openmausbot/update.sh`. The server installer does not put it there yet, so until it does the `update` job is+ refused with `update_unavailable` and nothing changes.+- **Backups stay on the server.** `backup` copies the data to a Docker volume on the same server. A bucket the+ customer configures is phase 2.+- **Pausing is a command.** `mausbot-connector pause`; a switch in Settings is planned. The heartbeat keeps going+ while paused.+- **Emailed sign-in codes pass through us unless the customer sets a mail server.** Pairing codes never do. So+ principle 2 holds for sign-in by pairing code always, and by emailed code only with `OMB_SIGNIN_SMTP_URL`.+- **The home's own traffic is unchanged by connecting.** A report a person sends by tagging `@devs` carries their+ message, the bot's name and recent log lines to us, and its status is asked hourly while it is open; browser+ analytics are on until a person turns them off. Principle 6 is about the connector; these are the docs page's+ "What your server itself still sends".+- **`self-update` can replace the rules.** A new connector is new code from our registry, pinned by digest and not+ yet signed. The owner's policy file can leave `self-update` out on a customer-run server.+- **Only one layout is adopted.** Docker Compose from the server installer, the published image, data in a folder. A+ source build or an npm install cannot be connected.+- **The seat count is a lower bound for a domain entry.** `@example.com` on the sign-in list counts each person from+ it once they have signed in.- **The update window.** The connector receives and keeps the window the Admin signs, and runs an update when theAdmin sends the job. Choosing the window is the Admin's.+- **Not run on a real server yet.** The customer-run path is covered by unit tests and a run against a local Docker+ with a stand-in server; the connector's end-to-end run (`connector/e2e/run.sh`) still covers only the operated mode.### In reviewdiff --git a/server/index.ts b/server/index.tsindex 5aeadecdab..ae8acd07d5 100644--- a/server/index.ts+++ b/server/index.ts@@ -594,7 +594,7 @@ import { createBotSkillsRoutes } from "./routes/bot-skills.ts";import { createSkillShareRoutes } from "./routes/skill-share.ts";import { createTeamContextRoutes } from "./routes/team-context.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 { createTimeZoneRoutes } from "./routes/time-zone.ts";+import { createUpdateCheckRoutes, serverUpdateChecker } 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";@@ -12216,7 +12216,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 ? 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: CLOUD_PERSONAL })); 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) }) }), 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 ? 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: CLOUD_PERSONAL })); 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));if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));ROUTES.push(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 (ownerOrAdmin(auth) && 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), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), 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; } }) }));diff --git a/server/request-auth.ts b/server/request-auth.tsindex b4e677282d..54c2a0d230 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -41,6 +41,7 @@ export const SERVICE_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Re{ methods: ["GET"], path: /^\/api\/auth\/session$/ },{ methods: ["GET"], path: /^\/api\/edition$/ },{ methods: ["GET"], path: /^\/api\/brand$/ },+ { methods: ["GET"], path: /^\/api\/seats$/ }, // a number: the MausBot connector on the same server reads it{ methods: ["GET"], path: /^\/api\/bots$/ },{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/messages$/ },{ methods: ["GET"], path: /^\/api\/attachments\/[\w.-]+$/ },diff --git a/server/routes/seats.test.ts b/server/routes/seats.test.tsnew file mode 100644index 0000000000..21a224a68a--- /dev/null+++ b/server/routes/seats.test.ts@@ -0,0 +1,52 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { json, readBody } from "../harness/http.ts";+import { requiredScope, serviceAllowed } from "../request-auth.ts";+import { createSeatsRoutes, seatCount } from "./seats.ts";+import { dispatchRoutes } from "./table.ts";++const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++describe("seat count", () => {+ it("counts people once each: listed addresses and signed-in addresses, never devices or API tokens", () => {+ const list = { admins: ["[email protected]"], members: ["[email protected]", "@example.test"] };+ expect(seatCount(list, [])).toBe(2);+ expect(seatCount(list, [{ email: "[email protected]" }, { email: "[email protected]" }, {}])).toBe(2);+ expect(seatCount(list, [{ email: "[email protected]" }])).toBe(3);+ expect(seatCount(list, [{ email: "[email protected]", token: true }])).toBe(2);+ });++ it("counts a server with paired devices and no address as one person, and an empty one as none", () => {+ expect(seatCount({ admins: [], members: [] }, [{}, {}, {}])).toBe(1);+ expect(seatCount({ admins: [], members: [] }, [])).toBe(0);+ expect(seatCount({ admins: [], members: ["@example.test"] }, [])).toBe(0);+ });++ it("answers with the number alone, to an admin and to the server's own loopback, never to a chat-only session", async () => {+ const routes = [createSeatsRoutes({+ signInList: () => ({ admins: ["[email protected]"], members: [] }),+ sessions: () => [{ email: "[email protected]" }],+ })];+ 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 });+ if (!handled) json(res, 404, {});+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const response = await fetch(`${base}/api/seats`);+ const text = await response.text();+ expect(JSON.parse(text)).toEqual({ seats: 2 });+ expect(text).not.toContain("@");+ expect((await fetch(`${base}/api/seats`, { method: "POST" })).status).toBe(404);+ expect(requiredScope("GET", "/api/seats")).toBe("admin");+ expect(serviceAllowed("GET", "/api/seats")).toBe(true);+ expect(serviceAllowed("POST", "/api/seats")).toBe(false);+ });+});diff --git a/server/routes/seats.ts b/server/routes/seats.tsnew file mode 100644index 0000000000..4ae9a1fb97--- /dev/null+++ b/server/routes/seats.ts@@ -0,0 +1,34 @@+// GET /api/seats: how many people can sign in to this server. A number and nothing about who: the MausBot connector on+// a connected server reads it from the server's own loopback and reports it, so a plan's seats can be counted.+import type { SignInAllowList } from "../account-signin.ts";+import type { PublicSession } from "../sessions.ts";+import { PASS, type RouteHandler } from "./table.ts";++/**+ * People, not devices: each address on the sign-in list, and each address that holds a session (someone let in by an+ * `@domain` entry counts once they have signed in). Devices paired by code carry no address; they count as one person,+ * the server's owner, only while no address is known at all. API tokens are not people.+ */+export function seatCount(list: SignInAllowList, sessions: readonly Pick<PublicSession, "email" | "token">[]): number {+ const people = new Set<string>();+ for (const entry of [...list.admins, ...list.members]) if (!entry.startsWith("@")) people.add(entry.trim().toLowerCase());+ let paired = false;+ for (const session of sessions) {+ if (session.token) continue;+ if (session.email) people.add(session.email.trim().toLowerCase());+ else paired = true;+ }+ return people.size > 0 ? people.size : paired ? 1 : 0;+}++export interface SeatsRouteDeps {+ signInList(): SignInAllowList;+ sessions(): readonly Pick<PublicSession, "email" | "token">[];+}++export function createSeatsRoutes(deps: SeatsRouteDeps): RouteHandler {+ return async ({ res, path, method, json }) => {+ if (path !== "/api/seats" || method !== "GET") return PASS;+ return json(res, 200, { seats: seatCount(deps.signInList(), deps.sessions()) });+ };+}