Skip to content

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

Desktop: a stale data-folder lease from this computer no longer locks it out after a restart (#6202)

Milind Sonif8b6f75ebd33
diff --git a/electron/data-dir-lease.d.mts b/electron/data-dir-lease.d.mts
index 8153d9974f..0db231d3de 100644
--- a/electron/data-dir-lease.d.mts
+++ b/electron/data-dir-lease.d.mts
@@ -31,6 +31,10 @@ export declare function clearRecordsFromOtherMachines(
dataDir: string,
): { path: string; host: string; pid: number }[];
+export declare function macMountIsLocal(dfOutput: string, mountTable: string): boolean;
+
+export declare function inMacSyncedFolder(path: string, home: string): boolean;
+
export declare function clearRecordsFromEarlierRunOfThisContainer(
dataDir: string,
): { path: string; host: string; pid: number }[];
diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjs
index 1172ebe310..74320da358 100644
--- a/electron/data-dir-lease.mjs
+++ b/electron/data-dir-lease.mjs
@@ -1,8 +1,8 @@
import { execFileSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
-import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
-import { hostname, uptime } from "node:os";
-import { join } from "node:path";
+import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { homedir, hostname, uptime } from "node:os";
+import { dirname, join } from "node:path";
const LEASE_NAME = "openmausbot-server.lease";
const DELEGATED_CHILD_DIR = ".openmausbot-server-child";
@@ -12,6 +12,7 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{1
const MAX_PID = 0x7fffffff;
const MAX_BOOT_ID = 128;
const MAX_REAPER_GENERATIONS = 128;
+const MACHINE_ID = /^[0-9a-f]{32}$/;
export class DataDirLeaseError extends Error {
name = "DataDirLeaseError";
@@ -37,11 +38,7 @@ function readBootSession() {
return normalizeBootId(readFileSync("/proc/sys/kernel/random/boot_id", "utf8"));
}
if (process.platform === "darwin") {
- return normalizeBootId(execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], {
- encoding: "utf8",
- timeout: 5_000,
- stdio: ["ignore", "pipe", "ignore"],
- }));
+ return normalizeBootId(commandOutput("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"]));
}
} catch {
}
@@ -137,12 +134,138 @@ function ownerIsAlive(owner) {
return !ownerPredatesThisBoot(owner) && processIsAlive(owner.pid) && ownerIdentityMatches(owner);
}
-/** macOS renames the host on another network, so the same boot session (random per boot) also proves this machine. */
-function sameMachine(record) {
+/**
+ * An install's own id, which outlives a reboot and a rename: macOS IOPlatformUUID, Windows MachineGuid, Linux machine-id.
+ * Recorded hashed, never raw. A container's /etc/machine-id comes from its image, so every container (and every VM booted
+ * from that image) shares one: Linux trusts it only when systemd, which generates it per install, is PID 1 outside a
+ * container. Null wherever it cannot be read.
+ */
+let cachedMachineId;
+
+/** A probe's stdout, its window hidden on Windows; throws when it fails or runs past `timeout`. */
+function commandOutput(file, args, timeout = 5_000) {
+ return execFileSync(file, args, { encoding: "utf8", timeout, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
+}
+
+function linuxInstallHasOwnMachineId() {
+ // systemd writes /run/systemd/container inside LXC, nspawn and other containers it detects.
+ if (["/.dockerenv", "/run/.containerenv", "/run/systemd/container"].some((marker) => existsSync(marker))) return false;
+ try {
+ return readFileSync("/proc/1/comm", "utf8").trim() === "systemd";
+ } catch {
+ return false;
+ }
+}
+
+function readRawMachineId() {
+ try {
+ if (process.platform === "darwin") {
+ return /"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{32,36})"/.exec(commandOutput("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"]))?.[1] ?? null;
+ }
+ if (process.platform === "win32") {
+ const reg = join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
+ // /reg:64: a 32-bit process would otherwise read the WOW64 view, which has no MachineGuid.
+ const output = commandOutput(reg, ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid", "/reg:64"]);
+ return /MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{32,36})\s*$/m.exec(output)?.[1] ?? null;
+ }
+ if (process.platform === "linux" && linuxInstallHasOwnMachineId()) {
+ for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
+ try {
+ const id = readFileSync(path, "utf8").trim();
+ if (/^[0-9A-Fa-f]{32}$/.test(id)) return id;
+ } catch {
+ }
+ }
+ }
+ } catch {
+ }
+ return null;
+}
+
+function machineId() {
+ if (cachedMachineId === undefined) {
+ const raw = readRawMachineId();
+ cachedMachineId = raw === null
+ ? null
+ : createHash("sha256").update(`openmausbot-machine:${raw.toLowerCase()}`).digest("hex").slice(0, 32);
+ }
+ return cachedMachineId;
+}
+
+/**
+ * From `df -P <path>` and `mount`: whether the volume holding the path is mounted local, never a network share (smbfs,
+ * nfs, afpfs, webdav). A mount point may itself hold " on " or " (", so df names it and only the line naming exactly
+ * that mount point counts. False on any doubt.
+ */
+export function macMountIsLocal(dfOutput, mountTable) {
+ const lines = String(dfOutput).trimEnd().split("\n");
+ if (lines.length !== 2) return false;
+ const point = /^.*?\s\d+\s+\d+\s+\d+\s+\d+%\s+(\/.*)$/.exec(lines[1])?.[1];
+ if (!point) return false;
+ const marker = ` on ${point} (`;
+ const matches = String(mountTable).split("\n").filter((line) => line.includes(marker) && line.endsWith(")"));
+ if (matches.length !== 1) return false;
+ const line = matches[0];
+ return line.slice(line.indexOf(marker) + marker.length, -1).split(", ").includes("local");
+}
+
+const MAC_SYNCED_FOLDERS = [["Library", "Mobile Documents"], ["Library", "CloudStorage"]];
+
+/** iCloud Drive and File Provider sync folders (Dropbox, OneDrive, Google Drive) are local disks other Macs write to. */
+export function inMacSyncedFolder(path, home) {
+ const lower = path.toLowerCase();
+ return MAC_SYNCED_FOLDERS.some((parts) => {
+ const root = join(home, ...parts).toLowerCase();
+ return lower === root || lower.startsWith(`${root}/`);
+ });
+}
+
+function onLocalUnsyncedMacVolume(dir) {
+ try {
+ const path = realpathSync(dir);
+ const home = homedir();
+ let realHome = home;
+ try {
+ realHome = realpathSync(home);
+ } catch {
+ }
+ if (inMacSyncedFolder(path, home) || inMacSyncedFolder(path, realHome)) return false;
+ return macMountIsLocal(commandOutput("/bin/df", ["-P", path]), commandOutput("/sbin/mount", []));
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * macOS gives the host a new name on another network, and before boot sessions and machine ids were recorded nothing
+ * else identified the Mac; such a record is this Mac's when it was written in an earlier boot on a folder only this Mac
+ * mounts and no sync service mirrors. Known open risk: an older build on another Mac reaching this folder some other way.
+ */
+function olderBuildRecordFromEarlierMacBoot(record, dir) {
+ if (process.platform !== "darwin" || dir === undefined || record.machine !== undefined) return false;
+ const boot = bootSession();
+ if (boot === null || typeof record.boot !== "string" || record.boot === boot) return false;
+ return onLocalUnsyncedMacVolume(dir);
+}
+
+/**
+ * Another machine id is another machine. The same id is this machine under any hostname only on macOS, which renames the
+ * host on another network; Linux and Windows keep theirs, and a VM cloned from a template keeps the template's id. Then:
+ * the same host, or the same boot session (random per boot), proves this machine. `dir`, the folder the record sits in,
+ * admits an older build's record from an earlier boot of this Mac; without it that is never presumed, as when clearing a
+ * single-machine volume.
+ */
+function sameMachine(record, dir) {
if (fromAnotherPidNamespace(record)) return false;
+ const machine = machineId();
+ if (machine !== null && typeof record.machine === "string") {
+ if (record.machine !== machine) return false;
+ if (process.platform === "darwin") return true;
+ }
if (record.host === hostname()) return true;
const boot = bootSession();
- return boot !== null && typeof record.boot === "string" && record.boot === boot;
+ if (boot !== null && typeof record.boot === "string" && record.boot === boot) return true;
+ return olderBuildRecordFromEarlierMacBoot(record, dir);
}
function otherMachineAdvice(path, t) {
@@ -167,7 +290,8 @@ function isLeaseOwner(value) {
&& (value.boot === undefined || isBootIdentity(value.boot))
&& (value.uptime === undefined || (Number.isInteger(value.uptime) && value.uptime >= 0))
&& (value.ns === undefined || isPidNamespace(value.ns))
- && (value.start === undefined || isStartTicks(value.start));
+ && (value.start === undefined || isStartTicks(value.start))
+ && (value.machine === undefined || value.machine === null || (typeof value.machine === "string" && MACHINE_ID.test(value.machine)));
}
function isReaperOwner(value, targetToken) {
@@ -245,14 +369,9 @@ function processCreationTimeMs(pid) {
return wmicCreationTimeMs(pid) ?? cimCreationTimeMs(pid);
}
-/** A Windows probe's stdout, its window hidden; throws when it fails or runs past `timeout`. */
-function windowsOutput(file, args, timeout) {
- return execFileSync(file, args, { encoding: "utf8", timeout, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
-}
-
function wmicCreationTimeMs(pid) {
try {
- const output = windowsOutput("wmic", ["process", "where", `ProcessId=${pid}`, "get", "CreationDate", "/format:csv"], 5_000);
+ const output = commandOutput("wmic", ["process", "where", `ProcessId=${pid}`, "get", "CreationDate", "/format:csv"], 5_000);
for (const line of output.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
@@ -275,7 +394,7 @@ function wmicCreationTimeMs(pid) {
function cimCreationTimeMs(pid) {
const powershell = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
try {
- const output = windowsOutput(powershell, [
+ const output = commandOutput(powershell, [
"-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
`$p = Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}'; if ($p) { ([DateTimeOffset]$p.CreationDate).ToUnixTimeMilliseconds() }`,
], 15_000);
@@ -377,6 +496,7 @@ function claimReaperAuthority(leasePath, expected) {
boot: bootSession(),
uptime: uptimeMs(),
...processIdentity(),
+ machine: machineId(),
targetToken: expected.token,
};
if (publishRecord(
@@ -388,7 +508,7 @@ function claimReaperAuthority(leasePath, expected) {
const current = readReaper(reaperPath, expected.token);
if (!current) continue;
- if (!sameMachine(current)) {
+ if (!sameMachine(current, dirname(leasePath))) {
throw leaseError(
`A stale OpenMausBot data-directory lease is being recovered on another machine. Recovery record: ${JSON.stringify(reaperPath)}.`,
);
@@ -403,7 +523,7 @@ function retireDeadOwner(leasePath, expected) {
if (!claimReaperAuthority(leasePath, expected)) return false;
const current = readOwner(leasePath);
if (!current || current.token !== expected.token) return true;
- if (!sameMachine(current)) {
+ if (!sameMachine(current, dirname(leasePath))) {
throw leaseError(
`The stale OpenMausBot data-directory lease changed ownership to another machine. Lease record: ${JSON.stringify(leasePath)}.`,
);
@@ -444,7 +564,7 @@ function assertNoLiveDelegatedChild(dataDir, t) {
const childLeasePath = join(dataDir, DELEGATED_CHILD_DIR, LEASE_NAME);
const child = readOwner(childLeasePath);
if (!child) return;
- if (!sameMachine(child)) {
+ if (!sameMachine(child, dataDir)) {
throw leaseError(
`This OpenMausBot data directory still has a delegated server on another machine. Delegated server lease: ${JSON.stringify(childLeasePath)}.${otherMachineAdvice(childLeasePath, t)}`,
);
@@ -491,7 +611,7 @@ function validateChildDelegation(dataDir, encoded) {
const matchesLiveParent = (owner) => Boolean(owner
&& owner.pid === capability.pid
&& owner.token === capability.token
- && sameMachine(owner)
+ && sameMachine(owner, dataDir)
&& ownerIsAlive(owner));
if (!matchesLiveParent(readOwner(parentLeasePath))) {
throw invalid();
@@ -525,6 +645,7 @@ function acquireDataDirLeaseInternal(dataDir, options = {}) {
boot: bootSession(),
uptime: uptimeMs(),
...processIdentity(),
+ machine: machineId(),
};
const candidatePath = `${leasePath}.candidate-${owner.pid}-${owner.token}`;
try {
@@ -548,7 +669,7 @@ function acquireDataDirLeaseInternal(dataDir, options = {}) {
const current = readOwner(leasePath);
if (!current) continue;
- if (!sameMachine(current)) {
+ if (!sameMachine(current, dataDir)) {
throw leaseError(
`This OpenMausBot data directory is already owned by a process on another machine. Lease record: ${JSON.stringify(leasePath)}.${otherMachineAdvice(leasePath, options.t)}`,
);
diff --git a/electron/data-dir-lease.node-test.mjs b/electron/data-dir-lease.node-test.mjs
index 3f5e4d7451..002f4538a8 100644
--- a/electron/data-dir-lease.node-test.mjs
+++ b/electron/data-dir-lease.node-test.mjs
@@ -11,6 +11,8 @@ import {
acquireDataDirLeaseForProcess,
clearRecordsFromEarlierRunOfThisContainer,
clearRecordsFromOtherMachines,
+ inMacSyncedFolder,
+ macMountIsLocal,
} from "./data-dir-lease.mjs";
const MODULE_URL = new URL("./data-dir-lease.mjs", import.meta.url).href;
@@ -534,6 +536,120 @@ test("a delegated child from an earlier boot cannot block a new parent", (t) =>
// macOS renames the host when it joins another network.
const renamedHost = (current) => (current.host === "Ryans-MacBook-Pro.local" ? "Ryans-MBP.lan" : "Ryans-MacBook-Pro.local");
+const anotherMachineId = (current) => (current.machine === "0".repeat(32) ? "1".repeat(32) : "0".repeat(32));
+const withoutMachineId = ({ machine: _machine, ...record }) => record;
+
+test("a record names this machine by a hashed id where the platform has one", () => {
+ const { dataDir } = temporaryDirectory();
+ const record = recordWrittenByThisProcess(dataDir);
+ if (process.platform === "darwin" || process.platform === "win32") assert.match(record.machine, /^[0-9a-f]{32}$/);
+ else assert.ok(record.machine === null || /^[0-9a-f]{32}$/.test(record.machine));
+});
+
+// Only macOS renames the host per network; elsewhere the same id under another hostname may be a VM cloned from a template.
+test("a lease with this machine id under another hostname from an earlier boot: recovered on macOS, refused elsewhere", async (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.machine === null) return t.skip("no machine id on this platform");
+ const leasePath = path.join(dataDir, LEASE_NAME);
+ // A live pid too: a lease from an earlier boot of this machine is stale whatever now runs under its pid.
+ for (const pid of [await exitedPid(), process.pid]) {
+ const planted = `${JSON.stringify({ ...current, host: renamedHost(current), boot: current.boot === null ? null : randomUUID(), uptime: Math.floor(osUptime() * 1000) + 3_600_000, pid, token: randomUUID() })}\n`;
+ writeFileSync(leasePath, planted, { mode: 0o600 });
+ if (process.platform !== "darwin") {
+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);
+ assert.equal(readFileSync(leasePath, "utf8"), planted);
+ continue;
+ }
+ const lease = acquireDataDirLease(dataDir);
+ const written = JSON.parse(readFileSync(leasePath, "utf8"));
+ assert.deepEqual({ host: written.host, machine: written.machine }, { host: hostname(), machine: current.machine });
+ assert.equal(lease.release(), true);
+ }
+});
+
+test("a Mac's volume is local only when the mount line naming df's mount point says so", () => {
+ const df = (filesystem, point) => `Filesystem 512-blocks Used Available Capacity Mounted on\n${filesystem} 1942597960 1842607672 39598832 98% ${point}\n`;
+ const table = [
+ "/dev/disk3s3s1 on / (apfs, sealed, local, read-only, journaled)",
+ "/dev/disk3s1 on /System/Volumes/Data (apfs, local, journaled, nobrowse, protect, root data)",
+ "//u@nas/Files on /Volumes/Files on NAS (smbfs, nodev, nosuid, mounted by u)",
+ "/dev/disk5s1 on /Volumes/Backup (local) (apfs, local, nodev, nosuid, journaled, noowners)",
+ ].join("\n");
+ assert.equal(macMountIsLocal(df("/dev/disk3s1", "/System/Volumes/Data"), table), true);
+ assert.equal(macMountIsLocal(df("//u@nas/Files", "/Volumes/Files on NAS"), table), false);
+ assert.equal(macMountIsLocal(df("/dev/disk5s1", "/Volumes/Backup (local)"), table), true);
+ // A mount point the table does not name, an unreadable df and an empty table are all doubts.
+ assert.equal(macMountIsLocal(df("/dev/disk9s1", "/Volumes/Gone"), table), false);
+ assert.equal(macMountIsLocal("df: /x: No such file or directory\n", table), false);
+ assert.equal(macMountIsLocal(df("/dev/disk3s1", "/System/Volumes/Data"), ""), false);
+});
+
+test("iCloud Drive and File Provider folders count as synced, whatever their case", () => {
+ const home = "/Users/someone";
+ assert.equal(inMacSyncedFolder("/Users/someone/Library/Mobile Documents/com~apple~CloudDocs/omb", home), true);
+ assert.equal(inMacSyncedFolder("/Users/someone/library/cloudstorage/Dropbox/omb", home), true);
+ assert.equal(inMacSyncedFolder("/Users/someone/Library/CloudStorage", home), true);
+ assert.equal(inMacSyncedFolder("/Users/someone/Library/CloudStorageOld/omb", home), false);
+ assert.equal(inMacSyncedFolder("/Users/someone/.openmausbot", home), false);
+ assert.equal(inMacSyncedFolder("/Users/other/Library/CloudStorage/Dropbox", home), false);
+});
+
+test("a live owner with this machine id under another hostname still blocks a second instance", (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.machine === null) return t.skip("no machine id on this platform");
+ plantOwner(dataDir, { host: renamedHost(current), pid: process.pid, token: randomUUID() });
+
+ // Without a boot session (Windows) the other hostname is refused before the pid is even asked.
+ assert.throws(() => acquireDataDirLease(dataDir), current.boot === null ? /another machine/i : /already using this data directory/i);
+});
+
+test("a lease with another machine id fails closed even under this hostname", async (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.machine === null) return t.skip("no machine id on this platform");
+ const leasePath = path.join(dataDir, LEASE_NAME);
+ for (const boot of [current.boot, randomUUID()]) {
+ const planted = `${JSON.stringify({ ...current, machine: anotherMachineId(current), boot, pid: await exitedPid(), token: randomUUID() })}\n`;
+ writeFileSync(leasePath, planted, { mode: 0o600 });
+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);
+ assert.equal(readFileSync(leasePath, "utf8"), planted);
+ }
+});
+
+// An older build wrote no machine id. On a Mac's local disk, its record from an earlier boot is this Mac's whatever the
+// hostname was then; elsewhere (Windows and Linux keep their hostname across networks) another hostname still fails closed.
+test("an older build's lease from an earlier boot under another hostname: recovered on a Mac's local disk, refused elsewhere", async (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.boot === null) return t.skip("no boot identity on this platform");
+ const leasePath = path.join(dataDir, LEASE_NAME);
+ const older = withoutMachineId({ ...current, host: renamedHost(current), boot: randomUUID(), pid: await exitedPid(), token: randomUUID() });
+ writeFileSync(leasePath, `${JSON.stringify(older)}\n`, { mode: 0o600 });
+
+ if (process.platform !== "darwin") {
+ assert.throws(() => acquireDataDirLease(dataDir), /already owned by a process on another machine/i);
+ assert.deepEqual(JSON.parse(readFileSync(leasePath, "utf8")), older);
+ return;
+ }
+ const lease = acquireDataDirLease(dataDir);
+ assert.equal(JSON.parse(readFileSync(leasePath, "utf8")).host, hostname());
+ assert.equal(lease.release(), true);
+});
+
+test("an older build's lease from this boot under another hostname is judged by its pid", async (t) => {
+ const { dataDir } = temporaryDirectory();
+ const current = recordWrittenByThisProcess(dataDir);
+ if (current.boot === null) return t.skip("no boot identity on this platform");
+ const leasePath = path.join(dataDir, LEASE_NAME);
+ writeFileSync(leasePath, `${JSON.stringify(withoutMachineId({ ...current, host: renamedHost(current), pid: process.pid, token: randomUUID() }))}\n`);
+ assert.throws(() => acquireDataDirLease(dataDir), /already using this data directory/i);
+ rmSync(leasePath);
+ writeFileSync(leasePath, `${JSON.stringify(withoutMachineId({ ...current, host: renamedHost(current), pid: await exitedPid(), token: randomUUID() }))}\n`);
+ const lease = acquireDataDirLease(dataDir);
+ assert.equal(lease.release(), true);
+});
test("a lease this computer left under its old hostname is recovered", async (t) => {
const { dataDir } = temporaryDirectory();
@@ -564,7 +680,7 @@ test("a delegated child this computer left under its old hostname cannot block a
test("a lease under another name from another boot still fails closed, and says how to recover", async () => {
const { dataDir } = temporaryDirectory();
const current = recordWrittenByThisProcess(dataDir);
- const foreign = { host: renamedHost(current), boot: randomUUID(), pid: await exitedPid(), token: randomUUID() };
+ const foreign = { host: renamedHost(current), boot: randomUUID(), machine: anotherMachineId(current), pid: await exitedPid(), token: randomUUID() };
const leasePath = plantOwner(dataDir, foreign);
const planted = JSON.parse(readFileSync(leasePath, "utf8"));
assert.throws(() => acquireDataDirLease(dataDir), (error) => {
@@ -856,7 +972,7 @@ test("a Windows owner that can be neither signalled nor listed still fails close
});
// A Cloud home's volume mounts on one machine at a time, and each new home on it has a new hostname and boot.
-const otherMachine = (current) => ({ host: renamedHost(current), boot: randomUUID(), uptime: 1 });
+const otherMachine = (current) => ({ host: renamedHost(current), boot: randomUUID(), uptime: 1, machine: anotherMachineId(current) });
test("on request, the lease, delegated child and recovery record another machine left are cleared and their holder named; then the lease is free", async () => {
const { dataDir } = temporaryDirectory();
diff --git a/server/data-dir-lease.test.ts b/server/data-dir-lease.test.ts
index 4ef706a748..62929a512e 100644
--- a/server/data-dir-lease.test.ts
+++ b/server/data-dir-lease.test.ts
@@ -63,7 +63,7 @@ describe("OpenMausBot data-directory lease", () => {
// across a restart cannot be mistaken for a live owner, and ns/start which
// pid namespace and process, so a container's reused pid cannot either.
// Each is null where the platform does not expose it.
- const { boot, ns, start, ...rest } = stored;
+ const { boot, ns, start, machine, ...rest } = stored;
expect(rest).toEqual({
version: 1,
pid: process.pid,
@@ -74,8 +74,10 @@ describe("OpenMausBot data-directory lease", () => {
});
expect(boot === null || (typeof boot === "string" && boot.length > 0)).toBe(true);
expect(process.platform === "linux" ? /^[1-9]\d*$/.test(ns) && Number.isSafeInteger(start) : ns === null && start === null).toBe(true);
+ // machine: a hashed id that survives a restart and a hostname change, null where unreadable.
+ expect(machine === null || /^[0-9a-f]{32}$/.test(machine)).toBe(true);
expect(Object.keys(stored).sort()).toEqual(
- ["boot", "createdAt", "host", "ns", "pid", "start", "token", "uptime", "version"],
+ ["boot", "createdAt", "host", "machine", "ns", "pid", "start", "token", "uptime", "version"],
);
expect(() => acquireDataDirLease(dir)).toThrow(/already using this data directory/i);