Skip to content

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

feat(config): dated copies of the settings file, and a save that refuses to replace one it could not read

David Neyra4924584f7b0e
diff --git a/server/config-backup.test.ts b/server/config-backup.test.ts
new file mode 100644
index 0000000000..271f898beb
--- /dev/null
+++ b/server/config-backup.test.ts
@@ -0,0 +1,155 @@
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ CONFIG_BACKUP_KEEP,
+ configSaveRefusal,
+ listConfigBackups,
+ readConfigFile,
+ restoreConfigBackup,
+ writeConfigBackup,
+} from "./config-backup.ts";
+
+const dirs: string[] = [];
+const tempDir = () => { const dir = mkdtempSync(join(tmpdir(), "omb-config-backup-")); dirs.push(dir); return dir; };
+const configPath = (dir: string) => join(dir, "config.json");
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("reading the settings file", () => {
+ it("tells a file that is not there from one that cannot be read", () => {
+ const dir = tempDir();
+ expect(readConfigFile(configPath(dir))).toEqual({ state: "missing" });
+ mkdirSync(configPath(dir));
+ expect(readConfigFile(configPath(dir)).state).toBe("unreadable");
+ });
+
+ it("tells a file that is not a settings file from one that is", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), "{ not json");
+ expect(readConfigFile(configPath(dir)).state).toBe("invalid");
+ writeFileSync(configPath(dir), "[1,2]");
+ expect(readConfigFile(configPath(dir)).state).toBe("invalid");
+ writeFileSync(configPath(dir), JSON.stringify({ mcpServers: { notes: {} } }));
+ const read = readConfigFile(configPath(dir));
+ expect(read.state).toBe("ok");
+ expect(read.state === "ok" && read.value.mcpServers).toEqual({ notes: {} });
+ });
+});
+
+describe("a save that cannot read the file", () => {
+ it("refuses to replace it and says how to recover", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), "{ not json");
+ const read = readConfigFile(configPath(dir));
+ expect(read.state).toBe("invalid");
+ const error = configSaveRefusal(read as { state: string; reason: string }, configPath(dir));
+ expect((error as { status?: number }).status).toBe(503);
+ expect(error.message).toContain(configPath(dir));
+ expect(error.message).toContain("openmausbot config restore");
+ });
+
+ it("keeps the bytes of a file it could not understand", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), "{ not json");
+ const read = readConfigFile(configPath(dir));
+ configSaveRefusal(read as { state: string; reason: string }, configPath(dir));
+ const aside = readdirSync(dir).filter((name) => name.startsWith("config.json.unreadable-"));
+ expect(aside).toHaveLength(1);
+ expect(readFileSync(join(dir, aside[0]!), "utf8")).toBe("{ not json");
+ });
+});
+
+describe("the dated copies", () => {
+ it("hold the file as it was", () => {
+ const dir = tempDir();
+ const name = writeConfigBackup(configPath(dir), "{\"a\":1}", new Date("2026-11-16T00:30:00Z"));
+ expect(name).toBe("config.json.bak.20261116-003000");
+ expect(readFileSync(join(dir, name!), "utf8")).toBe("{\"a\":1}");
+ expect(statSync(join(dir, name!)).mode & 0o777).toBe(0o600);
+ });
+
+ it("do not overwrite each other within a second", () => {
+ const dir = tempDir();
+ const now = new Date("2026-11-16T00:30:00Z");
+ expect(writeConfigBackup(configPath(dir), "one", now)).toBe("config.json.bak.20261116-003000");
+ expect(writeConfigBackup(configPath(dir), "two", now)).toBe("config.json.bak.20261116-003000-1");
+ });
+
+ it("keep only the newest ones", () => {
+ const dir = tempDir();
+ for (let second = 0; second < CONFIG_BACKUP_KEEP + 4; second += 1) {
+ writeConfigBackup(configPath(dir), `copy ${second}`, new Date(Date.UTC(2026, 10, 16, 0, 0, second)));
+ }
+ const copies = listConfigBackups(dir);
+ expect(copies).toHaveLength(CONFIG_BACKUP_KEEP);
+ expect(copies[copies.length - 1]!.name).toBe("config.json.bak.20261116-000013");
+ });
+
+ it("are listed oldest first", () => {
+ const dir = tempDir();
+ writeConfigBackup(configPath(dir), "a", new Date("2026-11-16T00:00:00Z"));
+ writeConfigBackup(configPath(dir), "b", new Date("2026-11-16T01:00:00Z"));
+ expect(listConfigBackups(dir).map((copy) => copy.stamp)).toEqual(["20261116-000000", "20261116-010000"]);
+ });
+});
+
+describe("putting a copy back", () => {
+ it("makes it the settings file again", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), JSON.stringify({ old: true }, null, 2));
+ const name = writeConfigBackup(configPath(dir), readFileSync(configPath(dir), "utf8"));
+ writeFileSync(configPath(dir), JSON.stringify({ new: true }));
+ expect(restoreConfigBackup(dir, name!).ok).toBe(true);
+ expect(readFileSync(configPath(dir), "utf8")).toBe(JSON.stringify({ old: true }, null, 2));
+ });
+
+ it("keeps the file it replaces, so the restore is reversible", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), JSON.stringify({ old: true }));
+ const name = writeConfigBackup(configPath(dir), readFileSync(configPath(dir), "utf8"));
+ writeFileSync(configPath(dir), JSON.stringify({ new: true }));
+ const restored = restoreConfigBackup(dir, name!);
+ expect(restored.ok && restored.kept).toBeTruthy();
+ expect(JSON.parse(readFileSync((restored as { kept: string }).kept, "utf8"))).toEqual({ new: true });
+ });
+
+ it("never overwrites the copy it restores from", () => {
+ const dir = tempDir();
+ writeFileSync(configPath(dir), JSON.stringify({ old: true }));
+ const name = writeConfigBackup(configPath(dir), readFileSync(configPath(dir), "utf8"), new Date("2026-11-16T00:30:00Z"));
+ writeFileSync(configPath(dir), JSON.stringify({ new: true }));
+ const restored = restoreConfigBackup(dir, name!);
+ expect(restored.ok && restored.kept).toBeTruthy();
+ expect(readFileSync(join(dir, name!), "utf8")).toBe(JSON.stringify({ old: true }));
+ expect((restored as { kept: string }).kept).not.toBe(join(dir, name!));
+ });
+
+ it("keeps a settings file it could not understand", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), JSON.stringify({ old: true }));
+ writeFileSync(configPath(dir), "{ not json");
+ const restored = restoreConfigBackup(dir, "config.json.bak.20261116-003000");
+ expect(restored.ok && restored.kept).toBeTruthy();
+ expect(readFileSync((restored as { kept: string }).kept, "utf8")).toBe("{ not json");
+ expect(JSON.parse(readFileSync(configPath(dir), "utf8"))).toEqual({ old: true });
+ });
+
+ it("changes nothing in a dry run", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), JSON.stringify({ old: true }));
+ writeFileSync(configPath(dir), JSON.stringify({ new: true }));
+ const restored = restoreConfigBackup(dir, "config.json.bak.20261116-003000", { dryRun: true });
+ expect(restored.ok && restored.restored).toBe(false);
+ expect(readFileSync(configPath(dir), "utf8")).toBe(JSON.stringify({ new: true }));
+ });
+
+ it("refuses a copy that is not a settings file, and a name that is not a copy", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), "{ not json");
+ expect(restoreConfigBackup(dir, "config.json.bak.20261116-003000").ok).toBe(false);
+ expect(restoreConfigBackup(dir, "../secret").ok).toBe(false);
+ expect(restoreConfigBackup(dir, "/etc/passwd").ok).toBe(false);
+ });
+});
diff --git a/server/config-backup.ts b/server/config-backup.ts
new file mode 100644
index 0000000000..082e6b4410
--- /dev/null
+++ b/server/config-backup.ts
@@ -0,0 +1,151 @@
+// Dated copies of the settings file, and the rule that a save never replaces a file it could not read.
+//
+// config.json holds every credential and connection of the install. A save that starts from a failed read writes
+// only the patched sections over the whole file and the rest is gone: the dated copies are what make that
+// recoverable, and the refusal is what keeps it from happening.
+import { existsSync, readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { writeFileAtomic } from "./atomic.ts";
+import { parseJson, type JsonObject } from "./schema.ts";
+import { keepUnreadableAside } from "./unreadable-aside.ts";
+
+/** The dated copies kept beside config.json: `config.json.bak.20261116-003000`. */
+export const CONFIG_BACKUP_PREFIX = "config.json.bak.";
+/** How many dated copies are kept; the oldest go first. */
+export const CONFIG_BACKUP_KEEP = 10;
+
+const BACKUP_NAME = /^config\.json\.bak\.(\d{8})-(\d{6})(?:-\d+)?$/;
+
+export interface ConfigBackup {
+ /** The file name, which carries the moment the copy was taken. */
+ name: string;
+ path: string;
+ /** `YYYYMMDD-HHMMSS` in UTC. */
+ stamp: string;
+ bytes: number;
+}
+
+export type ConfigFileRead =
+ | { state: "missing" }
+ | { state: "ok"; value: JsonObject; text: string }
+ | { state: "unreadable"; reason: string }
+ | { state: "invalid"; reason: string };
+
+/** The settings file as it is on disk. A file that is there but cannot be understood is never taken for an empty
+ * one: it is reported, so a save can refuse to replace it. */
+export function readConfigFile(path: string): ConfigFileRead {
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { state: "missing" };
+ return { state: "unreadable", reason: error instanceof Error ? error.message : "unable to read the file" };
+ }
+ try {
+ const value = parseJson(text);
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { state: "invalid", reason: "it is not a JSON object" };
+ return { state: "ok", value: value as JsonObject, text };
+ } catch {
+ // A JSON error can quote the file, and the file holds credentials.
+ return { state: "invalid", reason: "it is not valid JSON" };
+ }
+}
+
+/** The error a save refuses with: the file on disk is left as it is, and its bytes are kept. */
+export function configSaveRefusal(read: { state: "unreadable" | "invalid"; reason: string }, path: string): Error {
+ const why = read.state === "invalid" ? `it is not a settings file (${read.reason})` : `it could not be read (${read.reason})`;
+ const aside = read.state === "invalid" ? keepUnreadableAside(path) : null;
+ const kept = aside ? ` A copy of it was kept at ${aside}.` : "";
+ return Object.assign(
+ new Error(`The settings file ${path} was left as it is because ${why}, so nothing was saved. Repair the file, or put a dated copy back with "openmausbot config restore".${kept}`),
+ { status: 503 },
+ );
+}
+
+function stampOf(now: Date): string {
+ const pad = (value: number) => String(value).padStart(2, "0");
+ return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`;
+}
+
+/** A dated copy of the file as it is now, kept beside it. `skip` is a copy that must not be written over. A copy that
+ * cannot be written does not stop the save; the caller says so. */
+export function writeConfigBackup(path: string, text: string, now: Date = new Date(), skip?: string): string | null {
+ const dir = dirname(path);
+ const base = CONFIG_BACKUP_PREFIX + stampOf(now);
+ for (let taken = 0; taken < 100; taken += 1) {
+ const name = taken === 0 ? base : `${base}-${taken}`;
+ if (name === skip) continue;
+ const target = join(dir, name);
+ if (existsSync(target)) continue;
+ try {
+ writeFileAtomic(target, text, { mode: 0o600 });
+ } catch {
+ return null;
+ }
+ pruneConfigBackups(dir);
+ return name;
+ }
+ return null;
+}
+
+/** The dated copies kept beside the settings file, oldest first. */
+export function listConfigBackups(dir: string): ConfigBackup[] {
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ return [];
+ }
+ return names.filter((name) => BACKUP_NAME.test(name)).sort().map((name) => {
+ const path = join(dir, name);
+ let bytes = 0;
+ try {
+ bytes = statSync(path).size;
+ } catch {
+ }
+ const stamp = BACKUP_NAME.exec(name)!;
+ return { name, path, stamp: `${stamp[1]}-${stamp[2]}`, bytes };
+ });
+}
+
+function pruneConfigBackups(dir: string): void {
+ const copies = listConfigBackups(dir);
+ for (const copy of copies.slice(0, Math.max(0, copies.length - CONFIG_BACKUP_KEEP))) {
+ try {
+ unlinkSync(copy.path);
+ } catch {
+ }
+ }
+}
+
+export type ConfigRestore = { ok: true; name: string; kept: string | null; restored: boolean } | { ok: false; error: string };
+
+/** Puts a dated copy back as the settings file. The file it replaces is kept, so the restore is itself reversible.
+ * A dry run reports what it would do and changes nothing. */
+export function restoreConfigBackup(dir: string, name: string, options: { dryRun?: boolean } = {}): ConfigRestore {
+ if (!BACKUP_NAME.test(name)) return { ok: false, error: `${name} is not a dated copy of the settings file; run openmausbot config backups to see the copies` };
+ const source = join(dir, name);
+ let text: string;
+ try {
+ text = readFileSync(source, "utf8");
+ } catch {
+ return { ok: false, error: `The copy ${name} could not be read; run openmausbot config backups to see the copies` };
+ }
+ try {
+ const parsed = parseJson(text);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { ok: false, error: `The copy ${name} is not a settings file, so it was not put back` };
+ } catch {
+ return { ok: false, error: `The copy ${name} is not valid JSON, so it was not put back` };
+ }
+ const target = join(dir, "config.json");
+ const current = readConfigFile(target);
+ if (options.dryRun) return { ok: true, name, kept: null, restored: false };
+ let kept: string | null = null;
+ if (current.state === "ok") {
+ const copy = writeConfigBackup(target, current.text, new Date(), name);
+ kept = copy ? join(dir, copy) : null;
+ } else if (current.state === "invalid") kept = keepUnreadableAside(target);
+ writeFileAtomic(target, text, { mode: 0o600 });
+ return { ok: true, name, kept, restored: true };
+}
diff --git a/server/config-cli.ts b/server/config-cli.ts
new file mode 100644
index 0000000000..a6be0fb152
--- /dev/null
+++ b/server/config-cli.ts
@@ -0,0 +1,95 @@
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { listConfigBackups, restoreConfigBackup } from "./config-backup.ts";
+
+export const CONFIG_USAGE = `openmausbot config backups [--data-dir DIR] [--json]
+openmausbot config restore NAME [--data-dir DIR] [--dry-run] [--json]
+
+Shows and puts back the dated copies of the settings file. Every save keeps a
+copy of the file as it was, named config.json.bak.YYYYMMDD-HHMMSS, beside it,
+and the last ten are kept. A save never replaces a file it could not read: it
+fails and says so, so a settings file that cannot be read is never overwritten.
+
+backups list the dated copies, oldest first
+restore put a copy back, by name or "latest"; the file it replaces is kept,
+ so the restore can be undone. Stop the server first if it is
+ running, so nothing it holds in memory is written over the copy.
+
+--data-dir DIR the OpenMausBot data folder (default ~/.openmausbot)
+--dry-run say what a restore would do, and change nothing
+--json print the result as JSON`;
+
+export interface ConfigCliArgs {
+ command: "backups" | "restore";
+ dataDir: string;
+ name: string | undefined;
+ json: boolean;
+ help: boolean;
+ dryRun: boolean;
+}
+
+export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): ConfigCliArgs | { error: string } {
+ const json = argv.includes("--json");
+ const help = argv.includes("--help") || argv.includes("-h");
+ const dryRun = argv.includes("--dry-run");
+ let dataDir = env.OMB_DATA_DIR || join(homedir(), ".openmausbot");
+ let name: string | undefined;
+ const words = argv.filter((arg) => arg !== "--json" && arg !== "--help" && arg !== "-h" && arg !== "--dry-run");
+ const command = words[0];
+ if (command !== "backups" && command !== "restore") {
+ return { error: command ? `unknown command "${command}"; say "backups" or "restore"` : "say what to do: \"backups\" or \"restore\"" };
+ }
+ for (let index = 1; index < words.length; index += 1) {
+ const arg = words[index]!;
+ if (arg === "--data-dir") {
+ const value = words[index + 1];
+ if (value === undefined || value.startsWith("--")) return { error: "--data-dir needs the folder that holds config.json" };
+ dataDir = resolve(value);
+ index += 1;
+ } else if (command === "restore" && name === undefined && !arg.startsWith("-")) name = arg;
+ else return { error: `unknown argument "${arg}"; see openmausbot config --help` };
+ }
+ if (command === "restore" && name === undefined) return { error: "restore needs the name of a copy, or \"latest\"; run openmausbot config backups to see them" };
+ return { command, dataDir, name, json, help, dryRun };
+}
+
+export function runConfigCli(
+ argv: string[],
+ io: { log(line: string): void; error(line: string): void } = console,
+ env: NodeJS.ProcessEnv = process.env,
+): number {
+ const args = parseConfigArgs(argv, env);
+ if ("error" in args) {
+ if (args.json) io.log(JSON.stringify({ ok: false, error: args.error }));
+ else io.error(`config: ${args.error}`);
+ return 2;
+ }
+ if (args.help) {
+ io.log(CONFIG_USAGE);
+ return 0;
+ }
+ const copies = listConfigBackups(args.dataDir);
+ if (args.command === "backups") {
+ if (args.json) io.log(JSON.stringify({ ok: true, dataDir: args.dataDir, backups: copies.map((copy) => ({ name: copy.name, stamp: copy.stamp, bytes: copy.bytes })) }));
+ else if (!copies.length) io.log(`config: no dated copies of the settings file in ${args.dataDir}`);
+ else for (const copy of copies) io.log(`${copy.stamp} ${copy.name} ${copy.bytes} bytes`);
+ return 0;
+ }
+ const name = args.name === "latest" ? copies[copies.length - 1]?.name : args.name;
+ if (!name) {
+ if (args.json) io.log(JSON.stringify({ ok: false, error: `there is no dated copy to put back in ${args.dataDir}` }));
+ else io.error(`config: there is no dated copy to put back in ${args.dataDir}; a copy is taken at every save`);
+ return 1;
+ }
+ const restored = restoreConfigBackup(args.dataDir, name, { dryRun: args.dryRun });
+ if (!restored.ok) {
+ if (args.json) io.log(JSON.stringify({ ok: false, error: restored.error }));
+ else io.error(`config: ${restored.error}`);
+ return 1;
+ }
+ if (args.json) io.log(JSON.stringify({ ok: true, restored: restored.name, kept: restored.kept, restoredNow: restored.restored }));
+ else if (!restored.restored) io.log(`config: ${restored.name} would be put back as config.json; nothing was changed`);
+ else io.log(`config: put ${restored.name} back as config.json${restored.kept ? `; the file it replaced was kept at ${restored.kept}` : ""}`);
+ return 0;
+}
diff --git a/server/unreadable-aside.ts b/server/unreadable-aside.ts
new file mode 100644
index 0000000000..65062970c6
--- /dev/null
+++ b/server/unreadable-aside.ts
@@ -0,0 +1,22 @@
+// Copies of a file whose content could not be understood, kept beside it so the bytes are not lost.
+import { createHash } from "node:crypto";
+import { chmodSync, constants, copyFileSync, existsSync, readdirSync, readFileSync } from "node:fs";
+import { basename, dirname } from "node:path";
+
+/** Copies of unreadable content kept beside the file; a further one is not copied. */
+const ASIDE_COPIES = 5;
+
+/** Copies the unreadable file beside itself, named by its content so the same content is copied once. Returns the copy's
+ * path, or null when there is nothing to copy or the copy cannot be made. The file itself stays where it is. */
+export function keepUnreadableAside(file: string): string | null {
+ try {
+ const aside = `${file}.unreadable-${createHash("sha256").update(readFileSync(file)).digest("hex").slice(0, 12)}`;
+ if (existsSync(aside)) return aside;
+ if (readdirSync(dirname(file)).filter((name) => name.startsWith(`${basename(file)}.unreadable-`)).length >= ASIDE_COPIES) return null;
+ copyFileSync(file, aside, constants.COPYFILE_EXCL);
+ chmodSync(aside, 0o600);
+ return aside;
+ } catch {
+ return null;
+ }
+}