Skip to content

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

Customer-run connector: the box on or off in the heartbeat, the owner in the seat count, and help that names backupId

milind-sonia84951d8d347
diff --git a/apps/docs/content/docs/self-hosting/connected-servers.mdx b/apps/docs/content/docs/self-hosting/connected-servers.mdx
index 163cf77206..b9ed5ad854 100644
--- a/apps/docs/content/docs/self-hosting/connected-servers.mdx
+++ b/apps/docs/content/docs/self-hosting/connected-servers.mdx
@@ -114,12 +114,12 @@ People sign in to your server with your server's own sign-in: a pairing code you
| When | What |
|---|---|
| Once, at enrolment | The one-time code, the connector's public key, the mode, and the server's facts: operating system, kernel, architecture, CPU count, memory, free disk, Docker version, whether AppArmor and user namespaces are on |
-| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and each server check as an id and a pass or fail; the server's state, image and version; the connector's version and image; the mode; whether you paused; the seat count |
+| Every 30 seconds | Those facts, plus total disk, available memory, load, uptime, clock difference and each server check as an id and a pass or fail; the server's state, image and version, and whether its bots' sandbox is on or off; the connector's version and image; the mode; whether you paused; the seat count |
| After each job | The result: the server's state, image and version, or the id and time of a backup. A failure is a fixed code and a fixed sentence |
-The seat count is the number of people who can sign in: the addresses on your sign-in list, plus any other address that has signed in. It is a number. No address, name or role is sent.
+The seat count is the number of people who can sign in: the addresses on your sign-in list, plus any other address that has signed in, plus you when you signed in with a pairing code and no admin address is on the list. It is a number. No address, name or role is sent.
-To build this the connector reads three things from your server, on the server's own loopback: that it answers, its version, and its seat count. It keeps one field from each answer and drops the rest. It reads no chat, file, key, name or address, and it sends no line of any log.
+To build this the connector reads four things from your server, on the server's own loopback: that it answers, whether its bots' sandbox is on or off (not its checks), its version, and its seat count. It keeps those fields and drops the rest of each answer. It reads no chat, file, key, name or address, and it sends no line of any log.
## What your server itself still sends
diff --git a/connector/src/adopted-home.ts b/connector/src/adopted-home.ts
index 054dd83803..33948a499a 100644
--- a/connector/src/adopted-home.ts
+++ b/connector/src/adopted-home.ts
@@ -6,7 +6,7 @@ import { randomBytes } from "node:crypto";
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, VERSION_LABEL, olderVersionRefusal, parseHomeReads, type HomeFacts, type JobSource } from "./customer-run.ts";
+import { CUSTOMER_HOME_IMAGE, HOME_READS_COMMAND, VERSION_LABEL, boxReport, olderVersionRefusal, parseHomeReads, type HomeFacts, type JobSource } from "./customer-run.ts";
import type { ContainerInfo, Docker, Mount } from "./docker.ts";
import { JobFailure } from "./failure.ts";
import { backupId, helperSpec } from "./home.ts";
@@ -162,7 +162,7 @@ export class AdoptedHome {
}
const facts = await this.read(container);
this.lastSeats = facts.seats;
- this.lastHealth = { ok: facts.answers, version: facts.version, image: await this.imageOf(container), box: null, at: this.now() };
+ this.lastHealth = { ok: facts.answers, version: facts.version, image: await this.imageOf(container), box: boxReport(facts.box), at: this.now() };
return this.lastHealth;
}
@@ -408,7 +408,7 @@ export class AdoptedHome {
try {
return parseHomeReads((await this.docker.exec(container.Id, [...HOME_READS_COMMAND], 30_000)).output);
} catch {
- return { answers: false, version: null, seats: null };
+ return { answers: false, version: null, seats: null, box: null };
}
}
diff --git a/connector/src/customer-run.ts b/connector/src/customer-run.ts
index af5f2b0370..6090c22cb4 100644
--- a/connector/src/customer-run.ts
+++ b/connector/src/customer-run.ts
@@ -5,7 +5,7 @@
// Security invariant: nothing in this file passes through text a person wrote. Every string that leaves is either a
// constant below, an enumerated code, or matches one of the patterns below (a version, an image reference, an id).
import {
- checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeReport, type HostFacts, type HomeState, type HostHealth,
+ checkJob, type CheckId, type ConnectorIdentity, type CopyInfo, type Heartbeat, type HomeHealth, type HomeReport, type HostFacts, type HomeState, type HostHealth,
type Job, type JobError, type JobErrorCode, type JobReply, type JobType,
} from "./protocol.ts";
@@ -143,8 +143,8 @@ export function answerCustomerRunRequest(request: CustomerRunRequest, facts: Ser
}
}
-// 3. WHAT THE CONNECTOR READS FROM THE HOME. Three GETs on the home's own loopback, with no body, and from each answer
-// one field: that it answers as MausBot, its version, and its seat count. Every other field of those answers (the
+// 3. WHAT THE CONNECTOR READS FROM THE HOME. Three GETs on the home's own loopback, with no body, and from them four
+// fields: that it answers as MausBot and whether its bot box is on or off, its version, and its seat count. Every other field of those answers (the
// server's name among them) is dropped here and never kept.
export const HOME_READS = ["/api/health", "/.well-known/openmausbot/environment", "/api/seats"] as const;
@@ -159,6 +159,8 @@ export interface HomeFacts {
answers: boolean;
version: string | null;
seats: number | null;
+ /** Whether its bots run in the bot box, from the health answer: on, off, or null when it does not say. */
+ box: "on" | "off" | null;
}
const parsed = (text: string | undefined): Record<string, unknown> => {
@@ -172,7 +174,8 @@ const parsed = (text: string | undefined): Record<string, unknown> => {
export function parseHomeReads(output: string): HomeFacts {
const [health, environment, seats] = output.split(RECORD_END);
- return { answers: parsed(health).app === "openmausbot", version: versionOrNull(parsed(environment).version), seats: seatsOrNull(parsed(seats).seats) };
+ const said = parsed(health);
+ return { answers: said.app === "openmausbot", version: versionOrNull(parsed(environment).version), seats: seatsOrNull(parsed(seats).seats), box: boxOnOff(said.box) };
}
// 4. WHAT LEAVES THE SERVER. The heartbeat (every 30 seconds) and each job's reply, rebuilt here field by field. A
@@ -190,6 +193,12 @@ const versionOrNull = (value: unknown) => (typeof value === "string" && VERSION.
const imageOrNull = (value: unknown) => (typeof value === "string" && IMAGE.test(value) ? value : null);
const machine = (value: unknown) => (typeof value === "string" && MACHINE.test(value) ? value : "unknown");
const count = (value: unknown, max = 1e15) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max ? value : 0);
+const boxOnOff = (value: unknown) => (value === "on" || value === "off" ? value : null);
+/** The bot box as a customer-run server reports it: on or off, never its checks. */
+export const boxReport = (value: unknown): HomeHealth["box"] => {
+ const said = boxOnOff(value);
+ return said ? { box: said, checks: null, failed: [] } : null;
+};
const seatsOrNull = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 1_000_000 ? value : null);
/** The server's facts as they leave it, at enrolment and in every heartbeat. */
@@ -215,7 +224,7 @@ function reducedHome(home: HomeReport): HomeReport {
return {
state: HOME_STATES.includes(home.state) ? home.state : "absent",
image: imageOrNull(home.image),
- health: health ? { ok: health.ok === true, version: versionOrNull(health.version), image: imageOrNull(health.image), box: null, at: count(health.at) } : null,
+ health: health ? { ok: health.ok === true, version: versionOrNull(health.version), image: imageOrNull(health.image), box: boxReport(health.box?.box), at: count(health.at) } : null,
};
}
diff --git a/connector/src/main.ts b/connector/src/main.ts
index 0327986184..c02a89f84e 100644
--- a/connector/src/main.ts
+++ b/connector/src/main.ts
@@ -314,10 +314,18 @@ async function probeCommand(): Promise<void> {
if (!ok) process.exitCode = 1;
}
+const JOB_USAGE = [
+ "usage: mausbot-connector job <type> [args as JSON], for example:",
+ " job status the server's state, and its backups with their ids",
+ " job backup",
+ " job restore '{\"backupId\":\"<id>\"}' put a backup back (root only on a server its owner runs); the id is one of job status's backups[].id",
+ " job update '{\"image\":\"ghcr.io/…@sha256:…\"}'",
+].join("\n");
+
/** `job <type> [args as JSON]`: one job, run by the running connector; prints its reply, exits 1 when it failed. */
async function jobCommand(): Promise<void> {
const [type, args] = process.argv.slice(3);
- if (!type) throw new Error("usage: mausbot-connector job <type> [args as JSON], e.g. job update '{\"image\":\"ghcr.io/…@sha256:…\"}'");
+ if (!type) throw new Error(JOB_USAGE);
let parsed: unknown = {};
if (args) {
try { parsed = JSON.parse(args); } catch { throw new Error("the job's arguments are not JSON"); }
@@ -371,7 +379,7 @@ const commands: Record<string, () => Promise<void> | void> = {
const command = commands[process.argv[2] ?? "run"];
if (!command) {
- console.error("usage: mausbot-connector run | enroll | status | probe [--json] | job <type> [args] | audit [--tail N | --verify] | pause | resume | version");
+ console.error(`usage: mausbot-connector run | enroll | status | probe [--json] | job <type> [args] | audit [--tail N | --verify] | pause | resume | version\n${JOB_USAGE}`);
process.exitCode = 2;
} else {
Promise.resolve().then(command).catch((error) => {
diff --git a/connector/src/protocol.ts b/connector/src/protocol.ts
index a3906a30a6..20e044c929 100644
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@ -378,7 +378,7 @@ function noArgs(args: Record<string, unknown>): Checked<Record<string, never>> {
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;
+ return extra.length ? `unknown argument ${JSON.stringify(extra[0])}; this job takes ${keys.length ? keys.join(", ") : "none"}` : null;
}
function httpsOrigin(value: string): boolean {
diff --git a/connector/test/customer-run.test.ts b/connector/test/customer-run.test.ts
index 70bd7a3308..e822a8ab8c 100644
--- a/connector/test/customer-run.test.ts
+++ b/connector/test/customer-run.test.ts
@@ -71,7 +71,7 @@ async function server(options: { image?: string; seats?: number | null } = {}) {
return {
code: 0,
output: [
- JSON.stringify({ app: "openmausbot", pid: 41, owner: EMAIL }),
+ JSON.stringify({ app: "openmausbot", pid: 41, owner: EMAIL, box: "on" }),
JSON.stringify({ environmentId: "env-1", label: SERVER_NAME, version: "0.1.151", admin: EMAIL }),
home.seats === null ? JSON.stringify({ error: "Not found" }) : JSON.stringify({ seats: home.seats, people: [EMAIL] }),
].map((answer) => `${answer}\n\u001e\n`).join(""),
@@ -238,13 +238,16 @@ describe("a customer-run server: what leaves it", () => {
return out;
};
- it("reads three fields from the home and drops everything else it answered", async () => {
+ it("reads four fields from the home and drops everything else it answered", async () => {
const fixture = await server();
expect(HOME_READS).toEqual(["/api/health", "/.well-known/openmausbot/environment", "/api/seats"]);
const facts = parseHomeReads(fixture.docker.onExec!({} as never, []).output);
- expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7 });
- expect(parseHomeReads("not json\n\u001e\n{\"version\":\"<script>\"}\n\u001e\n{\"seats\":\"seven\"}\n\u001e\n")).toEqual({ answers: false, version: null, seats: null });
- expect(parseHomeReads("")).toEqual({ answers: false, version: null, seats: null });
+ expect(facts).toEqual({ answers: true, version: "0.1.151", seats: 7, box: "on" });
+ expect(parseHomeReads("not json\n\u001e\n{\"version\":\"<script>\"}\n\u001e\n{\"seats\":\"seven\"}\n\u001e\n")).toEqual({ answers: false, version: null, seats: null, box: null });
+ expect(parseHomeReads("")).toEqual({ answers: false, version: null, seats: null, box: null });
+ // On or off, nothing else: a server without the field, or with anything else in it, says nothing about its box.
+ expect(parseHomeReads(`${JSON.stringify({ app: "openmausbot", box: "off" })}\n\u001e\n`).box).toBe("off");
+ expect(parseHomeReads(`${JSON.stringify({ app: "openmausbot", box: { checks: "33/33" } })}\n\u001e\n`).box).toBeNull();
});
it("sends a heartbeat of versions, states, counts and the seat count, with no address, name or sentence in it", async () => {
@@ -257,7 +260,7 @@ describe("a customer-run server: what leaves it", () => {
for (const secret of [EMAIL, "@customer", "lovelace", SERVER_NAME, "Lovelace", WRITTEN, "said so", "env-1"]) expect(sent, secret).not.toContain(secret);
expect(beat.heartbeat).toEqual({
host: { ...host, diskTotalGb: 200, memAvailableMb: 9000, load1: 0.1, uptimeS: 50, clockSkewS: 0, checks: [{ id: "disk", ok: true, warning: true }, { id: "clock", ok: true }] },
- home: { state: "running", image: RUNNING, health: { ok: true, version: "0.1.151", image: RUNNING, box: null, at: 1_800_000_000_000 } },
+ home: { state: "running", image: RUNNING, health: { ok: true, version: "0.1.151", image: RUNNING, box: { box: "on", checks: null, failed: [] }, at: 1_800_000_000_000 } },
connector: identity, mode: "customer-run", paused: false, seats: 7,
});
for (const text of strings(beat)) expect(text, text).toMatch(TOLD);
diff --git a/connector/test/protocol.test.ts b/connector/test/protocol.test.ts
index c3054b70cf..b7c81ecf4b 100644
--- a/connector/test/protocol.test.ts
+++ b/connector/test/protocol.test.ts
@@ -22,7 +22,7 @@ describe("the connector protocol", () => {
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"' });
+ expect(checkJob({ id: "j5", type: "update", args: { image: HOME, force: true } })).toMatchObject({ ok: false, code: "invalid_args", message: 'unknown argument "force"; this job takes image' });
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" });
}
diff --git a/docs/design/self-hosted-design.md b/docs/design/self-hosted-design.md
index 902ec88d29..a54ac1613c 100644
--- a/docs/design/self-hosted-design.md
+++ b/docs/design/self-hosted-design.md
@@ -146,7 +146,7 @@ Backward compatible: a field is only ever added, and only by a customer-run serv
| Where | Field | Meaning |
|---|---|---|
| `EnrollRequest` (`POST /api/cloud/box/v1/enroll`) | `mode: "customer-run"` | Present only for a customer-run server; absent means `operated`, exactly the request sent before. Store it with the box |
-| `Heartbeat.heartbeat` | `mode: "customer-run"`, `paused: boolean`, `seats: number \| null` | Present only for a customer-run server. `host`, `home` and `connector` keep their shape; `host.checks[]` carries `id`, `ok` and `warning` without `fix`; `home.health.box` is always null |
+| `Heartbeat.heartbeat` | `mode: "customer-run"`, `paused: boolean`, `seats: number \| null` | Present only for a customer-run server. `host`, `home` and `connector` keep their shape; `host.checks[]` carries `id`, `ok` and `warning` without `fix`; `home.health.box` is `{ box: "on" \| "off", checks: null, failed: [] }` (whether the bots' sandbox is on, never its checks), or null when the server does not say |
| `JobErrorCode` | `refused_by_mode`, `paused`, `update_unavailable`, `update_not_started`, `older_version` | Only from a customer-run server. Its error `message` is a fixed sentence per code |
For a customer-run box the Admin should: send `start` with no arguments; send `update` with
diff --git a/server/index.ts b/server/index.ts
index 448ef4bd6b..16bec41a19 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12414,7 +12414,7 @@ ROUTES.push(createComputerRoutes({
ROUTES.push(createStatusRoutes({
store, cfg,
staticDir: STATIC_DIR,
- sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown,
+ sharedWorkspaceFullAccessEnabled, adminActivityRecording, configStatus, broadcast, threadShown, boxOn: () => botBox.enabled(),
browserEngineInstall: { get: () => browserEngineInstall, set: (install) => { browserEngineInstall = install; } },
browserEngineInstallError: { set: (error) => { browserEngineInstallError = error; } },
}));
diff --git a/server/routes/seats.test.ts b/server/routes/seats.test.ts
index 21a224a68a..8ec0739549 100644
--- a/server/routes/seats.test.ts
+++ b/server/routes/seats.test.ts
@@ -21,6 +21,14 @@ describe("seat count", () => {
expect(seatCount(list, [{ email: "[email protected]", token: true }])).toBe(2);
});
+ // Found on a real server: the owner paired by code and one member on the list counted 1.
+ it("counts the owner paired by code besides the people with an address, unless the owner has one too", () => {
+ const owner = { scopes: ["admin", "client"] };
+ expect(seatCount({ admins: [], members: ["[email protected]"] }, [owner, { email: "[email protected]", scopes: ["client"] }])).toBe(2);
+ expect(seatCount({ admins: ["[email protected]"], members: ["[email protected]"] }, [owner])).toBe(2);
+ expect(seatCount({ admins: [], members: ["[email protected]"] }, [owner, { email: "[email protected]", scopes: ["admin", "client"] }])).toBe(2);
+ });
+
it("counts a server with paired devices and no address as one person, and an empty one as none", () => {
expect(seatCount({ admins: [], members: [] }, [{}, {}, {}])).toBe(1);
expect(seatCount({ admins: [], members: [] }, [])).toBe(0);
diff --git a/server/routes/seats.ts b/server/routes/seats.ts
index 4ae9a1fb97..9fc86fb9e2 100644
--- a/server/routes/seats.ts
+++ b/server/routes/seats.ts
@@ -4,26 +4,32 @@ import type { SignInAllowList } from "../account-signin.ts";
import type { PublicSession } from "../sessions.ts";
import { PASS, type RouteHandler } from "./table.ts";
+type SeatSession = Pick<PublicSession, "email" | "token"> & { scopes?: readonly string[] };
+
/**
* People, not devices: each address on the sign-in list, and each address that holds a session (someone let in by an
- * `@domain` entry counts once they have signed in). Devices paired by code carry no address; they count as one person,
- * the server's owner, only while no address is known at all. API tokens are not people.
+ * `@domain` entry counts once they have signed in). Devices paired by code carry no address: they count as one person,
+ * the server's owner, unless the owner is known by an address already (an admin on the list, or an admin session
+ * with an address). The owner paired by code with a member on the list is two people, not one. API tokens are not people.
*/
-export function seatCount(list: SignInAllowList, sessions: readonly Pick<PublicSession, "email" | "token">[]): number {
+export function seatCount(list: SignInAllowList, sessions: readonly SeatSession[]): number {
const people = new Set<string>();
for (const entry of [...list.admins, ...list.members]) if (!entry.startsWith("@")) people.add(entry.trim().toLowerCase());
let paired = false;
+ let ownerKnown = list.admins.some((entry) => !entry.startsWith("@"));
for (const session of sessions) {
if (session.token) continue;
- if (session.email) people.add(session.email.trim().toLowerCase());
- else paired = true;
+ if (session.email) {
+ people.add(session.email.trim().toLowerCase());
+ if (session.scopes?.includes("admin")) ownerKnown = true;
+ } else paired = true;
}
- return people.size > 0 ? people.size : paired ? 1 : 0;
+ return people.size + (paired && !ownerKnown ? 1 : 0);
}
export interface SeatsRouteDeps {
signInList(): SignInAllowList;
- sessions(): readonly Pick<PublicSession, "email" | "token">[];
+ sessions(): readonly SeatSession[];
}
export function createSeatsRoutes(deps: SeatsRouteDeps): RouteHandler {
diff --git a/server/routes/status-box.test.ts b/server/routes/status-box.test.ts
new file mode 100644
index 0000000000..99cb0d51c4
--- /dev/null
+++ b/server/routes/status-box.test.ts
@@ -0,0 +1,30 @@
+// The MausBot connector on a server its owner runs reads whether the bot box is on from the server's own health answer.
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { describe, expect, it } from "vitest";
+
+import { json, readBody } from "../harness/http.ts";
+import { createStatusRoutes, type StatusRouteDeps } from "./status.ts";
+import { dispatchRoutes } from "./table.ts";
+
+async function health(boxOn?: () => boolean): Promise<Record<string, unknown>> {
+ const routes = [createStatusRoutes({ staticDir: null, sharedWorkspaceFullAccessEnabled: () => false, ...(boxOn ? { boxOn } : {}) } as unknown as StatusRouteDeps)];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: { kind: "loopback", scopes: ["client"], trust: "service" }, json, readBody });
+ });
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ try {
+ return await (await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/api/health`)).json() as Record<string, unknown>;
+ } finally {
+ server.close();
+ }
+}
+
+describe("the health answer behind the gate", () => {
+ it("says whether the bot box is on, on or off and nothing more", async () => {
+ expect((await health(() => true)).box).toBe("on");
+ expect((await health(() => false)).box).toBe("off");
+ expect(await health()).not.toHaveProperty("box");
+ });
+});
diff --git a/server/routes/status.ts b/server/routes/status.ts
index f71ddd37f8..9789c28474 100644
--- a/server/routes/status.ts
+++ b/server/routes/status.ts
@@ -31,6 +31,8 @@ export interface StatusRouteDeps {
browserEngineInstallError: { set(error: string | null): void };
/** On a Team Cloud: false for someone else's private chat, whose words never reach this session's lists. */
threadShown?(auth: RequestAuth): (threadId: string) => boolean;
+ /** Whether bots run in the bot box: the MausBot connector reads it on a server its owner runs, on or off and nothing more. */
+ boxOn?(): boolean;
}
/** A decision in a conversation the reader may not see keeps its when, which bot, which tool and what was decided (the
@@ -52,7 +54,7 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {
return json(res, 200, { app: "openmausbot", pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {
guardedMessages: 1, guardedRequests: 1, guardedFullAccess: 1, guardedOnBehalfOf: 1,
...(sharedWorkspaceFullAccessEnabled() ? { sharedWorkspaceFullAccess: 1 } : {}),
- } });
+ }, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}) });
}
// JSON-only, so a form posted from another local page cannot start the install. One install at a time.
if (method === "POST" && path === "/api/browser-engine/install") {