Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Own server: the server owner's policy file, which the connector obeys
milind-soni402a959936af
diff --git a/connector/src/jobs.ts b/connector/src/jobs.tsindex 975559b2bd..27c7b32f8c 100644--- a/connector/src/jobs.ts+++ b/connector/src/jobs.ts@@ -4,6 +4,7 @@ import { auditArgs, type AuditEvent, type AuditLog, type AuditSource } from "./aimport { asJobError } from "./failure.ts";import type { Home } from "./home.ts";import { errorText, type Log } from "./log.ts";+import { policyRefusal, readPolicy } from "./policy.ts";import type { ConnectorIdentity, HostHealth, Job, JobArgs, JobReply, JobResults, JobType } from "./protocol.ts";/** Jobs that change the home, its data or the connector; they wait for each other. */@@ -80,7 +81,7 @@ export interface Desk {submit(job: Job, by: AuditSource): Promise<JobReply | null>;}-export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audit: AuditLog; log: Log }): Desk {+export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audit: AuditLog; log: Log; policyFile?: string }): Desk {const record = (event: AuditEvent): boolean => {try {deps.audit.append(event);@@ -95,6 +96,12 @@ export function jobDesk(deps: { run: (job: Job) => Promise<JobReply | null>; audif (!record({ event: "job", by, id: job.id, type: job.type, args: auditArgs(job) }) && !READS.has(job.type)) {return { id: job.id, ok: false, error: { code: "audit_unavailable", message: `The audit log at ${deps.audit.file} cannot be written, so nothing was done. Run the install command again to repair it.` } };}+ const refusal = by === "admin" && deps.policyFile ? policyRefusal(job, readPolicy(deps.policyFile), deps.policyFile) : null;+ if (refusal) {+ const refused: JobReply = { id: job.id, ok: false, error: { code: "refused_by_policy", message: refusal } };+ record(resultEvent(by, job.type, refused));+ return refused;+ }const reply = await deps.run(job);if (reply) record(resultEvent(by, job.type, reply));return reply;diff --git a/connector/src/main.ts b/connector/src/main.tsindex 9a89dfb986..69e2d9293b 100644--- a/connector/src/main.ts+++ b/connector/src/main.ts@@ -12,6 +12,7 @@ import { Home } from "./home.ts";import { hostChecks, hostFacts, hostHealth, probeBox, type BoxProbeResult, type HostReader } from "./host.ts";import { jobDesk, jobRunner, resultEvent } from "./jobs.ts";import { sendLocalJob, serveLocalJobs } from "./local.ts";+import { POLICY_FILE } from "./policy.ts";import { errorText, log, registerSecret } from "./log.ts";import { PROTOCOL_VERSION, type ConnectorIdentity, type Heartbeat, type HostHealth } from "./protocol.ts";import { SELF_UPDATE_DEADLINE_MS, SelfUpdater, ownContainer } from "./self-update.ts";@@ -133,7 +134,7 @@ async function run(): Promise<void> {admin: () => ({ origin: current.admin, token: current.agentToken }),selfUpdate: (job) => home.exclusive(() => updater.run(job, { pause: () => agent.stop(), resume: () => agent.start() })),});- const desk = jobDesk({ run: runner, audit, log });+ const desk = jobDesk({ run: runner, audit, log, policyFile: join(PATHS.hostConfig, POLICY_FILE) });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);diff --git a/connector/src/policy.ts b/connector/src/policy.tsnew file mode 100644index 0000000000..c9d64d57e6--- /dev/null+++ b/connector/src/policy.ts@@ -0,0 +1,54 @@+// The server owner's own rules for what MausBot may do here: /etc/mausbot/policy.json on the host, root's, which the+// connector reads (mounted read-only) before each job MausBot sends and never writes. Jobs root runs on the server+// itself are the owner's own and are not limited by it.+//+// { "jobs": ["status", "host-health", "update", "backup"], "updates": "hold" }+//+// `jobs`: the only kinds MausBot may run here (absent: all of them). `updates: "hold"`: MausBot's home updates wait.+// A self-update of the connector is always accepted, so a held or locked-down server never strands an old connector.+import { readFileSync } from "node:fs";++import { JOB_TYPES, type Job, type JobType } from "./protocol.ts";++export const POLICY_FILE = "policy.json";++export interface Policy {+ jobs: JobType[] | null;+ updates: "automatic" | "hold";+}++const READS: ReadonlySet<JobType> = new Set(["status", "host-health"]);++/** The policy in `text` (null: no file, every job allowed), or why it cannot be used. */+export function parsePolicy(text: string | null): { ok: true; policy: Policy } | { ok: false; problem: string } {+ if (text === null) return { ok: true, policy: { jobs: null, updates: "automatic" } };+ let raw: unknown;+ try { raw = JSON.parse(text); } catch { return { ok: false, problem: "it is not JSON" }; }+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { ok: false, problem: "it is not a JSON object" };+ const { jobs, updates, ...rest } = raw as Record<string, unknown>;+ const unknown = Object.keys(rest);+ if (unknown.length) return { ok: false, problem: `it has a setting this connector does not know: ${unknown[0]}` };+ if (jobs !== undefined && (!Array.isArray(jobs) || jobs.some((type) => !(JOB_TYPES as readonly unknown[]).includes(type)))) {+ return { ok: false, problem: `"jobs" must list job kinds from: ${JOB_TYPES.join(", ")}` };+ }+ if (updates !== undefined && updates !== "automatic" && updates !== "hold") return { ok: false, problem: '"updates" must be "automatic" or "hold"' };+ return { ok: true, policy: { jobs: (jobs as JobType[] | undefined) ?? null, updates: (updates as Policy["updates"] | undefined) ?? "automatic" } };+}++export function readPolicy(file: string): ReturnType<typeof parsePolicy> {+ let text: string | null;+ try { text = readFileSync(file, "utf8"); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return { ok: false, problem: `it cannot be read (${(error as NodeJS.ErrnoException).code})` };+ text = null;+ }+ return parsePolicy(text);+}++/** Why the server's policy refuses `job` from MausBot, or null. A self-update is never refused. */+export function policyRefusal(job: Job, read: ReturnType<typeof parsePolicy>, file: string): string | null {+ if (job.type === "self-update") return null;+ if (!read.ok) return READS.has(job.type) ? null : `This server's policy ${file} cannot be used (${read.problem}), so MausBot changes nothing here until it is fixed.`;+ if (read.policy.jobs && !read.policy.jobs.includes(job.type)) return `This server's policy ${file} does not let MausBot run ${job.type} jobs.`;+ if (job.type === "update" && read.policy.updates === "hold") return `This server's policy ${file} holds updates.`;+ return null;+}diff --git a/connector/src/protocol.ts b/connector/src/protocol.tsindex b6410acb5f..1b20e84155 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" | "audit_unavailable"+ | "invalid_job" | "unknown_job" | "invalid_args" | "busy" | "interrupted" | "audit_unavailable" | "refused_by_policy"| "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/test/audit.test.ts b/connector/test/audit.test.tsindex 9e0e38ad64..c7ea5029f6 100644--- a/connector/test/audit.test.ts+++ b/connector/test/audit.test.ts@@ -6,6 +6,7 @@ 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 { parsePolicy } from "../src/policy.ts";import type { Job, JobReply } from "../src/protocol.ts";const HOME = `ghcr.io/milind-soni/openmausbot-cloud-home@sha256:${"a".repeat(64)}`;@@ -98,6 +99,45 @@ describe("the job desk", () => {});});+describe("the server owner's policy", () => {+ const ran: string[] = [];+ const desk = (dir: string) => jobDesk({+ run: async (job) => { ran.push(`${job.type}`); return { id: job.id, ok: true, result: { home: { state: "running", image: HOME, health: null } } } as JobReply; },+ audit: new AuditLog(join(dir, "audit.jsonl")), log: () => {}, policyFile: join(dir, "policy.json"),+ });+ const SELF = { id: "self-1", type: "self-update", args: { image: `ghcr.io/milind-soni/mausbot-connector@sha256:${"b".repeat(64)}` } } as Job;+ const UPDATE = { id: "u1", type: "update", args: { image: HOME } } as Job;++ it("limits what MausBot may run here, records each refusal, and never limits root on the server or a self-update", async () => {+ const dir = folder();+ ran.splice(0);+ writeFileSync(join(dir, "policy.json"), JSON.stringify({ jobs: ["status", "backup"], updates: "hold" }));+ const refused = await desk(dir).submit(UPDATE, "admin");+ expect(refused).toEqual({ id: "u1", ok: false, error: { code: "refused_by_policy", message: `This server's policy ${join(dir, "policy.json")} does not let MausBot run update jobs.` } });+ expect((await desk(dir).submit(SELF, "admin"))?.ok).toBe(true);+ expect((await desk(dir).submit({ ...UPDATE, id: "local-1" }, "local"))?.ok).toBe(true);+ expect(ran).toEqual(["self-update", "update"]);+ expect(lines(join(dir, "audit.jsonl")).filter((line) => line.event === "result").map((line) => (line as { error?: { code: string } }).error?.code ?? "ok")).toEqual(["refused_by_policy", "ok", "ok"]);+ writeFileSync(join(dir, "policy.json"), JSON.stringify({ updates: "hold" }));+ expect(await desk(dir).submit(UPDATE, "admin")).toMatchObject({ error: { code: "refused_by_policy", message: expect.stringContaining("holds updates") } });+ expect((await desk(dir).submit({ id: "b1", type: "backup", args: {} }, "admin"))?.ok).toBe(true);+ });++ it("changes nothing for MausBot while the policy cannot be used, but still answers a status and takes a self-update", async () => {+ const dir = folder();+ ran.splice(0);+ writeFileSync(join(dir, "policy.json"), '{"updates": "sometimes"}');+ expect(await desk(dir).submit(UPDATE, "admin")).toMatchObject({ error: { code: "refused_by_policy", message: expect.stringContaining('"updates" must be "automatic" or "hold"') } });+ expect((await desk(dir).submit({ id: "s1", type: "status", args: {} }, "admin"))?.ok).toBe(true);+ expect((await desk(dir).submit(SELF, "admin"))?.ok).toBe(true);+ expect(ran).toEqual(["status", "self-update"]);+ expect(parsePolicy(null)).toEqual({ ok: true, policy: { jobs: null, updates: "automatic" } });+ expect(parsePolicy('{"jobs": ["shell"]}')).toMatchObject({ ok: false });+ expect(parsePolicy('{"support": "always"}')).toEqual({ ok: false, problem: "it has a setting this connector does not know: support" });+ expect(parsePolicy("[]")).toMatchObject({ ok: false });+ });+});+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();