Skip to content

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

Own server: an audit log the server's owner can read, and jobs from root on the server

milind-soni337ca3f5f012
diff --git a/connector/install.sh b/connector/install.sh
index 2f7fd3743f..67ec14f994 100644
--- a/connector/install.sh
+++ b/connector/install.sh
@@ -13,6 +13,7 @@ ADMIN_URL="${MAUSBOT_ADMIN_URL:-@MAUSBOT_ADMIN_URL@}"
CONNECTOR_IMAGE="${MAUSBOT_CONNECTOR_IMAGE:-@MAUSBOT_CONNECTOR_IMAGE@}"
ETC_DIR="${MAUSBOT_ETC_DIR:-/etc/mausbot}"
+AUDIT_DIR="${MAUSBOT_AUDIT_DIR:-/var/log/mausbot}"
APPARMOR_DIR="${MAUSBOT_APPARMOR_DIR:-/etc/apparmor.d}"
PROFILE=omb-home-narrow
SECCOMP=seccomp-omb-home.json
@@ -219,6 +220,8 @@ install_profiles() {
start_connector() {
say "Starting the MausBot connector..."
docker volume create "$STATE_VOLUME" >/dev/null
+ # The audit log: every job MausBot runs here, root's, for you to read (mausbot-connector audit).
+ install -d -m 0750 "$AUDIT_DIR"
docker rm -f "$CONNECTOR" "$CONNECTOR_NEXT" >/dev/null 2>&1 || true
instance=$(cat /proc/sys/kernel/random/uuid)
set -- --label "$ROLE_LABEL=connector" --label "com.mausbot.instance=$instance" \
@@ -229,7 +232,7 @@ start_connector() {
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" \
+ -v /var/run/docker.sock:/var/run/docker.sock -v "$STATE_VOLUME:/state" -v "$ETC_DIR:/etc/mausbot:ro" -v "$AUDIT_DIR:/var/log/mausbot" \
--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
@@ -327,9 +330,10 @@ uninstall() {
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
+ rm -rf "$AUDIT_DIR"
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 "MausBot is removed from this server. Your data is kept in the Docker volume $DATA_VOLUME, with its backups, and the audit log in $AUDIT_DIR."
say "To delete the data too, run: $(command_line uninstall --delete-data)"
fi
}
diff --git a/connector/src/audit.ts b/connector/src/audit.ts
new file mode 100644
index 0000000000..0e10a75a27
--- /dev/null
+++ b/connector/src/audit.ts
@@ -0,0 +1,117 @@
+// The audit log on the server: one JSON line for each job and for each request MausBot's Admin makes to the home, written
+// by the connector to /var/log/mausbot/audit.jsonl on the host, root's, for the server's owner to read. It is only ever
+// appended to. Each line carries the SHA-256 of the line before it, so a line taken out or changed breaks the chain
+// (verifyAudit). It never holds a secret, an environment value or a pairing code.
+import { createHash } from "node:crypto";
+import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync } from "node:fs";
+import { dirname } from "node:path";
+
+import type { Job, JobError, JobType } from "./protocol.ts";
+
+/** Who asked: the Admin over the connector's connection, or root on this server through `mausbot-connector job`. */
+export type AuditSource = "admin" | "local";
+
+export type AuditEvent =
+ | { event: "connector"; what: "started" | "enrolled"; version: string; image: string | null; serverId?: string }
+ | { event: "job"; by: AuditSource; id: string; type: JobType; args: Record<string, unknown> }
+ | { event: "result"; by: AuditSource; id: string; type: JobType; ok: true; detail?: Record<string, unknown> }
+ | { event: "result"; by: AuditSource; id: string; type: JobType; ok: false; error: JobError }
+ | { event: "step"; id: string; type: JobType; step: string; detail?: Record<string, unknown> }
+ | { event: "request"; by: "admin"; method: string; path: string; status: number; member?: { email: string; role: string; device: string | null } };
+
+export type AuditLine = AuditEvent & { seq: number; at: string; prev: string };
+
+const GENESIS = "0".repeat(64);
+const TAIL_BYTES = 64 * 1024;
+
+export const lineHash = (line: string) => createHash("sha256").update(line).digest("hex");
+
+/** What a job's arguments say, without a value that could be a secret: an environment's names, a URL's origin. */
+export function auditArgs(job: Job): Record<string, unknown> {
+ const args = job.args as Record<string, unknown>;
+ switch (job.type) {
+ case "start":
+ return { image: args.image, env: Object.keys((args.env ?? {}) as Record<string, string>).sort() };
+ case "import-disk":
+ return { from: new URL(String(args.url)).origin };
+ default:
+ return { ...args };
+ }
+}
+
+/**
+ * A request the Admin sent to the home through the connector. For a pairing it names who it opens a session for and on
+ * which device, from the Admin's own claim in the request; never the code the home answers with.
+ */
+export function auditRequest(method: string, target: string, status: number, body: string | null): Extract<AuditEvent, { event: "request" }> {
+ const path = target.split("?")[0]!.slice(0, 200);
+ const event: Extract<AuditEvent, { event: "request" }> = { event: "request", by: "admin", method, path, status };
+ if (method !== "POST" || path !== "/api/cloud/pairing" || !body) return event;
+ try {
+ const parsed = JSON.parse(body) as { label?: unknown; member?: { email?: unknown; role?: unknown } };
+ const { email, role } = parsed.member ?? {};
+ if (typeof email === "string" && typeof role === "string") {
+ event.member = { email: email.slice(0, 320), role: role.slice(0, 40), device: typeof parsed.label === "string" ? parsed.label.slice(0, 80) : null };
+ }
+ } catch {
+ // An unreadable body is the home's to refuse; the line still says the request came.
+ }
+ return event;
+}
+
+export class AuditLog {
+ readonly file: string;
+ private readonly now: () => number;
+
+ constructor(file: string, now: () => number = Date.now) {
+ this.file = file;
+ this.now = now;
+ }
+
+ /** Appends one line; throws when it cannot, so a job is never run unrecorded. */
+ append(event: AuditEvent): AuditLine {
+ mkdirSync(dirname(this.file), { recursive: true, mode: 0o750 });
+ const last = this.lastLine();
+ let seq = 1;
+ if (last) {
+ try { seq = (JSON.parse(last) as { seq?: number }).seq! + 1; } catch { seq = Number.NaN; }
+ if (!Number.isInteger(seq)) seq = 1;
+ }
+ const line: AuditLine = { seq, at: new Date(this.now()).toISOString(), prev: last ? lineHash(last) : GENESIS, ...event };
+ appendFileSync(this.file, `${JSON.stringify(line)}\n`, { mode: 0o600 });
+ return line;
+ }
+
+ /** The newest `count` lines, oldest first. */
+ tail(count: number): string[] {
+ if (!existsSync(this.file)) return [];
+ return readFileSync(this.file, "utf8").split("\n").filter(Boolean).slice(-count);
+ }
+
+ /** Reads back only the end of the file: the log grows for as long as the server runs. */
+ private lastLine(): string | null {
+ if (!existsSync(this.file)) return null;
+ const size = statSync(this.file).size;
+ if (size === 0) return null;
+ const length = Math.min(size, TAIL_BYTES);
+ const buffer = Buffer.alloc(length);
+ const fd = openSync(this.file, "r");
+ try { readSync(fd, buffer, 0, length, size - length); } finally { closeSync(fd); }
+ const lines = buffer.toString("utf8").split("\n").filter(Boolean);
+ return lines.at(-1) ?? null;
+ }
+}
+
+/** Checks the chain from the first line: each line's `prev` is the hash of the line before it, and `seq` counts up by one. */
+export function verifyAudit(text: string): { ok: true; lines: number } | { ok: false; line: number; why: string } {
+ const lines = text.split("\n").filter(Boolean);
+ let prev = GENESIS;
+ for (const [index, raw] of lines.entries()) {
+ let line: Partial<AuditLine>;
+ try { line = JSON.parse(raw) as Partial<AuditLine>; } catch { return { ok: false, line: index + 1, why: "not JSON" }; }
+ if (line.prev !== prev) return { ok: false, line: index + 1, why: "the line before it was changed or removed" };
+ if (line.seq !== index + 1) return { ok: false, line: index + 1, why: `numbered ${line.seq}, expected ${index + 1}` };
+ prev = lineHash(raw);
+ }
+ return { ok: true, lines: lines.length };
+}
diff --git a/connector/src/jobs.ts b/connector/src/jobs.ts
index cb355e86d9..975559b2bd 100644
--- a/connector/src/jobs.ts
+++ b/connector/src/jobs.ts
@@ -1,7 +1,9 @@
// 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 { auditArgs, type AuditEvent, type AuditLog, type AuditSource } from "./audit.ts";
import { asJobError } from "./failure.ts";
import type { Home } from "./home.ts";
+import { errorText, type Log } from "./log.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. */
@@ -66,3 +68,53 @@ export function jobRunner(deps: RunnerDeps): (job: Job) => Promise<JobReply | nu
}
};
}
+
+/** Jobs only read: they run even when the audit log cannot be written, and that is logged. */
+const READS: ReadonlySet<JobType> = new Set(["status", "host-health"]);
+
+export interface Desk {
+ /**
+ * Every job, from any channel, comes in here: recorded in the audit log, run, and its result recorded. A job that
+ * would change something is refused when it cannot be recorded. Null: the new connector answers a self-update.
+ */
+ submit(job: Job, by: AuditSource): Promise<JobReply | null>;
+}
+
+export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audit: AuditLog; log: Log }): Desk {
+ const record = (event: AuditEvent): boolean => {
+ try {
+ deps.audit.append(event);
+ return true;
+ } catch (error) {
+ deps.log(`could not write the audit log ${deps.audit.file}: ${errorText(error)}`);
+ return false;
+ }
+ };
+ return {
+ async submit(job, by) {
+ if (!record({ event: "job", by, id: job.id, type: job.type, args: auditArgs(job) }) && !READS.has(job.type)) {
+ return { id: job.id, ok: false, error: { code: "audit_unavailable", message: `The audit log at ${deps.audit.file} cannot be written, so nothing was done. Run the install command again to repair it.` } };
+ }
+ const reply = await deps.run(job);
+ if (reply) record(resultEvent(by, job.type, reply));
+ return reply;
+ },
+ };
+}
+
+export function resultEvent(by: AuditSource, type: JobType, reply: JobReply): AuditEvent {
+ return reply.ok ? { event: "result", by, id: reply.id, type, ok: true, detail: resultDetail(reply.result as Record<string, unknown>) } : { event: "result", by, id: reply.id, type, ok: false, error: reply.error };
+}
+
+/** The images and copies a result names: what the server's owner looks for afterwards. */
+function resultDetail(result: Record<string, unknown>): Record<string, unknown> {
+ const home = result.home as { state?: string; image?: string | null } | undefined;
+ const detail: Record<string, unknown> = {};
+ if (home) Object.assign(detail, { home: home.state, image: home.image ?? null });
+ for (const key of ["previousImage", "backupId", "bytes", "sha256"]) if (result[key] !== undefined) detail[key] = result[key];
+ const copy = (result.snapshot ?? result.backup) as { id?: string } | null | undefined;
+ if (copy?.id) detail.copy = copy.id;
+ const connector = result.connector as { version?: string; image?: string | null } | undefined;
+ if (connector) Object.assign(detail, { connector: connector.version, connectorImage: connector.image ?? null });
+ return detail;
+}
diff --git a/connector/src/local.ts b/connector/src/local.ts
new file mode 100644
index 0000000000..52f11e26ea
--- /dev/null
+++ b/connector/src/local.ts
@@ -0,0 +1,73 @@
+// Jobs from root on this server: `mausbot-connector job <type> [args]`, run with `docker exec` in the connector's
+// container, sends one job over a Unix socket in the container's own /tmp, which nothing outside the container can
+// open. It goes through the same checks, queue and audit log as a job from MausBot, and is recorded as `local`.
+import { randomBytes } from "node:crypto";
+import { chmodSync, rmSync } from "node:fs";
+import { createConnection, createServer, type Server } from "node:net";
+
+import type { Desk } from "./jobs.ts";
+import { errorText, type Log } from "./log.ts";
+import { checkJob, type JobReply } from "./protocol.ts";
+
+const MAX_REQUEST_BYTES = 64 * 1024;
+
+export function localJobId(): string {
+ return `local-${new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14)}-${randomBytes(3).toString("hex")}`;
+}
+
+/** Answers one JSON line `{type, args}` per connection with the job's reply, as one JSON line. */
+export function serveLocalJobs(socketPath: string, desk: Desk, log: Log): Promise<Server> {
+ rmSync(socketPath, { force: true });
+ const server = createServer((socket) => {
+ let text = "";
+ const answer = (reply: JobReply | { ok: false; error: { code: string; message: string } }) => socket.end(`${JSON.stringify(reply)}\n`);
+ socket.setEncoding("utf8");
+ socket.on("error", () => {});
+ socket.on("data", (chunk: string) => {
+ text += chunk;
+ if (text.length > MAX_REQUEST_BYTES) {
+ answer({ ok: false, error: { code: "invalid_job", message: "the job is too large" } });
+ socket.destroy();
+ return;
+ }
+ const end = text.indexOf("\n");
+ if (end < 0) return;
+ socket.removeAllListeners("data");
+ let request: unknown;
+ try { request = JSON.parse(text.slice(0, end)); } catch { request = null; }
+ const fields = typeof request === "object" && request !== null && !Array.isArray(request) ? request as Record<string, unknown> : {};
+ const checked = checkJob({ id: localJobId(), type: fields.type, args: fields.args });
+ if (!checked.ok) {
+ answer({ ok: false, error: { code: checked.code, message: checked.message } });
+ return;
+ }
+ log(`job ${checked.job.id}: ${checked.job.type} (from this server)`);
+ desk.submit(checked.job, "local").then(
+ (reply) => answer(reply ?? { ok: false, error: { code: "self_update_failed", message: "the new connector took over and answered this job" } }),
+ (error) => answer({ ok: false, error: { code: "docker", message: errorText(error) } }),
+ );
+ });
+ });
+ return new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(socketPath, () => {
+ chmodSync(socketPath, 0o600);
+ resolve(server);
+ });
+ });
+}
+
+/** Sends one job to the running connector and waits for its reply, as long as the job takes. */
+export function sendLocalJob(socketPath: string, type: string, args: unknown): Promise<Record<string, unknown>> {
+ return new Promise((resolve, reject) => {
+ const socket = createConnection(socketPath);
+ let text = "";
+ socket.setEncoding("utf8");
+ socket.on("connect", () => socket.write(`${JSON.stringify({ type, args })}\n`));
+ socket.on("data", (chunk: string) => { text += chunk; });
+ socket.on("end", () => {
+ try { resolve(JSON.parse(text) as Record<string, unknown>); } catch { reject(new Error("the connector gave no answer")); }
+ });
+ socket.on("error", (error) => reject(new Error(`the connector is not running here (${error.message})`)));
+ });
+}
diff --git a/connector/src/main.ts b/connector/src/main.ts
index 4970322607..9a89dfb986 100644
--- a/connector/src/main.ts
+++ b/connector/src/main.ts
@@ -1,18 +1,21 @@
-// mausbot-connector: `run` (the service), `enroll` (the code on stdin), `status`, `probe`, `version`.
-import { readFileSync, statfsSync } from "node:fs";
+// mausbot-connector: `run` (the service), `enroll` (the code on stdin), `status`, `probe`, `job` (one job from root on this
+// server), `audit` (the audit log, checked), `version`.
+import { existsSync, readFileSync, statfsSync } from "node:fs";
import { join } from "node:path";
import { Agent } from "./agent.ts";
+import { AuditLog, verifyAudit } from "./audit.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 { jobDesk, jobRunner, resultEvent } from "./jobs.ts";
+import { sendLocalJob, serveLocalJobs } from "./local.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 { AUDIT_FILE, CONNECTOR_VERSION, PATHS, SECCOMP_FILE, envSeconds } from "./settings.ts";
import { StateStore, type AgentRecord } from "./state.ts";
import { httpTransfer } from "./transfer.ts";
@@ -34,6 +37,7 @@ const reader: HostReader = {
},
};
+const auditLog = () => new AuditLog(join(PATHS.audit, AUDIT_FILE));
const identity = (): ConnectorIdentity => ({ version: CONNECTOR_VERSION, protocol: PROTOCOL_VERSION, image: process.env.MAUSBOT_CONNECTOR_IMAGE || null });
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -93,16 +97,23 @@ async function run(): Promise<void> {
const docker = new SocketDocker(PATHS.docker);
const instance = process.env.MAUSBOT_INSTANCE || "unknown";
log(`MausBot connector ${CONNECTOR_VERSION} starting`);
+ const audit = auditLog();
+ const note = (event: Parameters<AuditLog["append"]>[0]) => {
+ try { audit.append(event); } catch (error) { log(`could not write the audit log ${audit.file}: ${errorText(error)}`); }
+ };
+ note({ event: "connector", what: "started", version: CONNECTOR_VERSION, image: identity().image });
// 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");
+ const enrolledNow = !record;
while (!record) {
await sleep(2_000);
record = state.agent();
}
registerSecret(record.agentToken);
let current: AgentRecord = record;
+ if (enrolledNow) note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, serverId: record.serverId });
const host = hostReporter(docker, () => current.admin);
const home = new Home({
docker, state, log, readHealth, seccomp, transfer: httpTransfer,
@@ -115,14 +126,15 @@ async function run(): Promise<void> {
return { heartbeat: { host: await host.health(false), home: await home.report(), connector: identity() } };
};
let agent: Agent;
- const handle = jobRunner({
+ const runner = 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) });
+ const desk = jobDesk({ run: runner, audit, log });
+ const makeAgent = (from: AgentRecord) => new Agent({ admin: from.admin, token: from.agentToken, log, heartbeat, handle: (job) => desk.submit(job, "admin"), status: (patch) => state.saveStatus(patch) });
agent = makeAgent(current);
const role = await updater.atStart(() => new Promise<boolean>((resolve) => {
@@ -141,13 +153,21 @@ async function run(): Promise<void> {
if (self) await docker.stopContainer(self.Id, 10).catch(() => {});
return;
}
+ const interrupted = state.home().operation?.type ?? "update";
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);
+ if (recovered) {
+ note(resultEvent("admin", interrupted, recovered));
+ agent.reply(recovered);
+ }
+ if (role.role === "candidate") {
+ note(resultEvent("admin", "self-update", role.reply));
+ agent.reply(role.reply);
+ }
agent.start();
+ await serveLocalJobs(PATHS.jobs, desk, log).catch((error) => log(`jobs from this server are off: ${errorText(error)}`));
setInterval(() => {
home.supervise().catch((error) => log(`supervising the home failed: ${errorText(error)}`));
@@ -156,6 +176,7 @@ async function run(): Promise<void> {
log("this server was connected again with a new code; reconnecting");
registerSecret(latest.agentToken);
current = latest;
+ note({ event: "connector", what: "enrolled", version: CONNECTOR_VERSION, image: identity().image, serverId: latest.serverId });
agent.stop();
agent = makeAgent(current);
agent.start();
@@ -210,17 +231,47 @@ async function probeCommand(): Promise<void> {
if (checks.some((check) => !check.ok)) process.exitCode = 1;
}
+/** `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:…\"}'");
+ let parsed: unknown = {};
+ if (args) {
+ try { parsed = JSON.parse(args); } catch { throw new Error("the job's arguments are not JSON"); }
+ }
+ const reply = await sendLocalJob(PATHS.jobs, type, parsed);
+ console.log(JSON.stringify(reply));
+ if (reply.ok !== true) process.exitCode = 1;
+}
+
+/** `audit [--tail N]` prints the newest lines; `audit --verify` checks every line's link to the one before it. */
+function auditCommand(): void {
+ const audit = auditLog();
+ const args = process.argv.slice(3);
+ if (args.includes("--verify")) {
+ const verdict = verifyAudit(existsSync(audit.file) ? readFileSync(audit.file, "utf8") : "");
+ console.log(verdict.ok ? `${audit.file}: ${verdict.lines} lines, each linked to the one before it` : `${audit.file}: line ${verdict.line}: ${verdict.why}`);
+ if (!verdict.ok) process.exitCode = 1;
+ return;
+ }
+ const at = args.indexOf("--tail");
+ const count = at >= 0 ? Number(args[at + 1]) : 50;
+ for (const line of audit.tail(Number.isInteger(count) && count > 0 ? count : 50)) console.log(line);
+}
+
const commands: Record<string, () => Promise<void> | void> = {
run,
enroll: enrollCommand,
status: statusCommand,
probe: probeCommand,
+ job: jobCommand,
+ audit: auditCommand,
version: () => console.log(CONNECTOR_VERSION),
};
const command = commands[process.argv[2] ?? "run"];
if (!command) {
- console.error("usage: mausbot-connector run | enroll | status | probe | version");
+ console.error("usage: mausbot-connector run | enroll | status | probe | job <type> [args] | audit [--tail N | --verify] | version");
process.exitCode = 2;
} else {
Promise.resolve().then(command).catch((error) => {
diff --git a/connector/src/protocol.ts b/connector/src/protocol.ts
index 10be62e43b..b6410acb5f 100644
--- a/connector/src/protocol.ts
+++ b/connector/src/protocol.ts
@@ -154,7 +154,7 @@ export interface JobResults {
}
export type JobErrorCode =
- | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted"
+ | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable"
| "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";
diff --git a/connector/src/settings.ts b/connector/src/settings.ts
index 013ae5bde5..891ba15dfe 100644
--- a/connector/src/settings.ts
+++ b/connector/src/settings.ts
@@ -33,8 +33,14 @@ export const PATHS = {
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",
+ /** /var/log/mausbot on the host, mounted read-write: the audit log the server's owner reads. */
+ audit: process.env.MAUSBOT_AUDIT_DIR || "/var/log/mausbot",
+ /** In the container's own /tmp: `mausbot-connector job` reaches the running connector here. */
+ jobs: process.env.MAUSBOT_JOBS_SOCKET || "/tmp/mausbot-jobs.sock",
} as const;
+export const AUDIT_FILE = "audit.jsonl";
+
export const SECCOMP_FILE = "seccomp-omb-home.json";
export const APPARMOR_PROFILE = "omb-home-narrow";
diff --git a/connector/test/audit.test.ts b/connector/test/audit.test.ts
new file mode 100644
index 0000000000..9e0e38ad64
--- /dev/null
+++ b/connector/test/audit.test.ts
@@ -0,0 +1,127 @@
+import { mkdtempSync, 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 { AuditLog, auditArgs, auditRequest, verifyAudit, type AuditLine } from "../src/audit.ts";
+import { jobDesk } from "../src/jobs.ts";
+import { localJobId, sendLocalJob, serveLocalJobs } from "../src/local.ts";
+import type { Job, JobReply } from "../src/protocol.ts";
+
+const HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)}`;
+const SECRET = "Bootstrap-secret-0123456789abcdefghijklmnopq";
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+const folder = () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-connector-audit-"));
+ dirs.push(dir);
+ return dir;
+};
+const lines = (file: string) => readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line) as AuditLine);
+
+describe("the audit log", () => {
+ it("appends one line per event, each linked to the one before it, root's alone", () => {
+ const file = join(folder(), "log", "audit.jsonl");
+ let clock = Date.parse("2026-11-06T02:00:00Z");
+ const audit = new AuditLog(file, () => clock++);
+ audit.append({ event: "connector", what: "started", version: "1.0.0", image: null });
+ audit.append({ event: "job", by: "admin", id: "u1", type: "update", args: { image: HOME } });
+ // Another process (a connector taking over from this one) appends to the same file: the chain still holds.
+ new AuditLog(file).append({ event: "result", by: "admin", id: "u1", type: "update", ok: true, detail: { image: HOME } });
+ const written = lines(file);
+ expect(written.map((line) => [line.seq, line.event])).toEqual([[1, "connector"], [2, "job"], [3, "result"]]);
+ expect(written[0]).toMatchObject({ at: "2026-11-06T02:00:00.000Z", prev: "0".repeat(64) });
+ expect(verifyAudit(readFileSync(file, "utf8"))).toEqual({ ok: true, lines: 3 });
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
+ expect(audit.tail(2).map((line) => JSON.parse(line).seq)).toEqual([2, 3]);
+ });
+
+ it("shows a line changed or taken out", () => {
+ const file = join(folder(), "audit.jsonl");
+ const audit = new AuditLog(file);
+ for (const id of ["a", "b", "c"]) audit.append({ event: "job", by: "local", id, type: "backup", args: {} });
+ const text = readFileSync(file, "utf8").split("\n");
+ expect(verifyAudit([text[0], text[2]].join("\n"))).toMatchObject({ ok: false, line: 2, why: "the line before it was changed or removed" });
+ expect(verifyAudit([text[0].replace('"by":"local"', '"by":"admin"'), text[1], text[2]].join("\n"))).toMatchObject({ ok: false, line: 2 });
+ expect(verifyAudit(text.slice(1).join("\n"))).toMatchObject({ ok: false, line: 1 });
+ expect(verifyAudit("")).toEqual({ ok: true, lines: 0 });
+ });
+
+ it("records what a job asked for without a value that could be a secret", () => {
+ const start: Job = { id: "s1", type: "start", args: { image: HOME, env: { OMB_PUBLIC_URL: "https://acme.example", OMB_CLOUD_BOOTSTRAP_SECRET: SECRET } } };
+ expect(auditArgs(start)).toEqual({ image: HOME, env: ["OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_PUBLIC_URL"] });
+ expect(JSON.stringify(auditArgs(start))).not.toContain(SECRET);
+ expect(auditArgs({ id: "i1", type: "import-disk", args: { url: "https://bucket.example/home.tar.gz?X-Signature=abcdef" } })).toEqual({ from: "https://bucket.example" });
+ expect(auditArgs({ id: "r1", type: "restore", args: { backupId: "20261028-104512-3fa9" } })).toEqual({ backupId: "20261028-104512-3fa9" });
+ });
+
+ it("names who an Admin pairing is for and on which device, never the code or a query", () => {
+ const body = JSON.stringify({ label: "Ana's laptop", ttlSeconds: 600, member: { email: "[email protected]", role: "admin", sig: "x" } });
+ expect(auditRequest("POST", "/api/cloud/pairing", 200, body)).toEqual({
+ event: "request", by: "admin", method: "POST", path: "/api/cloud/pairing", status: 200, member: { email: "[email protected]", role: "admin", device: "Ana's laptop" },
+ });
+ expect(auditRequest("GET", "/api/cloud/health?token=abc", 200, null)).toEqual({ event: "request", by: "admin", method: "GET", path: "/api/cloud/health", status: 200 });
+ expect(auditRequest("POST", "/api/cloud/pairing", 400, "not json")).not.toHaveProperty("member");
+ });
+});
+
+describe("the job desk", () => {
+ const reply = (job: Job): JobReply => ({ id: job.id, ok: true, result: { home: { state: "running", image: HOME, health: null }, previousImage: null, snapshot: { id: "snapshot", kind: "snapshot", createdAt: 1, image: HOME } } } as JobReply);
+
+ it("records each job and its result, whoever sent it", async () => {
+ const file = join(folder(), "audit.jsonl");
+ const ran: string[] = [];
+ const desk = jobDesk({ run: async (job) => { ran.push(job.id); return reply(job); }, audit: new AuditLog(file), log: () => {} });
+ await desk.submit({ id: "u1", type: "update", args: { image: HOME } }, "admin");
+ await desk.submit({ id: "local-1", type: "restart", args: {} }, "local");
+ expect(ran).toEqual(["u1", "local-1"]);
+ expect(lines(file).map((line) => { const { event, by, id } = line as AuditLine & { by: string; id: string }; return { event, by, id }; })).toEqual([
+ { event: "job", by: "admin", id: "u1" }, { event: "result", by: "admin", id: "u1" },
+ { event: "job", by: "local", id: "local-1" }, { event: "result", by: "local", id: "local-1" },
+ ]);
+ expect(lines(file)[1]).toMatchObject({ ok: true, detail: { home: "running", image: HOME, copy: "snapshot" } });
+ });
+
+ it("does nothing that changes the server when it cannot record it, and still answers a status", async () => {
+ const dir = folder();
+ writeFileSync(join(dir, "log"), "a file where the folder should be");
+ const logged: string[] = [];
+ const ran: string[] = [];
+ const desk = jobDesk({ run: async (job) => { ran.push(job.type); return reply(job); }, audit: new AuditLog(join(dir, "log", "audit.jsonl")), log: (line) => logged.push(line) });
+ const refused = await desk.submit({ id: "u1", type: "update", args: { image: HOME } }, "admin");
+ expect(refused).toMatchObject({ ok: false, error: { code: "audit_unavailable" } });
+ expect((await desk.submit({ id: "s1", type: "status", args: {} }, "admin"))?.ok).toBe(true);
+ expect(ran).toEqual(["status"]);
+ expect(logged.some((line) => line.startsWith("could not write the audit log"))).toBe(true);
+ });
+});
+
+describe.skipIf(process.platform === "win32")("jobs from root on this server", () => {
+ it("go through the same checks and desk as MausBot's, and only root can reach the socket", async () => {
+ const dir = folder();
+ const socket = join(dir, "jobs.sock");
+ const submitted: { job: Job; by: string }[] = [];
+ const server = await serveLocalJobs(socket, { submit: async (job, by) => { submitted.push({ job, by }); return reply(job); } }, () => {});
+ try {
+ expect(statSync(socket).mode & 0o777).toBe(0o600);
+ const answered = await sendLocalJob(socket, "update", { image: HOME });
+ expect(answered).toMatchObject({ ok: true, result: { home: { image: HOME } } });
+ expect(submitted).toHaveLength(1);
+ expect(submitted[0]).toMatchObject({ by: "local", job: { type: "update", args: { image: HOME } } });
+ expect(submitted[0]!.job.id).toMatch(/^local-\d{14}-[0-9a-f]{6}$/);
+ expect(await sendLocalJob(socket, "shell", { command: "id" })).toMatchObject({ ok: false, error: { code: "unknown_job" } });
+ expect(await sendLocalJob(socket, "update", { image: "docker.io/someone/else:latest" })).toMatchObject({ ok: false, error: { code: "invalid_args" } });
+ expect(submitted).toHaveLength(1);
+ } finally {
+ server.close();
+ }
+ await expect(sendLocalJob(socket, "status", {})).rejects.toThrow("the connector is not running here");
+ expect(localJobId()).not.toBe(localJobId());
+ });
+
+ function reply(job: Job): JobReply {
+ return { id: job.id, ok: true, result: { home: { state: "running", image: HOME, health: null }, previousImage: null, snapshot: null } } as JobReply;
+ }
+});
diff --git a/connector/test/install-script.test.ts b/connector/test/install-script.test.ts
index 2a5a505732..a19936cb2f 100644
--- a/connector/test/install-script.test.ts
+++ b/connector/test/install-script.test.ts
@@ -4,7 +4,7 @@ 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";
+import { APPARMOR_PROFILE, LABELS, NAMES, PATHS, SECCOMP_FILE } from "../src/settings.ts";
const SCRIPT = join(import.meta.dirname, "..", "install.sh");
const script = readFileSync(SCRIPT, "utf8");
@@ -34,21 +34,24 @@ esac`);
tool("apparmor_parser", `echo "apparmor_parser $*" >> "${log}"`);
const etc = join(dir, "etc-mausbot");
const apparmor = join(dir, "apparmor.d");
+ const audit = join(dir, "log-mausbot");
mkdirSync(etc);
mkdirSync(apparmor);
+ mkdirSync(audit);
+ writeFileSync(join(audit, "audit.jsonl"), "{}\n");
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,
+ PATH: `${bin}:/usr/bin:/bin`, MAUSBOT_ETC_DIR: etc, MAUSBOT_APPARMOR_DIR: apparmor, MAUSBOT_AUDIT_DIR: audit,
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 };
+ return { ...result, calls, etc, apparmor, audit };
}
describe("install.sh", () => {
@@ -76,7 +79,9 @@ describe("install.sh", () => {
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("-v /var/run/docker.sock:/var/run/docker.sock -v \"$STATE_VOLUME:/state\" -v \"$ETC_DIR:/etc/mausbot:ro\" -v \"$AUDIT_DIR:/var/log/mausbot\"");
+ expect(script).toContain('AUDIT_DIR="${MAUSBOT_AUDIT_DIR:-/var/log/mausbot}"');
+ expect(PATHS.audit).toBe("/var/log/mausbot");
expect(script).toContain('apparmor_parser -r -W "$APPARMOR_DIR/$PROFILE"');
});
@@ -91,7 +96,8 @@ describe("install.sh", () => {
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(`Your data is kept in the Docker volume ${NAMES.dataVolume}, with its backups, and the audit log in ${result.audit}.`);
+ expect(existsSync(join(result.audit, "audit.jsonl"))).toBe(true);
expect(result.stdout).toContain("curl -fsSL https://cloud.example.test/install.sh | sudo sh -s -- uninstall --delete-data");
});
@@ -103,6 +109,7 @@ describe("install.sh", () => {
"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.");
+ expect(existsSync(deleted.audit)).toBe(false);
for (const typo of [["uninstall", "--delete-dat"], ["uninstall", "--delete-data=yes"], ["uninstall", "-f"]]) {
const refused = run(typo);
expect(refused.status, typo.join(" ")).toBe(1);