Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
MausBot connector: run a Cloud home on its owner's own server, over one outbound connection (#3732)
Milind Soni9cd48bc396cb
diff --git a/.gitattributes b/.gitattributesindex 0508856489..223ce9c15c 100644--- a/.gitattributes+++ b/.gitattributes@@ -7,6 +7,9 @@ shared/mascot-bodies.ts text eol=lf# git runs hooks through sh; a CRLF shebang line is "/bin/sh^M: bad interpreter" on every platform.scripts/git-hooks/* text eol=lfdeploy/podman/*.sh text eol=lf+# install.sh is piped to sh on a customer's server, and the AppArmor profile is loaded as it is.+connector/**/*.sh text eol=lf+connector/profiles/* text eol=lf# Vendor patch hashes and original notices must survive Windows checkout# byte-for-byte. Do not let core.autocrlf rewrite these reviewed inputs.third_party/browser/** text eol=lfdiff --git a/.github/workflows/connector-e2e.yml b/.github/workflows/connector-e2e.ymlnew file mode 100644index 0000000000..ac5c908bfc--- /dev/null+++ b/.github/workflows/connector-e2e.yml@@ -0,0 +1,59 @@+name: Connector e2e++# The MausBot connector on a stock ubuntu-24.04 runner, as a person installs it on their own server: a fake Admin,+# install.sh with a one-time code, then start, update, an unclean kill and a forced rollback (connector/e2e/run.sh).+# It pulls published home images and talks to no production service.+on:+ pull_request:+ paths:+ - connector/**+ - .github/workflows/connector-e2e.yml+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: connector-e2e-${{ github.ref }}+ cancel-in-progress: true++jobs:+ e2e:+ name: install, start, update and roll back on Ubuntu 24.04+ runs-on: ubuntu-24.04+ timeout-minutes: 40+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: pnpm/action-setup@ff378ebe6b225b0680b81c1ad4498ae0d1d3a5e3 # v6.0.10+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 24+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ env:+ ELECTRON_SKIP_BINARY_DOWNLOAD: "1"+ - name: The connector's unit tests, on Linux and Node 24+ run: pnpm exec vitest run connector/test --maxWorkers=2+ - name: Leave the 20 GB a server needs free for Docker+ # The installer refuses a server with less, as it should; a runner sometimes has less to start with.+ run: |+ set -euo pipefail+ free_gb() { df -BG --output=avail /var/lib/docker | tail -n 1 | tr -dc '0-9'; }+ echo "free for Docker: $(free_gb) GB"+ if [ "$(free_gb)" -lt 30 ]; then+ sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup /opt/hostedtoolcache/CodeQL+ echo "free for Docker now: $(free_gb) GB"+ fi+ - name: Install, start, update, kill and roll back+ env:+ OUT: ${{ runner.temp }}/connector-e2e+ run: bash connector/e2e/run.sh+ - name: Keep the evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: connector-e2e+ path: ${{ runner.temp }}/connector-e2e+ retention-days: 14diff --git a/.github/workflows/connector-release.yml b/.github/workflows/connector-release.ymlnew file mode 100644index 0000000000..7a438b609b--- /dev/null+++ b/.github/workflows/connector-release.yml@@ -0,0 +1,67 @@+name: Connector image++# The MausBot connector (connector/), published with every OpenMausBot release as+# ghcr.io/milind-soni/mausbot-connector for linux/amd64 and linux/arm64. The+# Admin pins it by digest; the summary prints it. Only a release tag publishes:+# no pull request starts this, and a manual run on a branch builds nothing.+on:+ # release.yml dispatches this on the tag it just published: a tag created+ # with the workflow token never fires push events on its own.+ workflow_dispatch:+ push:+ tags: ["v*"]++permissions:+ contents: read++jobs:+ publish:+ name: publish to GHCR+ if: startsWith(github.ref, 'refs/tags/v')+ runs-on: ubuntu-latest+ timeout-minutes: 30+ permissions:+ contents: read+ packages: write+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Prove the image runs before it is published+ run: |+ set -euo pipefail+ docker build -t mausbot-connector:release connector+ test "$(docker run --rm mausbot-connector:release version)" = "$(sed -n 's/^export const CONNECTOR_VERSION = "\(.*\)";$/\1/p' connector/src/settings.ts)"+ docker run --rm --entrypoint sh mausbot-connector:release -c 'bwrap --version && test -s /app/profiles/seccomp-omb-home.json && test -s /app/profiles/omb-home-narrow.apparmor && test -s /app/install.sh'+ - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0+ - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0+ - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}+ - id: repo+ # Image references must be lowercase; the owner's name need not be.+ run: echo "owner=${GITHUB_REPOSITORY_OWNER,,}" >> "$GITHUB_OUTPUT"+ - id: meta+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0+ with:+ images: ghcr.io/${{ steps.repo.outputs.owner }}/mausbot-connector+ tags: |+ type=sha,format=long+ type=ref,event=tag+ - id: build+ uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0+ with:+ context: connector+ platforms: linux/amd64,linux/arm64+ push: true+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha,scope=connector+ cache-to: type=gha,scope=connector,mode=max+ - name: Connector image digest+ env:+ DIGEST: ${{ steps.build.outputs.digest }}+ IMAGE: ghcr.io/${{ steps.repo.outputs.owner }}/mausbot-connector+ run: echo "MAUSBOT_CONNECTOR_IMAGE=${IMAGE}@${DIGEST}" | tee -a "$GITHUB_STEP_SUMMARY"diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 69a4982826..1980bb2465 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -498,7 +498,7 @@ jobs:cancel-in-progress: falsepermissions:contents: write- # to dispatch the npm and Docker publishes on the new tag+ # to dispatch the npm, Docker and connector publishes on the new tagactions: writesteps:- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1@@ -701,9 +701,9 @@ jobs:--repo milind-soni/openmausbot-releases --json isDraft --jq .isDraft | grep -q falseecho "v$VERSION is live on the canonical feed and its legacy updater bridge"# Publishing created the tag with this workflow's token, and GitHub- # starts no workflow from events that token creates. Start the two+ # starts no workflow from events that token creates. Start the# tag-driven publishes by hand, on the tag, so they see refs/tags/v*.- for workflow in npm-package.yml docker.yml; do+ for workflow in npm-package.yml docker.yml connector-release.yml; doGH_TOKEN="$CANONICAL_TOKEN" gh workflow run "$workflow" --repo "$GITHUB_REPOSITORY" --ref "v$VERSION"done- echo "dispatched the npm package and Docker image publishes on v$VERSION"+ echo "dispatched the npm package, Docker image and connector image publishes on v$VERSION"diff --git a/connector/.dockerignore b/connector/.dockerignorenew file mode 100644index 0000000000..688dc37a67--- /dev/null+++ b/connector/.dockerignore@@ -0,0 +1,3 @@+test+e2e+*.test.tsdiff --git a/connector/Dockerfile b/connector/Dockerfilenew file mode 100644index 0000000000..66ea6564eb--- /dev/null+++ b/connector/Dockerfile@@ -0,0 +1,22 @@+# The MausBot connector, published as ghcr.io/milind-soni/mausbot-connector for linux/amd64 and linux/arm64. It runs on+# a server of its owner's with the Docker socket, its state volume and /etc/mausbot (read-only), and talks only outward.+# Node runs its TypeScript as it is; it has no npm dependencies. bubblewrap is here only for the box probe, which runs+# from this image with the home's own security settings.+FROM node:24-bookworm-slim+RUN apt-get update \+ && apt-get install -y --no-install-recommends bubblewrap ca-certificates \+ && rm -rf /var/lib/apt/lists/* \+ && bwrap --version+WORKDIR /app+COPY package.json ./package.json+COPY profiles ./profiles+COPY install.sh ./install.sh+COPY src ./src+RUN printf '#!/bin/sh\nexec node --disable-warning=ExperimentalWarning /app/src/main.ts "$@"\n' > /usr/local/bin/mausbot-connector \+ && chmod 0755 /usr/local/bin/mausbot-connector \+ && chmod -R go-w /app \+ && mausbot-connector version+ENV NODE_ENV=production+USER root+ENTRYPOINT ["mausbot-connector"]+CMD ["run"]diff --git a/connector/e2e/run.sh b/connector/e2e/run.shnew file mode 100644index 0000000000..c12d7ebef7--- /dev/null+++ b/connector/e2e/run.sh@@ -0,0 +1,185 @@+#!/usr/bin/env bash+# The connector end to end on a stock Ubuntu 24.04 host with Docker and AppArmor on, installed as a person installs it:+# a fake Admin (connector/test/fake-admin.ts) mints a one-time code; install.sh checks the host, installs the profiles,+# starts the connector and enrols; then start (the box passes every check), update to another digest, an unclean kill+# started again, an update forced to fail rolled back (image and data), and uninstall keeping the data.+# Nothing reaches a production service: the home's connected-apps broker points at a closed loopback port and its+# HighLevel relay is off; the Admin is the fake one on loopback.+# OUT=<evidence folder> bash connector/e2e/run.sh+set -euo pipefail+ROOT=$(cd "$(dirname "$0")/../.." && pwd)+OUT=${OUT:-$(mktemp -d)}+mkdir -p "$OUT"+# Two published homes with the same 32-check bot box (v0.1.129 and v0.1.130).+HOME_A=ghcr.io/milind-soni/openmausbot-cloud-home@sha256:2909b6a9e02565f524db94d9ea5759f0290c8c90fc9d6e753d7f284ca5e5ba75+HOME_B=ghcr.io/milind-soni/openmausbot-cloud-home@sha256:495c1bd14a5677a1f9e8b6f8560e4971093e64bb07934fb8e8920de9f66da9d6+CONNECTOR_IMAGE=mausbot-connector:e2e+PORT=18990+ADMIN="http://127.0.0.1:$PORT"+CODE="MB-E2E-$(openssl rand -hex 4 | tr a-f A-F)"+SECRET=$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n')+if [ -n "${GITHUB_ACTIONS:-}" ]; then echo "::add-mask::$SECRET"; fi+INSTALL_ENV=(MAUSBOT_ADMIN_URL="$ADMIN" MAUSBOT_CONNECTOR_IMAGE="$CONNECTOR_IMAGE" MAUSBOT_UPDATE_WAIT_S=90)++step() { printf '\n== %s\n' "$*"; }+fail() {+ printf 'FAILED: %s\n' "$*" >&2+ docker logs mausbot-connector >"$OUT/connector.log" 2>&1 || true+ docker logs mausbot-home 2>&1 | tail -n 80 >"$OUT/home.log" || true+ exit 1+}+control() { curl -sS --max-time 30 "$ADMIN/control/$1"; }+job() { # type args-json [id] → the reply, as the Admin receives it+ curl -sS --max-time 1800 -X POST -H 'content-type: application/json' \+ --data "$(jq -cn --arg type "$1" --argjson args "$2" --arg id "${3:-}" '{type: $type, args: $args} + (if $id == "" then {} else {id: $id} end)')" \+ "$ADMIN/control/job"+}+expect() { # jq-filter json what+ jq -e "$1" >/dev/null <<<"$2" || fail "$3: $(head -c 800 <<<"$2")"+}+box_checks() { # the status reply once the home's box has run its self-check+ local status=""+ for _ in $(seq 1 60); do+ status=$(job status '{}')+ if jq -e '.result.home.health.box.checks != null' >/dev/null <<<"$status"; then break; fi+ sleep 2+ done+ printf '%s' "$status"+}+home_settings() { # the home container's settings, without its environment (it holds the secret)+ docker inspect -f '{"apparmor": {{json .AppArmorProfile}}, "host": {{json .HostConfig}}, "stopTimeout": {{json .Config.StopTimeout}}, "image": {{json .Config.Image}}}' mausbot-home+}+EVENTS=""+cleanup() {+ if [ -n "$EVENTS" ]; then kill "$EVENTS" 2>/dev/null || true; fi+ kill "$ADMIN_PID" 2>/dev/null || true+}++step "the connector image, as the release builds it"+docker build -q -t "$CONNECTOR_IMAGE" "$ROOT/connector" >/dev/null++step "a fake Admin with one one-time code"+node "$ROOT/connector/test/fake-admin.ts" "$PORT" "$CODE" >"$OUT/admin.log" 2>&1 &+ADMIN_PID=$!+trap cleanup EXIT+for _ in $(seq 1 30); do+ if control state >/dev/null 2>&1; then break; fi+ sleep 1+done+control state >/dev/null || fail "the fake Admin did not start: $(cat "$OUT/admin.log")"++step "install.sh with the code, as a person runs it"+sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" "$CODE" | tee "$OUT/install.txt"+[ "$(tail -n 1 "$OUT/install.txt")" = "Connected. Your server shows up in MausBot in a minute." ] || fail "install.sh did not end connected"+state=$(control state)+expect '.connected and (.servers | length) == 1' "$state" "enrolled once"+expect '.servers[0].host | .arch == "x86_64" and .apparmor and .userns and .cpus >= 2 and .diskGb >= 20 and (.docker | length) > 0' "$state" "enrolled with the host's facts"+expect '.servers[0].connector.protocol == 1 and .servers[0].connector.image == "mausbot-connector:e2e"' "$state" "enrolled with its identity"+state_dir=/var/lib/docker/volumes/mausbot-connector/_data+[ "$(sudo stat -c %a "$state_dir")" = 700 ] || fail "the connector's state folder is not root's alone"+[ "$(sudo stat -c %a "$state_dir/agent.json")" = 600 ] || fail "the agent token is not root's alone"++step "running it again repairs and stays connected, without a new code"+sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" | tee "$OUT/repair.txt"+[ "$(tail -n 1 "$OUT/repair.txt")" = "Connected. Your server shows up in MausBot in a minute." ] || fail "the repair did not end connected"+expect '(.servers | length) == 1 and .connections >= 2 and .connected' "$(control state)" "the same server, connected again"++step "a heartbeat with every check passing"+for _ in $(seq 1 40); do+ if [ "$(control state | jq '.heartbeats')" -ge 1 ]; then break; fi+ sleep 1+done+expect '.heartbeats >= 1 and .lastHeartbeat.host.arch == "x86_64" and ([.lastHeartbeat.host.checks[] | select(.ok | not)] | length) == 0 and (.lastHeartbeat.host.checks | any(.id == "box" and .ok))' "$(control state)" "the heartbeat"++ENV_JSON=$(jq -cn --arg secret "$SECRET" '{+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "e2e-connector-home", OMB_CLOUD_ADMIN_URL: "https://admin.e2e.invalid",+ OMB_PUBLIC_URL: "https://home.e2e.invalid", OMB_CLOUD_BOOTSTRAP_SECRET: $secret,+ OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_RELAY_URL: "off"+}')++step "start: the home runs with the bot box's settings, and the box passes every check"+reply=$(job start "$(jq -cn --arg image "$HOME_A" --argjson env "$ENV_JSON" '{image: $image, env: $env}')" start-1)+printf '%s\n' "$reply" >"$OUT/start.json"+expect ".ok and .result.home.state == \"running\" and .result.home.image == \"$HOME_A\" and .result.home.health.ok" "$reply" "start"+status=$(box_checks)+printf '%s\n' "$status" >"$OUT/status-start.json"+expect '.result.home.health.box | .box == "bwrap" and .checks == "32/32" and .failed == []' "$status" "the box passes 32/32"+settings=$(home_settings)+printf '%s\n' "$settings" >"$OUT/home-settings.json"+expect '.apparmor == "omb-home-narrow" and .stopTimeout == 30' "$settings" "the home's AppArmor profile and stop timeout"+expect '.host | .Init and .ShmSize == 536870912 and (.MaskedPaths // [] | length) == 0 and (.ReadonlyPaths // [] | length) == 0 and (.Privileged | not) and .OomScoreAdj == -800 and .RestartPolicy.Name == "no"' "$settings" "the home's container settings"+expect '.host | (.CapDrop | map(sub("^CAP_"; ""))) == ["ALL"] and (.CapAdd | map(sub("^CAP_"; "")) | sort) == ["CHOWN", "KILL", "SETGID", "SETUID"]' "$settings" "the home's capabilities"+expect '.host | .PortBindings["8080/tcp"] == [{"HostIp": "127.0.0.1", "HostPort": "8080"}] and (.SecurityOpt | any(startswith("seccomp="))) and (.SecurityOpt | any(. == "no-new-privileges=true" or . == "no-new-privileges"))' "$settings" "the home's port and seccomp"+docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' mausbot-home | grep -qx "OMB_COMPOSIO_BROKER_URL=http://127.0.0.1:9" || fail "the home could reach the production connected-apps broker"+docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' mausbot-home | grep -qx "OMB_HIGHLEVEL_RELAY_URL=off" || fail "the home could reach the production HighLevel relay"+docker exec -u maus mausbot-home sh -c 'echo kept > /data/e2e-marker'++step "update to another digest: a safety copy, a swap, and the new image's health"+reply=$(job update "$(jq -cn --arg image "$HOME_B" '{image: $image}')" update-1)+printf '%s\n' "$reply" >"$OUT/update.json"+expect ".ok and .result.previousImage == \"$HOME_A\" and .result.home.image == \"$HOME_B\" and .result.home.health.ok and .result.snapshot.kind == \"snapshot\"" "$reply" "update"+status=$(box_checks)+expect '.result.home.health.box.checks == "32/32"' "$status" "the box after the update"+[ "$(docker exec -u maus mausbot-home cat /data/e2e-marker)" = kept ] || fail "the data did not survive the update"+docker volume inspect mausbot-snapshot >/dev/null || fail "the update kept no safety copy"++step "a home killed uncleanly is started again on its volume"+docker kill -s KILL mausbot-home >/dev/null+for _ in $(seq 1 60); do+ if [ "$(docker inspect -f '{{.State.Running}}' mausbot-home 2>/dev/null)" = true ] && job status '{}' | jq -e '.result.home.health.ok' >/dev/null; then break; fi+ sleep 2+done+expect '.result.home.state == "running" and .result.home.health.ok' "$(job status '{}')" "the home after a SIGKILL"+docker logs mausbot-connector >"$OUT/connector.log" 2>&1+grep -q "the home stopped on its own (exit 137); starting it again" "$OUT/connector.log" || fail "the connector did not start the killed home again"+grep -q "cleared the data-directory lease records a stopped home left" "$OUT/connector.log" || fail "the connector did not clear the lease the killed home left"+[ "$(docker exec -u maus mausbot-home cat /data/e2e-marker)" = kept ] || fail "the data did not survive the kill"++step "an update forced to fail rolls back: the previous image, and the data as it was"+# The new home is frozen the moment it starts, so it never answers; what is written to the data after the swap must+# be gone once the rollback has put the safety copy back.+FIFO=$(mktemp -u)+mkfifo "$FIFO"+timeout 900 docker events --filter container=mausbot-home --filter event=start --format '{{.Actor.Attributes.image}}' >"$FIFO" &+EVENTS=$!+(+ while read -r started; do+ [ "$started" = "$HOME_A" ] || continue+ docker pause mausbot-home >/dev/null+ docker run --rm -v mausbot-data:/data --entrypoint sh "$HOME_B" -c 'echo lost > /data/e2e-after-swap'+ echo frozen >"$OUT/sabotaged"+ break+ done <"$FIFO"+) &+sleep 2+reply=$(job update "$(jq -cn --arg image "$HOME_A" '{image: $image}')" update-2)+printf '%s\n' "$reply" >"$OUT/rollback.json"+kill "$EVENTS" 2>/dev/null || true+EVENTS=""+rm -f "$FIFO"+[ -f "$OUT/sabotaged" ] || fail "the new home was never frozen, so this proved nothing: $reply"+expect ".ok == false and .error.code == \"update_rolled_back\" and .error.image == \"$HOME_B\"" "$reply" "the forced update"+status=$(job status '{}')+expect ".result.home.image == \"$HOME_B\" and .result.home.health.ok" "$status" "the previous image runs again"+[ "$(docker exec -u maus mausbot-home cat /data/e2e-marker)" = kept ] || fail "the data from before the update is gone"+if docker exec mausbot-home test -e /data/e2e-after-swap; then fail "what was written after the swap survived the rollback"; fi+status=$(box_checks)+expect '.result.home.health.box.checks == "32/32"' "$status" "the box after the rollback"++step "nothing secret in the connector's log"+docker logs mausbot-connector >"$OUT/connector.log" 2>&1+if grep -qF "$SECRET" "$OUT/connector.log"; then fail "the bootstrap secret reached the connector's log"; fi+if grep -q "ombs_" "$OUT/connector.log"; then fail "the agent token reached the connector's log"; fi++step "uninstall stops everything and keeps the data; --delete-data deletes it"+sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" uninstall | tee "$OUT/uninstall.txt"+for container in mausbot-connector mausbot-home; do+ if docker inspect "$container" >/dev/null 2>&1; then fail "$container is still there after uninstall"; fi+done+[ ! -e /etc/apparmor.d/omb-home-narrow ] || fail "the AppArmor profile is still installed"+[ "$(docker run --rm -v mausbot-data:/data --entrypoint cat "$HOME_B" /data/e2e-marker)" = kept ] || fail "uninstall did not keep the data"+docker volume inspect mausbot-snapshot >/dev/null || fail "uninstall did not keep the safety copy"+sudo env "${INSTALL_ENV[@]}" sh "$ROOT/connector/install.sh" uninstall --delete-data | tee -a "$OUT/uninstall.txt"+if docker volume inspect mausbot-data >/dev/null 2>&1; then fail "--delete-data kept the data"; fi++step "all passed"diff --git a/connector/install.sh b/connector/install.shnew file mode 100644index 0000000000..2f7fd3743f--- /dev/null+++ b/connector/install.sh@@ -0,0 +1,347 @@+#!/bin/sh+# MausBot on a server of your own: checks the server, installs the bot box's two security profiles, starts the MausBot+# 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>+# 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)+#+# MausBot serves this file with its own address and the connector's image (pinned by digest) filled in below.+set -eu++ADMIN_URL="${MAUSBOT_ADMIN_URL:-@MAUSBOT_ADMIN_URL@}"+CONNECTOR_IMAGE="${MAUSBOT_CONNECTOR_IMAGE:-@MAUSBOT_CONNECTOR_IMAGE@}"++ETC_DIR="${MAUSBOT_ETC_DIR:-/etc/mausbot}"+APPARMOR_DIR="${MAUSBOT_APPARMOR_DIR:-/etc/apparmor.d}"+PROFILE=omb-home-narrow+SECCOMP=seccomp-omb-home.json+CONNECTOR=mausbot-connector+CONNECTOR_NEXT=mausbot-connector-next+HOME_CONTAINER=mausbot-home+DATA_VOLUME=mausbot-data+STATE_VOLUME=mausbot-connector+SNAPSHOT_VOLUME=mausbot-snapshot+ROLE_LABEL=com.mausbot.role+MIN_DOCKER=24+MIN_CPUS=2+MIN_MEMORY_MB=3500+MIN_DISK_GB=20++say() { printf '%s\n' "$*"; }+note() { printf ' %s\n' "$*"; }+fail() {+ printf '\n%s\n' "$*" >&2+ exit 1+}++command_line() { # what to run again, as the person ran it+ printf 'curl -fsSL %s/install.sh | sudo sh -s -- %s' "$ADMIN_URL" "$*"+}++need_root() {+ [ "$(id -u)" = 0 ] || fail "Please run this as root: put sudo before sh, like this: $(command_line "$@")"+}++need_settings() {+ case "$ADMIN_URL" in+ @*) fail "This installer was not downloaded from MausBot. Copy the install command from MausBot and run that." ;;+ esac+ case "$CONNECTOR_IMAGE" in+ @*) fail "This installer was not downloaded from MausBot. Copy the install command from MausBot and run that." ;;+ esac+}++tty_available() {+ [ -t 1 ] || return 1+ (exec </dev/tty) 2>/dev/null+}++check_os() {+ [ -r /etc/os-release ] || fail "This server's operating system can't be identified. MausBot runs on Ubuntu 22.04 or 24.04, or Debian 12."+ os_id=$(. /etc/os-release && printf '%s' "${ID:-}")+ os_version=$(. /etc/os-release && printf '%s' "${VERSION_ID:-}")+ os_name=$(. /etc/os-release && printf '%s' "${PRETTY_NAME:-$os_id $os_version}")+ case "$os_id $os_version" in+ "ubuntu 22.04" | "ubuntu 24.04" | "debian 12") note "operating system: $os_name" ;;+ *)+ if [ "${MAUSBOT_ALLOW_UNTESTED_OS:-}" = 1 ]; then+ note "operating system: $os_name (not one MausBot is tested on; going on as asked)"+ else+ fail "MausBot runs on Ubuntu 22.04 or 24.04, or Debian 12. This server runs $os_name. Please pick one of those, or run again with MAUSBOT_ALLOW_UNTESTED_OS=1 to try anyway."+ fi+ ;;+ esac+}++check_arch() {+ arch=$(uname -m)+ [ "$arch" = x86_64 ] || fail "This server has an ARM processor ($arch). MausBot runs on Intel or AMD (x86-64) servers for now. Please pick an x86-64 server."+ note "processor: x86-64"+}++install_docker() {+ say "Installing Docker with Docker's official script (get.docker.com)..."+ tmp_docker=$(mktemp)+ curl -fsSL https://get.docker.com -o "$tmp_docker" || fail "Docker's install script could not be downloaded. Check that this server can reach https://get.docker.com, then run this command again."+ sh "$tmp_docker" || fail "Docker's install script failed (its output is above). Fix that, then run this command again."+ rm -f "$tmp_docker"+ if command -v systemctl >/dev/null 2>&1; then systemctl enable --now docker >/dev/null 2>&1 || true; fi+}++offer_docker() {+ if [ "${MAUSBOT_INSTALL_DOCKER:-}" = 1 ]; then+ install_docker+ return+ fi+ if tty_available; then+ printf "Docker isn't installed. Install it now with Docker's official script (get.docker.com)? [Y/n] " >/dev/tty+ answer=""+ read -r answer </dev/tty || answer=n+ case "$answer" in+ "" | y | Y | yes | Yes) install_docker; return ;;+ esac+ fi+ fail "Docker isn't installed. Install it with: curl -fsSL https://get.docker.com | sudo sh and then run this command again."+}++check_docker() {+ command -v docker >/dev/null 2>&1 || offer_docker+ server=$(docker version --format '{{.Server.Version}}' 2>/dev/null || true)+ if [ -z "$server" ]; then+ fail "Docker is installed but not running. Start it with: sudo systemctl enable --now docker and then run this command again."+ fi+ major=${server%%.*}+ case "$major" in '' | *[!0-9]*) major=0 ;; esac+ [ "$major" -ge "$MIN_DOCKER" ] || fail "Docker $server is too old; MausBot needs Docker $MIN_DOCKER or newer. Update it with: curl -fsSL https://get.docker.com | sudo sh"+ security=$(docker info --format '{{json .SecurityOptions}}' 2>/dev/null || true)+ case "$security" in+ *rootless*) fail "Docker runs in rootless mode here. MausBot needs the standard Docker service: run curl -fsSL https://get.docker.com | sudo sh" ;;+ esac+ note "Docker: $server"+}++check_apparmor() {+ enabled=$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null || true)+ case "$security" in+ *name=apparmor*name=seccomp* | *name=seccomp*name=apparmor*) docker_confines=yes ;;+ *) docker_confines=no ;;+ esac+ if [ "$enabled" != Y ] || ! command -v apparmor_parser >/dev/null 2>&1 || [ "$docker_confines" != yes ]; then+ fail "Your server is missing AppArmor's tools, a standard part of Ubuntu and Debian. Run: sudo apt-get install -y apparmor then restart the server and run this command again."+ fi+ note "AppArmor: on"+}++check_userns() {+ max=$(cat /proc/sys/user/max_user_namespaces 2>/dev/null || echo 1)+ clone=$(cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null || echo 1)+ if [ "$max" = 0 ] || [ "$clone" != 1 ]; then+ fail "Your server switches off a Linux feature our bots' safety box needs. Run: printf 'user.max_user_namespaces=63000\\nkernel.unprivileged_userns_clone=1\\n' | sudo tee /etc/sysctl.d/90-mausbot.conf && sudo sysctl --system and then run this command again."+ fi+}++check_resources() {+ cpus=$(nproc 2>/dev/null || echo 1)+ [ "$cpus" -ge "$MIN_CPUS" ] || fail "This server has $cpus processor core. MausBot needs at least $MIN_CPUS. Please pick a bigger server."+ memory_mb=$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo)+ memory_gb=$(awk -v m="$memory_mb" 'BEGIN { printf "%.1f", m / 1024 }')+ [ "$memory_mb" -ge "$MIN_MEMORY_MB" ] || fail "This server has $memory_gb GB of memory. MausBot needs at least 4 GB (and 32 GB for a team of five). Please pick a bigger server."+ root=$(docker info --format '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker)+ [ -d "$root" ] || root=/+ free_gb=$(df -Pk "$root" | awk 'NR == 2 { print int($4 / 1048576) }')+ used_pct=$(df -Pk "$root" | awk 'NR == 2 { sub("%", "", $5); print $5 }')+ [ "$free_gb" -ge "$MIN_DISK_GB" ] || fail "Your server has only $free_gb GB free. MausBot needs at least $MIN_DISK_GB GB: free some space or add a disk."+ note "size: $cpus cores, $memory_gb GB memory, $free_gb GB free disk"+ if [ "$memory_mb" -lt 7500 ]; then note "note: with $memory_gb GB of memory, bots will be slow when several work at once. We suggest at least 8 GB."; fi+ if [ "${used_pct:-0}" -ge 85 ]; then note "note: the disk is $used_pct% full. Free some space or add a disk before it fills up."; fi+}++reachable() { # url: any HTTP answer counts+ curl -sS -o /dev/null --max-time 15 "$1" >/dev/null 2>&1+}++check_network() {+ blocked=""+ for url in https://ghcr.io/v2/ https://pkg-containers.githubusercontent.com/ "$ADMIN_URL/" https://cloudflare.com/cdn-cgi/trace; do+ if ! reachable "$url"; then+ host=$(printf '%s' "$url" | sed -e 's#^[a-z]*://##' -e 's#/.*##')+ blocked="$blocked $host"+ fi+ done+ if [ -n "$blocked" ]; then+ if [ -n "${https_proxy:-}${HTTPS_PROXY:-}" ]; then+ fail "This server reaches the internet only through a web proxy, and MausBot can't use a web proxy yet. It needs direct outbound HTTPS (port 443) to:$blocked"+ fi+ fail "Your network blocks outbound HTTPS (port 443) to:$blocked. Ask your IT team to allow it, then run this command again."+ fi+ note "network: MausBot, ghcr.io and Cloudflare reachable"+}++check_clock() {+ admin_date=$(curl -sSI --max-time 15 "$ADMIN_URL/" 2>/dev/null | tr -d '\r' | sed -n 's/^[Dd]ate: //p' | head -n 1)+ if [ -n "$admin_date" ]; then+ theirs=$(date -d "$admin_date" +%s 2>/dev/null || echo "")+ if [ -n "$theirs" ]; then+ skew=$(( $(date +%s) - theirs ))+ [ "$skew" -lt 0 ] && skew=$(( -skew ))+ if [ "$skew" -gt 300 ]; then+ fail "Your server's clock is $(( skew / 60 )) minutes off, so it can't check MausBot's messages. Run: sudo timedatectl set-ntp true and then run this command again."+ fi+ fi+ fi+ if command -v timedatectl >/dev/null 2>&1 && [ "$(timedatectl show -p NTPSynchronized --value 2>/dev/null || echo yes)" != yes ]; then+ note "note: this server's clock is not kept in time. Run: sudo timedatectl set-ntp true"+ fi+}++pull_connector() {+ if ! docker image inspect "$CONNECTOR_IMAGE" >/dev/null 2>&1; then+ docker pull -q "$CONNECTOR_IMAGE" >/dev/null || fail "The MausBot connector could not be downloaded from ghcr.io. Check that this server can reach https://ghcr.io, then run this command again."+ fi+}++install_profiles() {+ say "Installing the bot box's security profiles..."+ tmp_profiles=$(mktemp -d)+ docker run --rm --network none --entrypoint cat "$CONNECTOR_IMAGE" "/app/profiles/$SECCOMP" >"$tmp_profiles/$SECCOMP"+ docker run --rm --network none --entrypoint cat "$CONNECTOR_IMAGE" "/app/profiles/$PROFILE.apparmor" >"$tmp_profiles/$PROFILE"+ install -d -m 0755 "$ETC_DIR"+ install -m 0644 "$tmp_profiles/$SECCOMP" "$ETC_DIR/$SECCOMP"+ install -m 0644 "$tmp_profiles/$PROFILE" "$APPARMOR_DIR/$PROFILE"+ rm -rf "$tmp_profiles"+ apparmor_parser -r -W "$APPARMOR_DIR/$PROFILE" || fail "AppArmor refused the bot box's profile (its message is above). Run this command again; if it still fails, send us that message."+ if [ -r /sys/kernel/security/apparmor/profiles ] && ! grep -q "^$PROFILE " /sys/kernel/security/apparmor/profiles; then+ fail "AppArmor did not load the bot box's profile. Restart the server and run this command again."+ fi+}++start_connector() {+ say "Starting the MausBot connector..."+ docker volume create "$STATE_VOLUME" >/dev/null+ docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || true+ instance=$(cat /proc/sys/kernel/random/uuid)+ set -- --label "$ROLE_LABEL=connector" --label "com.mausbot.instance=$instance" \+ -e "MAUSBOT_INSTANCE=$instance" -e "MAUSBOT_CONNECTOR_IMAGE=$CONNECTOR_IMAGE"+ case "${MAUSBOT_UPDATE_WAIT_S:-}" in+ '' | *[!0-9]*) ;;+ *) set -- "$@" -e "MAUSBOT_UPDATE_WAIT_S=$MAUSBOT_UPDATE_WAIT_S" ;;+ esac+ docker 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" \+ --log-opt max-size=10m --log-opt max-file=3 \+ "$@" "$CONNECTOR_IMAGE" run >/dev/null || fail "The MausBot connector could not be started (Docker's message is above). Run this command again."+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ if docker exec "$CONNECTOR" mausbot-connector version >/dev/null 2>&1; then return; fi+ sleep 1+ done+ fail "The MausBot connector did not start. Its log: $(docker logs --tail 5 "$CONNECTOR" 2>&1 | tr '\n' ' ')"+}++check_box() {+ say "Checking that the bots' safety box works here..."+ probe=$(docker exec "$CONNECTOR" mausbot-connector probe 2>&1 || true)+ problems=$(printf '%s\n' "$probe" | sed -n 's/^fail [a-z]* //p')+ warnings=$(printf '%s\n' "$probe" | sed -n 's/^warn [a-z]* //p')+ if [ -n "$warnings" ]; then printf '%s\n' "$warnings" | sed 's/^/ note: /'; fi+ [ -z "$problems" ] || fail "$problems"+ printf '%s\n' "$probe" | grep -q '^ok box' || fail "The bots' safety box could not be checked on this server. Run this command again."+}++connect() {+ code=$1+ if [ -n "$code" ]; then+ say "Connecting to MausBot..."+ # The code works once: its refusal is read from this one attempt.+ if ! refusal=$(printf '%s\n' "$code" | docker exec -i -e "MAUSBOT_ADMIN_URL=$ADMIN_URL" "$CONNECTOR" mausbot-connector enroll 2>&1 >/dev/null); then+ fail "$(printf '%s\n' "$refusal" | tail -n 1)"+ fi+ elif ! docker exec "$CONNECTOR" mausbot-connector status | grep -q '"enrolled":true'; then+ fail "Add the one-time code MausBot shows next to the install command, like this: $(command_line '<code>')"+ fi+ waited=0+ while [ "$waited" -lt 60 ]; do+ if docker exec "$CONNECTOR" mausbot-connector status 2>/dev/null | grep -q '"connected":true'; then return; fi+ sleep 1+ waited=$((waited + 1))+ done+ fail "The connector could not reach MausBot at $ADMIN_URL. Its log: $(docker logs --tail 5 "$CONNECTOR" 2>&1 | tr '\n' ' ')"+}++install_connector() {+ code=""+ for arg in "$@"; do+ case "$arg" in+ --install-docker) MAUSBOT_INSTALL_DOCKER=1 ;;+ -*) fail "Unknown option $arg. Usage: $(command_line '<code>')" ;;+ *) code=$arg ;;+ esac+ done+ case "$code" in+ *[!A-Za-z0-9-]*) fail "That code doesn't look right. Copy the install command from MausBot again." ;;+ esac+ need_root "${code:-<code>}"+ need_settings+ say "Checking this server..."+ check_os+ check_arch+ check_docker+ check_apparmor+ check_userns+ check_resources+ check_network+ check_clock+ pull_connector+ install_profiles+ start_connector+ check_box+ connect "$code"+ say ""+ say "Connected. Your server shows up in MausBot in a minute."+}++# Removal never deletes the data, its safety copy or its backups unless --delete-data is typed.+uninstall() {+ delete=no+ for arg in "$@"; do+ case "$arg" in+ --delete-data) delete=yes ;;+ *) fail "Unknown option $arg. Usage: $(command_line uninstall) [--delete-data]" ;;+ esac+ done+ need_root uninstall+ command -v docker >/dev/null 2>&1 || fail "Docker isn't installed here, so MausBot isn't either."+ say "Stopping MausBot on this server..."+ docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || true+ docker stop -t 30 "$HOME_CONTAINER" >/dev/null 2>&1 || true+ for container in "$HOME_CONTAINER" $(docker ps -aq --filter "label=$ROLE_LABEL=helper" 2>/dev/null); do+ docker rm -f "$container" >/dev/null 2>&1 || true+ done+ if command -v apparmor_parser >/dev/null 2>&1 && [ -f "$APPARMOR_DIR/$PROFILE" ]; then apparmor_parser -R "$APPARMOR_DIR/$PROFILE" >/dev/null 2>&1 || true; fi+ rm -f "$APPARMOR_DIR/$PROFILE" "$ETC_DIR/$SECCOMP"+ rmdir "$ETC_DIR" 2>/dev/null || true+ # The connector's own state (its token, the home's settings) is not your data: MausBot hands both out again.+ docker volume rm "$STATE_VOLUME" >/dev/null 2>&1 || true+ if [ "$delete" = yes ]; then+ for volume in "$DATA_VOLUME" "$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+ say "MausBot is removed from this server, and so is its data."+ else+ say "MausBot is removed from this server. Your data is kept in the Docker volume $DATA_VOLUME, with its backups."+ say "To delete the data too, run: $(command_line uninstall --delete-data)"+ fi+}++case "${1:-}" in+ uninstall)+ shift+ uninstall "$@"+ ;;+ -h | --help)+ say "Usage: $(command_line '<code>')"+ say " $(command_line uninstall) [--delete-data]"+ ;;+ *) install_connector "$@" ;;+esacdiff --git a/connector/package.json b/connector/package.jsonnew file mode 100644index 0000000000..05e59643ba--- /dev/null+++ b/connector/package.json@@ -0,0 +1,10 @@+{+ "name": "mausbot-connector",+ "private": true,+ "type": "module",+ "description": "Runs a MausBot Cloud home on a server of its owner's, under MausBot's control, over one outbound connection.",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=24"+ }+}diff --git a/connector/profiles/omb-home-narrow.apparmor b/connector/profiles/omb-home-narrow.apparmornew file mode 100644index 0000000000..1f33ff1961--- /dev/null+++ b/connector/profiles/omb-home-narrow.apparmor@@ -0,0 +1,65 @@+# omb-home-narrow: omb-home, plus a refusal of every filesystem type a user namespace may mount that bubblewrap+# never does (it mounts only tmpfs, proc and devpts, and binds). Overlay and FUSE in user namespaces are where most+# unprivileged-namespace kernel bugs have been; a bot cannot reach them through this container.+abi <abi/3.0>,+include <tunables/global>++profile omb-home-narrow flags=(attach_disconnected,mediate_deleted) {+ include <abstractions/base>++ network,+ deny network alg,+ deny network vsock,+ capability,+ file,+ umount,+ # The bot box: tmpfs, proc, devpts and bind mounts in its own namespaces, then pivot_root into them.+ mount,+ pivot_root,+ deny mount fstype=overlay,+ deny mount fstype=fuse,+ deny mount fstype=fuseblk,+ deny mount fstype=sysfs,+ deny mount fstype=mqueue,+ deny mount fstype=cgroup,+ deny mount fstype=cgroup2,+ deny mount fstype=ramfs,+ deny mount fstype=binfmt_misc,+ deny mount fstype=bpf,++ signal (receive) peer=unconfined,+ signal (receive) peer=runc,+ signal (receive) peer=crun,+ signal (send,receive) peer=omb-home-narrow,++ deny @{PROC}/* w,+ deny @{PROC}/{[^1-9/],[^1-9/][^0-9/],[^1-9s/][^0-9y/][^0-9s/],[^1-9/][^0-9/][^0-9/][^0-9/]*}/** w,+ deny @{PROC}/sys/[^k]** w,+ deny @{PROC}/sys/kernel/{?,??,[^s][^h][^m]**} w,+ deny @{PROC}/sysrq-trigger rwklx,+ deny @{PROC}/kcore rwklx,++ # systempaths=unconfined lifts Docker's masks over /proc and /sys; these put back what the masks hid.+ deny @{PROC}/acpi/{,**} rwklx,+ deny @{PROC}/asound/{,**} rwklx,+ deny @{PROC}/interrupts rwklx,+ deny @{PROC}/keys rwklx,+ deny @{PROC}/latency_stats rwklx,+ deny @{PROC}/sched_debug rwklx,+ deny @{PROC}/scsi/{,**} rwklx,+ deny @{PROC}/timer_list rwklx,+ deny @{PROC}/timer_stats rwklx,+ deny @{PROC}/sys/** w,+ deny /sys/devices/system/cpu/cpu*/thermal_throttle/** rwklx,++ deny /sys/[^f]*/** wklx,+ deny /sys/f[^s]*/** wklx,+ deny /sys/fs/[^c]*/** wklx,+ deny /sys/fs/c[^g]*/** wklx,+ deny /sys/fs/cg[^r]*/** wklx,+ deny /sys/firmware/{,**} rwklx,+ deny /sys/devices/virtual/powercap/{,**} rwklx,+ deny /sys/kernel/security/** rwklx,++ ptrace (trace,tracedby,read,readby) peer=omb-home-narrow,+}diff --git a/connector/profiles/seccomp-omb-home.json b/connector/profiles/seccomp-omb-home.jsonnew file mode 100644index 0000000000..3eefa043e7--- /dev/null+++ b/connector/profiles/seccomp-omb-home.json@@ -0,0 +1,939 @@+{+ "defaultAction": "SCMP_ACT_ERRNO",+ "defaultErrnoRet": 1,+ "archMap": [+ {+ "architecture": "SCMP_ARCH_X86_64",+ "subArchitectures": [+ "SCMP_ARCH_X86",+ "SCMP_ARCH_X32"+ ]+ },+ {+ "architecture": "SCMP_ARCH_AARCH64",+ "subArchitectures": [+ "SCMP_ARCH_ARM"+ ]+ },+ {+ "architecture": "SCMP_ARCH_MIPS64",+ "subArchitectures": [+ "SCMP_ARCH_MIPS",+ "SCMP_ARCH_MIPS64N32"+ ]+ },+ {+ "architecture": "SCMP_ARCH_MIPS64N32",+ "subArchitectures": [+ "SCMP_ARCH_MIPS",+ "SCMP_ARCH_MIPS64"+ ]+ },+ {+ "architecture": "SCMP_ARCH_MIPSEL64",+ "subArchitectures": [+ "SCMP_ARCH_MIPSEL",+ "SCMP_ARCH_MIPSEL64N32"+ ]+ },+ {+ "architecture": "SCMP_ARCH_MIPSEL64N32",+ "subArchitectures": [+ "SCMP_ARCH_MIPSEL",+ "SCMP_ARCH_MIPSEL64"+ ]+ },+ {+ "architecture": "SCMP_ARCH_S390X",+ "subArchitectures": [+ "SCMP_ARCH_S390"+ ]+ },+ {+ "architecture": "SCMP_ARCH_RISCV64",+ "subArchitectures": null+ },+ {+ "architecture": "SCMP_ARCH_LOONGARCH64",+ "subArchitectures": null+ }+ ],+ "syscalls": [+ {+ "names": [+ "accept",+ "accept4",+ "access",+ "adjtimex",+ "alarm",+ "bind",+ "brk",+ "cachestat",+ "capget",+ "capset",+ "chdir",+ "chmod",+ "chown",+ "chown32",+ "clock_adjtime",+ "clock_adjtime64",+ "clock_getres",+ "clock_getres_time64",+ "clock_gettime",+ "clock_gettime64",+ "clock_nanosleep",+ "clock_nanosleep_time64",+ "close",+ "close_range",+ "connect",+ "copy_file_range",+ "creat",+ "dup",+ "dup2",+ "dup3",+ "epoll_create",+ "epoll_create1",+ "epoll_ctl",+ "epoll_ctl_old",+ "epoll_pwait",+ "epoll_pwait2",+ "epoll_wait",+ "epoll_wait_old",+ "eventfd",+ "eventfd2",+ "execve",+ "execveat",+ "exit",+ "exit_group",+ "faccessat",+ "faccessat2",+ "fadvise64",+ "fadvise64_64",+ "fallocate",+ "fanotify_mark",+ "fchdir",+ "fchmod",+ "fchmodat",+ "fchmodat2",+ "fchown",+ "fchown32",+ "fchownat",+ "fcntl",+ "fcntl64",+ "fdatasync",+ "fgetxattr",+ "flistxattr",+ "flock",+ "fork",+ "fremovexattr",+ "fsetxattr",+ "fstat",+ "fstat64",+ "fstatat64",+ "fstatfs",+ "fstatfs64",+ "fsync",+ "ftruncate",+ "ftruncate64",+ "futex",+ "futex_requeue",+ "futex_time64",+ "futex_wait",+ "futex_waitv",+ "futex_wake",+ "futimesat",+ "getcpu",+ "getcwd",+ "getdents",+ "getdents64",+ "getegid",+ "getegid32",+ "geteuid",+ "geteuid32",+ "getgid",+ "getgid32",+ "getgroups",+ "getgroups32",+ "getitimer",+ "getpeername",+ "getpgid",+ "getpgrp",+ "getpid",+ "getppid",+ "getpriority",+ "getrandom",+ "getresgid",+ "getresgid32",+ "getresuid",+ "getresuid32",+ "getrlimit",+ "get_robust_list",+ "getrusage",+ "getsid",+ "getsockname",+ "getsockopt",+ "get_thread_area",+ "gettid",+ "gettimeofday",+ "getuid",+ "getuid32",+ "getxattr",+ "getxattrat",+ "inotify_add_watch",+ "inotify_init",+ "inotify_init1",+ "inotify_rm_watch",+ "io_cancel",+ "ioctl",+ "io_destroy",+ "io_getevents",+ "io_pgetevents",+ "io_pgetevents_time64",+ "ioprio_get",+ "ioprio_set",+ "io_setup",+ "io_submit",+ "ipc",+ "kill",+ "landlock_add_rule",+ "landlock_create_ruleset",+ "landlock_restrict_self",+ "lchown",+ "lchown32",+ "lgetxattr",+ "link",+ "linkat",+ "listen",+ "listmount",+ "listxattr",+ "listxattrat",+ "llistxattr",+ "_llseek",+ "lremovexattr",+ "lseek",+ "lsetxattr",+ "lstat",+ "lstat64",+ "madvise",+ "map_shadow_stack",+ "membarrier",+ "memfd_create",+ "memfd_secret",+ "mincore",+ "mkdir",+ "mkdirat",+ "mknod",+ "mknodat",+ "mlock",+ "mlock2",+ "mlockall",+ "mmap",+ "mmap2",+ "mprotect",+ "mq_getsetattr",+ "mq_notify",+ "mq_open",+ "mq_timedreceive",+ "mq_timedreceive_time64",+ "mq_timedsend",+ "mq_timedsend_time64",+ "mq_unlink",+ "mremap",+ "mseal",+ "msgctl",+ "msgget",+ "msgrcv",+ "msgsnd",+ "msync",+ "munlock",+ "munlockall",+ "munmap",+ "name_to_handle_at",+ "nanosleep",+ "newfstatat",+ "_newselect",+ "open",+ "openat",+ "openat2",+ "pause",+ "pidfd_open",+ "pidfd_send_signal",+ "pipe",+ "pipe2",+ "pkey_alloc",+ "pkey_free",+ "pkey_mprotect",+ "poll",+ "ppoll",+ "ppoll_time64",+ "prctl",+ "pread64",+ "preadv",+ "preadv2",+ "prlimit64",+ "process_mrelease",+ "pselect6",+ "pselect6_time64",+ "pwrite64",+ "pwritev",+ "pwritev2",+ "read",+ "readahead",+ "readlink",+ "readlinkat",+ "readv",+ "recv",+ "recvfrom",+ "recvmmsg",+ "recvmmsg_time64",+ "recvmsg",+ "remap_file_pages",+ "removexattr",+ "removexattrat",+ "rename",+ "renameat",+ "renameat2",+ "restart_syscall",+ "riscv_hwprobe",+ "rmdir",+ "rseq",+ "rt_sigaction",+ "rt_sigpending",+ "rt_sigprocmask",+ "rt_sigqueueinfo",+ "rt_sigreturn",+ "rt_sigsuspend",+ "rt_sigtimedwait",+ "rt_sigtimedwait_time64",+ "rt_tgsigqueueinfo",+ "sched_getaffinity",+ "sched_getattr",+ "sched_getparam",+ "sched_get_priority_max",+ "sched_get_priority_min",+ "sched_getscheduler",+ "sched_rr_get_interval",+ "sched_rr_get_interval_time64",+ "sched_setaffinity",+ "sched_setattr",+ "sched_setparam",+ "sched_setscheduler",+ "sched_yield",+ "seccomp",+ "select",+ "semctl",+ "semget",+ "semop",+ "semtimedop",+ "semtimedop_time64",+ "send",+ "sendfile",+ "sendfile64",+ "sendmmsg",+ "sendmsg",+ "sendto",+ "setfsgid",+ "setfsgid32",+ "setfsuid",+ "setfsuid32",+ "setgid",+ "setgid32",+ "setgroups",+ "setgroups32",+ "setitimer",+ "setpgid",+ "setpriority",+ "setregid",+ "setregid32",+ "setresgid",+ "setresgid32",+ "setresuid",+ "setresuid32",+ "setreuid",+ "setreuid32",+ "setrlimit",+ "set_robust_list",+ "setsid",+ "setsockopt",+ "set_thread_area",+ "set_tid_address",+ "setuid",+ "setuid32",+ "setxattr",+ "setxattrat",+ "shmat",+ "shmctl",+ "shmdt",+ "shmget",+ "shutdown",+ "sigaltstack",+ "signalfd",+ "signalfd4",+ "sigprocmask",+ "sigreturn",+ "socketcall",+ "socketpair",+ "splice",+ "stat",+ "stat64",+ "statfs",+ "statfs64",+ "statmount",+ "statx",+ "symlink",+ "symlinkat",+ "sync",+ "sync_file_range",+ "syncfs",+ "sysinfo",+ "tee",+ "tgkill",+ "time",+ "timer_create",+ "timer_delete",+ "timer_getoverrun",+ "timer_gettime",+ "timer_gettime64",+ "timer_settime",+ "timer_settime64",+ "timerfd_create",+ "timerfd_gettime",+ "timerfd_gettime64",+ "timerfd_settime",+ "timerfd_settime64",+ "times",+ "tkill",+ "truncate",+ "truncate64",+ "ugetrlimit",+ "umask",+ "uname",+ "unlink",+ "unlinkat",+ "uretprobe",+ "utime",+ "utimensat",+ "utimensat_time64",+ "utimes",+ "vfork",+ "vmsplice",+ "wait4",+ "waitid",+ "waitpid",+ "write",+ "writev"+ ],+ "action": "SCMP_ACT_ALLOW"+ },+ {+ "names": [+ "clone",+ "unshare",+ "mount",+ "umount2",+ "pivot_root",+ "sethostname"+ ],+ "action": "SCMP_ACT_ALLOW",+ "comment": "MausBot bot box (bubblewrap): its own user, mount, pid, net, ipc, uts and cgroup namespaces, the mounts inside them, and its hostname"+ },+ {+ "names": [+ "process_vm_readv",+ "process_vm_writev",+ "ptrace"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "minKernel": "4.8"+ }+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 38,+ "op": "SCMP_CMP_LT"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 39,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 41,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 42,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 43,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 44,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "socket"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 45,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "personality"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 0,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "personality"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 8,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "personality"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 131072,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "personality"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 131080,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "personality"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 4294967295,+ "op": "SCMP_CMP_EQ"+ }+ ]+ },+ {+ "names": [+ "sync_file_range2",+ "swapcontext"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "ppc64le"+ ]+ }+ },+ {+ "names": [+ "arm_fadvise64_64",+ "arm_sync_file_range",+ "sync_file_range2",+ "breakpoint",+ "cacheflush",+ "set_tls"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "arm",+ "arm64"+ ]+ }+ },+ {+ "names": [+ "arch_prctl"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "amd64",+ "x32"+ ]+ }+ },+ {+ "names": [+ "modify_ldt"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "amd64",+ "x32",+ "x86"+ ]+ }+ },+ {+ "names": [+ "s390_pci_mmio_read",+ "s390_pci_mmio_write",+ "s390_runtime_instr"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "s390",+ "s390x"+ ]+ }+ },+ {+ "names": [+ "riscv_flush_icache"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "arches": [+ "riscv64"+ ]+ }+ },+ {+ "names": [+ "open_by_handle_at"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_DAC_READ_SEARCH"+ ]+ }+ },+ {+ "names": [+ "bpf",+ "clone",+ "clone3",+ "fanotify_init",+ "fsconfig",+ "fsmount",+ "fsopen",+ "fspick",+ "lookup_dcookie",+ "lsm_get_self_attr",+ "lsm_list_modules",+ "lsm_set_self_attr",+ "mount",+ "mount_setattr",+ "move_mount",+ "open_tree",+ "perf_event_open",+ "quotactl",+ "quotactl_fd",+ "setdomainname",+ "sethostname",+ "setns",+ "syslog",+ "umount",+ "umount2",+ "unshare"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_ADMIN"+ ]+ }+ },+ {+ "names": [+ "clone"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 0,+ "value": 2114060288,+ "op": "SCMP_CMP_MASKED_EQ"+ }+ ],+ "excludes": {+ "caps": [+ "CAP_SYS_ADMIN"+ ],+ "arches": [+ "s390",+ "s390x"+ ]+ }+ },+ {+ "names": [+ "clone"+ ],+ "action": "SCMP_ACT_ALLOW",+ "args": [+ {+ "index": 1,+ "value": 2114060288,+ "op": "SCMP_CMP_MASKED_EQ"+ }+ ],+ "comment": "s390 parameter ordering for clone is different",+ "includes": {+ "arches": [+ "s390",+ "s390x"+ ]+ },+ "excludes": {+ "caps": [+ "CAP_SYS_ADMIN"+ ]+ }+ },+ {+ "names": [+ "clone3"+ ],+ "action": "SCMP_ACT_ERRNO",+ "errnoRet": 38,+ "excludes": {+ "caps": [+ "CAP_SYS_ADMIN"+ ]+ }+ },+ {+ "names": [+ "reboot"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_BOOT"+ ]+ }+ },+ {+ "names": [+ "chroot"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_CHROOT"+ ]+ }+ },+ {+ "names": [+ "delete_module",+ "init_module",+ "finit_module"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_MODULE"+ ]+ }+ },+ {+ "names": [+ "acct"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_PACCT"+ ]+ }+ },+ {+ "names": [+ "kcmp",+ "pidfd_getfd",+ "process_madvise",+ "process_vm_readv",+ "process_vm_writev",+ "ptrace"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_PTRACE"+ ]+ }+ },+ {+ "names": [+ "iopl",+ "ioperm"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_RAWIO"+ ]+ }+ },+ {+ "names": [+ "settimeofday",+ "stime",+ "clock_settime",+ "clock_settime64"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_TIME"+ ]+ }+ },+ {+ "names": [+ "vhangup"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_TTY_CONFIG"+ ]+ }+ },+ {+ "names": [+ "get_mempolicy",+ "mbind",+ "set_mempolicy",+ "set_mempolicy_home_node"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYS_NICE"+ ]+ }+ },+ {+ "names": [+ "syslog"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_SYSLOG"+ ]+ }+ },+ {+ "names": [+ "bpf"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_BPF"+ ]+ }+ },+ {+ "names": [+ "perf_event_open"+ ],+ "action": "SCMP_ACT_ALLOW",+ "includes": {+ "caps": [+ "CAP_PERFMON"+ ]+ }+ }+ ]+}diff --git a/connector/src/agent.ts b/connector/src/agent.tsnew file mode 100644index 0000000000..4d82f3f6fe--- /dev/null+++ b/connector/src/agent.ts@@ -0,0 +1,246 @@+// The connector's one connection to the Admin: outbound, held open, re-opened with backoff. Jobs arrive on it and+// their replies go back on it, again on each new connection until the Admin acknowledges them.+import { errorText, type Log } from "./log.ts";+import { CLOSE_REPLACED, CLOSE_UNAUTHORIZED, CONNECT_PATH, HEARTBEAT_INTERVAL_MS, checkJob, type Heartbeat, type Job, type JobAck, type JobReply } from "./protocol.ts";+import type { StatusRecord } from "./state.ts";++const MAX_MESSAGE_BYTES = 1024 * 1024;+const KEPT_REPLIES = 200;+const UNACKED_MAX_AGE_MS = 24 * 60 * 60_000;+const STABLE_MS = 60_000;+const UNAUTHORIZED_RETRY_MS = 5 * 60_000;+const REPLACED_RETRY_MS = 60_000;++export interface Socket {+ readonly readyState: number;+ readonly bufferedAmount: number;+ send(data: string): void;+ close(code?: number, reason?: string): void;+ onopen: ((event: unknown) => void) | null;+ onmessage: ((event: { data: unknown }) => void) | null;+ onclose: ((event: { code: number; reason: string }) => void) | null;+ onerror: ((event: unknown) => void) | null;+}++export type SocketFactory = (url: string, headers: Record<string, string>) => Socket;++/** Node's own WebSocket client (undici), which takes request headers. */+export const nodeSocket: SocketFactory = (url, headers) => new WebSocket(url, { headers }) as unknown as Socket;++export interface AgentOptions {+ admin: string;+ token: string;+ log: Log;+ socket?: SocketFactory;+ heartbeat: () => Promise<Heartbeat>;+ handle: (job: Job) => Promise<JobReply | null>;+ status?: (patch: Partial<StatusRecord>) => void;+ now?: () => number;+ random?: () => number;+ setTimer?: (callback: () => void, ms: number) => unknown;+ clearTimer?: (handle: unknown) => void;+ heartbeatMs?: number;+}++function isAck(message: unknown): message is JobAck {+ return typeof message === "object" && message !== null && typeof (message as JobAck).ack === "string" && Object.keys(message).length === 1;+}++export function connectUrl(admin: string): string {+ const url = new URL(CONNECT_PATH, admin);+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";+ return url.href;+}++/** 1 s, 2 s, 4 s … up to a minute, each between half and one and a half times that, so many servers spread out. */+export function backoffMs(attempt: number, random: number): number {+ return Math.round(Math.min(60_000, 1000 * 2 ** Math.min(attempt, 6)) * (0.5 + random));+}++export class Agent {+ private readonly options: AgentOptions;+ private readonly now: () => number;+ private readonly random: () => number;+ private readonly setTimer: (callback: () => void, ms: number) => unknown;+ private readonly clearTimer: (handle: unknown) => void;+ private socket: Socket | null = null;+ private attempt = 0;+ private openedAt = 0;+ private retry: unknown = null;+ private beat: unknown = null;+ private stopped = true;+ /** Replies the Admin has not acknowledged yet, sent again on each connection. */+ private readonly unacked = new Map<string, { text: string; at: number }>();+ private readonly replies = new Map<string, JobReply | "running">();+ /** Called once each time the Admin has accepted a connection. */+ onConnected: (() => void) | null = null;++ constructor(options: AgentOptions) {+ this.options = options;+ this.now = options.now ?? Date.now;+ this.random = options.random ?? Math.random;+ this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));+ this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));+ }++ get connected(): boolean {+ return this.socket?.readyState === 1 && this.openedAt > 0;+ }++ start(): void {+ if (!this.stopped) return;+ this.stopped = false;+ this.connect();+ }++ /** Closes the connection and stops re-opening it; replies made meanwhile wait for `start()`. */+ stop(): void {+ this.stopped = true;+ if (this.retry) this.clearTimer(this.retry);+ this.retry = null;+ this.stopBeat();+ const socket = this.socket;+ this.socket = null;+ this.openedAt = 0;+ socket?.close(1000, "connector stopping");+ this.options.status?.({ connected: false });+ }++ /** A reply to send now and on each new connection, until the Admin acknowledges it. */+ reply(reply: JobReply): void {+ 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);+ this.unacked.delete(reply.id);+ this.unacked.set(reply.id, { text, at: this.now() });+ for (const [id, entry] of this.unacked) {+ if (this.unacked.size <= KEPT_REPLIES && this.now() - entry.at < UNACKED_MAX_AGE_MS) break;+ this.unacked.delete(id);+ }+ this.send(text);+ }++ private send(text: string): void {+ if (!this.connected) return;+ try {+ this.socket!.send(text);+ } catch (error) {+ this.options.log(`could not send to MausBot: ${errorText(error)}`);+ }+ }++ private connect(): void {+ if (this.stopped) return;+ let socket: Socket;+ try {+ socket = (this.options.socket ?? nodeSocket)(connectUrl(this.options.admin), { authorization: `Bearer ${this.options.token}` });+ } catch (error) {+ this.options.log(`could not open the connection to MausBot: ${errorText(error)}`);+ this.scheduleRetry(backoffMs(this.attempt++, this.random()));+ return;+ }+ this.socket = socket;+ socket.onopen = () => {+ if (this.socket !== socket) return;+ this.openedAt = this.now();+ this.options.status?.({ connected: true, unauthorized: false, lastConnectedAt: this.openedAt, lastError: null });+ this.options.log("connected to MausBot");+ for (const { text } of this.unacked.values()) socket.send(text);+ this.startBeat();+ this.onConnected?.();+ };+ socket.onmessage = (event) => this.received(event.data);+ socket.onerror = () => {};+ socket.onclose = (event) => {+ if (this.socket !== socket) return;+ const wasOpen = this.openedAt > 0;+ const lasted = wasOpen ? this.now() - this.openedAt : 0;+ this.socket = null;+ this.openedAt = 0;+ this.stopBeat();+ if (lasted >= STABLE_MS) this.attempt = 0;+ if (event.code === CLOSE_UNAUTHORIZED) {+ this.options.status?.({ connected: false, unauthorized: true, lastError: "MausBot no longer knows this server" });+ this.options.log("MausBot no longer knows this server; run the install command again with a new code to connect it");+ this.scheduleRetry(UNAUTHORIZED_RETRY_MS);+ return;+ }+ this.options.status?.({ connected: false, lastError: wasOpen ? `the connection closed (${event.code})` : "MausBot could not be reached" });+ if (wasOpen) this.options.log(`the connection to MausBot closed (${event.code}${event.reason ? `: ${event.reason}` : ""})`);+ this.scheduleRetry(event.code === CLOSE_REPLACED ? REPLACED_RETRY_MS : backoffMs(this.attempt++, this.random()));+ };+ }++ private scheduleRetry(ms: number): void {+ if (this.stopped) return;+ if (this.retry) this.clearTimer(this.retry);+ this.retry = this.setTimer(() => {+ this.retry = null;+ this.connect();+ }, ms);+ }++ private startBeat(): void {+ this.stopBeat();+ const tick = () => {+ this.heartbeat();+ this.beat = this.setTimer(tick, this.options.heartbeatMs ?? HEARTBEAT_INTERVAL_MS);+ };+ tick();+ }++ private stopBeat(): void {+ if (this.beat) this.clearTimer(this.beat);+ this.beat = null;+ }++ private heartbeat(): void {+ this.options.heartbeat().then((beat) => {+ if (!this.connected) return;+ this.socket!.send(JSON.stringify(beat));+ this.options.status?.({ lastHeartbeatAt: this.now() });+ }, (error) => this.options.log(`could not make a heartbeat: ${errorText(error)}`));+ }++ private received(data: unknown): void {+ const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : data instanceof ArrayBuffer ? Buffer.from(data).toString("utf8") : null;+ if (text === null || text.length > MAX_MESSAGE_BYTES) {+ this.options.log("ignored a message from MausBot that is not a job");+ return;+ }+ let message: unknown;+ try {+ message = JSON.parse(text);+ } catch {+ this.options.log("ignored a message from MausBot that is not JSON");+ return;+ }+ if (isAck(message)) {+ this.unacked.delete(message.ack);+ return;+ }+ const checked = checkJob(message);+ if (!checked.ok) {+ 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;+ }+ const { job } = checked;+ const known = this.replies.get(job.id);+ if (known === "running") return;+ if (known) {+ this.reply(known);+ return;+ }+ this.replies.set(job.id, "running");+ this.options.log(`job ${job.id}: ${job.type}`);+ this.options.handle(job).then((reply) => {+ if (reply === null) {+ this.replies.delete(job.id);+ return;+ }+ this.options.log(`job ${job.id}: ${reply.ok ? "done" : `failed (${reply.error.code})`}`);+ this.reply(reply);+ }, (error) => this.reply({ id: job.id, ok: false, error: { code: "docker", message: errorText(error) } }));+ }+}diff --git a/connector/src/docker.ts b/connector/src/docker.tsnew file mode 100644index 0000000000..407e1bd79b--- /dev/null+++ b/connector/src/docker.ts@@ -0,0 +1,333 @@+// The Docker Engine API over its Unix socket: only the calls the connector makes, and only the fields it reads.+import { request } from "node:http";++export interface DockerVersion {+ Version: string;+ ApiVersion: string;+ MinAPIVersion?: string;+}++export interface DockerInfo {+ ServerVersion: string;+ OperatingSystem: string;+ KernelVersion: string;+ Architecture: string;+ NCPU: number;+ MemTotal: number;+ SecurityOptions: string[] | null;+ DockerRootDir: string;+}++export interface ImageInfo {+ Id: string;+ RepoDigests: string[] | null;+ Config: { Labels: Record<string, string> | null } | null;+}++export interface ContainerInfo {+ Id: string;+ Name: string;+ Created: string;+ Config: { Image: string; Env: string[] | null; Labels: Record<string, string> | null; Cmd: string[] | null; Entrypoint: string[] | null };+ HostConfig: Record<string, unknown>;+ State: { Status: string; Running: boolean; Paused: boolean; Restarting: boolean; ExitCode: number; StartedAt: string; FinishedAt: string; Error?: string };+ Mounts: { Type: string; Name?: string; Source: string; Destination: string }[] | null;+}++export interface ContainerSummary {+ Id: string;+ Names: string[];+ Image: string;+ State: string;+ Labels: Record<string, string> | null;+}++export interface VolumeInfo {+ Name: string;+ Labels: Record<string, string> | null;+ CreatedAt?: string;+}++export interface Mount {+ Type: "volume";+ Source: string;+ Target: string;+ ReadOnly?: boolean;+}++/** The body of `POST /containers/create`, as far as the connector fills it. */+export interface ContainerSpec {+ Image: string;+ Env?: string[];+ Cmd?: string[];+ Entrypoint?: string[];+ User?: string;+ Labels?: Record<string, string>;+ ExposedPorts?: Record<string, Record<string, never>>;+ StopTimeout?: number;+ WorkingDir?: string;+ HostConfig: {+ Init?: boolean;+ ShmSize?: number;+ PortBindings?: Record<string, { HostIp: string; HostPort: string }[]>;+ Mounts?: Mount[];+ Binds?: string[];+ SecurityOpt?: string[];+ MaskedPaths?: string[];+ ReadonlyPaths?: string[];+ CapDrop?: string[];+ CapAdd?: string[];+ OomScoreAdj?: number;+ RestartPolicy?: { Name: string };+ NetworkMode?: string;+ ReadonlyRootfs?: boolean;+ Tmpfs?: Record<string, string>;+ LogConfig?: { Type: string; Config: Record<string, string> };+ AutoRemove?: boolean;+ };+}++export interface Docker {+ version(): Promise<DockerVersion>;+ info(): Promise<DockerInfo>;+ /** Pulls `image` (a digest reference); throws with Docker's own words when it cannot. */+ pull(image: string): Promise<void>;+ imageInspect(image: string): Promise<ImageInfo | null>;+ removeImage(image: string): Promise<void>;+ containerInspect(name: string): Promise<ContainerInfo | null>;+ listContainers(labels: Record<string, string>): Promise<ContainerSummary[]>;+ /** Every container, running or not, that mounts `volume`. */+ containersUsing(volume: string): Promise<ContainerSummary[]>;+ createContainer(name: string, spec: ContainerSpec): Promise<string>;+ startContainer(name: string): Promise<void>;+ stopContainer(name: string, timeoutS: number): Promise<void>;+ unpauseContainer(name: string): Promise<void>;+ removeContainer(name: string): Promise<void>;+ renameContainer(name: string, to: string): Promise<void>;+ /** 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>;+ volumeInspect(name: string): Promise<VolumeInfo | null>;+ createVolume(name: string, labels: Record<string, string>): Promise<void>;+ removeVolume(name: string): Promise<void>;+ listVolumes(labels: Record<string, string>): Promise<VolumeInfo[]>;+}++export class DockerError extends Error {+ readonly status: number;+ constructor(status: number, message: string) {+ super(message);+ this.name = "DockerError";+ this.status = status;+ }+}++/** Docker 24 speaks API 1.43; newer engines speak it too, up to the newest version the connector knows. */+const MIN_API = [1, 43] as const;+const MAX_API = [1, 47] as const;++function apiParts(value: string | undefined): [number, number] | null {+ const match = /^(\d+)\.(\d+)$/.exec(value ?? "");+ return match ? [Number(match[1]), Number(match[2])] : null;+}++const below = (a: readonly [number, number], b: readonly [number, number]) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);++/** The API version to speak with an engine, or null when it is too old or too new for the connector. */+export function negotiateApi(version: Pick<DockerVersion, "ApiVersion" | "MinAPIVersion">): string | null {+ const engine = apiParts(version.ApiVersion);+ if (!engine || below(engine, MIN_API)) return null;+ const chosen = below(engine, MAX_API) ? engine : MAX_API;+ const engineMin = apiParts(version.MinAPIVersion);+ if (engineMin && below(chosen, engineMin)) return null;+ return `${chosen[0]}.${chosen[1]}`;+}++/** Splits an image reference with a digest into what `POST /images/create` takes. */+export function pullParams(image: string): { fromImage: string; tag: string } {+ const at = image.indexOf("@");+ if (at > 0) return { fromImage: image.slice(0, at), tag: image.slice(at + 1) };+ const colon = image.lastIndexOf(":");+ return colon > image.lastIndexOf("/") ? { fromImage: image.slice(0, colon), tag: image.slice(colon + 1) } : { fromImage: image, tag: "latest" };+}++/** A container's log stream without a TTY is framed: 8 header bytes (stream, 0, 0, 0, big-endian length), then data. */+export function demuxLogs(raw: Buffer): string {+ const parts: Buffer[] = [];+ let offset = 0;+ while (offset + 8 <= raw.length) {+ const length = raw.readUInt32BE(offset + 4);+ parts.push(raw.subarray(offset + 8, offset + 8 + length));+ offset += 8 + length;+ }+ return Buffer.concat(parts).toString("utf8");+}++/** Docker answers a pull 200 and reports a failure inside the stream, one JSON object per line. */+export function pullFailure(stream: string): string | null {+ for (const line of stream.split("\n")) {+ if (!line.trim()) continue;+ try {+ const event = JSON.parse(line) as { error?: string; errorDetail?: { message?: string } };+ if (event.error || event.errorDetail?.message) return event.errorDetail?.message ?? event.error ?? "the pull failed";+ } catch {+ continue;+ }+ }+ return null;+}++export class SocketDocker implements Docker {+ private readonly socketPath: string;+ private api: string | null = null;++ constructor(socketPath: string) {+ this.socketPath = socketPath;+ }++ private call(method: string, path: string, options: { body?: unknown; timeoutMs?: number; versioned?: boolean } = {}): Promise<{ status: number; body: Buffer }> {+ return new Promise((resolve, reject) => {+ const payload = options.body === undefined ? undefined : Buffer.from(JSON.stringify(options.body));+ const req = request({+ socketPath: this.socketPath,+ method,+ path: options.versioned === false ? path : `/v${this.api}${path}`,+ headers: { host: "docker", ...(payload ? { "content-type": "application/json", "content-length": payload.length } : {}) },+ timeout: options.timeoutMs ?? 60_000,+ }, (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));+ res.on("error", reject);+ });+ req.on("timeout", () => req.destroy(new Error(`Docker did not answer ${method} ${path} in time`)));+ req.on("error", (error) => reject(error.message.includes("ENOENT") || error.message.includes("EACCES")+ ? new Error(`the Docker socket ${this.socketPath} cannot be reached (${error.message})`) : error));+ req.end(payload);+ });+ }++ private async ready(): Promise<void> {+ if (this.api) return;+ const version = await this.version();+ const api = negotiateApi(version);+ if (!api) throw new DockerError(0, `Docker ${version.Version} (API ${version.ApiVersion}) is not one the connector supports; MausBot needs Docker 24 or newer`);+ this.api = api;+ }++ private async json<T>(method: string, path: string, options: { body?: unknown; timeoutMs?: number; ok?: number[]; missing?: true } = {}): Promise<T | null> {+ await this.ready();+ const response = await this.call(method, path, options);+ if (options.missing && response.status === 404) return null;+ if (!(options.ok ?? [200, 201, 204, 304]).includes(response.status)) {+ let message = response.body.toString("utf8").trim();+ try { message = (JSON.parse(message) as { message?: string }).message ?? message; } catch { /* plain text */ }+ throw new DockerError(response.status, message || `Docker answered ${response.status} to ${method} ${path}`);+ }+ if (!response.body.length) return null;+ try {+ return JSON.parse(response.body.toString("utf8")) as T;+ } catch {+ return null;+ }+ }++ async version(): Promise<DockerVersion> {+ const response = await this.call("GET", "/version", { versioned: false, timeoutMs: 15_000 });+ if (response.status !== 200) throw new DockerError(response.status, "Docker did not report its version");+ return JSON.parse(response.body.toString("utf8")) as DockerVersion;+ }++ async info(): Promise<DockerInfo> {+ return (await this.json<DockerInfo>("GET", "/info", { timeoutMs: 30_000 }))!;+ }++ async pull(image: string): Promise<void> {+ await this.ready();+ const { fromImage, tag } = pullParams(image);+ const response = await this.call("POST", `/images/create?fromImage=${encodeURIComponent(fromImage)}&tag=${encodeURIComponent(tag)}`, { timeoutMs: 30 * 60_000 });+ const text = response.body.toString("utf8");+ if (response.status !== 200) {+ let message = text.trim();+ try { message = (JSON.parse(message) as { message?: string }).message ?? message; } catch { /* plain text */ }+ throw new DockerError(response.status, message);+ }+ const failure = pullFailure(text);+ if (failure) throw new DockerError(500, failure);+ }++ async imageInspect(image: string): Promise<ImageInfo | null> {+ return this.json<ImageInfo>("GET", `/images/${encodeURIComponent(image)}/json`, { missing: true });+ }++ async removeImage(image: string): Promise<void> {+ await this.json("DELETE", `/images/${encodeURIComponent(image)}`, { ok: [200, 404, 409] });+ }++ async containerInspect(name: string): Promise<ContainerInfo | null> {+ return this.json<ContainerInfo>("GET", `/containers/${encodeURIComponent(name)}/json`, { missing: true });+ }++ async listContainers(labels: Record<string, string>): Promise<ContainerSummary[]> {+ const filters = encodeURIComponent(JSON.stringify({ label: Object.entries(labels).map(([key, value]) => `${key}=${value}`) }));+ return (await this.json<ContainerSummary[]>("GET", `/containers/json?all=1&filters=${filters}`)) ?? [];+ }++ async containersUsing(volume: string): Promise<ContainerSummary[]> {+ const filters = encodeURIComponent(JSON.stringify({ volume: [volume] }));+ return (await this.json<ContainerSummary[]>("GET", `/containers/json?all=1&filters=${filters}`)) ?? [];+ }++ async createContainer(name: string, spec: ContainerSpec): Promise<string> {+ const created = await this.json<{ Id: string }>("POST", `/containers/create?name=${encodeURIComponent(name)}`, { body: spec, ok: [201] });+ return created!.Id;+ }++ async startContainer(name: string): Promise<void> {+ await this.json("POST", `/containers/${encodeURIComponent(name)}/start`, { ok: [204, 304], timeoutMs: 120_000 });+ }++ async stopContainer(name: string, timeoutS: number): Promise<void> {+ await this.json("POST", `/containers/${encodeURIComponent(name)}/stop?t=${timeoutS}`, { ok: [204, 304, 404], timeoutMs: (timeoutS + 60) * 1000 });+ }++ async unpauseContainer(name: string): Promise<void> {+ await this.json("POST", `/containers/${encodeURIComponent(name)}/unpause`, { ok: [204, 404, 409] });+ }++ async removeContainer(name: string): Promise<void> {+ await this.json("DELETE", `/containers/${encodeURIComponent(name)}?force=1`, { ok: [204, 404], timeoutMs: 120_000 });+ }++ async renameContainer(name: string, to: string): Promise<void> {+ await this.json("POST", `/containers/${encodeURIComponent(name)}/rename?name=${encodeURIComponent(to)}`, { ok: [204] });+ }++ async waitContainer(name: string, timeoutMs: number): Promise<number> {+ const result = await this.json<{ StatusCode: number }>("POST", `/containers/${encodeURIComponent(name)}/wait`, { ok: [200], timeoutMs });+ return result?.StatusCode ?? -1;+ }++ async logs(name: string, tail: number): Promise<string> {+ await this.ready();+ const response = await this.call("GET", `/containers/${encodeURIComponent(name)}/logs?stdout=1&stderr=1&tail=${tail}`);+ return response.status === 200 ? demuxLogs(response.body) : "";+ }++ async volumeInspect(name: string): Promise<VolumeInfo | null> {+ return this.json<VolumeInfo>("GET", `/volumes/${encodeURIComponent(name)}`, { missing: true });+ }++ async createVolume(name: string, labels: Record<string, string>): Promise<void> {+ await this.json("POST", "/volumes/create", { body: { Name: name, Labels: labels }, ok: [200, 201] });+ }++ async removeVolume(name: string): Promise<void> {+ await this.json("DELETE", `/volumes/${encodeURIComponent(name)}`, { ok: [204, 404], timeoutMs: 120_000 });+ }++ async listVolumes(labels: Record<string, string>): Promise<VolumeInfo[]> {+ const filters = encodeURIComponent(JSON.stringify({ label: Object.entries(labels).map(([key, value]) => `${key}=${value}`) }));+ return (await this.json<{ Volumes: VolumeInfo[] | null }>("GET", `/volumes?filters=${filters}`))?.Volumes ?? [];+ }+}diff --git a/connector/src/enroll.ts b/connector/src/enroll.tsnew file mode 100644index 0000000000..909fdf333e--- /dev/null+++ b/connector/src/enroll.ts@@ -0,0 +1,50 @@+// Trades the one-time code for this server's own agent token, once, over HTTPS.+import { errorText } from "./log.ts";+import { ENROLL_PATH, checkEnrollCode, checkEnrollResponse, isLoopbackHost, type ConnectorIdentity, type HostFacts } from "./protocol.ts";+import type { AgentRecord } from "./state.ts";++/** The Admin's origin: https, or http on this machine's loopback for a test Admin. */+export function adminOrigin(raw: string | undefined): string {+ let url: URL;+ try {+ url = new URL(raw ?? "");+ } catch {+ throw new Error("The install command did not say which MausBot to connect to. Copy the install command from MausBot again.");+ }+ if (url.username || url.password || (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname)))) {+ throw new Error(`${url.origin} is not a MausBot address this connector may use.`);+ }+ return url.origin;+}++export async function enroll(options: {+ admin: string;+ code: string;+ host: HostFacts;+ connector: ConnectorIdentity;+ fetch?: typeof fetch;+ now?: () => number;+}): Promise<AgentRecord> {+ const code = checkEnrollCode(options.code.trim());+ if (!code.ok) throw new Error(code.message);+ let response: Response;+ try {+ response = await (options.fetch ?? fetch)(`${options.admin}${ENROLL_PATH}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ code: code.value, host: options.host, connector: options.connector }),+ signal: AbortSignal.timeout(30_000),+ });+ } catch (error) {+ throw new Error(`This server can't reach MausBot at ${options.admin} (${errorText(error)}). Check that it can make outbound HTTPS connections, then run the install command again.`);+ }+ if (response.status === 400 || response.status === 401 || response.status === 403 || response.status === 404 || response.status === 410) {+ throw new Error("This code isn't valid anymore: a code works once, for one hour. Make a new one in MausBot and run the install command again.");+ }+ if (!response.ok) throw new Error(`MausBot answered ${response.status} to the connection request. Try the install command again in a minute.`);+ let body: unknown;+ try { body = await response.json(); } catch { body = null; }+ const checked = checkEnrollResponse(body);+ if (!checked.ok) throw new Error(`MausBot's answer could not be used (${checked.message}). Try the install command again.`);+ return { version: 1, admin: options.admin, ...checked.value, enrolledAt: (options.now ?? Date.now)() };+}diff --git a/connector/src/failure.ts b/connector/src/failure.tsnew file mode 100644index 0000000000..56e84088f2--- /dev/null+++ b/connector/src/failure.ts@@ -0,0 +1,24 @@+import type { JobError, JobErrorCode } from "./protocol.ts";+import { redact } from "./log.ts";++/** A job that could not do what it was asked, with what to tell the Admin. */+export class JobFailure extends Error {+ readonly code: JobErrorCode;+ readonly image: string | undefined;++ constructor(code: JobErrorCode, message: string, image?: string) {+ super(message);+ this.name = "JobFailure";+ this.code = code;+ this.image = image;+ }++ toJobError(): JobError {+ return { code: this.code, message: redact(this.message), ...(this.image ? { image: this.image } : {}) };+ }+}++export function asJobError(error: unknown, fallback: JobErrorCode = "docker"): JobError {+ if (error instanceof JobFailure) return error.toJobError();+ return { code: fallback, message: redact(error instanceof Error ? error.message : String(error)) };+}diff --git a/connector/src/home-health.ts b/connector/src/home-health.tsnew file mode 100644index 0000000000..5aa38460e1--- /dev/null+++ b/connector/src/home-health.ts@@ -0,0 +1,79 @@+// Reads the home's health the way the Admin does: a GET of /api/cloud/health signed with the home's bootstrap secret,+// through the edge on the server's loopback, under the home's public name (the edge answers no other).+import { createHash, createHmac, randomBytes } from "node:crypto";+import { request } from "node:http";++import type { HomeHealth } from "./protocol.ts";++export const HEALTH_PATH = "/api/cloud/health";++/** Must match server/cloud-home.ts cloudRequestSignature (the connector test holds them equal). */+export function cloudRequestSignature(secret: string, timestamp: string, nonce: string, method: string, target: string, body: Buffer | string): string {+ const bodyHash = createHash("sha256").update(body).digest("base64url");+ return createHmac("sha256", secret).update(`v1\n${timestamp}\n${nonce}\n${method}\n${target}\n${bodyHash}`).digest("base64url");+}++export function signedHeaders(secret: string, method: string, target: string, body = "", now = Date.now()): Record<string, string> {+ const timestamp = String(Math.floor(now / 1000));+ const nonce = randomBytes(18).toString("base64url");+ return {+ "x-omb-cloud-timestamp": timestamp,+ "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${cloudRequestSignature(secret, timestamp, nonce, method, target, body)}`,+ };+}++export interface HealthTarget {+ port: number;+ publicHost: string;+ secret: string;+}++export type HealthRead = (target: HealthTarget) => Promise<{ status: number; report: Record<string, unknown> | null }>;++export const readHealth: HealthRead = (target) => new Promise((resolve) => {+ const req = request({+ host: "127.0.0.1",+ port: target.port,+ method: "GET",+ path: HEALTH_PATH,+ timeout: 10_000,+ headers: { host: target.publicHost, ...signedHeaders(target.secret, "GET", HEALTH_PATH) },+ }, (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () => {+ let report: Record<string, unknown> | null = null;+ try { report = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>; } catch { report = null; }+ resolve({ status: res.statusCode ?? 0, report });+ });+ res.on("error", () => resolve({ status: 0, report: null }));+ });+ req.on("timeout", () => req.destroy(new Error("timeout")));+ req.on("error", () => resolve({ status: 0, report: null }));+ req.end();+});++const text = (value: unknown, max = 200) => (typeof value === "string" && value.length <= max ? value : null);++/** The fixed fields of a health report; `ok` once it answers and names the image the home should run. */+export function summarizeHealth(status: number, report: Record<string, unknown> | null, expectedImage: string | null, at = Date.now()): HomeHealth {+ const box = report && typeof report.box === "object" && report.box !== null ? report.box as Record<string, unknown> : null;+ const image = text(report?.image, 300);+ return {+ ok: status === 200 && report !== null && (expectedImage === null || image === expectedImage),+ version: text(report?.version, 40),+ image,+ box: box ? {+ box: text(box.box, 40),+ checks: text(box.checks, 20),+ failed: Array.isArray(box.failed) ? box.failed.filter((id): id is string => typeof id === "string" && id.length <= 80).slice(0, 64) : [],+ } : null,+ at,+ };+}++/** The home's public name, which the edge answers for. */+export function publicHost(env: Record<string, string>): string {+ return new URL(env.OMB_PUBLIC_URL).hostname;+}diff --git a/connector/src/home.ts b/connector/src/home.tsnew file mode 100644index 0000000000..1c61ebe1ef--- /dev/null+++ b/connector/src/home.ts@@ -0,0 +1,696 @@+// The home on this server: one container from our image on one data volume, run with exactly the settings the bot box+// needs, kept running, updated with a safety copy and rolled back when the new version does not come up.+import { createHash, randomBytes } from "node:crypto";+import { rmSync } from "node:fs";++import { DockerError, type ContainerSpec, type Docker, type Mount } from "./docker.ts";+import { JobFailure } from "./failure.ts";+import { publicHost, summarizeHealth, type HealthRead } from "./home-health.ts";+import { errorText, registerSecret, type Log } from "./log.ts";+import { EXPORT_PATH, UPDATE_HEALTH_WINDOW_MS, type CopyInfo, type HomeHealth, type HomeReport, type HomeState, type JobError, type JobReply, type JobResults } from "./protocol.ts";+import {+ APPARMOR_PROFILE, BACKUPS_KEPT, HOME_CAPABILITIES, HOME_OOM_SCORE_ADJ, HOME_PORT, HOME_SHM_BYTES, HOME_STOP_TIMEOUT_S, LABELS, LEASE_FIXED_VERSION, NAMES,+} from "./settings.ts";+import type { HomeRecord, Operation, StateStore } from "./state.ts";+import type { Transfer } from "./transfer.ts";++const DATA: Mount = { Type: "volume", Source: NAMES.dataVolume, Target: "/data" };+/** What a copy of /data needs as root: read every file, and write it back with its owner, mode and times. */+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"];++/** A digest of the home's environment, kept as a label: a start with another environment makes a new container. */+export function envDigest(env: Record<string, string>): string {+ return createHash("sha256").update(JSON.stringify(Object.entries(env).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))).digest("hex");+}++/** The home container, with exactly the settings its bot box needs on a stock Docker host, and nothing more. */+export function homeSpec(image: string, env: Record<string, string>, seccomp: string): ContainerSpec {+ const environment = { ...env, OMB_CLOUD_IMAGE: image };+ return {+ Image: image,+ Env: Object.entries(environment).map(([name, value]) => `${name}=${value}`),+ Labels: { [LABELS.role]: "home", [LABELS.image]: image, [LABELS.env]: envDigest(environment) },+ ExposedPorts: { [`${HOME_PORT}/tcp`]: {} },+ StopTimeout: HOME_STOP_TIMEOUT_S,+ HostConfig: {+ Init: true,+ ShmSize: HOME_SHM_BYTES,+ PortBindings: { [`${HOME_PORT}/tcp`]: [{ HostIp: "127.0.0.1", HostPort: String(HOME_PORT) }] },+ Mounts: [DATA],+ SecurityOpt: [`apparmor=${APPARMOR_PROFILE}`, `seccomp=${seccomp}`, "no-new-privileges=true"],+ // Docker's `--security-opt systempaths=unconfined`: no masked or read-only /proc paths (the AppArmor profile denies them).+ MaskedPaths: [],+ ReadonlyPaths: [],+ CapDrop: ["ALL"],+ CapAdd: [...HOME_CAPABILITIES],+ OomScoreAdj: HOME_OOM_SCORE_ADJ,+ RestartPolicy: { Name: "no" },+ LogConfig: { Type: "json-file", Config: { "max-size": "20m", "max-file": "5" } },+ },+ };+}++/** A short-lived container from the home's own image that runs one fixed command on the volumes, without a network. */+export function helperSpec(image: string, mounts: Mount[], command: string[], caps: string[]): ContainerSpec {+ return {+ Image: image,+ Entrypoint: [command[0]],+ Cmd: command.slice(1),+ User: "0:0",+ WorkingDir: "/",+ Labels: { [LABELS.role]: "helper" },+ HostConfig: {+ Mounts: mounts,+ NetworkMode: "none",+ CapDrop: ["ALL"],+ CapAdd: caps,+ SecurityOpt: ["no-new-privileges=true"],+ LogConfig: { Type: "json-file", Config: { "max-size": "1m" } },+ },+ };+}++/** "v0.1.130" → [0, 1, 130]. */+export function imageVersion(label: string | undefined): [number, number, number] | null {+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(label ?? "");+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;+}++function versionBelow(a: readonly number[], b: readonly number[]): boolean {+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];+ return false;+}++const lastLine = (text: string) => text.trim().split("\n").pop()?.slice(0, 300) ?? "";+const spoken = (ms: number) => (ms % 60_000 === 0 ? `${ms / 60_000} minutes` : `${Math.round(ms / 1000)} seconds`);+const gb = (bytes: number) => Math.round((bytes / 1e9) * 10) / 10;++export interface HomeOptions {+ docker: Docker;+ state: StateStore;+ log: Log;+ readHealth: HealthRead;+ /** The seccomp profile install.sh put in /etc/mausbot, as JSON text. */+ seccomp: () => string;+ /** Free bytes where Docker keeps its volumes. */+ diskFree: () => number;+ transfer: Transfer;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+ updateWindowMs?: number;+ startWindowMs?: number;+ pollMs?: number;+}++type Waited = { ok: true } | { ok: false; reason: string };++export class Home {+ private readonly docker: Docker;+ private readonly state: StateStore;+ private readonly log: Log;+ private readonly options: HomeOptions;+ private readonly now: () => number;+ private readonly sleep: (ms: number) => Promise<void>;+ private readonly updateWindowMs: number;+ private readonly startWindowMs: number;+ private readonly pollMs: number;+ private lastHealth: HomeHealth | null = null;+ private chain: Promise<unknown> = Promise.resolve();+ private active = 0;+ private crashes = 0;+ private nextRestartAt = 0;++ constructor(options: HomeOptions) {+ 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.updateWindowMs = options.updateWindowMs ?? UPDATE_HEALTH_WINDOW_MS;+ this.startWindowMs = options.startWindowMs ?? UPDATE_HEALTH_WINDOW_MS;+ this.pollMs = options.pollMs ?? 2_000;+ const env = this.state.homeEnv();+ if (env) registerHomeSecrets(env);+ }++ /** True while a job or a restart holds the home. */+ get busy(): boolean {+ return this.active > 0;+ }++ /** Runs `work` alone: jobs that change the home or its data never overlap. */+ 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;+ }++ async report(): Promise<HomeReport> {+ const record = this.state.home();+ const info = await this.docker.containerInspect(NAMES.home);+ let state: HomeState;+ if (record.operation?.type === "update") state = "updating";+ else if (record.operation?.type === "restore" || record.operation?.type === "import-disk") state = "restoring";+ else if (!info) state = "absent";+ else if (info.State.Running) state = this.lastHealth?.ok && this.lastHealth.image === info.Config.Image ? "running" : "starting";+ else state = record.desired === "running" ? "crashed" : "stopped";+ return { state, image: info?.Config.Image ?? record.image, health: this.lastHealth };+ }++ /** Reads the running home's signed health report; the next report() carries it. */+ async refreshHealth(): Promise<HomeHealth | null> {+ const env = this.state.homeEnv();+ const info = await this.docker.containerInspect(NAMES.home);+ if (!env || !info?.State.Running) return this.lastHealth;+ const { status, report } = await this.options.readHealth({ port: HOME_PORT, publicHost: publicHost(env), secret: env.OMB_CLOUD_BOOTSTRAP_SECRET });+ this.lastHealth = summarizeHealth(status, report, info.Config.Image, 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(jobId: string, image: string, env: Record<string, string>): Promise<JobResults["start"]> {+ return this.exclusive(async () => {+ registerHomeSecrets(env);+ this.state.saveHomeEnv(env);+ const record = this.state.home();+ this.state.saveHome({ ...record, desired: "running", image, operation: { jobId, type: "start", phase: "start", previousImage: record.image, nextImage: image, target: null, dataAtRisk: false, wasRunning: false, startedAt: this.now() } });+ try {+ await this.ensureImage(image);+ await this.ensureDataVolume();+ await this.ensureContainer(image, env);+ await this.startHome(image);+ const waited = await this.waitHealthy(image, this.startWindowMs);+ if (!waited.ok) throw new JobFailure("unhealthy", waited.reason);+ } finally {+ const after = this.state.home();+ this.state.saveHome({ ...after, previousImage: record.image && record.image !== image ? record.image : after.previousImage, operation: null });+ }+ return { home: await this.report() };+ });+ }++ stop(): Promise<JobResults["stop"]> {+ return this.exclusive(async () => {+ this.state.saveHome({ ...this.state.home(), desired: "stopped" });+ await this.docker.stopContainer(NAMES.home, HOME_STOP_TIMEOUT_S);+ this.lastHealth = null;+ return { home: await this.report() };+ });+ }++ restart(): Promise<JobResults["restart"]> {+ return this.exclusive(async () => {+ const { image, env } = this.current();+ this.state.saveHome({ ...this.state.home(), desired: "running" });+ await this.docker.stopContainer(NAMES.home, HOME_STOP_TIMEOUT_S);+ await this.ensureContainer(image, env);+ await this.startHome(image);+ const waited = await this.waitHealthy(image, this.startWindowMs);+ if (!waited.ok) throw new JobFailure("unhealthy", waited.reason);+ return { home: await this.report() };+ });+ }++ /** Pull → safety copy of /data → swap → wait for the new image's health → else put back the old image and the copy. */+ update(jobId: string, image: string): Promise<JobResults["update"]> {+ return this.exclusive(async () => {+ const { image: previous, env } = this.current();+ const record = this.state.home();+ const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;+ this.begin({ jobId, type: "update", phase: "pull", previousImage: previous, nextImage: image, target: null, dataAtRisk: false, wasRunning });+ try {+ await this.ensureImage(image);+ await this.ensureRoomForCopy(previous);+ } catch (error) {+ this.finish({});+ throw error;+ }+ this.phase({ phase: "stop" });+ const snapshot = await this.stopAndCopy(previous, wasRunning);+ this.phase({ phase: "swap", dataAtRisk: true });+ this.state.saveHome({ ...this.state.home(), desired: "running" });+ let failure: string | null = null;+ try {+ await this.createContainer(image, env);+ await this.startHome(image);+ this.phase({ phase: "wait" });+ const waited = await this.waitHealthy(image, this.updateWindowMs);+ if (!waited.ok) failure = waited.reason;+ } catch (error) {+ failure = errorText(error);+ }+ if (failure !== null) {+ this.log(`update to ${image} failed (${failure}); rolling back to ${previous}`);+ await this.rollBack(previous, env, `The new version did not become healthy (${failure})`);+ }+ this.finish({ image, previousImage: previous, desired: "running" });+ const older = record.previousImage;+ if (older && older !== image && older !== previous) await this.docker.removeImage(older).catch(() => {});+ this.log(`updated the home from ${previous} to ${image}`);+ return { home: await this.report(), previousImage: previous, snapshot };+ });+ }++ backup(jobId: string): Promise<JobResults["backup"]> {+ return this.exclusive(async () => {+ const { image } = this.current();+ await this.ensureRoomForCopy(image);+ const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;+ const id = backupId(this.now());+ this.begin({ jobId, type: "backup", phase: "stop", previousImage: image, nextImage: null, target: `${NAMES.backupPrefix}${id}`, dataAtRisk: false, wasRunning });+ try {+ await this.docker.stopContainer(NAMES.home, HOME_STOP_TIMEOUT_S);+ this.phase({ phase: "copy" });+ await this.copyVolume(image, NAMES.dataVolume, `${NAMES.backupPrefix}${id}`, "backup");+ } finally {+ if (wasRunning) await this.restartAfter(image);+ 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((copy) => copy.id === id) ?? { id, kind: "backup", createdAt: this.now(), image } };+ });+ }++ restore(jobId: string, id: string): Promise<JobResults["restore"]> {+ return this.exclusive(async () => {+ const { image, env } = this.current();+ 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(image);+ const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;+ this.begin({ jobId, type: "restore", phase: "stop", previousImage: image, nextImage: null, target: source, dataAtRisk: false, wasRunning });+ await this.stopAndCopy(image, wasRunning);+ this.phase({ phase: "copy", dataAtRisk: true });+ try {+ await this.overwriteVolume(image, source, NAMES.dataVolume);+ } catch (error) {+ await this.putBackSnapshot(image);+ this.finish({});+ if (wasRunning) await this.restartAfter(image);+ 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" });+ await this.ensureContainer(image, env);+ await this.startHome(image);+ const waited = await this.waitHealthy(image, this.startWindowMs);+ this.finish({});+ if (!waited.ok) throw new JobFailure("unhealthy", `Backup ${id} is back, but the home did not become healthy (${waited.reason}).`);+ return { home: await this.report(), backupId: id };+ });+ }++ /** A gzip tar of /data, copied while the home is stopped, then uploaded to the Admin once the home runs again. */+ exportDisk(jobId: string, admin: { origin: string; token: string }): Promise<JobResults["export-disk"]> {+ return this.exclusive(async () => {+ const { image } = this.current();+ await this.ensureRoomForCopy(image);+ const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;+ const archive = `export-${jobId}.tar.gz`;+ this.begin({ jobId, type: "export-disk", phase: "stop", previousImage: image, nextImage: null, target: archive, dataAtRisk: false, wasRunning });+ try {+ await this.docker.stopContainer(NAMES.home, HOME_STOP_TIMEOUT_S);+ this.phase({ phase: "archive" });+ const made = await this.helper(image, [{ ...DATA, ReadOnly: true }, this.stateMount()], ["tar", "-C", "/data", "-czf", `/state/${archive}`, "."], READ_CAPS);+ if (made.code !== 0) throw new JobFailure("docker", `Archiving the data failed (${lastLine(made.output)}).`);+ } catch (error) {+ rmSync(this.state.path(archive), { force: true });+ if (wasRunning) await this.restartAfter(image);+ this.finish({});+ throw error;+ }+ if (wasRunning) await this.restartAfter(image);+ this.phase({ phase: "upload" });+ try {+ const sent = await this.options.transfer.upload(`${admin.origin}${EXPORT_PATH}/${jobId}`, { authorization: `Bearer ${admin.token}` }, this.state.path(archive));+ return { bytes: sent.bytes, sha256: sent.sha256 };+ } catch (error) {+ throw new JobFailure("transfer_failed", `The data could not be sent to MausBot (${errorText(error)}).`);+ } finally {+ rmSync(this.state.path(archive), { force: true });+ this.finish({});+ }+ });+ }++ /** Replaces /data with the gzip tar at `url`, keeping a safety copy until the home runs on it. */+ importDisk(jobId: string, url: string, admin: { origin: string; token: string }): Promise<JobResults["import-disk"]> {+ return this.exclusive(async () => {+ const { image, env } = this.current();+ const archive = `import-${jobId}.tar.gz`;+ const wasRunning = (await this.docker.containerInspect(NAMES.home))?.State.Running === true;+ this.begin({ jobId, type: "import-disk", phase: "download", previousImage: image, nextImage: null, target: archive, dataAtRisk: false, wasRunning });+ let bytes: number;+ try {+ // The token goes only to the Admin itself, never to a storage address it hands out.+ const headers: Record<string, string> = new URL(url).origin === admin.origin ? { authorization: `Bearer ${admin.token}` } : {};+ bytes = (await this.options.transfer.download(url, headers, this.state.path(archive), Math.max(0, this.options.diskFree() - 2e9))).bytes;+ await this.ensureRoomForCopy(image);+ } catch (error) {+ rmSync(this.state.path(archive), { force: true });+ this.finish({});+ throw error instanceof JobFailure ? error : new JobFailure("transfer_failed", `The data could not be downloaded (${errorText(error)}).`);+ }+ this.phase({ phase: "stop" });+ try {+ await this.stopAndCopy(image, wasRunning);+ } finally {+ if (this.state.home().operation === null) rmSync(this.state.path(archive), { force: true });+ }+ this.phase({ phase: "extract", dataAtRisk: true });+ try {+ await this.wipeVolume(image, NAMES.dataVolume);+ const unpacked = await this.helper(image, [DATA, { ...this.stateMount(), ReadOnly: true }], ["tar", "-C", "/data", "-xzpf", `/state/${archive}`], COPY_CAPS);+ if (unpacked.code !== 0) throw new Error(lastLine(unpacked.output) || `tar exited ${unpacked.code}`);+ } catch (error) {+ await this.putBackSnapshot(image);+ this.finish({});+ if (wasRunning) await this.restartAfter(image);+ throw new JobFailure("transfer_failed", `The archive could not be unpacked (${errorText(error)}); the data is as it was.`);+ } finally {+ rmSync(this.state.path(archive), { force: true });+ }+ this.phase({ phase: "start", dataAtRisk: false });+ this.finish({});+ if (wasRunning || this.state.home().desired === "running") {+ await this.ensureContainer(image, env);+ await this.startHome(image);+ const waited = await this.waitHealthy(image, this.startWindowMs);+ if (!waited.ok) throw new JobFailure("unhealthy", `The data is in place, but the home did not become healthy on it (${waited.reason}).`);+ }+ return { home: await this.report(), bytes };+ });+ }++ /** Starts the home again when it stopped on its own; waits longer after each crash in a row. */+ async supervise(): Promise<void> {+ if (this.busy) return;+ const record = this.state.home();+ const env = this.state.homeEnv();+ if (record.desired !== "running" || !record.image || !env || record.operation) return;+ const info = await this.docker.containerInspect(NAMES.home);+ if (info?.State.Running) {+ if (this.now() - Date.parse(info.State.StartedAt) > 10 * 60_000) this.crashes = 0;+ return;+ }+ if (this.now() < this.nextRestartAt) return;+ this.crashes += 1;+ this.nextRestartAt = this.now() + Math.min(300_000, 5_000 * 2 ** Math.min(this.crashes - 1, 6));+ const image = record.image;+ this.log(info ? `the home stopped on its own (exit ${info.State.ExitCode}); starting it again` : "the home's container is gone; making it again");+ await this.exclusive(async () => {+ await this.ensureContainer(image, env);+ await this.startHome(image);+ }).catch((error) => this.log(`could not start the home again: ${errorText(error)}`));+ }++ /** 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 record = this.state.home();+ const op = record.operation;+ if (!op) return null;+ this.log(`the connector restarted during ${op.type} (${op.phase}); finishing it safely`);+ const env = this.state.homeEnv();+ const previous = op.previousImage ?? record.image;+ let image = previous;+ let outcome = "nothing was changed";+ if (op.type === "update" && op.phase === "wait" && op.nextImage && env) {+ const waited = await this.waitHealthy(op.nextImage, 60_000);+ if (waited.ok) {+ this.finish({ image: op.nextImage, previousImage: previous, desired: "running" });+ return { id: op.jobId, ok: true, result: { home: await this.report(), previousImage: previous, snapshot: (await this.copies()).snapshot } } as JobReply;+ }+ }+ if (op.dataAtRisk && previous) {+ await this.docker.removeContainer(NAMES.home);+ await this.putBackSnapshot(previous);+ outcome = "the data was put back as it was before";+ }+ if (op.type === "backup" && op.target) await this.docker.removeVolume(op.target);+ if ((op.type === "export-disk" || op.type === "import-disk") && op.target) rmSync(this.state.path(op.target), { force: true });+ if (op.type === "start") image = op.nextImage;+ this.finish({ image, ...(op.type === "update" ? { desired: "running" as const } : {}) });+ if (image && env && (op.wasRunning || this.state.home().desired === "running")) {+ await this.ensureContainer(image, env);+ await this.startHome(image).catch((error) => this.log(`could not start the home: ${errorText(error)}`));+ outcome += op.type === "update" ? `, and the home runs ${image} again` : ", and the home was started again";+ }+ const error: JobError = { code: "interrupted", message: `The connector restarted during this ${op.type}; ${outcome}.`, ...(op.type === "update" && image ? { image } : {}) };+ return { id: op.jobId, ok: false, error };+ });+ }++ private current(): { image: string; env: Record<string, string> } {+ const record = this.state.home();+ const env = this.state.homeEnv();+ if (!record.image || !env) throw new JobFailure("no_home", "This server has no home yet: start one first.");+ return { image: record.image, env };+ }++ private begin(op: Omit<Operation, "startedAt">): void {+ this.state.saveHome({ ...this.state.home(), operation: { ...op, startedAt: this.now() } });+ }++ private phase(patch: Partial<Operation>): void {+ const record = this.state.home();+ if (record.operation) this.state.saveHome({ ...record, operation: { ...record.operation, ...patch } });+ }++ private finish(patch: Partial<HomeRecord>): void {+ this.state.saveHome({ ...this.state.home(), ...patch, operation: null });+ }++ private async ensureImage(image: string): Promise<void> {+ if (await this.docker.imageInspect(image)) return;+ this.log(`downloading ${image}`);+ try {+ await this.docker.pull(image);+ } catch (error) {+ throw new JobFailure("pull_failed", `Could not download ${image} (${errorText(error)}). Nothing was changed.`);+ }+ }++ private async ensureDataVolume(): Promise<void> {+ if (!(await this.docker.volumeInspect(NAMES.dataVolume))) await this.docker.createVolume(NAMES.dataVolume, { [LABELS.role]: "data" });+ }++ /** Keeps a container made from the same image and environment; anything else is made again. */+ private async ensureContainer(image: string, env: Record<string, string>): Promise<void> {+ const info = await this.docker.containerInspect(NAMES.home);+ const wanted = envDigest({ ...env, OMB_CLOUD_IMAGE: image });+ if (info && info.Config.Image === image && info.Config.Labels?.[LABELS.env] === wanted) return;+ await this.createContainer(image, env);+ }++ private async createContainer(image: string, env: Record<string, string>): Promise<void> {+ await this.docker.removeContainer(NAMES.home);+ await this.docker.createContainer(NAMES.home, homeSpec(image, env, this.options.seccomp()));+ }++ private async startHome(image: string): Promise<void> {+ await this.clearStaleLease(image);+ try {+ await this.docker.startContainer(NAMES.home);+ } catch (error) {+ const message = errorText(error);+ if (/port is already allocated|address already in use/i.test(message)) {+ throw new JobFailure("port_in_use", `Port ${HOME_PORT} on this server's loopback is used by another program, and MausBot's home needs it.`);+ }+ if (error instanceof DockerError && /apparmor|seccomp/i.test(message)) {+ throw new JobFailure("box_unavailable", "The bot box's security profiles are not installed on this server. Run the install command again to repair it.");+ }+ throw new JobFailure("docker", `Docker could not start the home (${message}).`);+ }+ this.lastHealth = null;+ }++ /**+ * Until a home image clears it itself (LEASE_FIXED_VERSION), a home killed uncleanly leaves its data-directory lease+ * on the volume and the next one refuses to start: containers share the host's boot id and reuse pids. Only ever+ * while no container at all runs on the volume, so a live server's lease is never touched.+ */+ private async clearStaleLease(image: string): Promise<void> {+ const version = imageVersion((await this.docker.imageInspect(image))?.Config?.Labels?.["org.opencontainers.image.version"]);+ if (version && !versionBelow(version, LEASE_FIXED_VERSION)) return;+ if ((await this.docker.containersUsing(NAMES.dataVolume)).some((container) => container.State === "running" || container.State === "paused")) return;+ const cleared = await this.helper(image, [DATA], [+ "find", "/data", "-maxdepth", "3", "(",+ "-path", "/data/.openmausbot/openmausbot-server.lease*", "-o", "-path", "/data/.openmausbot/.openmausbot-server-child/openmausbot-server.lease",+ ")", "-print", "-delete",+ ], DELETE_CAPS);+ const paths = cleared.output.split("\n").map((line) => line.trim()).filter((line) => line.startsWith("/data/"));+ if (paths.length) this.log(`cleared the data-directory lease records a stopped home left: ${paths.join(", ")}`);+ }++ private async waitHealthy(image: string, windowMs: number): Promise<Waited> {+ const deadline = this.now() + windowMs;+ const env = this.state.homeEnv();+ if (!env) return { ok: false, reason: "the home has no environment" };+ for (;;) {+ const info = await this.docker.containerInspect(NAMES.home);+ if (!info || !info.State.Running) {+ const why = info ? await this.startupFailure(info.State.ExitCode) : "its container is gone";+ return { ok: false, reason: `the home stopped: ${why}` };+ }+ const { status, report } = await this.options.readHealth({ port: HOME_PORT, publicHost: publicHost(env), secret: env.OMB_CLOUD_BOOTSTRAP_SECRET });+ this.lastHealth = summarizeHealth(status, report, image, this.now());+ if (this.lastHealth.ok) return { ok: true };+ if (this.now() >= deadline) return { ok: false, reason: `it did not report ${image} within ${spoken(windowMs)}` };+ await this.sleep(this.pollMs);+ }+ }++ /** The home's own last word when it exits at boot ("Cloud home startup failed: …"); its launcher never logs a secret. */+ private async startupFailure(exitCode: number): Promise<string> {+ const lines = (await this.docker.logs(NAMES.home, 40).catch(() => "")).split("\n");+ const said = lines.reverse().find((line) => line.includes("startup failed:"));+ return said ? said.slice(said.indexOf("startup failed:") + 16).trim().slice(0, 300) : `exit ${exitCode}`;+ }++ private stateMount(): Mount {+ return { Type: "volume", Source: NAMES.stateVolume, Target: "/state" };+ }++ 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): Promise<void> {+ const measured = await this.helper(image, [{ ...DATA, ReadOnly: 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 safety 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 snapshot(image: string): Promise<CopyInfo> {+ await this.copyVolume(image, NAMES.dataVolume, NAMES.snapshotVolume, "snapshot");+ return { id: "snapshot", kind: "snapshot", createdAt: this.now(), image };+ }++ /** Stops the home and copies /data aside; when the copy fails, the home runs again as it was and the job ends. */+ private async stopAndCopy(image: string, wasRunning: boolean): Promise<CopyInfo> {+ await this.docker.stopContainer(NAMES.home, HOME_STOP_TIMEOUT_S);+ this.phase({ phase: "snapshot" });+ try {+ return await this.snapshot(image);+ } catch (error) {+ this.finish({});+ if (wasRunning) await this.restartAfter(image);+ throw error;+ }+ }++ private async copyVolume(image: string, from: string, to: string, kind: "backup" | "snapshot"): Promise<void> {+ await this.docker.removeVolume(to);+ await this.docker.createVolume(to, { [LABELS.role]: kind, [LABELS.created]: String(this.now()), [LABELS.image]: image });+ const copied = await this.helper(image, [{ Type: "volume", Source: from, Target: "/from", ReadOnly: true }, { Type: "volume", Source: to, Target: "/to" }],+ ["cp", "-a", "/from/.", "/to/"], COPY_CAPS);+ if (copied.code !== 0) {+ await this.docker.removeVolume(to);+ throw new JobFailure("docker", `Copying the data failed (${lastLine(copied.output)}); nothing was changed.`);+ }+ }++ private async wipeVolume(image: string, volume: string): Promise<void> {+ const wiped = await this.helper(image, [{ Type: "volume", Source: volume, Target: "/to" }], ["find", "/to", "-mindepth", "1", "-delete"], DELETE_CAPS);+ if (wiped.code !== 0) throw new Error(`clearing the data failed (${lastLine(wiped.output)})`);+ }++ private async overwriteVolume(image: string, from: string, to: string): Promise<void> {+ await this.wipeVolume(image, to);+ const copied = await this.helper(image, [{ Type: "volume", Source: from, Target: "/from", ReadOnly: true }, { Type: "volume", Source: to, Target: "/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(image: 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.overwriteVolume(image, NAMES.snapshotVolume, NAMES.dataVolume);+ }++ private async rollBack(previous: string, env: Record<string, string>, why: string): Promise<never> {+ this.phase({ phase: "rollback" });+ if ((await this.docker.containerInspect(NAMES.home))?.State.Paused) await this.docker.unpauseContainer(NAMES.home);+ await this.docker.removeContainer(NAMES.home);+ await this.putBackSnapshot(previous);+ this.phase({ dataAtRisk: false });+ let back = false;+ try {+ await this.createContainer(previous, env);+ await this.startHome(previous);+ back = (await this.waitHealthy(previous, this.startWindowMs)).ok;+ } catch (error) {+ this.log(`the previous version did not start again: ${errorText(error)}`);+ }+ this.finish({ image: previous, desired: "running" });+ if (!back) throw new JobFailure("rollback_failed", `${why}. The previous version and its data are back, but it did not become healthy either.`, previous);+ throw new JobFailure("update_rolled_back", `${why}. The previous version and its data are back.`, previous);+ }++ private async restartAfter(image: string): Promise<void> {+ const env = this.state.homeEnv();+ if (!env) return;+ try {+ await this.ensureContainer(image, env);+ await this.startHome(image);+ } catch (error) {+ this.log(`could not start the home again: ${errorText(error)}`);+ }+ }+}++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 };+}++/** "20261028-104512-3fa9": sortable, and a valid `restore` id. */+export function backupId(now: number): string {+ const stamp = new Date(now).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);+ return `${stamp}-${randomBytes(2).toString("hex")}`;+}++/** Every value of a secret-shaped name in the home's environment never reaches a log. */+export function registerHomeSecrets(env: Record<string, string>): void {+ for (const [name, value] of Object.entries(env)) if (/(?:SECRET|TOKEN|GRANT|KEY|PASSWORD)$/.test(name)) registerSecret(value);+}++/** The free bytes on the filesystem of `path`; 0 when it cannot be read. */+export function freeBytes(statfs: () => { bavail: number | bigint; bsize: number | bigint }): number {+ try {+ const stats = statfs();+ return Number(stats.bavail) * Number(stats.bsize);+ } catch {+ return 0;+ }+}+diff --git a/connector/src/host.ts b/connector/src/host.tsnew file mode 100644index 0000000000..72a5e64e1b--- /dev/null+++ b/connector/src/host.ts@@ -0,0 +1,175 @@+// What this server is and whether MausBot can run on it, from Docker's own report and the host's /proc (the+// connector's container shares the host's kernel). Every failing check carries the plain-words fix for its owner.+import { createHash, randomBytes } from "node:crypto";++import type { Docker, DockerInfo } from "./docker.ts";+import { errorText } from "./log.ts";+import type { HostCheck, HostFacts, HostHealth } from "./protocol.ts";+import { APPARMOR_PROFILE, HOME_CAPABILITIES, LABELS, SECCOMP_FILE } from "./settings.ts";++const MIN_DISK_GB = 20;+const MIN_MEMORY_GB = 4;+const MAX_CLOCK_SKEW_S = 300;++export interface HostReader {+ /** A /proc file's text, or null. */+ proc(path: string): string | null;+ /** The installed seccomp profile (/etc/mausbot) and the one this connector carries, as text, or null. */+ installedSeccomp(): string | null;+ shippedSeccomp(): string | null;+ /** Bytes free and in total where Docker keeps its volumes. */+ disk(): { free: number; total: number };+}++const int = (value: string | null | undefined) => {+ const parsed = Number.parseInt(String(value ?? "").trim(), 10);+ return Number.isFinite(parsed) ? parsed : null;+};++/** Unprivileged user namespaces: some kernels switch them off with either of these. */+export function usernsAllowed(reader: Pick<HostReader, "proc">): boolean {+ const max = int(reader.proc("/proc/sys/user/max_user_namespaces"));+ const clone = reader.proc("/proc/sys/kernel/unprivileged_userns_clone");+ return (max === null || max > 0) && (clone === null || clone.trim() === "1");+}++export function dockerMajor(version: string): number {+ return int(/^(\d+)/.exec(version)?.[1]) ?? 0;+}++const securityOption = (info: DockerInfo, name: string) => (info.SecurityOptions ?? []).some((option) => option.split(",").includes(`name=${name}`));++export function hostFacts(info: DockerInfo, reader: HostReader): HostFacts {+ return {+ os: info.OperatingSystem,+ kernel: info.KernelVersion,+ arch: info.Architecture,+ cpus: info.NCPU,+ memMb: Math.round(info.MemTotal / 1048576),+ diskGb: Math.floor(reader.disk().free / 1e9),+ docker: info.ServerVersion,+ apparmor: securityOption(info, "apparmor"),+ userns: usernsAllowed(reader),+ };+}++const digest = (text: string | null) => (text === null ? null : createHash("sha256").update(text).digest("hex"));++export interface BoxProbeResult {+ ok: boolean;+ /** Plain words for the owner when the box cannot start. */+ fix?: string;+}++/** Each check MausBot needs to pass on a server, in order, with the line its owner sees when it fails. */+export function hostChecks(info: DockerInfo, reader: HostReader, extra: { clockSkewS: number | null; box: BoxProbeResult | null }): HostCheck[] {+ const checks: HostCheck[] = [];+ const add = (check: HostCheck) => checks.push(check);+ add(info.Architecture === "x86_64"+ ? { id: "arch", ok: true }+ : { id: "arch", ok: false, fix: "This server has an ARM processor. MausBot runs on Intel or AMD (x86-64) servers for now. Please pick an x86-64 server." });+ add(dockerMajor(info.ServerVersion) >= 24+ ? { id: "docker", ok: true }+ : { id: "docker", ok: false, fix: `Docker ${info.ServerVersion} is too old; MausBot needs Docker 24 or newer. Run: curl -fsSL https://get.docker.com | sudo sh` });+ add(securityOption(info, "rootless")+ ? { id: "rootless", ok: false, fix: "Docker runs in rootless mode here. MausBot needs the standard Docker service: run curl -fsSL https://get.docker.com | sudo sh" }+ : { id: "rootless", ok: true });+ add(securityOption(info, "apparmor") && securityOption(info, "seccomp")+ ? { id: "apparmor", ok: true }+ : { id: "apparmor", ok: false, fix: "Your server is missing AppArmor's tools, a standard part of Ubuntu and Debian. Run: sudo apt-get install -y apparmor, then restart the server." });+ const installed = digest(reader.installedSeccomp());+ add(installed !== null && installed === digest(reader.shippedSeccomp())+ ? { id: "profiles", ok: true }+ : { id: "profiles", ok: false, fix: "The bot box's security profiles on this server are missing or out of date. Run the install command again." });+ add(usernsAllowed(reader)+ ? { id: "userns", ok: true }+ : { id: "userns", ok: false, fix: "Your server switches off a Linux feature our bots' safety box needs. Run: printf 'user.max_user_namespaces=63000\\nkernel.unprivileged_userns_clone=1\\n' | sudo tee /etc/sysctl.d/90-mausbot.conf && sudo sysctl --system" });+ if (extra.box) add(extra.box.ok ? { id: "box", ok: true } : { id: "box", ok: false, fix: extra.box.fix });+ const { free, total } = reader.disk();+ const freeGb = Math.floor(free / 1e9);+ if (freeGb < MIN_DISK_GB) add({ id: "disk", ok: false, fix: `Your server has only ${freeGb} GB free. MausBot needs at least ${MIN_DISK_GB} GB: free some space or add a disk.` });+ else if (total > 0 && (total - free) / total >= 0.85) add({ id: "disk", ok: true, warning: true, fix: `Your server's disk is ${Math.round(((total - free) / total) * 100)}% full. Free some space or add a disk before it fills up.` });+ else add({ id: "disk", ok: true });+ const memGb = Math.round((info.MemTotal / 1073741824) * 10) / 10;+ add(memGb >= MIN_MEMORY_GB - 0.5+ ? { id: "memory", ok: true }+ : { id: "memory", ok: true, warning: true, fix: `This server has ${memGb} GB of memory; bots will be slow or stop. We suggest at least ${MIN_MEMORY_GB} GB, and 32 GB for a team of five.` });+ if (extra.clockSkewS !== null) {+ add(Math.abs(extra.clockSkewS) <= MAX_CLOCK_SKEW_S+ ? { id: "clock", ok: true }+ : { id: "clock", ok: false, fix: `Your server's clock is ${Math.round(Math.abs(extra.clockSkewS) / 60)} minutes off, so it can't check our messages. Run: sudo timedatectl set-ntp true` });+ }+ return checks;+}++export function hostHealth(info: DockerInfo, reader: HostReader, extra: { clockSkewS: number | null; box: BoxProbeResult | null }): HostHealth {+ const meminfo = reader.proc("/proc/meminfo") ?? "";+ const available = int(/^MemAvailable:\s+(\d+)/m.exec(meminfo)?.[1]);+ const load = Number.parseFloat((reader.proc("/proc/loadavg") ?? "").split(" ")[0] ?? "");+ const uptime = Number.parseFloat((reader.proc("/proc/uptime") ?? "").split(" ")[0] ?? "");+ const { total } = reader.disk();+ return {+ ...hostFacts(info, reader),+ diskTotalGb: Math.floor(total / 1e9),+ memAvailableMb: available === null ? 0 : Math.round(available / 1024),+ load1: Number.isFinite(load) ? Math.round(load * 100) / 100 : 0,+ uptimeS: Number.isFinite(uptime) ? Math.floor(uptime) : 0,+ clockSkewS: extra.clockSkewS,+ checks: hostChecks(info, reader, extra),+ };+}++/** The probe the home's own box check starts with (server/bot-box/detect.ts probeBwrap), run unprivileged. */+export const BOX_PROBE = [+ "bwrap", "--unshare-user", "--unshare-pid", "--unshare-net", "--unshare-ipc", "--unshare-uts", "--die-with-parent",+ "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64",+ "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "/bin/true",+];++const REINSTALL = "Run the install command again to repair it.";++/** What bubblewrap says when the box cannot start, mapped to whose it is to fix. */+export function boxProbeFix(output: string): string {+ if (/apparmor/i.test(output) && /profile|not found|load/i.test(output)) return `Our bots' safety box can't start on this server yet: its AppArmor profile is not loaded. ${REINSTALL}`;+ if (/No permissions to create new namespace/i.test(output)) return `Our bots' safety box can't start on this server yet: its seccomp profile was not applied. ${REINSTALL}`;+ if (/Failed to make \/ slave/i.test(output)) return `Our bots' safety box can't start on this server yet: its AppArmor profile is not loaded. ${REINSTALL}`;+ if (/Can't mount proc/i.test(output)) return "Our bots' safety box can't start on this server yet: Docker here is too old to unmask /proc. Run: curl -fsSL https://get.docker.com | sudo sh";+ if (/setting up uid map/i.test(output)) return `Our bots' safety box can't start on this server yet: the box ran without its AppArmor profile. ${REINSTALL}`;+ if (/Creating new namespace failed/i.test(output)) return "Our bots' safety box can't start on this server yet: Linux user namespaces are switched off. Run: printf 'user.max_user_namespaces=63000\\nkernel.unprivileged_userns_clone=1\\n' | sudo tee /etc/sysctl.d/90-mausbot.conf && sudo sysctl --system";+ return `Our bots' safety box can't start on this server yet. ${REINSTALL}`;+}++/** Runs BOX_PROBE in a throwaway container from `image` with the home's own security settings, as nobody. */+export async function probeBox(docker: Docker, image: string, seccomp: string): Promise<BoxProbeResult> {+ const name = `mausbot-probe-${randomBytes(4).toString("hex")}`;+ try {+ await docker.createContainer(name, {+ Image: image,+ Entrypoint: [BOX_PROBE[0]],+ Cmd: BOX_PROBE.slice(1),+ User: "65534:65534",+ Labels: { [LABELS.role]: "helper" },+ HostConfig: {+ Init: true,+ NetworkMode: "none",+ SecurityOpt: [`apparmor=${APPARMOR_PROFILE}`, `seccomp=${seccomp}`, "no-new-privileges=true"],+ MaskedPaths: [],+ ReadonlyPaths: [],+ CapDrop: ["ALL"],+ CapAdd: [...HOME_CAPABILITIES],+ },+ });+ try {+ await docker.startContainer(name);+ } catch (error) {+ return { ok: false, fix: boxProbeFix(errorText(error)) };+ }+ const code = await docker.waitContainer(name, 60_000);+ if (code === 0) return { ok: true };+ return { ok: false, fix: boxProbeFix(await docker.logs(name, 20)) };+ } finally {+ await docker.removeContainer(name).catch(() => {});+ }+}++export const PROFILE_FILES = { seccomp: SECCOMP_FILE, apparmor: `${APPARMOR_PROFILE}.apparmor` } as const;diff --git a/connector/src/jobs.ts b/connector/src/jobs.tsnew file mode 100644index 0000000000..cb355e86d9--- /dev/null+++ b/connector/src/jobs.ts@@ -0,0 +1,68 @@+// 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 { asJobError } from "./failure.ts";+import type { Home } from "./home.ts";+import type { ConnectorIdentity, HostHealth, Job, JobArgs, JobReply, JobResults, JobType } 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;+ hostHealth: () => Promise<HostHealth>;+ identity: () => ConnectorIdentity;+ admin: () => { origin: string; token: string };+ /** Null when the new connector took over and will answer this job itself. */+ selfUpdate: (job: Job<"self-update">) => Promise<JobReply | null>;+}++export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | null> {+ let waiting = 0;+ const run = async (job: Job): Promise<JobReply | null> => {+ const ok = <T extends JobType>(result: JobResults[T]): JobReply => ({ id: job.id, ok: true, result });+ try {+ switch (job.type) {+ case "start": {+ const { image, env } = job.args as JobArgs["start"];+ return ok(await deps.home.start(job.id, image, env));+ }+ case "stop":+ return ok(await deps.home.stop());+ case "restart":+ return ok(await deps.home.restart());+ case "update":+ return ok(await deps.home.update(job.id, (job.args as JobArgs["update"]).image));+ case "backup":+ return ok(await deps.home.backup(job.id));+ case "restore":+ return ok(await deps.home.restore(job.id, (job.args as JobArgs["restore"]).backupId));+ case "export-disk":+ return ok(await deps.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()));+ 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 });+ }+ case "host-health":+ return ok({ host: await deps.hostHealth() });+ case "self-update":+ return await deps.selfUpdate(job as Job<"self-update">);+ }+ } catch (error) {+ return { id: job.id, ok: false, error: asJobError(error) };+ }+ };+ return async (job) => {+ if (!CHANGES.has(job.type)) return run(job);+ if (waiting >= MAX_WAITING) return { id: job.id, ok: false, error: { code: "busy", message: `${MAX_WAITING} jobs are already waiting on this server; send this one again later.` } };+ waiting += 1;+ try {+ return await run(job);+ } finally {+ waiting -= 1;+ }+ };+}diff --git a/connector/src/log.ts b/connector/src/log.tsnew file mode 100644index 0000000000..f44aa66c7c--- /dev/null+++ b/connector/src/log.ts@@ -0,0 +1,24 @@+// One line per event on stdout (docker logs). Every secret the connector holds is registered here and replaced in any+// line that would carry it, so a value never reaches a log even through an error message.++const secrets = new Set<string>();++export function registerSecret(value: string | undefined | null): void {+ if (value && value.length >= 8) secrets.add(value);+}++export function redact(text: string): string {+ let out = text;+ for (const secret of secrets) if (out.includes(secret)) out = out.split(secret).join("[secret]");+ return out;+}++export type Log = (line: string) => void;++export const log: Log = (line) => {+ process.stdout.write(`${new Date().toISOString()} ${redact(line)}\n`);+};++export function errorText(error: unknown): string {+ return redact(error instanceof Error ? error.message : String(error));+}diff --git a/connector/src/main.ts b/connector/src/main.tsnew file mode 100644index 0000000000..4970322607--- /dev/null+++ b/connector/src/main.ts@@ -0,0 +1,230 @@+// mausbot-connector: `run` (the service), `enroll` (the code on stdin), `status`, `probe`, `version`.+import { readFileSync, statfsSync } from "node:fs";+import { join } from "node:path";++import { Agent } from "./agent.ts";+import { SocketDocker, type DockerInfo } from "./docker.ts";+import { adminOrigin, enroll } from "./enroll.ts";+import { readHealth } from "./home-health.ts";+import { Home } from "./home.ts";+import { hostChecks, hostFacts, hostHealth, probeBox, type BoxProbeResult, type HostReader } from "./host.ts";+import { jobRunner } from "./jobs.ts";+import { errorText, log, registerSecret } from "./log.ts";+import { PROTOCOL_VERSION, type ConnectorIdentity, type Heartbeat, type HostHealth } from "./protocol.ts";+import { SELF_UPDATE_DEADLINE_MS, SelfUpdater, ownContainer } from "./self-update.ts";+import { CONNECTOR_VERSION, PATHS, SECCOMP_FILE, envSeconds } from "./settings.ts";+import { StateStore, type AgentRecord } from "./state.ts";+import { httpTransfer } from "./transfer.ts";++const read = (path: string): string | null => {+ try { return readFileSync(path, "utf8"); } catch { return null; }+};++const reader: HostReader = {+ proc: read,+ installedSeccomp: () => read(join(PATHS.hostConfig, SECCOMP_FILE)),+ shippedSeccomp: () => read(join(PATHS.profiles, SECCOMP_FILE)),+ disk: () => {+ try {+ const stats = statfsSync(PATHS.state);+ return { free: Number(stats.bavail) * Number(stats.bsize), total: Number(stats.blocks) * Number(stats.bsize) };+ } catch {+ return { free: 0, total: 0 };+ }+ },+};++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));++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.`);+ return text;+}++/** 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) {+ 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;+ const dockerInfo = async (fresh: boolean) => {+ if (fresh || !info || Date.now() - info.at > 5 * 60_000) info = { at: Date.now(), value: await docker.info() };+ return info.value;+ };+ const probe = async (fresh: boolean) => {+ const image = process.env.MAUSBOT_CONNECTOR_IMAGE;+ if (!image) 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) }; }+ box = { at: Date.now(), value };+ }+ return box.value;+ };+ const skew = async (fresh: boolean) => {+ const origin = admin();+ if (!origin) return null;+ if (fresh || !clock || Date.now() - clock.at > 60 * 60_000) {+ let value: number | null = null;+ try {+ const sent = Date.now();+ const response = await fetch(origin, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(10_000) });+ const date = Date.parse(response.headers.get("date") ?? "");+ if (Number.isFinite(date)) value = Math.round(((sent + Date.now()) / 2 - date) / 1000);+ } catch {+ value = null;+ }+ clock = { at: Date.now(), skew: value };+ }+ return clock.skew;+ };+ return {+ 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 });+ },+ };+}++async function run(): Promise<void> {+ const state = new StateStore(PATHS.state);+ const docker = new SocketDocker(PATHS.docker);+ const instance = process.env.MAUSBOT_INSTANCE || "unknown";+ log(`MausBot connector ${CONNECTOR_VERSION} starting`);+ // A connector removed with SIGKILL never said it went offline.+ state.saveStatus({ connected: false });+ let record: AgentRecord | null = state.agent();+ if (!record) log("waiting for this server to be connected: run the install command with the code MausBot shows");+ while (!record) {+ await sleep(2_000);+ record = state.agent();+ }+ registerSecret(record.agentToken);+ let current: AgentRecord = record;+ const host = hostReporter(docker, () => current.admin);+ const home = new Home({+ docker, state, log, readHealth, seccomp, transfer: httpTransfer,+ diskFree: () => reader.disk().free,+ updateWindowMs: envSeconds("MAUSBOT_UPDATE_WAIT_S", 600, 60, 3600) * 1000,+ });+ 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() } };+ };+ let agent: Agent;+ const handle = jobRunner({+ home,+ hostHealth: () => host.health(true),+ identity,+ admin: () => ({ origin: current.admin, token: current.agentToken }),+ selfUpdate: (job) => home.exclusive(() => updater.run(job, { pause: () => agent.stop(), resume: () => agent.start() })),+ });+ const makeAgent = (from: AgentRecord) => new Agent({ admin: from.admin, token: from.agentToken, log, heartbeat, handle, status: (patch) => state.saveStatus(patch) });+ agent = makeAgent(current);++ const role = await updater.atStart(() => new Promise<boolean>((resolve) => {+ const timer = setTimeout(() => resolve(false), SELF_UPDATE_DEADLINE_MS);+ agent.onConnected = () => {+ clearTimeout(timer);+ agent.onConnected = null;+ resolve(true);+ };+ agent.start();+ }));+ if (role.role === "superseded") {+ log("a newer connector runs this server now; this one stops");+ agent.stop();+ const self = await ownContainer(docker, instance).catch(() => null);+ if (self) await docker.stopContainer(self.Id, 10).catch(() => {});+ return;+ }+ const recovered = await home.recover().catch((error) => {+ log(`could not finish the interrupted job: ${errorText(error)}`);+ return null;+ });+ if (recovered) agent.reply(recovered);+ if (role.role === "candidate") agent.reply(role.reply);+ agent.start();++ setInterval(() => {+ home.supervise().catch((error) => log(`supervising the home failed: ${errorText(error)}`));+ const latest = state.agent();+ if (latest && latest.agentToken !== current.agentToken) {+ log("this server was connected again with a new code; reconnecting");+ registerSecret(latest.agentToken);+ current = latest;+ agent.stop();+ agent = makeAgent(current);+ agent.start();+ }+ }, 10_000);+ const quit = () => {+ agent.stop();+ process.exit(0);+ };+ process.once("SIGTERM", quit);+ process.once("SIGINT", quit);+}++async function readStdin(): Promise<string> {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer);+ return Buffer.concat(chunks).toString("utf8");+}++async function enrollCommand(): Promise<void> {+ const admin = adminOrigin(process.env.MAUSBOT_ADMIN_URL);+ 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() });+ state.saveAgent(record);+ // Connected again only once the service has connected with this token.+ state.saveStatus({ connected: false, unauthorized: false, lastError: null });+ console.log(`This server is connected to MausBot (server ${record.serverId}).`);+}++function statusCommand(): void {+ const state = new StateStore(PATHS.state);+ const record = state.agent();+ const status = state.status();+ const home = state.home();+ console.log(JSON.stringify({+ enrolled: Boolean(record), admin: record?.admin ?? null, serverId: record?.serverId ?? null, cloudId: record?.cloudId ?? null,+ connected: status.connected, unauthorized: status.unauthorized, lastConnectedAt: status.lastConnectedAt, lastHeartbeatAt: status.lastHeartbeatAt,+ lastError: status.lastError, home: { desired: home.desired, image: home.image, operation: home.operation?.type ?? null },+ }));+}++/** One line per check for install.sh: `ok <id>`, `warn <id> <fix>` or `fail <id> <fix>`; exits 1 when any fails. */+async function probeCommand(): Promise<void> {+ const docker = new SocketDocker(PATHS.docker);+ const image = process.env.MAUSBOT_CONNECTOR_IMAGE;+ let box: BoxProbeResult | null = null;+ try { box = image ? await probeBox(docker, image, seccomp()) : null; } catch (error) { box = { ok: false, fix: errorText(error) }; }+ const checks = hostChecks(await docker.info(), reader, { clockSkewS: null, box });+ for (const check of checks) console.log(check.ok && !check.warning ? `ok ${check.id}` : `${check.ok ? "warn" : "fail"} ${check.id} ${check.fix ?? ""}`);+ if (checks.some((check) => !check.ok)) process.exitCode = 1;+}++const commands: Record<string, () => Promise<void> | void> = {+ run,+ enroll: enrollCommand,+ status: statusCommand,+ probe: probeCommand,+ version: () => console.log(CONNECTOR_VERSION),+};++const command = commands[process.argv[2] ?? "run"];+if (!command) {+ console.error("usage: mausbot-connector run | enroll | status | probe | version");+ process.exitCode = 2;+} else {+ Promise.resolve().then(command).catch((error) => {+ console.error(errorText(error));+ process.exitCode = 1;+ });+}diff --git a/connector/src/protocol.ts b/connector/src/protocol.tsnew file mode 100644index 0000000000..10be62e43b--- /dev/null+++ b/connector/src/protocol.ts@@ -0,0 +1,335 @@+// MausBot connector protocol v1: what the connector on an own server and the MausBot Cloud Admin say to each other.+// The Admin side copies this file as it is: it imports nothing.+//+// The connector only ever calls out. It enrols once over HTTPS with a one-time code, then holds one WebSocket to the+// Admin and runs the jobs the Admin sends on it; jobs that change the home or the connector run one at a time. There is+// no shell and no other command. Disk transfers are HTTPS, authorized with the same agent token.++export const PROTOCOL_VERSION = 1;++/** `POST {admin}{ENROLL_PATH}` with an `EnrollRequest`; answers an `EnrollResponse`. The code is single use. */+export const ENROLL_PATH = "/api/cloud/servers/agent/enroll";+/** `GET {admin}{CONNECT_PATH}`, upgraded to a WebSocket, with `Authorization: Bearer <agentToken>`. */+export const CONNECT_PATH = "/api/cloud/servers/agent/connect";+/** `PUT {admin}{EXPORT_PATH}/<job id>`, `content-type: application/gzip`: an `export-disk` job's archive of `/data`. */+export const EXPORT_PATH = "/api/cloud/servers/agent/export";++/** The Admin closes the WebSocket with this code when it no longer knows the token: the server was removed. */+export const CLOSE_UNAUTHORIZED = 4401;+/** The Admin closes an older WebSocket with this code when a newer one with the same token connects. */+export const CLOSE_REPLACED = 4409;++/** How often the connector sends a heartbeat while connected. */+export const HEARTBEAT_INTERVAL_MS = 30_000;+/** An `update` rolls back when the new home does not report its new image within this. */+export const UPDATE_HEALTH_WINDOW_MS = 10 * 60_000;++/** The only images a home may run, and the only ones the connector may become: our registry, pinned by digest. */+export const HOME_IMAGE = /^ghcr\.io\/milind-soni\/openmausbot-cloud-home@sha256:[0-9a-f]{64}$/;+export const CONNECTOR_IMAGE = /^ghcr\.io\/milind-soni\/mausbot-connector@sha256:[0-9a-f]{64}$/;++export interface ConnectorIdentity {+ version: string;+ protocol: typeof PROTOCOL_VERSION;+ /** The image the connector runs, as it was started (a digest reference once it updated itself). */+ image: string | null;+}++/** What the server is, sent at enrolment and in every heartbeat. Sizes are whole numbers. */+export interface HostFacts {+ /** e.g. "Ubuntu 24.04.1 LTS". */+ os: string;+ kernel: string;+ /** `uname -m`: "x86_64". */+ arch: string;+ cpus: number;+ memMb: number;+ /** Free space where Docker keeps its volumes, so where `/data` lives. */+ diskGb: number;+ /** Docker's server version. */+ docker: string;+ /** Docker runs containers under AppArmor. */+ apparmor: boolean;+ /** Unprivileged user namespaces are allowed (the bot box needs them). */+ userns: boolean;+}++export type CheckId = "arch" | "docker" | "rootless" | "apparmor" | "profiles" | "userns" | "box" | "disk" | "memory" | "clock";++/** One pre-check. `fix` is the plain-words line for the server's owner; never a technical cause. */+export interface HostCheck {+ id: CheckId;+ ok: boolean;+ /** A warning still lets MausBot run. */+ warning?: boolean;+ fix?: string;+}++export interface HostHealth extends HostFacts {+ diskTotalGb: number;+ memAvailableMb: number;+ load1: number;+ uptimeS: number;+ /** Seconds the server's clock is ahead of the Admin's (negative: behind); null until measured. */+ clockSkewS: number | null;+ checks: HostCheck[];+}++/** `absent`: never started. `crashed`: exited on its own; the connector starts it again (and says so here meanwhile). */+export type HomeState = "absent" | "stopped" | "starting" | "running" | "crashed" | "updating" | "restoring";++/** The home's own signed health report (`GET /api/cloud/health`), reduced to fixed fields. */+export interface HomeHealth {+ /** The report answered and names the image the home should run. */+ ok: boolean;+ version: string | null;+ image: string | null;+ /** The bot box: its kind, and the self-check's "passed/total" with the failed check ids. */+ box: { box: string | null; checks: string | null; failed: string[] } | null;+ at: number;+}++export interface HomeReport {+ state: HomeState;+ /** The image the home container runs (or ran last). */+ image: string | null;+ health: HomeHealth | null;+}++/** A copy of `/data`: a `backup` job's, or the safety copy taken before an update, a restore or an import. */+export interface CopyInfo {+ id: string;+ kind: "backup" | "snapshot";+ createdAt: number;+ /** The home image that ran on the data when it was copied. */+ image: string | null;+}++/** Connector → Admin, every `HEARTBEAT_INTERVAL_MS` and once right after connecting. */+export interface Heartbeat {+ heartbeat: { host: HostHealth; home: HomeReport; connector: ConnectorIdentity };+}++export interface JobArgs {+ /** Writes the home's environment (kept 0600 on the server) and starts the home on `image`. */+ start: { image: string; env: Record<string, string> };+ stop: Record<string, never>;+ restart: Record<string, never>;+ /** Pull → copy `/data` → swap the container → wait for the new image's health → else roll back image and data. */+ update: { image: string };+ status: Record<string, never>;+ backup: Record<string, never>;+ restore: { backupId: string };+ /** Uploads a gzip tar of `/data` to `PUT {admin}{EXPORT_PATH}/<job id>`. */+ "export-disk": Record<string, never>;+ /** Replaces `/data` with the gzip tar at `url` (https; the agent token is sent only to the Admin's own origin). */+ "import-disk": { url: string };+ "host-health": Record<string, never>;+ /** Swaps the connector itself for `image`, keeping the current one until the new one has connected. */+ "self-update": { image: string };+}++export type JobType = keyof JobArgs;+export const JOB_TYPES: readonly JobType[] = ["start", "stop", "restart", "update", "status", "backup", "restore", "export-disk", "import-disk", "host-health", "self-update"];++/** Admin → connector. `id` is the Admin's; a job sent again with the same id is answered again, never run twice. */+export interface Job<T extends JobType = JobType> {+ id: string;+ type: T;+ args: JobArgs[T];+}++export interface JobResults {+ start: { home: HomeReport };+ stop: { home: HomeReport };+ restart: { home: HomeReport };+ update: { home: HomeReport; previousImage: string | null; snapshot: CopyInfo | null };+ status: { home: HomeReport; connector: ConnectorIdentity; backups: CopyInfo[]; snapshot: CopyInfo | null };+ backup: { backup: CopyInfo };+ restore: { home: HomeReport; backupId: string };+ "export-disk": { bytes: number; sha256: string };+ "import-disk": { home: HomeReport; bytes: number };+ "host-health": { host: HostHealth };+ "self-update": { connector: ConnectorIdentity };+}++export type JobErrorCode =+ | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted"+ | "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";++/** `message` is plain words for the Admin's log and alerts; it never carries a secret. */+export interface JobError {+ code: JobErrorCode;+ message: string;+ /** `update_rolled_back`: the image the home runs again. */+ image?: string;+}++/**+ * Connector → Admin, once per job, then again on every new connection until the Admin acknowledges it (`JobAck`): a+ * reply written just before a connection died is not lost. The Admin keeps the first reply to an id and ignores repeats.+ */+export type JobReply<T extends JobType = JobType> = { id: string; ok: true; result: JobResults[T] } | { id: string; ok: false; error: JobError };++/** Admin → connector, once it has stored the reply to job `ack`. */+export interface JobAck {+ ack: string;+}++/** `POST {admin}{ENROLL_PATH}` body. */+export interface EnrollRequest {+ code: string;+ host: HostFacts;+ connector: ConnectorIdentity;+}++export interface EnrollResponse {+ serverId: string;+ cloudId: string;+ agentToken: string;+}++// Validation, shared so both sides refuse the same things.++const JOB_ID = /^[A-Za-z0-9_-]{1,64}$/;+const BACKUP_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;+const OPAQUE_ID = /^[A-Za-z0-9_-]{1,128}$/;+const TOKEN = /^[A-Za-z0-9_.~-]{32,512}$/;+const ENV_NAME = /^OMB_[A-Z0-9_]{1,60}$/;+// oxlint-disable-next-line no-control-regex+const ENV_VALUE = /^[^\0\r\n]{0,8192}$/;+const MAX_ENV = 64;++/** The home's boot contract: without these the home refuses to start. */+export const REQUIRED_HOME_ENV = ["OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_ADMIN_URL", "OMB_PUBLIC_URL", "OMB_CLOUD_BOOTSTRAP_SECRET"] as const;++/** Settings the image owns, or that make sense only on Fly; a home on an own server never takes them from outside. */+export const REFUSED_HOME_ENV = new Set([+ "OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_EDGE_CONFIG", "OMB_CLOUD_HARDEN",+ "OMB_DATA_DIR", "OMB_STATIC_DIR", "OMB_DUCKDB_DIR", "OMB_PORT", "OMB_WEBHOOK_PORT", "OMB_CLOUD_SECRETS_FD",+]);++export type Checked<T> = { ok: true; value: T } | { ok: false; message: string };++const plainObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;++function noArgs(args: Record<string, unknown>): Checked<Record<string, never>> {+ return Object.keys(args).length === 0 ? { ok: true, value: {} } : { ok: false, message: "this job takes no arguments" };+}++function only(args: Record<string, unknown>, keys: string[]): string | null {+ const extra = Object.keys(args).filter((key) => !keys.includes(key));+ return extra.length ? `unknown argument ${JSON.stringify(extra[0])}` : null;+}++function httpsOrigin(value: string): boolean {+ try {+ const url = new URL(value);+ return url.protocol === "https:" && !url.username && !url.password && (value === url.origin || value === `${url.origin}/`);+ } catch {+ return false;+ }+}++/** The home's environment: names are `OMB_*` and never one the image owns; values are one line. Never echoes a value. */+export function checkHomeEnv(env: unknown): Checked<Record<string, string>> {+ if (!plainObject(env)) return { ok: false, message: "env must be an object of names and values" };+ const entries = Object.entries(env);+ if (entries.length > MAX_ENV) return { ok: false, message: `env has more than ${MAX_ENV} names` };+ for (const [name, value] of entries) {+ if (!ENV_NAME.test(name)) return { ok: false, message: `env name ${JSON.stringify(name.slice(0, 64))} is not an OMB_ setting` };+ if (REFUSED_HOME_ENV.has(name)) return { ok: false, message: `env name ${name} is the image's own setting` };+ if (typeof value !== "string" || !ENV_VALUE.test(value)) return { ok: false, message: `env value of ${name} must be one line of at most 8192 characters` };+ }+ for (const name of REQUIRED_HOME_ENV) if (typeof env[name] !== "string" || !env[name]) return { ok: false, message: `env must set ${name}` };+ if (env.OMB_CLOUD_ROLE !== "home" && env.OMB_CLOUD_ROLE !== "team") return { ok: false, message: 'OMB_CLOUD_ROLE must be "home" or "team"' };+ if (!httpsOrigin(env.OMB_PUBLIC_URL as string)) return { ok: false, message: "OMB_PUBLIC_URL must be an https origin" };+ if (!httpsOrigin(env.OMB_CLOUD_ADMIN_URL as string)) return { ok: false, message: "OMB_CLOUD_ADMIN_URL must be an https origin" };+ return { ok: true, value: Object.fromEntries(entries) as Record<string, string> };+}++/** An https URL (or, for a test Admin, http on this machine's loopback) without credentials in it. */+export function checkTransferUrl(value: unknown): Checked<string> {+ if (typeof value !== "string" || value.length > 4096) return { ok: false, message: "url must be a string of at most 4096 characters" };+ let url: URL;+ try { url = new URL(value); } catch { return { ok: false, message: "url is not a URL" }; }+ if (url.username || url.password) return { ok: false, message: "url must not carry credentials" };+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) return { ok: false, message: "url must be https" };+ return { ok: true, value: url.href };+}++export function isLoopbackHost(hostname: string): boolean {+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(hostname);+}++/** A whole Admin → connector message: a job with a valid id, a known type and exactly that type's arguments. */+export function checkJob(message: unknown): { ok: true; job: Job } | { ok: false; id: string | null; code: "invalid_job" | "unknown_job" | "invalid_args"; message: string } {+ if (!plainObject(message)) return { ok: false, id: null, code: "invalid_job", message: "a job is a JSON object" };+ const id = typeof message.id === "string" && JOB_ID.test(message.id) ? message.id : null;+ if (!id) return { ok: false, id: null, code: "invalid_job", message: "a job needs an id of 1 to 64 letters, digits, - or _" };+ if (typeof message.type !== "string" || !(JOB_TYPES as readonly string[]).includes(message.type)) {+ return { ok: false, id, code: "unknown_job", message: `unknown job type ${JSON.stringify(String(message.type).slice(0, 32))}` };+ }+ const type = message.type as JobType;+ const args = message.args === undefined ? {} : message.args;+ if (!plainObject(args)) return { ok: false, id, code: "invalid_args", message: "args must be an object" };+ const checked = checkArgs(type, args);+ if (!checked.ok) return { ok: false, id, code: "invalid_args", message: checked.message };+ return { ok: true, job: { id, type, args: checked.value } as Job };+}++function checkArgs(type: JobType, args: Record<string, unknown>): Checked<JobArgs[JobType]> {+ switch (type) {+ case "start": {+ const extra = only(args, ["image", "env"]);+ if (extra) return { ok: false, message: extra };+ if (typeof args.image !== "string" || !HOME_IMAGE.test(args.image)) return { ok: false, message: "image must be ghcr.io/milind-soni/openmausbot-cloud-home@sha256:<digest>" };+ const env = checkHomeEnv(args.env);+ return env.ok ? { ok: true, value: { image: args.image, env: env.value } } : env;+ }+ case "update": {+ const extra = only(args, ["image"]);+ if (extra) return { ok: false, message: extra };+ if (typeof args.image !== "string" || !HOME_IMAGE.test(args.image)) return { ok: false, message: "image must be ghcr.io/milind-soni/openmausbot-cloud-home@sha256:<digest>" };+ return { ok: true, value: { image: args.image } };+ }+ case "self-update": {+ const extra = only(args, ["image"]);+ if (extra) return { ok: false, message: extra };+ if (typeof args.image !== "string" || !CONNECTOR_IMAGE.test(args.image)) return { ok: false, message: "image must be ghcr.io/milind-soni/mausbot-connector@sha256:<digest>" };+ return { ok: true, value: { image: args.image } };+ }+ case "restore": {+ const extra = only(args, ["backupId"]);+ if (extra) return { ok: false, message: extra };+ if (typeof args.backupId !== "string" || !BACKUP_ID.test(args.backupId)) return { ok: false, message: "backupId must be a backup's id" };+ return { ok: true, value: { backupId: args.backupId } };+ }+ case "import-disk": {+ const extra = only(args, ["url"]);+ if (extra) return { ok: false, message: extra };+ const url = checkTransferUrl(args.url);+ return url.ok ? { ok: true, value: { url: url.value } } : url;+ }+ default:+ return noArgs(args);+ }+}++export function checkEnrollResponse(value: unknown): Checked<EnrollResponse> {+ if (!plainObject(value)) return { ok: false, message: "the enrolment answer is not a JSON object" };+ const { serverId, cloudId, agentToken } = value;+ if (typeof serverId !== "string" || !OPAQUE_ID.test(serverId)) return { ok: false, message: "the enrolment answer has no valid serverId" };+ if (typeof cloudId !== "string" || !OPAQUE_ID.test(cloudId)) return { ok: false, message: "the enrolment answer has no valid cloudId" };+ if (typeof agentToken !== "string" || !TOKEN.test(agentToken)) return { ok: false, message: "the enrolment answer has no valid agentToken" };+ return { ok: true, value: { serverId, cloudId, agentToken } };+}++/** A one-time code as the Admin shows it: letters, digits and dashes. */+export function checkEnrollCode(value: unknown): Checked<string> {+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9-]{5,127}$/.test(value)+ ? { ok: true, value }+ : { ok: false, message: "the code is the one-time code MausBot shows next to the install command" };+}diff --git a/connector/src/self-update.ts b/connector/src/self-update.tsnew file mode 100644index 0000000000..894300883b--- /dev/null+++ b/connector/src/self-update.ts@@ -0,0 +1,180 @@+// The connector replaces itself the way it updates the home: by digest, and keeping the running one until the new one+// has shown it works. The new connector proves it by connecting to the Admin; then it answers the job, removes the old+// container and takes its name. If it has not within the deadline, the old one removes it and carries on. Each side+// settles the outcome with one atomic rename in the state volume, so they can never both win.+import { randomUUID } from "node:crypto";++import type { ContainerInfo, ContainerSpec, Docker } from "./docker.ts";+import { errorText, type Log } from "./log.ts";+import type { ConnectorIdentity, Job, JobReply } from "./protocol.ts";+import { LABELS, NAMES } from "./settings.ts";+import type { SelfUpdateRecord, StateStore } from "./state.ts";++export const SELF_UPDATE_DEADLINE_MS = 3 * 60_000;+const INSTANCE_ENV = "MAUSBOT_INSTANCE";+const IMAGE_ENV = "MAUSBOT_CONNECTOR_IMAGE";++export interface SelfUpdateDeps {+ docker: Docker;+ state: StateStore;+ log: Log;+ /** This connector's MAUSBOT_INSTANCE, also its container's instance label. */+ instance: string;+ identity: () => ConnectorIdentity;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+ deadlineMs?: number;+ pollMs?: number;+}++/** The container a connector process runs in, found by the instance label install.sh (or a self-update) gave it. */+export async function ownContainer(docker: Docker, instance: string): Promise<ContainerInfo | null> {+ const [found] = await docker.listContainers({ [LABELS.instance]: instance });+ return found ? docker.containerInspect(found.Id) : null;+}++const HOST_CONFIG_KEYS = ["Binds", "Mounts", "NetworkMode", "RestartPolicy", "SecurityOpt", "CapAdd", "CapDrop", "ReadonlyRootfs", "Tmpfs", "Init", "LogConfig"] as const;++/**+ * The same container as `current`, on `image`, with a new instance id. Only the connector's own MAUSBOT_ settings carry+ * over: the rest of an inspected environment is the old image's own ENV, which the new image sets for itself.+ */+export function successorSpec(current: ContainerInfo, image: string, instance: string): ContainerSpec {+ const env = (current.Config.Env ?? []).filter((entry) => entry.startsWith("MAUSBOT_") && !entry.startsWith(`${INSTANCE_ENV}=`) && !entry.startsWith(`${IMAGE_ENV}=`));+ const hostConfig: Record<string, unknown> = {};+ for (const key of HOST_CONFIG_KEYS) if (current.HostConfig[key] !== undefined && current.HostConfig[key] !== null) hostConfig[key] = current.HostConfig[key];+ return {+ Image: image,+ Env: [...env, `${INSTANCE_ENV}=${instance}`, `${IMAGE_ENV}=${image}`],+ ...(current.Config.Cmd ? { Cmd: current.Config.Cmd } : {}),+ Labels: { ...current.Config.Labels, [LABELS.instance]: instance, [LABELS.role]: "connector" },+ HostConfig: hostConfig as ContainerSpec["HostConfig"],+ };+}++export class SelfUpdater {+ private readonly deps: SelfUpdateDeps;+ private readonly now: () => number;+ private readonly sleep: (ms: number) => Promise<void>;++ constructor(deps: SelfUpdateDeps) {+ this.deps = deps;+ this.now = deps.now ?? Date.now;+ this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));+ }++ private fail(job: Job<"self-update">, message: string): JobReply {+ return { id: job.id, ok: false, error: { code: "self_update_failed", message } };+ }++ /**+ * In the running connector. `pause` stops its connection so the new one can take it; `resume` re-opens it after a+ * failure. Null: the new connector took over, answered the job, and removes this one.+ */+ async run(job: Job<"self-update">, agent: { pause(): void; resume(): void }): Promise<JobReply | null> {+ const { docker, state, log } = this.deps;+ const image = job.args.image;+ const self = await ownContainer(docker, this.deps.instance);+ if (!self) return this.fail(job, "The connector cannot find its own container, so it cannot replace itself. Run the install command again.");+ if (self.Config.Image === image) return { id: job.id, ok: true, result: { connector: this.deps.identity() } };+ try {+ await docker.pull(image);+ } catch (error) {+ return this.fail(job, `Could not download ${image} (${errorText(error)}). The connector was not changed.`);+ }+ const instance = randomUUID();+ const record: SelfUpdateRecord = {+ jobId: job.id, from: self.Config.Image, to: image, previousContainer: self.Id, candidateContainer: NAMES.connectorNext,+ deadline: this.now() + (this.deps.deadlineMs ?? SELF_UPDATE_DEADLINE_MS), candidateInstance: instance,+ };+ state.clearSelfUpdateOutcome();+ await docker.removeContainer(NAMES.connectorNext);+ state.saveSelfUpdate(record);+ try {+ await docker.createContainer(NAMES.connectorNext, successorSpec(self, image, instance));+ agent.pause();+ await docker.startContainer(NAMES.connectorNext);+ } catch (error) {+ state.settleSelfUpdate("aborted");+ state.clearSelfUpdateOutcome();+ await docker.removeContainer(NAMES.connectorNext).catch(() => {});+ agent.resume();+ return this.fail(job, `The new connector could not be started (${errorText(error)}). The connector was not changed.`);+ }+ log(`started the new connector on ${image}; waiting for it to connect`);+ const outcome = await this.awaitOutcome(record);+ if (outcome === "confirmed") {+ log("the new connector took over; this one stops");+ await docker.stopContainer(self.Id, 10).catch(() => {});+ return null;+ }+ await docker.removeContainer(NAMES.connectorNext).catch(() => {});+ state.clearSelfUpdateOutcome();+ agent.resume();+ return this.fail(job, `The new connector did not connect to MausBot within ${Math.round((this.deps.deadlineMs ?? SELF_UPDATE_DEADLINE_MS) / 60_000)} minutes; kept this one.`);+ }++ private async awaitOutcome(record: SelfUpdateRecord): Promise<"confirmed" | "aborted"> {+ for (;;) {+ const settled = this.deps.state.selfUpdateOutcome();+ if (settled) return settled.outcome;+ if (this.now() >= record.deadline) return this.deps.state.settleSelfUpdate("aborted");+ await this.sleep(this.deps.pollMs ?? 2_000);+ }+ }++ /**+ * At start, in either connector. The new one (its instance is the record's candidate) waits to be connected, then+ * settles the update as confirmed. The old one, started again mid-update (a reboot), waits for the outcome, and once+ * the new one has won it only waits to be removed. Returns what this process should do.+ */+ async atStart(connected: () => Promise<boolean>): Promise<{ role: "none" } | { role: "candidate"; reply: JobReply } | { role: "superseded" }> {+ const { docker, state, log } = this.deps;+ const record = state.selfUpdate();+ if (!record) {+ const settled = state.selfUpdateOutcome();+ if (settled?.outcome === "confirmed" && settled.record.candidateInstance !== this.deps.instance) {+ // Superseded only while the connector that won runs; a record it never cleared means nothing on its own.+ if ((await ownContainer(docker, settled.record.candidateInstance))?.State.Running) return { role: "superseded" };+ state.clearSelfUpdateOutcome();+ return { role: "none" };+ }+ if (settled?.outcome === "confirmed") await this.finishTakeover();+ else if (settled) state.clearSelfUpdateOutcome();+ return { role: "none" };+ }+ if (record.candidateInstance === this.deps.instance) {+ const outcome = state.settleSelfUpdate((await connected()) ? "confirmed" : "aborted");+ if (outcome !== "confirmed") {+ log("the update of the connector was called off; this one stops");+ return { role: "superseded" };+ }+ await this.finishTakeover();+ return { role: "candidate", reply: { id: record.jobId, ok: true, result: { connector: this.deps.identity() } } };+ }+ if ((await this.awaitOutcome(record)) === "confirmed") return { role: "superseded" };+ await docker.removeContainer(record.candidateContainer).catch(() => {});+ state.clearSelfUpdateOutcome();+ log("the new connector never connected; this one carries on");+ return { role: "none" };+ }++ /**+ * In the new connector once the update is confirmed: remove the old container and take the usual name. The confirmed+ * record stays until the next update, so an old connector that is still polling, or starts again, reads the outcome.+ */+ private async finishTakeover(): Promise<void> {+ const { docker, state, log } = this.deps;+ const settled = state.selfUpdateOutcome();+ if (!settled || settled.outcome !== "confirmed" || settled.record.candidateInstance !== this.deps.instance) return;+ const self = await ownContainer(docker, this.deps.instance);+ if (!self) return;+ try {+ if (settled.record.previousContainer !== self.Id) await docker.removeContainer(settled.record.previousContainer);+ if (self.Name.replace(/^\//, "") !== NAMES.connector) await docker.renameContainer(self.Id, NAMES.connector);+ log(`the connector now runs ${settled.record.to}`);+ } catch (error) {+ log(`could not finish replacing the old connector yet: ${errorText(error)}`);+ }+ }+}diff --git a/connector/src/settings.ts b/connector/src/settings.tsnew file mode 100644index 0000000000..013ae5bde5--- /dev/null+++ b/connector/src/settings.ts@@ -0,0 +1,62 @@+// Names, paths and limits the connector, install.sh and the e2e share. install.sh repeats the names it needs, and a+// test holds them equal.++export const CONNECTOR_VERSION = "1.0.0";++/** Docker objects the connector owns. */+export const NAMES = {+ connector: "mausbot-connector",+ connectorNext: "mausbot-connector-next",+ home: "mausbot-home",+ dataVolume: "mausbot-data",+ stateVolume: "mausbot-connector",+ snapshotVolume: "mausbot-snapshot",+ backupPrefix: "mausbot-backup-",+} as const;++export const LABELS = {+ role: "com.mausbot.role",+ instance: "com.mausbot.instance",+ created: "com.mausbot.created",+ image: "com.mausbot.image",+ env: "com.mausbot.env",+} as const;++/** Backups the connector keeps; a newer one replaces the oldest. */+export const BACKUPS_KEPT = 3;++/** Inside the connector's container. */+export const PATHS = {+ state: process.env.MAUSBOT_STATE_DIR || "/state",+ docker: process.env.MAUSBOT_DOCKER_SOCKET || "/var/run/docker.sock",+ /** /etc/mausbot on the host, mounted read-only: the seccomp profile install.sh put there. */+ hostConfig: process.env.MAUSBOT_HOST_CONFIG_DIR || "/etc/mausbot",+ /** The connector's own copies, which install.sh installs from this image. */+ profiles: process.env.MAUSBOT_PROFILES_DIR || "/app/profiles",+} as const;++export const SECCOMP_FILE = "seccomp-omb-home.json";+export const APPARMOR_PROFILE = "omb-home-narrow";++/** Where the home's edge listens on the server: loopback only, reached by the tunnel and by the connector. */+export const HOME_PORT = 8080;++/**+ * On a stock Docker host the bot box needs our AppArmor and seccomp profiles and no masked /proc paths; the home needs+ * Docker's init, shared memory for Chrome, time to stop cleanly (its launcher kills its children at 20 s), and only the+ * four capabilities its root launcher uses. No --privileged, no added capability, no restart policy: the connector+ * restarts the home.+ */+export const HOME_CAPABILITIES = ["CHOWN", "SETUID", "SETGID", "KILL"] as const;+export const HOME_STOP_TIMEOUT_S = 30;+export const HOME_SHM_BYTES = 512 * 1024 * 1024;+export const HOME_OOM_SCORE_ADJ = -800;++/** The first home image whose launcher clears another container's data-directory lease itself. */+export const LEASE_FIXED_VERSION = [0, 1, 131] as const;++export function envSeconds(name: string, fallback: number, min: number, max: number): number {+ const raw = process.env[name];+ const value = raw === undefined ? NaN : Number(raw);+ return Number.isInteger(value) && value >= min && value <= max ? value : fallback;+}diff --git a/connector/src/state.ts b/connector/src/state.tsnew file mode 100644index 0000000000..e0cf77af80--- /dev/null+++ b/connector/src/state.ts@@ -0,0 +1,167 @@+// The connector's state volume: small JSON files, each written whole (temp file, then rename) and readable by root only,+// in a folder only root may enter. The agent token and the home's environment live here and nowhere else.+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";++export interface AgentRecord {+ version: 1;+ admin: string;+ serverId: string;+ cloudId: string;+ agentToken: string;+ enrolledAt: number;+}++/** A step of a job that changes the home or its data, written before the step starts, so a restart can finish it. */+export interface Operation {+ jobId: string;+ type: "start" | "update" | "restore" | "import-disk" | "backup" | "export-disk";+ phase: string;+ previousImage: string | null;+ nextImage: string | null;+ /** What the job makes or reads besides the home: a backup's volume, an archive's file name in the state folder. */+ target: string | null;+ /** The safety copy holds the data as it was: a restart while this is true puts it back. */+ dataAtRisk: boolean;+ /** The home was running before the job and should run after it. */+ wasRunning: boolean;+ startedAt: number;+}++export interface HomeRecord {+ version: 1;+ /** What the Admin asked for last; the connector keeps the home that way. */+ desired: "running" | "stopped";+ image: string | null;+ /** The image before the last update, kept on the server so a rollback needs no download. */+ previousImage: string | null;+ operation: Operation | null;+}++export interface StatusRecord {+ connected: boolean;+ unauthorized: boolean;+ lastConnectedAt: number | null;+ lastHeartbeatAt: number | null;+ lastError: string | null;+}++export interface SelfUpdateRecord {+ jobId: string;+ from: string | null;+ to: string;+ /** The id of the container that started the update; the new one removes it once it has connected. */+ previousContainer: string;+ candidateContainer: string;+ /** The new connector's MAUSBOT_INSTANCE: how each side knows which one it is. */+ candidateInstance: string;+ deadline: number;+}++const FILES = {+ agent: "agent.json",+ home: "home.json",+ env: "home-env.json",+ status: "status.json",+ selfUpdate: "self-update.json",+} as const;++export class StateStore {+ readonly dir: string;++ constructor(dir: string) {+ this.dir = dir;+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ if (process.platform !== "win32" && (statSync(dir).mode & 0o077) !== 0) chmodSync(dir, 0o700);+ }++ path(name: string): string {+ return join(this.dir, name);+ }++ read<T>(name: string): T | null {+ const file = this.path(name);+ if (!existsSync(file)) return null;+ try {+ return JSON.parse(readFileSync(file, "utf8")) as T;+ } catch {+ throw new Error(`The connector's state file ${name} is unreadable. Run the install command again to repair it.`);+ }+ }++ write(name: string, value: unknown): void {+ const file = this.path(name);+ const temp = `${file}.${process.pid}.tmp`;+ writeFileSync(temp, `${JSON.stringify(value, null, 1)}\n`, { mode: 0o600 });+ if (process.platform !== "win32") chmodSync(temp, 0o600);+ renameSync(temp, file);+ }++ remove(name: string): void {+ rmSync(this.path(name), { force: true });+ }++ agent(): AgentRecord | null {+ return this.read<AgentRecord>(FILES.agent);+ }++ saveAgent(record: AgentRecord): void {+ this.write(FILES.agent, record);+ }++ home(): HomeRecord {+ return this.read<HomeRecord>(FILES.home) ?? { version: 1, desired: "stopped", image: null, previousImage: null, operation: null };+ }++ saveHome(record: HomeRecord): void {+ this.write(FILES.home, record);+ }++ homeEnv(): Record<string, string> | null {+ return this.read<Record<string, string>>(FILES.env);+ }++ saveHomeEnv(env: Record<string, string>): void {+ this.write(FILES.env, env);+ }++ status(): StatusRecord {+ return this.read<StatusRecord>(FILES.status) ?? { connected: false, unauthorized: false, lastConnectedAt: null, lastHeartbeatAt: null, lastError: null };+ }++ saveStatus(patch: Partial<StatusRecord>): void {+ this.write(FILES.status, { ...this.status(), ...patch });+ }++ selfUpdate(): SelfUpdateRecord | null {+ return this.read<SelfUpdateRecord>(FILES.selfUpdate);+ }++ saveSelfUpdate(record: SelfUpdateRecord): void {+ this.write(FILES.selfUpdate, record);+ }++ /** Decides a self-update once: the first of the two connectors to rename the record wins; the other learns which. */+ settleSelfUpdate(outcome: "confirmed" | "aborted"): "confirmed" | "aborted" {+ try {+ renameSync(this.path(FILES.selfUpdate), this.path(`self-update.${outcome}.json`));+ return outcome;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;+ return existsSync(this.path("self-update.confirmed.json")) ? "confirmed" : "aborted";+ }+ }++ selfUpdateOutcome(): { outcome: "confirmed" | "aborted"; record: SelfUpdateRecord } | null {+ for (const outcome of ["confirmed", "aborted"] as const) {+ const record = this.read<SelfUpdateRecord>(`self-update.${outcome}.json`);+ if (record) return { outcome, record };+ }+ return null;+ }++ clearSelfUpdateOutcome(): void {+ this.remove("self-update.confirmed.json");+ this.remove("self-update.aborted.json");+ }+}diff --git a/connector/src/transfer.ts b/connector/src/transfer.tsnew file mode 100644index 0000000000..15804b0424--- /dev/null+++ b/connector/src/transfer.ts@@ -0,0 +1,74 @@+// Streams an archive of /data to or from an https URL, hashing it on the way. Plain http only for a test Admin on this+// machine's loopback (protocol.ts checkTransferUrl).+import { createHash } from "node:crypto";+import { createReadStream, createWriteStream, statSync } from "node:fs";+import { request as httpRequest, type IncomingMessage } from "node:http";+import { request as httpsRequest } from "node:https";+import { Transform } from "node:stream";+import { pipeline } from "node:stream/promises";++export interface Transfer {+ /** Writes the body at `url` to `file`; refuses more than `maxBytes`. */+ download(url: string, headers: Record<string, string>, file: string, maxBytes: number): Promise<{ bytes: number }>;+ /** PUTs `file` to `url`. */+ upload(url: string, headers: Record<string, string>, file: string): Promise<{ bytes: number; sha256: string }>;+}++function requester(url: URL) {+ return url.protocol === "https:" ? httpsRequest : httpRequest;+}++function counter(limit: number, onChunk: (chunk: Buffer) => void) {+ let bytes = 0;+ const stream = new Transform({+ transform(chunk: Buffer, _encoding, done) {+ bytes += chunk.length;+ if (bytes > limit) return done(new Error(`the archive is larger than the ${Math.floor(limit / 1e9)} GB free on this server`));+ onChunk(chunk);+ done(null, chunk);+ },+ });+ return { stream, bytes: () => bytes };+}++export const httpTransfer: Transfer = {+ download(target, headers, file, maxBytes) {+ const url = new URL(target);+ return new Promise((resolve, reject) => {+ const req = requester(url)(url, { method: "GET", headers, timeout: 120_000 }, (res: IncomingMessage) => {+ if ((res.statusCode ?? 0) !== 200) {+ res.resume();+ reject(new Error(`the archive's address answered ${res.statusCode}`));+ return;+ }+ const count = counter(maxBytes, () => {});+ pipeline(res, count.stream, createWriteStream(file, { mode: 0o600 })).then(() => resolve({ bytes: count.bytes() }), reject);+ });+ req.on("timeout", () => req.destroy(new Error("the archive's address stopped answering")));+ req.on("error", reject);+ req.end();+ });+ },++ upload(target, headers, file) {+ const url = new URL(target);+ const size = statSync(file).size;+ const hash = createHash("sha256");+ return new Promise((resolve, reject) => {+ const req = requester(url)(url, {+ method: "PUT",+ headers: { ...headers, "content-type": "application/gzip", "content-length": String(size) },+ timeout: 120_000,+ }, (res: IncomingMessage) => {+ res.resume();+ res.on("end", () => ((res.statusCode ?? 0) >= 200 && (res.statusCode ?? 0) < 300+ ? resolve({ bytes: size, sha256: hash.digest("hex") })+ : reject(new Error(`the Admin answered ${res.statusCode} to the upload`))));+ });+ req.on("timeout", () => req.destroy(new Error("the Admin stopped answering the upload")));+ req.on("error", reject);+ const count = counter(Number.MAX_SAFE_INTEGER, (chunk) => hash.update(chunk));+ pipeline(createReadStream(file), count.stream, req).catch(reject);+ });+ },+};diff --git a/connector/test/agent.test.ts b/connector/test/agent.test.tsnew file mode 100644index 0000000000..664e3b686a--- /dev/null+++ b/connector/test/agent.test.ts@@ -0,0 +1,133 @@+import { afterEach, describe, expect, it } from "vitest";++import { Agent, backoffMs, connectUrl } from "../src/agent.ts";+import { adminOrigin, enroll } from "../src/enroll.ts";+import { CLOSE_UNAUTHORIZED, type HostFacts, type Job, type JobReply } from "../src/protocol.ts";+import type { StatusRecord } from "../src/state.ts";+import { FakeAdmin } from "./fake-admin.ts";++const host: HostFacts = { os: "Ubuntu 24.04.3 LTS", kernel: "6.8.0", arch: "x86_64", cpus: 4, memMb: 16_000, diskGb: 120, docker: "28.0.4", apparmor: true, userns: true };+const connector = { version: "1.0.0", protocol: 1 as const, image: null };+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));+ }+}++async function connected(options: { handle?: (job: Job) => Promise<JobReply | null>; setTimer?: (callback: () => void, ms: number) => unknown } = {}) {+ const admin = new FakeAdmin();+ const origin = await admin.listen();+ cleanups.push(() => admin.close());+ const record = await enroll({ admin: origin, code: admin.mintCode(), host, connector });+ const handled: Job[] = [];+ const statuses: Partial<StatusRecord>[] = [];+ const lines: string[] = [];+ const agent = new Agent({+ admin: origin, token: record.agentToken, log: (line) => lines.push(line), heartbeatMs: 100, random: () => 0,+ heartbeat: async () => ({ heartbeat: { host: { ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0, checks: [] }, home: { state: "running", image: null, health: null }, connector } }),+ handle: options.handle ?? (async (job) => {+ handled.push(job);+ return { id: job.id, ok: true, result: { host: { ...host } } } as unknown as JobReply;+ }),+ status: (patch) => statuses.push(patch),+ ...(options.setTimer ? { setTimer: options.setTimer } : {}),+ });+ cleanups.push(() => agent.stop());+ agent.start();+ await until(() => admin.connected);+ return { admin, origin, record, agent, handled, statuses, lines };+}++describe("the connector's connection to MausBot", () => {+ it("enrols once with the one-time code, then connects with its own token and sends a heartbeat every interval", async () => {+ const { admin, record, statuses, lines } = await connected();+ const [server] = admin.servers.values();+ expect(server).toMatchObject({ serverId: record.serverId, cloudId: record.cloudId, token: record.agentToken, enroll: { host, connector } });+ expect(record).toMatchObject({ version: 1, admin: admin.origin });+ await until(() => admin.heartbeats.length >= 3);+ expect(admin.heartbeats[0]).toMatchObject({ home: { state: "running" }, connector: { protocol: 1 }, host: { arch: "x86_64" } });+ expect(statuses).toContainEqual(expect.objectContaining({ connected: true, unauthorized: false }));+ expect(admin.connections).toHaveLength(1);+ expect(lines.join("\n")).not.toContain(record.agentToken);+ await expect(enroll({ admin: admin.origin, code: [...admin.codes][0] ?? "MB-USED-CODE", host, connector })).rejects.toThrow(+ "This code isn't valid anymore: a code works once, for one hour. Make a new one in MausBot and run the install command again.");+ });++ it("answers each job once: the same id again gets the same reply, and never a second run", async () => {+ const { admin, handled } = await connected();+ const first = await admin.job("host-health", {}, "job-1");+ expect(first).toMatchObject({ id: "job-1", ok: true });+ const again = await admin.job("host-health", {}, "job-1");+ expect(again).toEqual(first);+ expect(handled.map((job) => job.id)).toEqual(["job-1"]);+ });++ it("refuses a malformed job by its id, and ignores what has no id or is not JSON", async () => {+ const { admin, handled, lines } = await connected();+ expect(await admin.job("shell" as "status", { command: "id" }, "job-2")).toEqual({ id: "job-2", ok: false, error: { code: "unknown_job", message: 'unknown job type "shell"' } });+ expect(await admin.job("restore", { backupId: "../../etc" }, "job-3")).toMatchObject({ id: "job-3", ok: false, error: { code: "invalid_args" } });+ admin.send({ type: "status" });+ admin.send("not json");+ await until(() => lines.some((line) => line.includes("not JSON")));+ expect(lines).toContain("ignored a job without a valid id: a job needs an id of 1 to 64 letters, digits, - or _");+ expect(handled).toEqual([]);+ });++ it("keeps a reply made while the connection is down, comes back with backoff, and delivers it", async () => {+ let finish: (reply: JobReply) => void = () => {};+ const { admin } = await connected({ handle: (job) => new Promise((resolve) => { finish = resolve; void job; }) });+ admin.send({ id: "slow-1", type: "update", args: { image: `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"b".repeat(64)}` } });+ await new Promise((resolve) => setTimeout(resolve, 50));+ admin.drop();+ await until(() => !admin.connected);+ finish({ id: "slow-1", ok: false, error: { code: "update_rolled_back", message: "rolled back", image: "x" } });+ const reply = await admin.replyTo("slow-1", 5_000);+ expect(reply).toMatchObject({ id: "slow-1", ok: false, error: { code: "update_rolled_back" } });+ expect(admin.connections).toHaveLength(2);+ // Acknowledged: a later connection does not bring it again.+ const count = admin.replyCounts.get("slow-1");+ admin.drop();+ await until(() => admin.connections.length === 3);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(admin.replyCounts.get("slow-1")).toBe(count);+ expect(backoffMs(0, 0)).toBe(500);+ expect(backoffMs(3, 1)).toBe(12_000);+ expect(backoffMs(20, 0.5)).toBe(60_000);+ });++ it("slows right down when MausBot no longer knows its token, and says so", async () => {+ const waits: number[] = [];+ const { admin, record, statuses, lines } = await connected({+ setTimer: (callback, ms) => {+ waits.push(ms);+ return ms < 1000 ? setTimeout(callback, ms) : setTimeout(() => {}, 0);+ },+ });+ admin.revoked.add(record.agentToken);+ admin.drop();+ await until(() => statuses.some((patch) => patch.unauthorized === true));+ expect(waits).toContain(5 * 60_000);+ expect(lines).toContain("MausBot no longer knows this server; run the install command again with a new code to connect it");+ expect(CLOSE_UNAUTHORIZED).toBe(4401);+ });++ it("connects to the Admin's own origin over wss, and to a test Admin on loopback over ws only", () => {+ expect(connectUrl("https://cloud.openmausbot.com")).toBe("wss://cloud.openmausbot.com/api/cloud/servers/agent/connect");+ expect(connectUrl("http://127.0.0.1:9000")).toBe("ws://127.0.0.1:9000/api/cloud/servers/agent/connect");+ expect(adminOrigin("https://cloud.openmausbot.com/")).toBe("https://cloud.openmausbot.com");+ expect(adminOrigin("http://127.0.0.1:9000")).toBe("http://127.0.0.1:9000");+ for (const bad of ["http://cloud.openmausbot.com", "https://user:[email protected]", "ftp://x", undefined]) expect(() => adminOrigin(bad)).toThrow();+ });++ it("says plainly when MausBot cannot be reached at enrolment", async () => {+ await expect(enroll({ admin: "http://127.0.0.1:9", code: "MB-1A2B-3C4D", host, connector })).rejects.toThrow(/^This server can't reach MausBot at http:\/\/127\.0\.0\.1:9 /);+ await expect(enroll({ admin: "http://127.0.0.1:9", code: "MB 1A2B", host, connector })).rejects.toThrow("the code is the one-time code MausBot shows next to the install command");+ });+});diff --git a/connector/test/fake-admin.ts b/connector/test/fake-admin.tsnew file mode 100644index 0000000000..2b54807f39--- /dev/null+++ b/connector/test/fake-admin.ts@@ -0,0 +1,208 @@+// A stand-in for the MausBot Cloud Admin's side of the connector protocol (connector/src/protocol.ts): one-time codes,+// enrolment, the agent WebSocket with its Bearer token, heartbeats, jobs and their replies, and export uploads. The+// unit tests drive it in process; the e2e runs it as a program and drives it over its /control routes on loopback:+// node connector/test/fake-admin.ts <port> <code>+import { randomBytes } from "node:crypto";+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { fileURLToPath } from "node:url";++import { WebSocketServer, type WebSocket } from "ws";++import {+ CLOSE_REPLACED, CLOSE_UNAUTHORIZED, CONNECT_PATH, ENROLL_PATH, EXPORT_PATH,+ type EnrollRequest, type EnrollResponse, type Heartbeat, type JobReply, type JobType, type JobArgs,+} from "../src/protocol.ts";++interface EnrolledServer {+ serverId: string;+ cloudId: string;+ token: string;+ enroll: EnrollRequest;+}++export class FakeAdmin {+ readonly codes = new Set<string>();+ readonly servers = new Map<string, EnrolledServer>();+ readonly heartbeats: Heartbeat["heartbeat"][] = [];+ readonly replies: JobReply[] = [];+ /** Every reply message per job id, repeats included. */+ readonly replyCounts = new Map<string, number>();+ readonly exports = new Map<string, Buffer>();+ readonly connections: { token: string; at: number }[] = [];+ /** Tokens the Admin forgot: their next connection is closed with 4401. */+ readonly revoked = new Set<string>();+ private socket: WebSocket | null = null;+ private readonly waiting = new Map<string, (reply: JobReply) => void>();+ private readonly http: Server;+ private readonly wss: WebSocketServer;+ private nextJob = 1;++ constructor() {+ this.http = createServer((req, res) => {+ this.route(req, res).catch((error) => {+ res.writeHead(500).end(String(error));+ });+ });+ this.wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });+ this.http.on("upgrade", (req, socket, head) => {+ if (new URL(req.url ?? "/", "http://admin").pathname !== CONNECT_PATH) {+ socket.destroy();+ return;+ }+ const token = /^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1] ?? "";+ this.wss.handleUpgrade(req, socket, head, (ws) => {+ const known = [...this.servers.values()].some((server) => server.token === token);+ if (!known || this.revoked.has(token)) {+ ws.close(CLOSE_UNAUTHORIZED, "unknown token");+ return;+ }+ this.connections.push({ token, at: Date.now() });+ this.socket?.close(CLOSE_REPLACED, "a newer connection took over");+ this.socket = ws;+ ws.on("message", (data) => this.received(String(data)));+ ws.on("close", () => {+ if (this.socket === ws) this.socket = null;+ });+ });+ });+ }++ async listen(port = 0): Promise<string> {+ await new Promise<void>((resolve) => this.http.listen(port, "127.0.0.1", resolve));+ return this.origin;+ }++ get origin(): string {+ return `http://127.0.0.1:${(this.http.address() as AddressInfo).port}`;+ }++ get connected(): boolean {+ return this.socket !== null && this.socket.readyState === 1;+ }++ mintCode(code = `MB-${randomBytes(4).toString("hex").toUpperCase()}-${randomBytes(4).toString("hex").toUpperCase()}`): string {+ this.codes.add(code);+ return code;+ }++ async close(): Promise<void> {+ for (const client of this.wss.clients) client.terminate();+ this.wss.close();+ await new Promise<void>((resolve) => this.http.close(() => resolve()));+ }++ /** Drops the connection as a network failure would. */+ drop(): void {+ this.socket?.terminate();+ this.socket = null;+ }++ send(message: unknown): void {+ if (!this.socket) throw new Error("no connector is connected");+ this.socket.send(typeof message === "string" ? message : JSON.stringify(message));+ }++ /** Sends a job and resolves with the next reply to its id. */+ job<T extends JobType>(type: T, args: JobArgs[T] | Record<string, unknown>, id = `job-${this.nextJob++}`, timeoutMs = 30 * 60_000): Promise<JobReply> {+ const reply = new Promise<JobReply>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.waiting.delete(id);+ reject(new Error(`no reply to ${type} ${id}`));+ }, timeoutMs);+ this.waiting.set(id, (value) => {+ clearTimeout(timer);+ resolve(value);+ });+ });+ this.send({ id, type, args });+ return reply;+ }++ /** The reply to a job id, whenever it arrives (a job answered after a reconnect, or by a new connector). */+ replyTo(id: string, timeoutMs = 30 * 60_000): Promise<JobReply> {+ const answered = this.replies.find((reply) => reply.id === id);+ if (answered) return Promise.resolve(answered);+ return new Promise<JobReply>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`no reply to ${id}`)), timeoutMs);+ this.waiting.set(id, (value) => {+ clearTimeout(timer);+ resolve(value);+ });+ });+ }++ private received(text: string): void {+ const message = JSON.parse(text) as Heartbeat | JobReply;+ if ("heartbeat" in message) {+ this.heartbeats.push(message.heartbeat);+ return;+ }+ this.replyCounts.set(message.id, (this.replyCounts.get(message.id) ?? 0) + 1);+ this.send({ ack: message.id });+ if (this.replies.some((reply) => reply.id === message.id) && !this.waiting.has(message.id)) return;+ this.replies.push(message);+ const waiter = this.waiting.get(message.id);+ if (waiter) {+ this.waiting.delete(message.id);+ waiter(message);+ }+ }++ private async body(req: IncomingMessage): Promise<Buffer> {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ return Buffer.concat(chunks);+ }++ private json(res: ServerResponse, status: number, value: unknown): void {+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(value));+ }++ private async route(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const url = new URL(req.url ?? "/", "http://admin");+ if (req.method === "POST" && url.pathname === ENROLL_PATH) {+ let request: EnrollRequest;+ try { request = JSON.parse((await this.body(req)).toString("utf8")) as EnrollRequest; } catch { return this.json(res, 400, { error: "invalid_body" }); }+ if (!this.codes.delete(request.code)) return this.json(res, 401, { error: "invalid_code" });+ const answer: EnrollResponse = { serverId: `srv_${randomBytes(6).toString("hex")}`, cloudId: `cloud_${randomBytes(6).toString("hex")}`, agentToken: `ombs_${randomBytes(32).toString("base64url")}` };+ this.servers.set(answer.serverId, { ...answer, token: answer.agentToken, enroll: request });+ return this.json(res, 200, answer);+ }+ if (req.method === "PUT" && url.pathname.startsWith(`${EXPORT_PATH}/`)) {+ const token = /^Bearer (.+)$/.exec(String(req.headers.authorization ?? ""))?.[1] ?? "";+ if (![...this.servers.values()].some((server) => server.token === token)) return this.json(res, 401, { error: "unauthorized" });+ this.exports.set(url.pathname.slice(EXPORT_PATH.length + 1), await this.body(req));+ return this.json(res, 200, { ok: true });+ }+ // The e2e's handle on this Admin; never part of the protocol.+ if (url.pathname === "/control/state" && req.method === "GET") {+ return this.json(res, 200, { connected: this.connected, servers: [...this.servers.values()].map(({ serverId, cloudId, enroll }) => ({ serverId, cloudId, host: enroll.host, connector: enroll.connector })),+ heartbeats: this.heartbeats.length, lastHeartbeat: this.heartbeats.at(-1) ?? null, connections: this.connections.length });+ }+ if (url.pathname === "/control/job" && req.method === "POST") {+ const { type, args, id } = JSON.parse((await this.body(req)).toString("utf8")) as { type: JobType; args: Record<string, unknown>; id?: string };+ try {+ return this.json(res, 200, await this.job(type, args, id));+ } catch (error) {+ return this.json(res, 504, { error: String(error) });+ }+ }+ if (url.pathname === "/control/reply" && req.method === "GET") {+ try {+ return this.json(res, 200, await this.replyTo(url.searchParams.get("id") ?? "", Number(url.searchParams.get("timeoutMs") ?? 600_000)));+ } catch (error) {+ return this.json(res, 504, { error: String(error) });+ }+ }+ res.writeHead(404, { "content-type": "text/plain" }).end("not found");+ }+}++if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {+ const [port, code] = process.argv.slice(2);+ const admin = new FakeAdmin();+ if (code) admin.mintCode(code);+ const origin = await admin.listen(Number(port ?? 0));+ console.log(`fake admin on ${origin}`);+}diff --git a/connector/test/fake-docker.ts b/connector/test/fake-docker.tsnew file mode 100644index 0000000000..a1100c0753--- /dev/null+++ b/connector/test/fake-docker.ts@@ -0,0 +1,287 @@+// An in-memory Docker Engine for the connector's tests: images, containers, volumes holding files, and the fixed+// helper commands the connector runs (cp, find, du, tar, the box probe) carried out on those files.+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import type { ContainerInfo, ContainerSpec, ContainerSummary, Docker, DockerInfo, DockerVersion, ImageInfo, VolumeInfo } from "../src/docker.ts";+import { DockerError } from "../src/docker.ts";++export interface FakeContainer {+ id: string;+ name: string;+ spec: ContainerSpec;+ status: "created" | "running" | "exited" | "paused";+ exitCode: number;+ startedAt: number;+ logs: string;+}++export interface FakeVolume {+ labels: Record<string, string>;+ files: Map<string, string>;+}++const VERSION_LABEL = "org.opencontainers.image.version";++export class FakeDocker implements Docker {+ /** What `pull` can fetch: reference → image labels. */+ readonly registry = new Map<string, Record<string, string>>();+ readonly images = new Map<string, Record<string, string>>();+ readonly containers = new Map<string, FakeContainer>();+ readonly volumes = new Map<string, FakeVolume>();+ readonly calls: string[] = [];+ /** Commands the helpers ran, in order. */+ readonly helperRuns: string[][] = [];+ readonly startFailures = new Map<string, string>();+ info_: DockerInfo = {+ ServerVersion: "28.0.4", OperatingSystem: "Ubuntu 24.04.3 LTS", KernelVersion: "6.8.0-1021-azure", Architecture: "x86_64", NCPU: 4,+ MemTotal: 16 * 1073741824, SecurityOptions: ["name=apparmor", "name=seccomp,profile=builtin", "name=cgroupns"], DockerRootDir: "/var/lib/docker",+ };+ /** A copy of /data fails, as on a full disk. */+ failCopy = false;+ /** What the box probe prints and its exit code. */+ probe = { code: 0, output: "" };+ /** 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. */+ onConnectorStart: ((container: FakeContainer) => Promise<void> | void) | null = null;+ now: () => number = () => Date.now();+ private nextId = 1;+ private readonly stateDir: string;++ constructor(stateDir: string) {+ this.stateDir = stateDir;+ }++ publish(image: string, version: string | null): void {+ this.registry.set(image, version ? { [VERSION_LABEL]: version } : {});+ }++ volume(name: string): FakeVolume {+ const volume = this.volumes.get(name);+ if (!volume) throw new Error(`no volume ${name}`);+ return volume;+ }++ files(name: string): Record<string, string> {+ return Object.fromEntries([...this.volume(name).files].sort());+ }++ container(name: string): FakeContainer | null {+ return this.containers.get(name) ?? [...this.containers.values()].find((container) => container.id === name) ?? null;+ }++ async version(): Promise<DockerVersion> {+ return { Version: this.info_.ServerVersion, ApiVersion: "1.48", MinAPIVersion: "1.24" };+ }++ async info(): Promise<DockerInfo> {+ return this.info_;+ }++ async pull(image: string): Promise<void> {+ this.calls.push(`pull ${image}`);+ const labels = this.registry.get(image);+ if (!labels) throw new DockerError(404, `manifest for ${image} not found: manifest unknown`);+ this.images.set(image, labels);+ }++ async imageInspect(image: string): Promise<ImageInfo | null> {+ const labels = this.images.get(image);+ return labels ? { Id: `sha256:${image.length}`, RepoDigests: [image], Config: { Labels: labels } } : null;+ }++ async removeImage(image: string): Promise<void> {+ this.calls.push(`rmi ${image}`);+ if ([...this.containers.values()].some((container) => container.spec.Image === image)) return;+ this.images.delete(image);+ }++ async containerInspect(name: string): Promise<ContainerInfo | null> {+ const container = this.container(name);+ if (!container) return null;+ return {+ Id: container.id,+ Name: `/${container.name}`,+ Created: new Date(0).toISOString(),+ Config: { Image: container.spec.Image, Env: container.spec.Env ?? [], Labels: container.spec.Labels ?? {}, Cmd: container.spec.Cmd ?? null, Entrypoint: container.spec.Entrypoint ?? null },+ HostConfig: { ...container.spec.HostConfig } as Record<string, unknown>,+ State: {+ Status: container.status, Running: container.status === "running" || container.status === "paused", Paused: container.status === "paused",+ Restarting: false, ExitCode: container.exitCode, StartedAt: new Date(container.startedAt).toISOString(), FinishedAt: new Date(0).toISOString(),+ },+ Mounts: (container.spec.HostConfig.Mounts ?? []).map((mount) => ({ Type: mount.Type, Name: mount.Source, Source: mount.Source, Destination: mount.Target })),+ };+ }++ async listContainers(labels: Record<string, string>): Promise<ContainerSummary[]> {+ return [...this.containers.values()]+ .filter((container) => Object.entries(labels).every(([key, value]) => container.spec.Labels?.[key] === value))+ .map((container) => ({ Id: container.id, Names: [`/${container.name}`], Image: container.spec.Image, State: container.status, Labels: container.spec.Labels ?? {} }));+ }++ async containersUsing(volume: string): Promise<ContainerSummary[]> {+ return [...this.containers.values()]+ .filter((container) => (container.spec.HostConfig.Mounts ?? []).some((mount) => mount.Source === volume))+ .map((container) => ({ Id: container.id, Names: [`/${container.name}`], Image: container.spec.Image, State: container.status, Labels: container.spec.Labels ?? {} }));+ }++ async createContainer(name: string, spec: ContainerSpec): Promise<string> {+ this.calls.push(`create ${name} ${spec.Image}`);+ if (this.containers.has(name)) throw new DockerError(409, `Conflict. The container name "/${name}" is already in use`);+ if (!this.images.has(spec.Image)) throw new DockerError(404, `No such image: ${spec.Image}`);+ for (const mount of spec.HostConfig.Mounts ?? []) {+ if (!this.volumes.has(mount.Source)) this.volumes.set(mount.Source, { labels: {}, files: new Map() });+ }+ const id = `c${String(this.nextId++).padStart(11, "0")}`;+ this.containers.set(name, { id, name, spec, status: "created", exitCode: 0, startedAt: 0, logs: "" });+ return id;+ }++ async startContainer(name: string): Promise<void> {+ const container = this.container(name);+ if (!container) throw new DockerError(404, `No such container: ${name}`);+ this.calls.push(`start ${container.name}`);+ const failure = this.startFailures.get(container.name);+ if (failure) throw new DockerError(500, failure);+ if (container.status === "running") return;+ container.status = "running";+ container.startedAt = this.now();+ const role = container.spec.Labels?.["com.mausbot.role"];+ if (role === "helper") this.runHelper(container);+ else if (role === "home") this.onHomeStart?.(container);+ else if (role === "connector") await this.onConnectorStart?.(container);+ }++ async stopContainer(name: string): Promise<void> {+ const container = this.container(name);+ if (!container) return;+ if (container.status === "running" || container.status === "paused") this.calls.push(`stop ${container.name}`);+ if (container.status === "running" || container.status === "paused") container.status = "exited";+ }++ async unpauseContainer(name: string): Promise<void> {+ const container = this.container(name);+ if (container?.status === "paused") container.status = "running";+ }++ async removeContainer(name: string): Promise<void> {+ const container = this.container(name);+ if (!container) return;+ if (container.status === "paused") throw new DockerError(409, "You cannot remove a paused container. Unpause and then stop the container before attempting removal or force remove");+ this.calls.push(`rm ${container.name}`);+ this.containers.delete(container.name);+ }++ async renameContainer(name: string, to: string): Promise<void> {+ const container = this.container(name);+ if (!container) throw new DockerError(404, `No such container: ${name}`);+ if (this.containers.has(to)) throw new DockerError(409, `Conflict. The container name "/${to}" is already in use`);+ this.calls.push(`rename ${container.name} ${to}`);+ this.containers.delete(container.name);+ container.name = to;+ this.containers.set(to, container);+ }++ async waitContainer(name: string): Promise<number> {+ const container = this.container(name);+ if (!container) throw new DockerError(404, `No such container: ${name}`);+ return container.exitCode;+ }++ async logs(name: string): Promise<string> {+ return this.container(name)?.logs ?? "";+ }++ async volumeInspect(name: string): Promise<VolumeInfo | null> {+ const volume = this.volumes.get(name);+ return volume ? { Name: name, Labels: volume.labels } : null;+ }++ async createVolume(name: string, labels: Record<string, string>): Promise<void> {+ this.calls.push(`volume create ${name}`);+ if (!this.volumes.has(name)) this.volumes.set(name, { labels, files: new Map() });+ }++ async removeVolume(name: string): Promise<void> {+ if (!this.volumes.has(name)) return;+ if ([...this.containers.values()].some((container) => (container.spec.HostConfig.Mounts ?? []).some((mount) => mount.Source === name))) {+ throw new DockerError(409, `remove ${name}: volume is in use`);+ }+ this.calls.push(`volume rm ${name}`);+ this.volumes.delete(name);+ }++ async listVolumes(labels: Record<string, string>): Promise<VolumeInfo[]> {+ return [...this.volumes]+ .filter(([, volume]) => Object.entries(labels).every(([key, value]) => volume.labels[key] === value))+ .map(([name, volume]) => ({ Name: name, Labels: volume.labels }));+ }++ /** The connector's helpers run fixed commands; these are carried out on the volumes' files. */+ private runHelper(container: FakeContainer): void {+ const command = [...(container.spec.Entrypoint ?? []), ...(container.spec.Cmd ?? [])];+ this.helperRuns.push(command);+ 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) };+ };+ const writable = (target: string) => {+ const found = mounted(target);+ if (found.readOnly) throw new Error(`helper writes to read-only ${target}`);+ return found.volume;+ };+ const finish = (code: number, logs = "") => {+ container.status = "exited";+ container.exitCode = code;+ container.logs = logs;+ };+ const line = command.join(" ");+ if (line === "cp -a /from/. /to/") {+ if (this.failCopy) return finish(1, "cp: error writing '/to/big.bin': No space left on device");+ const from = mounted("/from").volume;+ const to = writable("/to");+ for (const [path, content] of from.files) to.files.set(path, content);+ return finish(0);+ }+ if (line === "find /to -mindepth 1 -delete") {+ writable("/to").files.clear();+ return finish(0);+ }+ if (command[0] === "find" && command[1] === "/data" && command.includes("-delete")) {+ const data = writable("/data");+ const patterns = command.flatMap((arg, index) => (arg === "-path" ? [command[index + 1]] : []));+ const matches = (path: string) => patterns.some((pattern) => {+ const regex = new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);+ return regex.test(`/data/${path}`);+ });+ const deleted = [...data.files.keys()].filter(matches);+ for (const path of deleted) data.files.delete(path);+ return finish(0, deleted.map((path) => `/data/${path}`).join("\n"));+ }+ if (line === "du -sk /data") {+ const bytes = [...mounted("/data").volume.files.values()].reduce((sum, content) => sum + content.length, 0);+ return finish(0, `${Math.ceil(bytes / 1024)}\t/data\n`);+ }+ if (command[0] === "tar" && command.includes("-czf")) {+ const archive = command[command.indexOf("-czf") + 1];+ if (!mounted("/state").readOnly) writeFileSync(join(this.stateDir, archive.replace("/state/", "")), JSON.stringify([...mounted("/data").volume.files]));+ return finish(0);+ }+ if (command[0] === "tar" && command.includes("-xzpf")) {+ const archive = command[command.indexOf("-xzpf") + 1];+ let entries: [string, string][];+ try {+ entries = JSON.parse(readFileSync(join(this.stateDir, archive.replace("/state/", "")), "utf8")) as [string, string][];+ } catch {+ return finish(2, "tar: This does not look like a tar archive");+ }+ const data = writable("/data");+ for (const [path, content] of entries) data.files.set(path, content);+ return finish(0);+ }+ if (command[0] === "bwrap") return finish(this.probe.code, this.probe.output);+ return finish(127, `unknown helper command: ${line}`);+ }+}diff --git a/connector/test/home.test.ts b/connector/test/home.test.tsnew file mode 100644index 0000000000..cb55e0d802--- /dev/null+++ b/connector/test/home.test.ts@@ -0,0 +1,394 @@+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { JobFailure } from "../src/failure.ts";+import type { HealthRead } from "../src/home-health.ts";+import { Home, homeSpec, imageVersion } from "../src/home.ts";+import { registerSecret } from "../src/log.ts";+import { StateStore, type Operation } from "../src/state.ts";+import type { Transfer } from "../src/transfer.ts";+import { FakeDocker } from "./fake-docker.ts";++const image = (letter: string) => `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${letter.repeat(64)}`;+const A = image("a"), B = image("b"), C = image("c");+const SECRET = "Bootstrap-secret-0123456789abcdefghijklmnopq";+const RELAY = "box_omb_relay-token-0123456789abcdefghijklmnop";+const env = {+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_PUBLIC_URL: "https://acme.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: SECRET, OMB_CLOUD_BOAT_TOKEN: RELAY,+};+const SECCOMP = '{"defaultAction":"SCMP_ACT_ERRNO","syscalls":[]}';+const LEASE = ".openmausbot/openmausbot-server.lease";++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function fixture(options: { free?: number } = {}) {+ const dir = mkdtempSync(join(tmpdir(), "omb-connector-home-"));+ dirs.push(dir);+ const state = new StateStore(join(dir, "state"));+ const docker = new FakeDocker(state.dir);+ let clock = 1_800_000_000_000;+ docker.now = () => clock;+ for (const [ref, version] of [[A, "v0.1.130"], [B, "v0.1.131"], [C, "v0.1.132"]] as const) docker.publish(ref, version);+ const healthy = new Set<string>([A, B, C]);+ const lines: string[] = [];+ const readHealth: HealthRead = async (target) => {+ const home = docker.container("mausbot-home");+ if (!home || home.status !== "running") return { status: 0, report: null };+ const homeEnv = Object.fromEntries((home.spec.Env ?? []).map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]));+ if (target.secret !== homeEnv.OMB_CLOUD_BOOTSTRAP_SECRET) return { status: 401, report: { error: "invalid_signature" } };+ if (target.publicHost !== new URL(homeEnv.OMB_PUBLIC_URL).hostname || target.port !== 8080) return { status: 403, report: null };+ if (!healthy.has(home.spec.Image)) return { status: 0, report: null };+ return { status: 200, report: { version: "0.1.130", image: homeEnv.OMB_CLOUD_IMAGE, box: { box: "bwrap", checks: "32/32", failed: [] } } };+ };+ const uploads: { url: string; headers: Record<string, string>; body: string }[] = [];+ const downloads: { url: string; headers: Record<string, string> }[] = [];+ let archive = JSON.stringify([["imported.txt", "from the old home"]]);+ const transfer: Transfer = {+ async download(url, headers, file) {+ downloads.push({ url, headers });+ writeFileSync(file, archive);+ return { bytes: archive.length };+ },+ async upload(url, headers, file) {+ const body = readFileSync(file, "utf8");+ uploads.push({ url, headers, body });+ return { bytes: body.length, sha256: "0".repeat(64) };+ },+ };+ const home = new Home({+ docker, state, log: (line) => lines.push(line), readHealth, seccomp: () => SECCOMP, transfer,+ diskFree: () => options.free ?? 500e9,+ now: () => clock,+ sleep: async (ms) => { clock += ms; },+ updateWindowMs: 600_000, startWindowMs: 600_000, pollMs: 2_000,+ });+ const data = () => docker.files("mausbot-data");+ const write = (path: string, content: string) => docker.volume("mausbot-data").files.set(path, content);+ return {+ dir, state, docker, home, healthy, lines, uploads, downloads, data, write,+ clock: () => clock,+ advance: (ms: number) => { clock += ms; },+ setArchive: (value: string) => { archive = value; },+ };+}++async function started(f: ReturnType<typeof fixture>, ref = A) {+ const result = await f.home.start("start-1", ref, env);+ expect(result.home).toMatchObject({ state: "running", image: ref, health: { ok: true, image: ref } });+ return result;+}++async function failure(promise: Promise<unknown>): Promise<JobFailure> {+ try {+ await promise;+ } catch (error) {+ if (error instanceof JobFailure) return error;+ throw error;+ }+ throw new Error("the job did not fail");+}++describe("the home on an own server", () => {+ it("starts the home with exactly the settings the bot box needs, and keeps its environment readable by root only", async () => {+ const f = fixture();+ const result = await started(f);+ expect(result.home.health?.box).toEqual({ box: "bwrap", checks: "32/32", failed: [] });+ const spec = f.docker.container("mausbot-home")!.spec;+ expect(spec).toEqual(homeSpec(A, env, SECCOMP));+ expect(spec.HostConfig).toMatchObject({+ Init: true, ShmSize: 512 * 1024 * 1024, MaskedPaths: [], ReadonlyPaths: [], CapDrop: ["ALL"], CapAdd: ["CHOWN", "SETUID", "SETGID", "KILL"], OomScoreAdj: -800,+ SecurityOpt: ["apparmor=omb-home-narrow", `seccomp=${SECCOMP}`, "no-new-privileges=true"], RestartPolicy: { Name: "no" },+ PortBindings: { "8080/tcp": [{ HostIp: "127.0.0.1", HostPort: "8080" }] }, Mounts: [{ Type: "volume", Source: "mausbot-data", Target: "/data" }],+ });+ expect(spec.StopTimeout).toBe(30);+ expect(Object.keys(spec.HostConfig)).not.toContain("Privileged");+ expect(spec.Env).toEqual([...Object.entries(env).map(([name, value]) => `${name}=${value}`), `OMB_CLOUD_IMAGE=${A}`]);+ expect(JSON.parse(readFileSync(f.state.path("home-env.json"), "utf8"))).toEqual(env);+ if (process.platform !== "win32") {+ expect(statSync(f.state.path("home-env.json")).mode & 0o777).toBe(0o600);+ expect(statSync(f.state.dir).mode & 0o777).toBe(0o700);+ }+ expect(f.state.home()).toMatchObject({ desired: "running", image: A, operation: null });+ for (const line of f.lines) {+ expect(line).not.toContain(SECRET);+ expect(line).not.toContain(RELAY);+ }+ });++ it("clears the lease a killed home left before each start, until the image clears it itself, and never while a home runs", async () => {+ const f = fixture();+ await f.docker.createVolume("mausbot-data", {});+ for (const path of [LEASE, `${LEASE}.reap-0f5e6c4a-1b2c-4d3e-8f9a-0b1c2d3e4f5a`, ".openmausbot/.openmausbot-server-child/openmausbot-server.lease"]) f.write(path, "{}");+ f.write(".openmausbot/state.json", "keep");+ f.write("notes/openmausbot-server.lease", "someone's file");+ await started(f);+ expect(f.data()).toEqual({ ".openmausbot/state.json": "keep", "notes/openmausbot-server.lease": "someone's file" });+ expect(f.lines.some((line) => line.startsWith("cleared the data-directory lease records a stopped home left: /data/.openmausbot/openmausbot-server.lease"))).toBe(true);+ // A start while the home runs never touches its live lease.+ f.write(LEASE, "{}");+ const finds = () => f.docker.helperRuns.filter((command) => command[0] === "find" && command[1] === "/data").length;+ const before = finds();+ await started(f);+ expect(finds()).toBe(before);+ expect(f.data()[LEASE]).toBe("{}");+ // Nor while any other container runs on the volume.+ await f.home.stop();+ await f.docker.createContainer("someones-own", { Image: A, HostConfig: { Mounts: [{ Type: "volume", Source: "mausbot-data", Target: "/data" }] } });+ await f.docker.startContainer("someones-own");+ await f.home.restart();+ expect(finds()).toBe(before);+ expect(f.data()[LEASE]).toBe("{}");+ await f.docker.removeContainer("someones-own");+ // An image from the release that fixed the lease clears it itself.+ await f.home.stop();+ await started(f, B);+ expect(finds()).toBe(before);+ expect(f.data()[LEASE]).toBe("{}");+ expect(imageVersion("v0.1.131")).toEqual([0, 1, 131]);+ expect(imageVersion("latest")).toBeNull();+ });++ it("updates by a safety copy and a swap, keeps the previous image for a rollback, and removes the one before it", async () => {+ const f = fixture();+ await started(f);+ f.write("a.txt", "1");+ f.docker.calls.splice(0);+ const result = await f.home.update("update-1", B);+ expect(result).toMatchObject({ home: { state: "running", image: B, health: { ok: true, image: B } }, previousImage: A, snapshot: { id: "snapshot", kind: "snapshot", image: A } });+ expect(f.docker.files("mausbot-snapshot")).toEqual({ "a.txt": "1" });+ expect(f.data()).toEqual({ "a.txt": "1" });+ const order = f.docker.calls.filter((call) => /^(pull|stop|rm|create|start) (mausbot-home|ghcr)/.test(call));+ expect(order).toEqual([`pull ${B}`, "stop mausbot-home", "rm mausbot-home", `create mausbot-home ${B}`, "start mausbot-home"]);+ expect(f.state.home()).toMatchObject({ desired: "running", image: B, previousImage: A, operation: null });+ expect(f.docker.images.has(A)).toBe(true);+ await f.home.update("update-2", C);+ expect(f.docker.calls).toContain(`rmi ${A}`);+ expect(f.docker.images.has(A)).toBe(false);+ expect(f.docker.images.has(B)).toBe(true);+ });++ it("rolls back to the previous image and the data as it was when the new version does not come up within ten minutes", async () => {+ const f = fixture();+ await started(f);+ f.write("a.txt", "1");+ f.healthy.delete(B);+ f.docker.onHomeStart = (container) => {+ if (container.spec.Image === B) f.write("written-by-the-new-version.txt", "x");+ };+ const began = f.clock();+ const failed = await failure(f.home.update("update-1", B));+ expect(failed.toJobError()).toEqual({+ code: "update_rolled_back", image: A,+ message: `The new version did not become healthy (it did not report ${B} within 10 minutes). The previous version and its data are back.`,+ });+ expect(f.clock() - began).toBeGreaterThanOrEqual(600_000);+ expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });+ expect(f.data()).toEqual({ "a.txt": "1" });+ expect(f.state.home()).toMatchObject({ desired: "running", image: A, operation: null });+ expect((await f.home.report())).toMatchObject({ state: "running", image: A, health: { ok: true, image: A } });+ });++ it("rolls back at once when the new version exits as it boots, saying what it said", async () => {+ const f = fixture();+ await started(f);+ f.docker.onHomeStart = (container) => {+ if (container.spec.Image !== B) return;+ container.status = "exited";+ container.exitCode = 1;+ container.logs = "cloud home: something\nCloud home startup failed: This volume belongs to another Cloud machine. No data was changed.\n";+ };+ const began = f.clock();+ const failed = await failure(f.home.update("update-1", B));+ expect(failed.code).toBe("update_rolled_back");+ expect(failed.message).toContain("the home stopped: This volume belongs to another Cloud machine. No data was changed.");+ expect(f.clock() - began).toBeLessThan(60_000);+ expect(f.docker.container("mausbot-home")?.spec.Image).toBe(A);+ });++ it("puts the data back even when the new version is frozen, and says so when the old one does not come back either", async () => {+ const f = fixture();+ await started(f);+ f.write("a.txt", "1");+ f.docker.onHomeStart = (container) => {+ if (container.spec.Image !== B) return;+ f.write("b.txt", "2");+ container.status = "paused";+ };+ f.healthy.delete(B);+ expect((await failure(f.home.update("update-1", B))).code).toBe("update_rolled_back");+ expect(f.data()).toEqual({ "a.txt": "1" });+ f.healthy.delete(A);+ f.healthy.delete(C);+ f.docker.onHomeStart = null;+ const failed = await failure(f.home.update("update-2", C));+ expect(failed.toJobError()).toMatchObject({ code: "rollback_failed", image: A });+ expect(failed.message).toContain("The previous version and its data are back, but it did not become healthy either.");+ });++ it("starts the home again as it was when the safety copy itself fails, before anything was swapped", async () => {+ const f = fixture();+ await started(f);+ f.write("a.txt", "1");+ const { backup } = await f.home.backup("backup-1");+ f.docker.failCopy = true;+ const admin = { origin: "https://cloud.example.test", token: "t".repeat(40) };+ for (const job of [() => f.home.update("update-1", B), () => f.home.restore("restore-1", backup.id), () => f.home.importDisk("import-1", "https://storage.example.test/d.tgz", admin)]) {+ expect(await failure(job())).toMatchObject({ code: "docker", message: "Copying the data failed (cp: error writing '/to/big.bin': No space left on device); nothing was changed." });+ expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });+ expect(f.state.home()).toMatchObject({ image: A, desired: "running", operation: null });+ expect(f.data()).toEqual({ "a.txt": "1" });+ }+ expect(readdirSync(f.state.dir).filter((name) => name.startsWith("import-"))).toEqual([]);+ });++ it("changes nothing when the new image cannot be downloaded or there is no room for a safety copy", async () => {+ const f = fixture();+ await started(f);+ f.docker.calls.splice(0);+ const missing = image("d");+ expect((await failure(f.home.update("update-1", missing))).toJobError()).toMatchObject({ code: "pull_failed" });+ expect(f.docker.calls.filter((call) => call.startsWith("stop") || call.startsWith("rm"))).toEqual([]);+ expect(f.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });+ expect(f.state.home().operation).toBeNull();++ const tight = fixture({ free: 0.5e9 });+ await started(tight);+ const full = await failure(tight.home.update("update-2", B));+ expect(full.toJobError()).toMatchObject({ code: "disk_full" });+ expect(full.message).toMatch(/needs about [\d.]+ GB and 0.5 GB are free/);+ expect(tight.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: A } });+ });++ it("keeps the newest three backups and restores one, taking a safety copy of the data first", async () => {+ const f = fixture();+ await started(f);+ const made: string[] = [];+ for (const n of [1, 2, 3, 4]) {+ f.write("n.txt", String(n));+ const { backup } = await f.home.backup(`backup-${n}`);+ expect(backup).toMatchObject({ kind: "backup", image: A });+ expect(backup.id).toMatch(/^\d{8}-\d{6}-[0-9a-f]{4}$/);+ made.push(backup.id);+ f.advance(60_000);+ }+ const { backups } = await f.home.copies();+ expect(backups.map((copy) => copy.id).sort()).toEqual(made.slice(1).sort());+ expect(f.docker.files(`mausbot-backup-${made[1]}`)).toEqual({ "n.txt": "2" });+ expect(f.docker.container("mausbot-home")?.status).toBe("running");+ f.write("n.txt", "now");+ const restored = await f.home.restore("restore-1", made[1]);+ expect(restored).toMatchObject({ backupId: made[1], home: { state: "running" } });+ expect(f.data()).toEqual({ "n.txt": "2" });+ expect(f.docker.files("mausbot-snapshot")).toEqual({ "n.txt": "now" });+ expect((await failure(f.home.restore("restore-2", "20260101-000000-0000"))).code).toBe("not_found");+ });++ it("sends a gzip tar of /data to the Admin with the agent token, with the home running again meanwhile, and leaves no archive behind", async () => {+ const f = fixture();+ await started(f);+ f.write("a.txt", "1");+ const result = await f.home.exportDisk("export-1", { origin: "https://cloud.example.test", token: "agent-token-0123456789abcdefghijklmnopqrst" });+ expect(result).toEqual({ bytes: f.uploads[0].body.length, sha256: "0".repeat(64) });+ expect(f.uploads).toEqual([{ url: "https://cloud.example.test/api/cloud/servers/agent/export/export-1", headers: { authorization: "Bearer agent-token-0123456789abcdefghijklmnopqrst" }, body: JSON.stringify([["a.txt", "1"]]) }]);+ expect(readdirSync(f.state.dir).filter((name) => name.startsWith("export-"))).toEqual([]);+ expect(f.docker.container("mausbot-home")?.status).toBe("running");+ });++ it("replaces /data with an archive, sends the token only to the Admin, and puts the data back when the archive is bad", async () => {+ const f = fixture();+ await started(f);+ f.write("old.txt", "1");+ const admin = { origin: "https://cloud.example.test", token: "agent-token-0123456789abcdefghijklmnopqrst" };+ const imported = await f.home.importDisk("import-1", "https://storage.example.test/disk.tgz?sig=x", admin);+ expect(imported).toMatchObject({ bytes: expect.any(Number), home: { state: "running" } });+ expect(f.data()).toEqual({ "imported.txt": "from the old home" });+ expect(f.docker.files("mausbot-snapshot")).toEqual({ "old.txt": "1" });+ expect(f.downloads[0]).toEqual({ url: "https://storage.example.test/disk.tgz?sig=x", headers: {} });+ await f.home.importDisk("import-2", "https://cloud.example.test/api/cloud/servers/agent/import/import-2", admin);+ expect(f.downloads[1].headers).toEqual({ authorization: `Bearer ${admin.token}` });+ f.setArchive("not an archive");+ const bad = await failure(f.home.importDisk("import-3", "https://storage.example.test/bad.tgz", admin));+ expect(bad.toJobError()).toMatchObject({ code: "transfer_failed" });+ expect(bad.message).toContain("the data is as it was");+ expect(f.data()).toEqual({ "imported.txt": "from the old home" });+ expect(f.docker.container("mausbot-home")?.status).toBe("running");+ expect(readdirSync(f.state.dir).filter((name) => name.startsWith("import-"))).toEqual([]);+ });++ it("starts a home that stopped on its own again, waiting longer each time, and never one the Admin stopped", async () => {+ const f = fixture();+ await started(f);+ const crash = () => Object.assign(f.docker.container("mausbot-home")!, { status: "exited", exitCode: 137 });+ crash();+ f.write(LEASE, "{}");+ await f.home.supervise();+ expect(f.docker.container("mausbot-home")?.status).toBe("running");+ expect(f.data()[LEASE]).toBeUndefined();+ expect(f.lines).toContain("the home stopped on its own (exit 137); starting it again");+ crash();+ await f.home.supervise();+ expect(f.docker.container("mausbot-home")?.status).toBe("exited");+ expect((await f.home.report()).state).toBe("crashed");+ await f.home.stop();+ expect((await f.home.report()).state).toBe("stopped");+ await f.home.supervise();+ expect(f.docker.container("mausbot-home")?.status).toBe("exited");+ });++ it("finishes an update the connector was in the middle of: kept when the new home is healthy, else rolled back", async () => {+ const kept = fixture();+ await started(kept);+ await kept.home.update("update-1", B);+ const op = (patch: Partial<Operation>): Operation => ({ jobId: "update-9", type: "update", phase: "wait", previousImage: A, nextImage: B, target: null, dataAtRisk: true, wasRunning: true, startedAt: 1, ...patch });+ kept.state.saveHome({ ...kept.state.home(), image: A, operation: op({}) });+ expect(await kept.home.recover()).toMatchObject({ id: "update-9", ok: true, result: { previousImage: A, home: { image: B } } });+ expect(kept.state.home()).toMatchObject({ image: B, operation: null });++ const back = fixture();+ await started(back);+ back.write("a.txt", "1");+ await back.home.update("update-1", B);+ back.healthy.delete(C);+ back.write("a.txt", "changed by C");+ back.state.saveHome({ ...back.state.home(), operation: op({ previousImage: B, nextImage: C }) });+ await back.docker.pull(C);+ await back.docker.removeContainer("mausbot-home");+ await back.docker.createContainer("mausbot-home", homeSpec(C, env, SECCOMP));+ await back.docker.startContainer("mausbot-home");+ const reply = await back.home.recover();+ expect(reply).toEqual({ id: "update-9", ok: false, error: { code: "interrupted", image: B, message: `The connector restarted during this update; the data was put back as it was before, and the home runs ${B} again.` } });+ expect(back.data()).toEqual({ "a.txt": "1" });+ expect(back.docker.container("mausbot-home")).toMatchObject({ status: "running", spec: { Image: B } });+ expect(await back.home.recover()).toBeNull();+ });++ it("never puts a secret in a job's error, even when Docker's own message carries one", async () => {+ registerSecret(SECRET);+ const f = fixture();+ await started(f);+ await f.home.stop();+ f.docker.startFailures.set("mausbot-home", `container create failed: env OMB_CLOUD_BOOTSTRAP_SECRET=${SECRET} rejected`);+ const failed = await failure(f.home.restart());+ expect(failed.code).toBe("docker");+ expect(JSON.stringify(failed.toJobError())).not.toContain(SECRET);+ f.docker.startFailures.set("mausbot-home", "driver failed programming external connectivity: Bind for 127.0.0.1:8080 failed: port is already allocated");+ expect((await failure(f.home.restart())).toJobError()).toEqual({ code: "port_in_use", message: "Port 8080 on this server's loopback is used by another program, and MausBot's home needs it." });+ f.docker.startFailures.set("mausbot-home", "OCI runtime create failed: apparmor failed to apply profile: write /proc/self/attr/apparmor/exec: no such file or directory");+ expect((await failure(f.home.restart())).code).toBe("box_unavailable");+ expect(existsSync(f.state.path("agent.json"))).toBe(false);+ });++ it("refuses jobs on a home that was never started", async () => {+ const f = fixture();+ for (const job of [() => f.home.update("u", B), () => f.home.restart(), () => f.home.backup("b"), () => f.home.restore("r", "x")]) {+ expect((await failure(job())).code).toBe("no_home");+ }+ expect((await f.home.report()).state).toBe("absent");+ });+});diff --git a/connector/test/host.test.ts b/connector/test/host.test.tsnew file mode 100644index 0000000000..0a0965e053--- /dev/null+++ b/connector/test/host.test.ts@@ -0,0 +1,110 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { demuxLogs, negotiateApi, pullFailure, pullParams, type DockerInfo } from "../src/docker.ts";+import { BOX_PROBE, boxProbeFix, hostChecks, hostFacts, hostHealth, probeBox, usernsAllowed, type HostReader } from "../src/host.ts";+import { FakeDocker } from "./fake-docker.ts";++const info: DockerInfo = {+ ServerVersion: "28.0.4", OperatingSystem: "Ubuntu 24.04.3 LTS", KernelVersion: "6.8.0-1021-azure", Architecture: "x86_64", NCPU: 4,+ MemTotal: 16 * 1073741824, SecurityOptions: ["name=apparmor", "name=seccomp,profile=builtin", "name=cgroupns"], DockerRootDir: "/var/lib/docker",+};+const proc: Record<string, string> = {+ "/proc/sys/user/max_user_namespaces": "63786\n", "/proc/sys/kernel/unprivileged_userns_clone": "1\n",+ "/proc/meminfo": "MemTotal: 16384000 kB\nMemFree: 100 kB\nMemAvailable: 8192000 kB\n", "/proc/loadavg": "0.42 0.30 0.20 1/300 4242\n", "/proc/uptime": "12345.67 9999.00\n",+};+const reader = (overrides: Partial<HostReader> & { procs?: Record<string, string | null> } = {}): HostReader => ({+ proc: (path) => (overrides.procs && path in overrides.procs ? overrides.procs[path] : proc[path] ?? null),+ installedSeccomp: () => "{}",+ shippedSeccomp: () => "{}",+ disk: () => ({ free: 120e9, total: 200e9 }),+ ...overrides,+});+const failing = (checks: { id: string; ok: boolean; warning?: boolean; fix?: string }[]) => checks.filter((check) => !check.ok || check.warning).map(({ id, ok, fix }) => ({ id, ok, fix }));++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe("the server's facts and checks", () => {+ it("reports what MausBot needs to know, from Docker's own report and the host's /proc", () => {+ expect(hostFacts(info, reader())).toEqual({ os: "Ubuntu 24.04.3 LTS", kernel: "6.8.0-1021-azure", arch: "x86_64", cpus: 4, memMb: 16384, diskGb: 120, docker: "28.0.4", apparmor: true, userns: true });+ expect(hostHealth(info, reader(), { clockSkewS: 2, box: { ok: true } })).toMatchObject({ diskTotalGb: 200, memAvailableMb: 8000, load1: 0.42, uptimeS: 12345, clockSkewS: 2 });+ expect(failing(hostChecks(info, reader(), { clockSkewS: 2, box: { ok: true } }))).toEqual([]);+ });++ it("says what is wrong in plain words, with the exact fix, for each check that fails", () => {+ const fixes = (value: DockerInfo, read: HostReader, extra = { clockSkewS: 0 as number | null, box: { ok: true } as { ok: boolean; fix?: string } }) => failing(hostChecks(value, read, extra));+ expect(fixes({ ...info, Architecture: "aarch64" }, reader())).toEqual([{ id: "arch", ok: false, fix: "This server has an ARM processor. MausBot runs on Intel or AMD (x86-64) servers for now. Please pick an x86-64 server." }]);+ expect(fixes({ ...info, ServerVersion: "20.10.24" }, reader())[0]).toEqual({ id: "docker", ok: false, fix: "Docker 20.10.24 is too old; MausBot needs Docker 24 or newer. Run: curl -fsSL https://get.docker.com | sudo sh" });+ expect(fixes({ ...info, SecurityOptions: [...info.SecurityOptions!, "name=rootless"] }, reader())[0].id).toBe("rootless");+ expect(fixes({ ...info, SecurityOptions: ["name=seccomp,profile=builtin"] }, reader())[0]).toMatchObject({ id: "apparmor", fix: expect.stringContaining("sudo apt-get install -y apparmor") });+ expect(fixes(info, reader({ installedSeccomp: () => null }))[0]).toEqual({ id: "profiles", ok: false, fix: "The bot box's security profiles on this server are missing or out of date. Run the install command again." });+ expect(fixes(info, reader({ installedSeccomp: () => '{"old":true}' }))[0].id).toBe("profiles");+ expect(fixes(info, reader({ procs: { "/proc/sys/kernel/unprivileged_userns_clone": "0\n" } }))[0]).toMatchObject({ id: "userns", fix: expect.stringContaining("kernel.unprivileged_userns_clone=1") });+ expect(fixes(info, reader({ procs: { "/proc/sys/user/max_user_namespaces": "0" } }))[0].id).toBe("userns");+ expect(fixes(info, reader(), { clockSkewS: 0, box: { ok: false, fix: "the probe's words" } })).toEqual([{ id: "box", ok: false, fix: "the probe's words" }]);+ expect(fixes(info, reader({ disk: () => ({ free: 12e9, total: 200e9 }) }))).toEqual([{ id: "disk", ok: false, fix: "Your server has only 12 GB free. MausBot needs at least 20 GB: free some space or add a disk." }]);+ expect(fixes(info, reader({ disk: () => ({ free: 25e9, total: 200e9 }) }))).toEqual([{ id: "disk", ok: true, fix: "Your server's disk is 88% full. Free some space or add a disk before it fills up." }]);+ expect(fixes({ ...info, MemTotal: 2 * 1073741824 }, reader())).toEqual([{ id: "memory", ok: true, fix: "This server has 2 GB of memory; bots will be slow or stop. We suggest at least 4 GB, and 32 GB for a team of five." }]);+ expect(fixes(info, reader(), { clockSkewS: -700, box: { ok: true } })).toEqual([{ id: "clock", ok: false, fix: "Your server's clock is 12 minutes off, so it can't check our messages. Run: sudo timedatectl set-ntp true" }]);+ expect(usernsAllowed({ proc: () => null })).toBe(true);+ });++ it("runs the box probe from its own image with the home's security settings, as nobody, and says whose the fix is", async () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-connector-probe-"));+ dirs.push(dir);+ const docker = new FakeDocker(dir);+ const image = `ghcr.io/milind-soni/mausbot-connector@sha256:${"1".repeat(64)}`;+ docker.publish(image, null);+ await docker.pull(image);+ expect(await probeBox(docker, image, "{}")).toEqual({ ok: true });+ expect(docker.helperRuns.at(-1)).toEqual(BOX_PROBE);+ docker.probe = { code: 1, output: "bwrap: Failed to make / slave: Permission denied\n" };+ expect(await probeBox(docker, image, "{}")).toEqual({ ok: false, fix: "Our bots' safety box can't start on this server yet: its AppArmor profile is not loaded. Run the install command again to repair it." });+ expect([...docker.containers.keys()]).toEqual([]);+ const created = docker.calls.filter((call) => call.startsWith("create mausbot-probe-"));+ expect(created).toHaveLength(2);+ expect(boxProbeFix("bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces.")).toContain("its seccomp profile was not applied");+ expect(boxProbeFix("bwrap: Can't mount proc on /newroot/proc: Operation not permitted")).toContain("Docker here is too old");+ expect(boxProbeFix("bwrap: setting up uid map: Permission denied")).toContain("without its AppArmor profile");+ expect(boxProbeFix("bwrap: Creating new namespace failed: Operation not permitted")).toContain("user namespaces are switched off");+ expect(boxProbeFix("OCI runtime create failed: apparmor failed to apply profile: profile omb-home-narrow not found")).toContain("its AppArmor profile is not loaded");+ expect(boxProbeFix("something else")).toBe("Our bots' safety box can't start on this server yet. Run the install command again to repair it.");+ });+});++describe("speaking to Docker", () => {+ it("speaks API 1.43 to Docker 24 and at most 1.47 to newer engines, and refuses older ones", () => {+ expect(negotiateApi({ ApiVersion: "1.43", MinAPIVersion: "1.12" })).toBe("1.43");+ expect(negotiateApi({ ApiVersion: "1.45" })).toBe("1.45");+ expect(negotiateApi({ ApiVersion: "1.52", MinAPIVersion: "1.44" })).toBe("1.47");+ expect(negotiateApi({ ApiVersion: "1.41" })).toBeNull();+ expect(negotiateApi({ ApiVersion: "1.60", MinAPIVersion: "1.50" })).toBeNull();+ expect(negotiateApi({ ApiVersion: "garbage" })).toBeNull();+ });++ it("pulls by digest, and reads a failure Docker reports inside a 200 stream", () => {+ const digest = `sha256:${"a".repeat(64)}`;+ expect(pullParams(`ghcr.io/milind-soni/openmausbot-cloud-home@${digest}`)).toEqual({ fromImage: "ghcr.io/milind-soni/openmausbot-cloud-home", tag: digest });+ expect(pullParams("localhost:5000/x:tag")).toEqual({ fromImage: "localhost:5000/x", tag: "tag" });+ expect(pullParams("localhost:5000/x")).toEqual({ fromImage: "localhost:5000/x", tag: "latest" });+ expect(pullFailure('{"status":"Pulling fs layer"}\n{"errorDetail":{"message":"manifest unknown"},"error":"manifest unknown"}\n')).toBe("manifest unknown");+ expect(pullFailure('{"status":"Digest: sha256:x"}\n{"status":"Status: Downloaded newer image"}\n')).toBeNull();+ });++ it("reads a container's framed log stream", () => {+ const frame = (stream: number, text: string) => {+ const body = Buffer.from(text);+ const header = Buffer.alloc(8);+ header[0] = stream;+ header.writeUInt32BE(body.length, 4);+ return Buffer.concat([header, body]);+ };+ expect(demuxLogs(Buffer.concat([frame(1, "out line\n"), frame(2, "err line\n")]))).toBe("out line\nerr line\n");+ expect(demuxLogs(Buffer.alloc(3))).toBe("");+ });+});diff --git a/connector/test/install-script.test.ts b/connector/test/install-script.test.tsnew file mode 100644index 0000000000..2a5a505732--- /dev/null+++ b/connector/test/install-script.test.ts@@ -0,0 +1,125 @@+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 { APPARMOR_PROFILE, LABELS, NAMES, SECCOMP_FILE } from "../src/settings.ts";++const SCRIPT = join(import.meta.dirname, "..", "install.sh");+const script = readFileSync(SCRIPT, "utf8");+const posix = process.platform !== "win32";+const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/** 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> } = {}) {+ const dir = mkdtempSync(join(tmpdir(), "omb-install-"));+ dirs.push(dir);+ const bin = join(dir, "bin");+ mkdirSync(bin);+ const log = join(dir, "calls.log");+ const tool = (name: string, body: string) => {+ writeFileSync(join(bin, name), `#!/bin/sh\n${body}\n`);+ chmodSync(join(bin, name), 0o755);+ };+ tool("docker", `echo "docker $*" >> "${log}"+case "$*" in+ "ps -aq --filter label=${LABELS.role}=helper") echo helper-1 ;;+ "volume ls -q --filter label=${LABELS.role}=backup") echo mausbot-backup-20261028-000000-ab12; echo mausbot-backup-20261029-000000-cd34 ;;+esac`);+ tool("id", `echo ${options.uid ?? 0}`);+ tool("apparmor_parser", `echo "apparmor_parser $*" >> "${log}"`);+ const etc = join(dir, "etc-mausbot");+ const apparmor = join(dir, "apparmor.d");+ mkdirSync(etc);+ mkdirSync(apparmor);+ writeFileSync(join(etc, SECCOMP_FILE), "{}");+ writeFileSync(join(apparmor, APPARMOR_PROFILE), "profile");+ const result = spawnSync("sh", [SCRIPT, ...args], {+ encoding: "utf8",+ env: {+ PATH: `${bin}:/usr/bin:/bin`, MAUSBOT_ETC_DIR: etc, MAUSBOT_APPARMOR_DIR: apparmor,+ 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 };+}++describe("install.sh", () => {+ it.skipIf(!posix)("is plain POSIX sh, as `curl … | sh` runs it", () => {+ expect(spawnSync("sh", ["-n", SCRIPT]).status).toBe(0);+ const dash = spawnSync("dash", ["-n", SCRIPT]);+ if (!dash.error) expect(dash.status).toBe(0);+ expect(script.startsWith("#!/bin/sh\n")).toBe(true);+ for (const bashism of [/\[\[/, /\bfunction\s+\w+/, /\blocal\s/, /<<</, /\$\{[A-Za-z_]+\[/, /\bsource\s/, /&>/]) expect(script, String(bashism)).not.toMatch(bashism);+ });++ it("names the same Docker objects, labels and profiles as the connector, and waits for MausBot to fill in its address and image", () => {+ const value = (name: string) => new RegExp(`^${name}=(\\S+)$`, "m").exec(script)?.[1];+ expect(value("CONNECTOR")).toBe(NAMES.connector);+ expect(value("CONNECTOR_NEXT")).toBe(NAMES.connectorNext);+ expect(value("HOME_CONTAINER")).toBe(NAMES.home);+ expect(value("DATA_VOLUME")).toBe(NAMES.dataVolume);+ expect(value("STATE_VOLUME")).toBe(NAMES.stateVolume);+ expect(value("SNAPSHOT_VOLUME")).toBe(NAMES.snapshotVolume);+ expect(value("ROLE_LABEL")).toBe(LABELS.role);+ expect(value("PROFILE")).toBe(APPARMOR_PROFILE);+ expect(value("SECCOMP")).toBe(SECCOMP_FILE);+ expect(script).toContain('ADMIN_URL="${MAUSBOT_ADMIN_URL:-@MAUSBOT_ADMIN_URL@}"');+ expect(script).toContain('CONNECTOR_IMAGE="${MAUSBOT_CONNECTOR_IMAGE:-@MAUSBOT_CONNECTOR_IMAGE@}"');+ expect(script).toContain('say "Connected. Your server shows up in MausBot in a minute."');+ expect(script).toContain(`com.mausbot.instance=$instance`);+ expect(script).toContain("--restart unless-stopped --network host");+ expect(script).toContain("-v /var/run/docker.sock:/var/run/docker.sock -v \"$STATE_VOLUME:/state\" -v \"$ETC_DIR:/etc/mausbot:ro\"");+ expect(script).toContain('apparmor_parser -r -W "$APPARMOR_DIR/$PROFILE"');+ });++ it.skipIf(!posix)("uninstall stops everything but keeps the data, its safety copy and its backups", () => {+ const result = run(["uninstall"]);+ expect(result.status, result.stderr).toBe(0);+ expect(result.calls).toEqual(expect.arrayContaining([+ `docker rm -f ${NAMES.connector} ${NAMES.connectorNext}`, `docker stop -t 30 ${NAMES.home}`, `docker rm -f ${NAMES.home}`, "docker rm -f helper-1",+ `docker volume rm ${NAMES.stateVolume}`,+ ]));+ expect(result.calls.filter((call) => /volume rm (mausbot-data|mausbot-snapshot|mausbot-backup-)/.test(call))).toEqual([]);+ expect(result.calls.some((call) => call.startsWith("apparmor_parser -R "))).toBe(true);+ expect(existsSync(join(result.apparmor, APPARMOR_PROFILE))).toBe(false);+ expect(existsSync(result.etc)).toBe(false);+ expect(result.stdout).toContain(`Your data is kept in the Docker volume ${NAMES.dataVolume}, with its backups.`);+ expect(result.stdout).toContain("curl -fsSL https://cloud.example.test/install.sh | sudo sh -s -- uninstall --delete-data");+ });++ it.skipIf(!posix)("deletes the data only when --delete-data is typed, and refuses anything else before touching a thing", () => {+ const deleted = run(["uninstall", "--delete-data"]);+ expect(deleted.status, deleted.stderr).toBe(0);+ expect(deleted.calls).toEqual(expect.arrayContaining([+ `docker volume rm ${NAMES.dataVolume}`, `docker volume rm ${NAMES.snapshotVolume}`,+ "docker volume rm mausbot-backup-20261028-000000-ab12", "docker volume rm mausbot-backup-20261029-000000-cd34",+ ]));+ expect(deleted.stdout).toContain("MausBot is removed from this server, and so is its data.");+ for (const typo of [["uninstall", "--delete-dat"], ["uninstall", "--delete-data=yes"], ["uninstall", "-f"]]) {+ const refused = run(typo);+ expect(refused.status, typo.join(" ")).toBe(1);+ expect(refused.calls, typo.join(" ")).toEqual([]);+ expect(refused.stderr).toContain("Unknown option");+ }+ });++ it.skipIf(!posix)("says in plain words what to run instead: as root, from MausBot's own command, with a code as MausBot shows it", () => {+ const user = run(["MB-1A2B-3C4D"], { uid: 1000 });+ expect(user.status).toBe(1);+ expect(user.stderr).toContain("Please run this as root: put sudo before sh, like this: curl -fsSL https://cloud.example.test/install.sh | sudo sh -s -- MB-1A2B-3C4D");+ expect(run(["uninstall"], { uid: 1000 }).stderr).toContain("Please run this as root");+ const copied = run(["MB-1A2B-3C4D"], { env: { MAUSBOT_ADMIN_URL: "", MAUSBOT_CONNECTOR_IMAGE: "" } });+ expect(copied.stderr).toContain("This installer was not downloaded from MausBot. Copy the install command from MausBot and run that.");+ const odd = run(["MB-1A2B;reboot"]);+ expect(odd.stderr).toContain("That code doesn't look right. Copy the install command from MausBot again.");+ expect(odd.calls).toEqual([]);+ });+});diff --git a/connector/test/jobs.test.ts b/connector/test/jobs.test.tsnew file mode 100644index 0000000000..2f131d8dd6--- /dev/null+++ b/connector/test/jobs.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import type { Home } from "../src/home.ts";+import { jobRunner } from "../src/jobs.ts";+import type { HostHealth, Job } from "../src/protocol.ts";++const HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)}`;++function runner(overrides: Partial<Record<keyof Home, unknown>> = {}) {+ const calls: string[] = [];+ const pending: (() => void)[] = [];+ const home = {+ refreshHealth: async () => { calls.push("refreshHealth"); return null; },+ copies: async () => ({ backups: [], snapshot: null }),+ report: async () => ({ state: "running", image: HOME, health: null }),+ update: (jobId: string, image: string) => new Promise((resolve) => {+ calls.push(`update ${jobId} ${image}`);+ pending.push(() => resolve({ home: { state: "running", image, health: null }, previousImage: null, snapshot: null }));+ }),+ stop: async () => { throw new Error("Docker is not running"); },+ ...overrides,+ } as unknown as Home;+ const run = jobRunner({+ home,+ hostHealth: async () => ({ arch: "x86_64" }) as HostHealth,+ identity: () => ({ version: "1.0.0", protocol: 1, image: null }),+ admin: () => ({ origin: "https://cloud.example.test", token: "t" }),+ selfUpdate: async (job) => ({ id: job.id, ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: job.args.image } } }),+ });+ return { run, calls, pending };+}++describe("the jobs the connector runs", () => {+ it("answers status with a fresh health read, the copies and the connector, and host-health with the host", async () => {+ const { run, calls } = runner();+ expect(await run({ id: "s", type: "status", args: {} })).toEqual({+ id: "s", ok: true, result: { home: { state: "running", image: HOME, health: null }, connector: { version: "1.0.0", protocol: 1, image: null }, backups: [], snapshot: null },+ });+ expect(calls).toEqual(["refreshHealth"]);+ expect(await run({ id: "h", type: "host-health", args: {} })).toEqual({ id: "h", ok: true, result: { host: { arch: "x86_64" } } });+ });++ it("turns any failure into the job's error, and refuses more than eight waiting changes", async () => {+ const { run, pending } = runner();+ expect(await run({ id: "x", type: "stop", args: {} })).toEqual({ id: "x", ok: false, error: { code: "docker", message: "Docker is not running" } });+ const waiting = Array.from({ length: 8 }, (_, i) => run({ id: `u${i}`, type: "update", args: { image: HOME } } as Job));+ expect(await run({ id: "u9", type: "update", args: { image: HOME } })).toEqual({ id: "u9", ok: false, error: { code: "busy", message: "8 jobs are already waiting on this server; send this one again later." } });+ expect(await run({ id: "s", type: "status", args: {} })).toMatchObject({ ok: true });+ for (const release of pending) release();+ expect((await Promise.all(waiting)).every((reply) => reply?.ok)).toBe(true);+ });+});diff --git a/connector/test/protocol.test.ts b/connector/test/protocol.test.tsnew file mode 100644index 0000000000..70dfc38c47--- /dev/null+++ b/connector/test/protocol.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";++import { cloudRequestSignature as homeSignature } from "../../server/cloud-home.ts";+import { cloudRequestSignature, summarizeHealth } from "../src/home-health.ts";+import { checkEnrollCode, checkEnrollResponse, checkHomeEnv, checkJob, checkTransferUrl, JOB_TYPES, REQUIRED_HOME_ENV } from "../src/protocol.ts";++const HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)}`;+const CONNECTOR = `ghcr.io/milind-soni/mausbot-connector@sha256:${"b".repeat(64)}`;+const env = {+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_PUBLIC_URL: "https://acme.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: "S".repeat(43),+};++describe("the connector protocol", () => {+ it("takes a job only with a valid id, a known type and exactly that type's arguments", () => {+ expect(checkJob({ id: "j1", type: "start", args: { image: HOME, env } })).toMatchObject({ ok: true, job: { id: "j1", type: "start" } });+ expect(checkJob({ id: "j2", type: "status" })).toEqual({ ok: true, job: { id: "j2", type: "status", args: {} } });+ expect(checkJob({ id: "j3", type: "shell", args: { command: "id" } })).toMatchObject({ ok: false, id: "j3", code: "unknown_job" });+ expect(checkJob({ id: "j4", type: "status", args: { verbose: true } })).toMatchObject({ ok: false, code: "invalid_args" });+ expect(checkJob({ id: "j5", type: "update", args: { image: HOME, force: true } })).toMatchObject({ ok: false, code: "invalid_args", message: 'unknown argument "force"' });+ for (const bad of [null, [], "status", { type: "status" }, { id: "", type: "status" }, { id: "x".repeat(65), type: "status" }, { id: "a b", type: "status" }]) {+ expect(checkJob(bad)).toMatchObject({ ok: false, id: null, code: "invalid_job" });+ }+ expect(JOB_TYPES).toEqual(["start", "stop", "restart", "update", "status", "backup", "restore", "export-disk", "import-disk", "host-health", "self-update"]);+ });++ it("runs only our images, and only by digest: the home's for the home, the connector's for itself", () => {+ const image = (type: "start" | "update" | "self-update", value: string) => checkJob({ id: "j", type, args: type === "start" ? { image: value, env } : { image: value } }).ok;+ expect(image("start", HOME)).toBe(true);+ expect(image("update", HOME)).toBe(true);+ expect(image("self-update", CONNECTOR)).toBe(true);+ for (const value of [+ "ghcr.io/milind-soni/openmausbot-cloud-home:latest", "ghcr.io/milind-soni/openmausbot-cloud-home:v0.1.130",+ `ghcr.io/someone-else/openmausbot-cloud-home@sha256:${"a".repeat(64)}`, `docker.io/library/ubuntu@sha256:${"a".repeat(64)}`,+ `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"A".repeat(64)}`, `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(63)}`,+ `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)} --privileged`, `ghcr.io/milind-soni/openmausbot@sha256:${"a".repeat(64)}`,+ ]) {+ expect(image("start", value), value).toBe(false);+ expect(image("update", value), value).toBe(false);+ }+ expect(image("update", CONNECTOR)).toBe(false);+ expect(image("self-update", HOME)).toBe(false);+ });++ it("starts a home only with its contract, OMB_ settings the image does not own, and one-line values, and never echoes a value", () => {+ expect(checkHomeEnv(env)).toEqual({ ok: true, value: env });+ expect(checkHomeEnv({ ...env, OMB_COMPOSIO_BROKER_URL: "http://127.0.0.1:9", OMB_HIGHLEVEL_RELAY_URL: "off", OMB_CLOUD_TEAM_ID: "t1" }).ok).toBe(true);+ for (const name of REQUIRED_HOME_ENV) {+ const { [name]: _dropped, ...rest } = env;+ expect(checkHomeEnv(rest), name).toMatchObject({ ok: false, message: `env must set ${name}` });+ }+ const refused = (extra: Record<string, unknown>) => checkHomeEnv({ ...env, ...extra });+ for (const name of ["FLY_APP_NAME", "PATH", "NODE_OPTIONS", "HOME", "LD_PRELOAD", "omb_lower", "OMB_"]) expect(refused({ [name]: "x" }).ok, name).toBe(false);+ for (const name of ["OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_HARDEN", "OMB_DATA_DIR", "OMB_PORT", "OMB_CLOUD_SECRETS_FD"]) {+ expect(refused({ [name]: "x" }), name).toMatchObject({ ok: false, message: `env name ${name} is the image's own setting` });+ }+ const secret = "T0P-SECRET-VALUE";+ for (const value of [`${secret}\nOMB_CLOUD_HARDEN=0`, `${secret}\r`, `${secret}\0`, 42, null, "x".repeat(8193)]) {+ const result = refused({ OMB_CLOUD_X_TOKEN: value });+ expect(result.ok).toBe(false);+ expect(JSON.stringify(result)).not.toContain(secret);+ }+ expect(refused({ OMB_CLOUD_ROLE: "admin" }).ok).toBe(false);+ expect(refused({ OMB_PUBLIC_URL: "http://acme.example.test" }).ok).toBe(false);+ expect(refused({ OMB_PUBLIC_URL: "https://acme.example.test/path" }).ok).toBe(false);+ expect(checkHomeEnv(Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`OMB_X${i}`, "v"]))).ok).toBe(false);+ expect(checkHomeEnv([]).ok).toBe(false);+ });++ it("transfers only over https, or http to a test Admin on this machine, never with credentials in the address", () => {+ expect(checkTransferUrl("https://storage.example.test/disk.tar.gz?sig=abc")).toEqual({ ok: true, value: "https://storage.example.test/disk.tar.gz?sig=abc" });+ expect(checkTransferUrl("http://127.0.0.1:8123/disk").ok).toBe(true);+ for (const url of ["http://storage.example.test/disk", "file:///etc/shadow", "https://user:[email protected]/", "not a url", "ftp://x/y", 7]) {+ expect(checkTransferUrl(url).ok, String(url)).toBe(false);+ }+ });++ it("keeps an enrolment answer only when every field is the Admin's shape, and a code only as MausBot shows it", () => {+ const good = { serverId: "srv_1a2b", cloudId: "cloud_3c4d", agentToken: "ombs_" + "t".repeat(43) };+ expect(checkEnrollResponse(good)).toEqual({ ok: true, value: good });+ expect(checkEnrollResponse({ ...good, extra: 1 })).toEqual({ ok: true, value: good });+ for (const bad of [null, {}, { ...good, agentToken: "short" }, { ...good, serverId: "a/b" }, { ...good, cloudId: 3 }]) expect(checkEnrollResponse(bad).ok).toBe(false);+ expect(checkEnrollCode("MB-1A2B-3C4D").ok).toBe(true);+ for (const code of ["", "abc", "MB 1A2B", "MB-1A2B;rm -rf /", "x".repeat(200)]) expect(checkEnrollCode(code).ok, code).toBe(false);+ });++ it("signs a health read byte for byte as the Admin and the home do", () => {+ const secret = "K".repeat(43);+ for (const [method, target, body] of [["GET", "/api/cloud/health", ""], ["POST", "/api/cloud/pairing", "{\"label\":\"x\"}"], ["GET", "/api/cloud/box?x=1", ""]] as const) {+ expect(cloudRequestSignature(secret, "1793183627", "nonce-0123456789ab", method, target, body)).toBe(homeSignature(secret, "1793183627", "nonce-0123456789ab", method, target, body));+ }+ });++ it("reduces a health report to fixed fields, healthy only when it names the image the home should run", () => {+ const report = { v: 1, version: "0.1.130", image: HOME, box: { box: "bwrap", reason: null, checks: "32/32", failed: [], boxed: 3 }, secretish: "x" };+ expect(summarizeHealth(200, report, HOME, 5)).toEqual({ ok: true, version: "0.1.130", image: HOME, box: { box: "bwrap", checks: "32/32", failed: [] }, at: 5 });+ expect(summarizeHealth(200, report, `${HOME.slice(0, -1)}b`, 5).ok).toBe(false);+ expect(summarizeHealth(401, { error: "invalid_signature" }, HOME, 5)).toMatchObject({ ok: false, image: null, box: null });+ expect(summarizeHealth(0, null, HOME, 5).ok).toBe(false);+ });+});diff --git a/connector/test/self-update.test.ts b/connector/test/self-update.test.tsnew file mode 100644index 0000000000..54d15637e6--- /dev/null+++ b/connector/test/self-update.test.ts@@ -0,0 +1,134 @@+import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import type { ContainerSpec } from "../src/docker.ts";+import type { Job, JobReply } from "../src/protocol.ts";+import { SelfUpdater, successorSpec } from "../src/self-update.ts";+import { StateStore } from "../src/state.ts";+import { FakeDocker, type FakeContainer } from "./fake-docker.ts";++const OLD = `ghcr.io/milind-soni/mausbot-connector@sha256:${"1".repeat(64)}`;+const NEW = `ghcr.io/milind-soni/mausbot-connector@sha256:${"2".repeat(64)}`;+const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++const envOf = (container: FakeContainer) => Object.fromEntries((container.spec.Env ?? []).map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]));++/** The connector container as install.sh starts it. */+function installed(instance: string): ContainerSpec {+ return {+ Image: OLD,+ Env: [`MAUSBOT_INSTANCE=${instance}`, `MAUSBOT_CONNECTOR_IMAGE=${OLD}`, "MAUSBOT_UPDATE_WAIT_S=60", "PATH=/usr/local/bin:/usr/bin:/bin"],+ Cmd: ["run"],+ Labels: { "com.mausbot.role": "connector", "com.mausbot.instance": instance },+ HostConfig: {+ Binds: ["/var/run/docker.sock:/var/run/docker.sock", "mausbot-connector:/state", "/etc/mausbot:/etc/mausbot:ro"],+ NetworkMode: "host", RestartPolicy: { Name: "unless-stopped" }, SecurityOpt: ["no-new-privileges=true"], CapDrop: ["ALL"], ReadonlyRootfs: true, Tmpfs: { "/tmp": "" },+ LogConfig: { Type: "json-file", Config: { "max-size": "10m", "max-file": "3" } },+ },+ };+}++async function fixture() {+ const dir = mkdtempSync(join(tmpdir(), "omb-connector-update-"));+ dirs.push(dir);+ const state = new StateStore(join(dir, "state"));+ const docker = new FakeDocker(state.dir);+ docker.publish(OLD, null);+ docker.publish(NEW, null);+ await docker.pull(OLD);+ await docker.createContainer("mausbot-connector", installed("instance-old"));+ await docker.startContainer("mausbot-connector");+ let clock = 1_800_000_000_000;+ const lines: string[] = [];+ const updater = (instance: string) => new SelfUpdater({+ docker, state, log: (line) => lines.push(line), instance, deadlineMs: 180_000, pollMs: 2_000,+ identity: () => ({ version: "1.0.0", protocol: 1, image: instance === "instance-old" ? OLD : NEW }),+ now: () => clock,+ sleep: async (ms) => { clock += ms; },+ });+ const agent = { paused: 0, resumed: 0, pause() { this.paused += 1; }, resume() { this.resumed += 1; } };+ const job: Job<"self-update"> = { id: "self-1", type: "self-update", args: { image: NEW } };+ return { dir, state, docker, updater, agent, job, lines };+}++describe("the connector replacing itself", () => {+ it("hands over once the new connector has connected: it answers the job, removes the old one and takes its name", async () => {+ const f = await fixture();+ let candidateReply: JobReply | null = null;+ f.docker.onConnectorStart = async (container) => {+ const started = await f.updater(envOf(container).MAUSBOT_INSTANCE).atStart(async () => true);+ if (started.role === "candidate") candidateReply = started.reply;+ };+ const reply = await f.updater("instance-old").run(f.job, f.agent);+ expect(reply).toBeNull();+ expect(candidateReply).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: NEW } } });+ expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);+ const now = f.docker.container("mausbot-connector")!;+ expect(now.spec.Image).toBe(NEW);+ const instance = envOf(now).MAUSBOT_INSTANCE;+ expect(instance).not.toBe("instance-old");+ expect(envOf(now)).toEqual({ MAUSBOT_UPDATE_WAIT_S: "60", MAUSBOT_INSTANCE: instance, MAUSBOT_CONNECTOR_IMAGE: NEW });+ expect(now.spec.Labels).toMatchObject({ "com.mausbot.role": "connector", "com.mausbot.instance": instance });+ expect(now.spec.HostConfig).toEqual(installed("x").HostConfig);+ expect(now.spec.Cmd).toEqual(["run"]);+ expect(f.agent).toMatchObject({ paused: 1, resumed: 0 });+ expect(readdirSync(f.state.dir).filter((name) => name.startsWith("self-update"))).toEqual(["self-update.confirmed.json"]);+ // Started again later, the new connector finds nothing left to do; the next update clears the record.+ expect((await f.updater(instance).atStart(async () => true)).role).toBe("none");+ expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);+ });++ it("keeps the running connector when the new one never connects, and removes the new one", async () => {+ const f = await fixture();+ const reply = await f.updater("instance-old").run(f.job, f.agent);+ expect(reply).toEqual({ id: "self-1", ok: false, error: { code: "self_update_failed", message: "The new connector did not connect to MausBot within 3 minutes; kept this one." } });+ expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);+ expect(f.docker.container("mausbot-connector")!.spec.Image).toBe(OLD);+ expect(f.agent).toMatchObject({ paused: 1, resumed: 1 });+ expect(readdirSync(f.state.dir).filter((name) => name.startsWith("self-update"))).toEqual([]);+ });++ it("a new connector that cannot connect calls the update off itself, and the old one carries on", async () => {+ const f = await fixture();+ let role = "";+ f.docker.onConnectorStart = async (container) => {+ role = (await f.updater(envOf(container).MAUSBOT_INSTANCE).atStart(async () => false)).role;+ };+ const reply = await f.updater("instance-old").run(f.job, f.agent);+ expect(role).toBe("superseded");+ expect(reply).toMatchObject({ ok: false, error: { code: "self_update_failed" } });+ expect(f.docker.container("mausbot-connector")!.spec.Image).toBe(OLD);+ expect(f.docker.container("mausbot-connector-next")).toBeNull();+ });++ it("an old connector started again mid-update waits for the outcome, and stands down only while the new one runs", async () => {+ const f = await fixture();+ const candidate = successorSpec((await f.docker.containerInspect("mausbot-connector"))!, NEW, "instance-new");+ await f.docker.pull(NEW);+ await f.docker.createContainer("mausbot-connector-next", candidate);+ await f.docker.startContainer("mausbot-connector-next");+ const record = { jobId: "self-1", from: OLD, to: NEW, previousContainer: f.docker.container("mausbot-connector")!.id, candidateContainer: "mausbot-connector-next", candidateInstance: "instance-new", deadline: 1_800_000_060_000 };+ f.state.saveSelfUpdate(record);+ f.state.settleSelfUpdate("confirmed");+ expect((await f.updater("instance-old").atStart(async () => true)).role).toBe("superseded");+ // The record outlived the connector that won: it means nothing on its own.+ await f.docker.removeContainer("mausbot-connector-next");+ expect((await f.updater("instance-old").atStart(async () => true)).role).toBe("none");+ expect(existsSync(f.state.path("self-update.confirmed.json"))).toBe(false);+ });++ it("changes nothing when the new image cannot be downloaded, and nothing at all when it already runs it", async () => {+ const f = await fixture();+ const missing = `ghcr.io/milind-soni/mausbot-connector@sha256:${"3".repeat(64)}`;+ expect(await f.updater("instance-old").run({ ...f.job, args: { image: missing } }, f.agent)).toMatchObject({ ok: false, error: { code: "self_update_failed" } });+ expect(await f.updater("instance-old").run({ ...f.job, args: { image: OLD } }, f.agent)).toEqual({ id: "self-1", ok: true, result: { connector: { version: "1.0.0", protocol: 1, image: OLD } } });+ expect(f.agent).toMatchObject({ paused: 0, resumed: 0 });+ expect([...f.docker.containers.keys()]).toEqual(["mausbot-connector"]);+ expect(await f.updater("instance-unknown").run(f.job, f.agent)).toMatchObject({ ok: false, error: { code: "self_update_failed", message: expect.stringContaining("cannot find its own container") } });+ });+});diff --git a/tsconfig.server.json b/tsconfig.server.jsonindex ea43fe2c1d..5c40e5fade 100644--- a/tsconfig.server.json+++ b/tsconfig.server.json@@ -24,7 +24,8 @@"include": ["server","companion",- "enterprise"+ "enterprise",+ "connector"],"exclude": ["server/drivers/pi-mcp-extension.ts"diff --git a/vite.config.ts b/vite.config.tsindex ee470b0ea7..d1b4d2da3a 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -22,6 +22,7 @@ const include = ["shared/**/*.test.ts","companion/**/*.test.ts","enterprise/**/*.test.ts",+ "connector/**/*.test.ts","scripts/**/*.test.mjs","scripts/**/*.test.ts",];