Skip to content

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

Compose: Caddy in its own container, reaching the server over Unix sockets, so HTTPS survives a server restart

milind-soni781164eee5fd
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 940f5acfd4..b5c36e3b9a 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -156,6 +156,25 @@ jobs:
test -n "$sse" # SSE streams, not buffered
grep -q '"baseUrl":"https://localhost"' <<<"$(body -b "$jar" $H/api/webhooks)" # OMB_WEBHOOK_PUBLIC_URL is advertised
test "$(code $H/api/bots)" = 403 # and without the cookie it is still closed
+ # Caddy has its own container and reaches the server over a Unix socket, so HTTPS comes back by itself
+ # whenever the server does. When Caddy shared the server's network, each of these left it in the old,
+ # dead network: 443 refused while both containers said healthy.
+ C="docker compose -f deploy/docker-compose.yml"
+ back() { # $1: what happened; HTTPS through Caddy answers again within two minutes, and is still remote
+ for i in $(seq 1 60); do
+ if grep -q '^{"app":"openmausbot"}$' <<<"$(body $H/api/health || true)" && [ "$(code $H/api/bots)" = 403 ]; then echo "HTTPS back after: $1"; return 0; fi
+ sleep 2
+ done
+ $C ps; $C logs --tail 30; echo "HTTPS did not come back after: $1"; return 1
+ }
+ $C restart && back "docker compose restart"
+ launcher=$(docker top "$($C ps -q omb)" -eo pid,args | awk '/server-launcher/ { print $1; exit }')
+ test -n "$launcher"
+ sudo kill -9 "$launcher" && sleep 5 && back "kill -9 of the server process, restarted by Docker"
+ test "$(docker inspect -f '{{.RestartCount}}' "$($C ps -q omb)")" -ge 1
+ $C stop omb && $C start omb && back "docker compose stop omb, then start omb"
+ $C stop && $C start && back "docker compose stop, then start (the documented backup)"
+ grep -q error <<<"$(body -X POST $H/hooks/wh_nope)" # hooks reach the receiver's socket again
docker compose -f deploy/docker-compose.yml down -v
- name: Cloud Pro home image (--target cloud-home) boots, stays private and pairs on a signed request
# The Fly home machine, built from the same runtime as the image above, with the environment
diff --git a/Dockerfile b/Dockerfile
index 270130e18f..9e6113ebc4 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -58,8 +58,10 @@ COPY cloudflare/control-plane/package.json ./cloudflare/control-plane/package.js
COPY scripts/install-git-hooks.mjs ./scripts/install-git-hooks.mjs
RUN pnpm install --frozen-lockfile
COPY . .
-# The Cloud home runs these as root, so nobody else may write them.
-RUN pnpm build:server && pnpm exec vite build && chmod -R go-w dist dist-server skills
+# The Cloud home runs these as root, so nobody else may write them. The web app's
+# build needs more heap than Node gives itself on a 4 GB server, where it ran out
+# of memory: a fixed limit, which such a server meets with swap (docs/deploy-vps.md).
+RUN pnpm build:server && NODE_OPTIONS=--max-old-space-size=6144 pnpm exec vite build && chmod -R go-w dist dist-server skills
# The Data engine's native modules (server/data/engine.ts), staged like the
# desktop app's extraResources for the image's CPU (amd64 -> x64, arm64), into
# one tree the runtime stages copy. pnpm installed both CPUs' packages
diff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
index 41b94bd3dd..05c85cdda5 100644
--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx
+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
@@ -290,7 +290,7 @@ same release without an npm install prompt or an implicit upgrade.
Check that installation succeeded before starting. A service restart by itself
does not update the installed package. For foreground `npx` usage, specify the
desired release as `npx --yes [email protected] serve --tunnel`.
-- **Path B:** `cd OpenMausBot/deploy && docker compose pull omb && docker compose up -d`.
+- **Path B:** `cd OpenMausBot/deploy && git pull && docker compose pull omb && docker compose up -d`. The `git pull` brings the current `docker-compose.yml` and `Caddyfile`. Building from source instead (`docker compose up -d --build`) needs about 6 GB of memory: on a smaller server, add swap first or use the published image.
Routines and queued work survive a restart; a turn running at that moment does not, so update between runs.
@@ -317,26 +317,39 @@ any configured home/data-directory overrides, and workspaces outside the app
directory. These are not included in the command above.
For path B, the whole `/data` volume includes the container's CLI homes. From
-`OpenMausBot/deploy`, stop the app before archiving; `deploy_data` is the default
-volume name, so use your actual volume name if you changed the Compose project:
+`OpenMausBot/deploy`, stop the whole project before archiving, and start it
+again after; `deploy_data` is the default volume name, so use your actual
+volume name if you changed the Compose project:
```sh
-docker compose stop omb
+docker compose stop
backup_dir=$(mktemp -d "$PWD/openmausbot-backup.XXXXXX")
docker run --rm -v deploy_data:/data:ro -v "$backup_dir":/b alpine sh -c 'umask 077; tar czf /b/openmausbot-data.tgz -C /data .'
+docker compose start
```
-Each command creates a fresh private folder in the current directory, so it
+To restore that archive, with the project stopped, replace what is in the
+volume with it (`openmausbot-backup.XXXXXX` is the folder the backup made):
+
+```sh
+docker compose stop
+docker run --rm -v deploy_data:/data -v "$PWD/openmausbot-backup.XXXXXX":/b:ro alpine sh -c 'find /data -mindepth 1 -delete && tar xzpf /b/openmausbot-data.tgz -C /data'
+docker compose start
+```
+
+Each backup creates a fresh private folder in the current directory, so it
cannot overwrite an older archive with more permissive access. Keep the
-archive inside that folder privately on another machine. Restore with the server stopped,
-using the same paths and original ownership. After backup or restore, start the
-service with `sudo systemctl start openmausbot`, or `docker compose start omb`.
+archive inside that folder privately on another machine. Restore paths A and C
+with the server stopped, using the same paths and original ownership. After
+backup or restore, start the service with `sudo systemctl start openmausbot`.
+Stop and start the Docker project as a whole, as above, rather than `omb` on
+its own.
## The rules the setup relies on
Read this before putting anything else in front of the server.
-- The server only ever listens on loopback (`127.0.0.1:8799`). Never publish that port yourself. The tunnel, Caddy and Tailscale each reach it from the same machine.
+- The server only ever listens on loopback (`127.0.0.1:8799`). Never publish that port yourself. The tunnel, Caddy and Tailscale each reach it from the same machine; path B's Caddy, in its own container, reaches it over a Unix socket (`OMB_TUNNEL_SOCKET`), and a request on that socket always counts as a remote one.
- A request that arrives through a proxy or the tunnel is treated as remote and needs a session, whatever headers it carries. A proxy of your own (nginx, Traefik, Cloudflare Tunnel) must forward the real `Host` and add `X-Forwarded-For` and `X-Forwarded-Proto`, must not buffer the event stream, and must **not** rewrite `Host` to `127.0.0.1`.
- Pairing is the login. Want a second wall in front of it? Path B's `Caddyfile` has a commented `basic_auth` block for a shared password.
- The session cookie is marked `Secure`; do not serve this over plain HTTP on the public internet.
diff --git a/compose.yaml b/compose.yaml
index 4f57dbaad5..ee87c5ce62 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -14,11 +14,15 @@ services:
restart: unless-stopped
volumes:
- data:/data
- ports:
- - "${OMB_BIND_ADDRESS:-127.0.0.1}:${OMB_HTTP_PORT:-8080}:80"
+ - edge:/run/openmausbot
environment:
OMB_PORT: "8799"
OMB_WEBHOOK_PORT: "8800"
+ # Caddy, in its own container, reaches the server over these (deploy/local/Caddyfile). A request on a socket is
+ # never a local one. Caddy does not share the server's network: a server restarted on its own would come back
+ # in a new one and leave Caddy, and the port, behind in the old one.
+ OMB_TUNNEL_SOCKET: /run/openmausbot/http.sock
+ OMB_WEBHOOK_SOCKET: /run/openmausbot/hooks.sock
# The name the desktop app shows for this server (a container's own hostname is a random id).
OMB_SERVER_NAME: ${OMB_SERVER_NAME:-mausbot-docker}
OMB_PUBLIC_URL: ${OMB_PUBLIC_URL:-http://localhost:${OMB_HTTP_PORT:-8080}}
@@ -36,7 +40,8 @@ services:
caddy:
image: ${CADDY_IMAGE:-caddy:2}
restart: unless-stopped
- network_mode: service:omb
+ ports:
+ - "${OMB_BIND_ADDRESS:-127.0.0.1}:${OMB_HTTP_PORT:-8080}:80"
environment:
OMB_HTTPS_HOST: ${OMB_HTTPS_HOST:-}
OMB_BIND_ADDRESS: ${OMB_BIND_ADDRESS:-127.0.0.1}
@@ -58,11 +63,19 @@ services:
condition: service_healthy
volumes:
- ./deploy/local/Caddyfile:/etc/caddy/Caddyfile:ro
+ - edge:/run/openmausbot
- caddy_data:/data
- caddy_config:/config
volumes:
data:
external: ${OMB_DATA_EXTERNAL:-false}
name: ${OMB_DATA_VOLUME:-${COMPOSE_PROJECT_NAME:-openmausbot}_data}
+ # The two sockets: in memory, made afresh by the server at each start. Not under /data, which every bot's sandbox
+ # sees; the sandbox has its own /run.
+ edge:
+ driver_opts:
+ type: tmpfs
+ device: tmpfs
+ o: mode=1777,size=1m
caddy_data:
caddy_config:
diff --git a/deploy/Caddyfile b/deploy/Caddyfile
index c26f8b32e8..c20bcbff92 100644
--- a/deploy/Caddyfile
+++ b/deploy/Caddyfile
@@ -1,5 +1,7 @@
# Edge for one OpenMausBot tenant: automatic HTTPS in front of a server that
-# only listens on loopback. Login is pairing (docs/self-hosting.md "Using it
+# only listens on loopback, reached over the Unix sockets it makes in the
+# `edge` volume (docker-compose.yml). A request on a socket is always a remote
+# one to the server, never a local one. Login is pairing (docs/self-hosting.md "Using it
# from your computer"): a remote browser without a session sees the pair
# page, everything else is refused by the server itself, so Caddy adds no
# password of its own. Caddy forwards the real Host and sets
@@ -12,7 +14,7 @@
# own per-hook secrets), so it sits outside any login. The path is passed
# through unchanged: the receiver routes on /hooks/<id>.
handle /hooks/* {
- reverse_proxy 127.0.0.1:8800
+ reverse_proxy unix//run/openmausbot/hooks.sock
}
handle {
@@ -22,9 +24,12 @@
# }
# and set both variables in .env (hash with `caddy hash-password`,
# every `$` doubled for Compose).
- reverse_proxy 127.0.0.1:8799 {
+ reverse_proxy unix//run/openmausbot/http.sock {
# SSE: stream events as they arrive
flush_interval -1
+ # Compression is `encode`'s job above; the server would gzip its
+ # JSON on its socket otherwise, as for the phone tunnel.
+ header_up -Accept-Encoding
}
}
}
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 8876a0dd94..6057131c15 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -1,8 +1,13 @@
# One OpenMausBot tenant: the harness server plus Caddy for TLS + login.
#
-# Caddy runs in the server's network namespace, so it reaches the server on
-# 127.0.0.1 — the server never binds a public interface. Ports are therefore
-# declared on the `omb` service (the namespace owner).
+# The server only listens on loopback inside its container, and on two Unix
+# sockets in the `edge` volume; Caddy, in its own container, reaches it through
+# those. A request on a socket is never a local one: it needs a session, and
+# X-Forwarded-For names the client, exactly as when Caddy shared the server's
+# network. Caddy no longer shares that network because a server restarted on
+# its own (a crash, `docker compose restart`, `stop omb`) came back in a new
+# one, leaving Caddy in the old one with HTTPS refused while both looked
+# healthy; a socket path is the same file again as soon as the server is back.
#
# cp .env.example .env # set DOMAIN
# docker compose pull omb && docker compose up -d # prebuilt image
@@ -23,12 +28,13 @@ services:
shm_size: 512m
volumes:
- data:/data
- ports:
- - "80:80"
- - "443:443"
+ - edge:/run/openmausbot
environment:
OMB_PORT: "8799"
OMB_WEBHOOK_PORT: "8800"
+ # What Caddy connects to (deploy/Caddyfile).
+ OMB_TUNNEL_SOCKET: /run/openmausbot/http.sock
+ OMB_WEBHOOK_SOCKET: /run/openmausbot/hooks.sock
# what the app prints as hook URLs — Caddy passes /hooks/* straight through
OMB_WEBHOOK_PUBLIC_URL: https://${DOMAIN}
# pairing links for remote clients point here (docs/self-hosting.md)
@@ -50,7 +56,9 @@ services:
caddy:
image: caddy:2
restart: unless-stopped
- network_mode: "service:omb"
+ ports:
+ - "80:80"
+ - "443:443"
depends_on:
omb:
condition: service_healthy
@@ -58,10 +66,18 @@ services:
DOMAIN: ${DOMAIN}
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
+ - edge:/run/openmausbot
- caddy_data:/data
- caddy_config:/config
volumes:
data:
+ # The two sockets: in memory, made afresh by the server at each start. Not
+ # under /data, which every bot's sandbox sees; the sandbox has its own /run.
+ edge:
+ driver_opts:
+ type: tmpfs
+ device: tmpfs
+ o: mode=1777,size=1m
caddy_data:
caddy_config:
diff --git a/deploy/local/Caddyfile b/deploy/local/Caddyfile
index da7145e06f..eac031f83f 100644
--- a/deploy/local/Caddyfile
+++ b/deploy/local/Caddyfile
@@ -5,11 +5,12 @@
}
encode zstd gzip
handle /hooks/* {
- reverse_proxy 127.0.0.1:8800
+ reverse_proxy unix//run/openmausbot/hooks.sock
}
handle {
- reverse_proxy 127.0.0.1:8799 {
+ reverse_proxy unix//run/openmausbot/http.sock {
header_up X-Forwarded-Proto {upstream_scheme}
+ header_up -Accept-Encoding
flush_interval -1
}
}
diff --git a/deploy/local/README.md b/deploy/local/README.md
index ebb2248776..d5e7e6382f 100644
--- a/deploy/local/README.md
+++ b/deploy/local/README.md
@@ -9,7 +9,7 @@ subprocesses.
To customize, copy `.env.example` to `.env` in the repository root.
The `.env` file is ignored by Git. Shell environment variables take precedence.
`OMB_HTTP_PORT` changes the host port and the default public URL.
-Internal service ports remain fixed inside the shared network namespace.
+Caddy reaches the server over Unix sockets in the `edge` volume, never its ports.
`ENGINES` selects space-separated npm packages; an empty value skips installation.
The image also carries Grok Build, pinned by `GROK_VERSION` in
`deploy/local/Dockerfile`; Grok and Codex sign in from the app's engine setup
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index 4ec5e9eb25..1452d470e8 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -270,7 +270,7 @@ same release without an npm install prompt or an implicit upgrade.
Check that installation succeeded before starting. A service restart by itself
does not update the installed package. For foreground `npx` usage, specify the
desired release as `npx --yes [email protected] serve --tunnel`.
-- **Path B:** `cd OpenMausBot/deploy && docker compose pull omb && docker compose up -d`.
+- **Path B:** `cd OpenMausBot/deploy && git pull && docker compose pull omb && docker compose up -d`. The `git pull` brings the current `docker-compose.yml` and `Caddyfile`. Building from source instead (`docker compose up -d --build`) needs about 6 GB of memory: on a smaller server, add swap first or use the published image.
Routines and queued work survive a restart. A teammate turn running at that moment runs again once at the next start, told to check what it already did, and the bot that asked for it is told. A person's own turn and a running routine are not run again: the conversation says it was interrupted. Update between runs where you can.
@@ -297,26 +297,39 @@ any configured home/data-directory overrides, and workspaces outside the app
directory. These are not included in the command above.
For path B, the whole `/data` volume includes the container's CLI homes. From
-`OpenMausBot/deploy`, stop the app before archiving; `deploy_data` is the default
-volume name, so use your actual volume name if you changed the Compose project:
+`OpenMausBot/deploy`, stop the whole project before archiving, and start it
+again after; `deploy_data` is the default volume name, so use your actual
+volume name if you changed the Compose project:
```sh
-docker compose stop omb
+docker compose stop
backup_dir=$(mktemp -d "$PWD/openmausbot-backup.XXXXXX")
docker run --rm -v deploy_data:/data:ro -v "$backup_dir":/b alpine sh -c 'umask 077; tar czf /b/openmausbot-data.tgz -C /data .'
+docker compose start
```
-Each command creates a fresh private folder in the current directory, so it
+To restore that archive, with the project stopped, replace what is in the
+volume with it (`openmausbot-backup.XXXXXX` is the folder the backup made):
+
+```sh
+docker compose stop
+docker run --rm -v deploy_data:/data -v "$PWD/openmausbot-backup.XXXXXX":/b:ro alpine sh -c 'find /data -mindepth 1 -delete && tar xzpf /b/openmausbot-data.tgz -C /data'
+docker compose start
+```
+
+Each backup creates a fresh private folder in the current directory, so it
cannot overwrite an older archive with more permissive access. Keep the
-archive inside that folder privately on another machine. Restore with the server stopped,
-using the same paths and original ownership. After backup or restore, start the
-service with `sudo systemctl start openmausbot`, or `docker compose start omb`.
+archive inside that folder privately on another machine. Restore paths A and C
+with the server stopped, using the same paths and original ownership. After
+backup or restore, start the service with `sudo systemctl start openmausbot`.
+Stop and start the Docker project as a whole, as above, rather than `omb` on
+its own.
## The rules the setup relies on
Read this before putting anything else in front of the server.
-- The server only ever listens on loopback (`127.0.0.1:8799`). Never publish that port yourself. The tunnel, Caddy and Tailscale each reach it from the same machine.
+- The server only ever listens on loopback (`127.0.0.1:8799`). Never publish that port yourself. The tunnel, Caddy and Tailscale each reach it from the same machine; path B's Caddy, in its own container, reaches it over a Unix socket (`OMB_TUNNEL_SOCKET`), and a request on that socket always counts as a remote one.
- A request that arrives through a proxy or the tunnel is treated as remote and needs a session, whatever headers it carries. A proxy of your own (nginx, Traefik, Cloudflare Tunnel) must forward the real `Host` and add `X-Forwarded-For` and `X-Forwarded-Proto`, must not buffer the event stream, and must **not** rewrite `Host` to `127.0.0.1`.
- Pairing is the login. Want a second wall in front of it? Path B's `Caddyfile` has a commented `basic_auth` block for a shared password.
- The session cookie is marked `Secure`; do not serve this over plain HTTP on the public internet.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 4d795a1a89..90d50045d9 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -342,7 +342,9 @@ docker compose pull omb && docker compose up -d
That uses the image CI publishes on every `main` push
(`ghcr.io/milind-soni/openmausbot`, tagged `latest`, `sha-…` and `v…`).
-To build from your checkout instead: `docker compose up -d --build`.
+To build from your checkout instead: `docker compose up -d --build`. The
+build needs about 6 GB of memory: on a smaller server, add swap first or use
+the published image.
Then sign the engine CLIs in **inside the container** (their logins live on
the `data` volume, so they survive restarts and image upgrades) and mint a
@@ -366,8 +368,13 @@ What the stack does, so you can adapt it:
`--build-arg ENGINES="…"` (or `ENGINES=` in `.env`) bakes engine CLIs
into the image.
- [`deploy/docker-compose.yml`](../deploy/docker-compose.yml) runs Caddy
- **in the server's network namespace**, so Caddy reaches the server on
- `127.0.0.1` and the server never binds anything public.
+ in its own container. It reaches the server over two Unix sockets in a
+ shared in-memory volume (`OMB_TUNNEL_SOCKET`, `OMB_WEBHOOK_SOCKET`), so the
+ server never binds anything but loopback, and a request that comes through
+ Caddy is a remote one, as one through any proxy is. Caddy used to share the
+ server's network instead; then a server container restarted on its own (a
+ crash, `docker compose restart`, `stop omb`) came back in a new network and
+ left Caddy refusing HTTPS in the old one while both showed healthy.
- [`deploy/Caddyfile`](../deploy/Caddyfile) terminates TLS and forwards
the real `Host` plus `X-Forwarded-For`/`X-Forwarded-Proto`; the server's
own pairing is the login. A shared-password `basic_auth` block is there,
diff --git a/scripts/docker-image.test.ts b/scripts/docker-image.test.ts
index 3c6cc806fd..5efd0825fd 100644
--- a/scripts/docker-image.test.ts
+++ b/scripts/docker-image.test.ts
@@ -331,4 +331,23 @@ describe("container images", () => {
expect(service.shm_size, file).toBe("512m");
}
});
+
+ // Caddy in the server's network (network_mode: service:omb) stayed in the old, dead one whenever the server's
+ // container restarted alone, and HTTPS was refused while both looked healthy. It reaches the server over sockets in
+ // a volume both mount instead, and the Caddyfile names the paths the server listens on.
+ it("runs Caddy in its own container, reaching the server's sockets, never in the server's network", () => {
+ for (const [file, caddyfile] of [["../compose.yaml", "../deploy/local/Caddyfile"], ["../deploy/docker-compose.yml", "../deploy/Caddyfile"]]) {
+ const { services, volumes } = parse(readFileSync(new URL(file, import.meta.url), "utf8"));
+ expect(services.caddy.network_mode, file).toBeUndefined();
+ expect(services.omb.ports, file).toBeUndefined();
+ expect(services.caddy.ports.length, file).toBeGreaterThan(0);
+ expect(services.omb.volumes, file).toContain("edge:/run/openmausbot");
+ expect(services.caddy.volumes, file).toContain("edge:/run/openmausbot");
+ expect(volumes.edge.driver_opts.type, file).toBe("tmpfs");
+ const { OMB_TUNNEL_SOCKET: api, OMB_WEBHOOK_SOCKET: hooks } = services.omb.environment;
+ expect([api, hooks], file).toEqual(["/run/openmausbot/http.sock", "/run/openmausbot/hooks.sock"]);
+ const proxied = [...readFileSync(new URL(caddyfile, import.meta.url), "utf8").matchAll(/reverse_proxy (\S+)/g)].map((m) => m[1]);
+ expect(proxied, caddyfile).toEqual([`unix/${hooks}`, `unix/${api}`]);
+ }
+ });
});
diff --git a/server/index.ts b/server/index.ts
index d0723dcff7..d32e93219b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -9520,11 +9520,11 @@ let webhookIngress: WebhookIngress | null = null;
let webhookIngressError: string | null = null;
try {
webhookIngress = await listenWebhookIngress(webhooks, {
- port: WEBHOOK_PORT, publicBaseUrl: WEBHOOK_PUBLIC_URL,
+ port: WEBHOOK_PORT, socketPath: process.env.OMB_WEBHOOK_SOCKET?.trim() || undefined, publicBaseUrl: WEBHOOK_PUBLIC_URL,
claimRequest: () => { cloudPower?.arrived("/hooks", {}); moveFreeze.assertTurns(); return workspaceMaintenance.request(); }, door: botApi.door,
});
const advertised = WEBHOOK_PUBLIC_URL ? ` (advertised as ${webhookIngress.baseUrl})` : "";
- console.log(`openmausbot webhook receiver on http://${webhookIngress.host}:${webhookIngress.port}${advertised}`);
+ console.log(`openmausbot webhook receiver on http://${webhookIngress.host}:${webhookIngress.port}${webhookIngress.socketServer ? ` and ${process.env.OMB_WEBHOOK_SOCKET?.trim()}` : ""}${advertised}`);
} catch (error) {
webhookIngressError = error instanceof Error ? error.message : String(error);
console.error(`openmausbot webhook receiver unavailable: ${webhookIngressError}`);
@@ -15453,7 +15453,8 @@ server.listen(PORT, listenHost(server), async () => {
moveFreeze.hold(() => memoryUpkeep.start(), () => memoryUpkeep.stop());
});
-// Tunnel requests have no peer address, which request-auth treats as proxied: a session is required, never loopback trust.
+// Requests on this socket (the phone tunnel, or the compose files' Caddy in its own container) have no peer address, which
+// request-auth treats as proxied: a session is required, never loopback trust.
const TUNNEL_SOCKET = process.env.OMB_TUNNEL_SOCKET?.trim() || null;
let tunnelListener: ReturnType<typeof createServer> | null = null;
if (TUNNEL_SOCKET) {
@@ -15514,7 +15515,7 @@ const gracefulShutdown = createGracefulShutdown({
memoryUpkeep.stop();
cacheKeepWarm.dispose(); warmSummaries.dispose();
skillReview.stop();
- webhookIngress?.server.close();
+ webhookIngress?.server.close(); webhookIngress?.socketServer?.close();
tunnelListener?.close(); stopCloudHomeConnectedApps();
},
async () => { await managedDesktop.close(); await registry.disposeAll(); },
diff --git a/server/webhook-ingress.test.ts b/server/webhook-ingress.test.ts
index 14fd3ed3b7..9a1c09fae1 100644
--- a/server/webhook-ingress.test.ts
+++ b/server/webhook-ingress.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync, statSync } from "node:fs";
+import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import { request } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -306,6 +306,34 @@ describe("advertised base URL", () => {
}
});
+ // The compose files' Caddy runs in its own container and reaches the receiver over this socket, so a server that
+ // restarts on its own never leaves Caddy behind in a network the new one is not in.
+ it.skipIf(process.platform === "win32")("answers on its Unix socket too, replacing one a stopped server left", async () => {
+ const socketPath = join(dir, "hooks.sock");
+ // A server killed with -9 never unlinks its socket: the next one must still listen there.
+ writeFileSync(socketPath, "left behind");
+ const receiver = await listenWebhookIngress(manager, { port: 0, socketPath });
+ try {
+ expect(statSync(socketPath).isSocket()).toBe(true);
+ const viaSocket = (path: string, method = "GET") => new Promise<{ status: number; body: string }>((resolve, reject) => {
+ const sent = request({ socketPath, path, method, headers: { host: "bots.example.com", "content-type": "application/json", "idempotency-key": "via-socket" } }, (response) => {
+ let body = "";
+ response.setEncoding("utf8").on("data", (chunk: string) => { body += chunk; }).on("end", () => resolve({ status: response.statusCode ?? 0, body }));
+ });
+ sent.on("error", reject);
+ sent.end(method === "POST" ? "{}" : undefined);
+ });
+ expect(await viaSocket("/health")).toEqual({ status: 200, body: JSON.stringify({ app: "openmausbot-webhooks", ready: true }) });
+ expect((await viaSocket("/api/bots")).status).toBe(404);
+ const before = queued.length;
+ expect((await viaSocket(`/hooks/${endpointId}/${secret}`, "POST")).status).toBe(202);
+ expect(queued).toHaveLength(before + 1);
+ } finally {
+ await new Promise<void>((resolve) => receiver.server.close(() => resolve()));
+ await new Promise<void>((resolve) => receiver.socketServer?.close(() => resolve()) ?? resolve());
+ }
+ });
+
it("refuses a base that is not an absolute http(s) URL, naming the fix", () => {
for (const bad of ["bots.example.com", "ftp://bots.example.com", "", "/hooks"]) {
expect(() => advertisedWebhookBase(bad)).toThrow(/absolute http\(s\) URL such as https:\/\//);
diff --git a/server/webhook-ingress.ts b/server/webhook-ingress.ts
index 66a7be5fd2..9cbf747579 100644
--- a/server/webhook-ingress.ts
+++ b/server/webhook-ingress.ts
@@ -1,3 +1,4 @@
+import { rmSync } from "node:fs";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { z } from "zod";
@@ -11,6 +12,8 @@ const serverAddressSchema = z.object({ port: z.number().int().min(1).max(65_535)
export interface WebhookIngress {
server: Server;
+ /** The same receiver on a Unix socket (OMB_WEBHOOK_SOCKET), for a proxy in another container: the compose files' Caddy. */
+ socketServer?: Server;
host: string;
port: number;
baseUrl: string;
@@ -169,35 +172,56 @@ export function advertisedWebhookBase(raw: string): string {
return raw.replace(/\/+$/, "");
}
+/** A TCP port on `host`, or a Unix socket's path when `host` is omitted. */
+function listenOn(server: Server, where: number | string, host?: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const onError = (error: Error) => reject(error);
+ const listening = () => {
+ server.off("error", onError);
+ resolve();
+ };
+ server.once("error", onError);
+ if (typeof where === "number") server.listen(where, host, listening);
+ else server.listen(where, listening);
+ });
+}
+
export async function listenWebhookIngress(
manager: WebhookManager,
- options: { host?: string; port: number; publicBaseUrl?: string; claimRequest?: () => () => void; door?: IngressDoor },
+ options: { host?: string; port: number; socketPath?: string; publicBaseUrl?: string; claimRequest?: () => () => void; door?: IngressDoor },
): Promise<WebhookIngress> {
const host = options.host ?? "127.0.0.1";
const advertised = options.publicBaseUrl === undefined ? undefined : advertisedWebhookBase(options.publicBaseUrl);
const handle = createWebhookIngressHandler(manager, options.claimRequest, options.door);
- const server = createServer(IDLE_HTTP_SERVER, (req, res) => {
+ const receive = (req: IncomingMessage, res: ServerResponse) => {
handle(req, res).catch((error: unknown) => {
console.error("webhooks: receiver failed", error);
if (res.headersSent) res.destroy();
else json(res, 500, { error: "Webhook receiver failed" });
});
- });
- await new Promise<void>((resolve, reject) => {
- const onError = (error: Error) => reject(error);
- server.once("error", onError);
- server.listen(options.port, host, () => {
- server.off("error", onError);
- resolve();
- });
- });
+ };
+ const server = createServer(IDLE_HTTP_SERVER, receive);
+ await listenOn(server, options.port, host);
const address = serverAddressSchema.safeParse(server.address());
if (!address.success) {
server.close();
throw new Error("Webhook receiver did not get a TCP address");
}
+ let socketServer: Server | undefined;
+ if (options.socketPath) {
+ // A socket left by a server that stopped without closing it would refuse the listen.
+ if (process.platform !== "win32") rmSync(options.socketPath, { force: true });
+ socketServer = createServer(IDLE_HTTP_SERVER, receive);
+ try {
+ await listenOn(socketServer, options.socketPath);
+ } catch (error) {
+ server.close();
+ throw error;
+ }
+ }
return {
server,
+ ...(socketServer ? { socketServer } : {}),
host,
port: address.data.port,
baseUrl: advertised ?? `http://${host}:${address.data.port}`,