Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud home: notice and set a clock a resume left behind (#7534)
Milind Sonib0b8cdf0f32e
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 6435f5b4fb..5dbccc60ca 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1742,7 +1742,7 @@ not open the browser.| Status | Body | Meaning || --- | --- | --- || `401` | `{"error":"invalid_signature"}` | Wrong key, tampered request, or malformed headers. Counts toward the per-source pairing lockout. |-| `401` | `{"error":"stale_request"}` | Timestamp more than 300 s from the machine's clock. |+| `401` | `{"error":"stale_request"}` | Timestamp more than 300 s from the machine's clock (or, while the home has measured its clock off, from the measured true time: "The home's clock" below). A health, power or diagnose read's refusal adds `clockErrorMs` when the home has measured its clock. || `401` | `{"error":"replayed_request"}` | Nonce already used in the last 10 minutes. || `429` | `{"error":"rate_limited","retryAfterSeconds":n}` | Too many bad signatures from this source. || `400` | `invalid_body`, `invalid_label`, `invalid_ttl`, `invalid_purpose`, `invalid_owner` | Not a JSON object; label not plain text of 80 characters or fewer; TTL not a positive integer; `purpose` present and not `"browser"`; `owner` missing on a browser sign-in, or not one email address of 254 characters or fewer in printable ASCII with exactly one `@` and no `<` or `>`. |@@ -1798,10 +1798,16 @@ wait for the next read, `truncated: true`):"room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2,"boot": { "waits": 5, "stopped": 1, "killed": 1, "stallMinutes": 4 } },"speed": { "windowS": 300, "steal": 1.2, "psi": { "cpu": 3.4, "memory": 0, "io": 0.8 }, "bootMs": 5400, "wakeMs": null,- "turnStarts": [12, 3, 1, 0, 0, 0], "loop": { "n": 2, "worstMs": 1800 } }+ "turnStarts": [12, 3, 1, 0, 0, 0], "loop": { "n": 2, "worstMs": 1800 } },+ "clock": { "v": 1, "errorMs": 21660000, "measuredAt": 1790021660000 }}```+**`clock`** is the home's clock as it last measured it ("The home's clock"+below): `errorMs` how far it is behind the true time (negative: ahead), and+`measuredAt` when, in true time; both `null` when nothing measured it in the+last 10 minutes. Older homes don't send it.+**`speed`** says how fast the machine is for this home (`server/cloud-speed.ts`),read from `/proc` when the report is built, with no timer or sampler of itsown. `windowS` is how many seconds the CPU figures cover: since the previous@@ -1995,6 +2001,66 @@ updates; a cloud computer that fails a turn arrives as its place's codeA home from before this answers `404`; the Admin then reads `/api/health`and shows its health as Unknown.+## The home's clock++A home its provider suspended and resumed is meant to get its clock set on+resume; once in a while it isn't, and both its wall clock and its monotonic+clock stopped while it was suspended, so the home can't tell by itself (Nov+2026: one home ran 6 h behind for 8+ hours, another 40 minutes behind for+10.5 hours; the Admin's signed reads were all `stale_request`, and routines+ran late). Measured on the provider's smallest machine (Nov 26 2026): its own+init holds the host's PTP clock and puts the guest's clock right within about+2.5 s of any change, and resumes after 5, 20 and 60 minutes came back right; a+home that stays behind is one whose init stopped keeping its clock, and a+restart fixes it. The Admin also sets such a clock from outside. `server/cloud-clock.ts`:++- **What starts a look.** A signed request from the Admin with a valid+ signature whose timestamp is 30 s or more from the home's clock, any wake+ (`server/cloud-power.ts`: a resume it noticed, a boot from sleep, the clock+ set forward), and the supervisor's own look every 10 minutes at one host. A+ request's timestamp is never taken as the time.+- **What it trusts.** The `Date` header of a fresh `HEAD /` to the home's+ Admin, the account service and a phone relay. An answer slower than 4 s or+ with an `Age` header is dropped. The largest group of two or more answers+ within 3 s of each other gives the time, and it must hold the Admin's own+ answer (one host with a wrong clock is outvoted; two hosts that aren't the+ Admin never move the clock); two such groups, or none, and nothing is+ measured. An error over 14 days (longer than any suspend) is not believed:+ nothing is set or let through on it. At most one look a minute. A clock+ 20 to 34 days behind can't measure at all: the hosts' certificates aren't+ valid yet for it.+- **Who sets it.** Only the root supervisor (`server/cloud-clock-keeper.ts`),+ which measures again by itself and then runs `date -u -s`, forward only, for+ an error of 30 s or more. The true time is anchored on the monotonic clock as+ its measurement starts, and it steps only if the wall clock is still 30 s or+ more behind at that moment (the platform may set it right meanwhile). The server writes a payload-free `check` line to+ it on an inherited pipe (`OMB_CLOUD_CLOCK_FD`); whatever is written there+ can make it look at most once a minute, never pick a time. It needs+ CAP_SYS_TIME: a home that runs as its own VM has it; a Docker container+ doesn't (those never suspend), so there it only logs and measures. It logs+ the clock source, a PTP clock and CAP_SYS_TIME at start.+- **The Admin's reads meanwhile.** While a measurement in the last 10 minutes+ says the clock is 30 s or more off, every signed request must fit the+ measured true time (a request signed hours ago that only fits the wrong+ clock is refused), and the health, power and diagnose reads (`GET` only)+ pass on that alone. Pairing, the sleep request and every other signed request still need+ the home's own clock. Nonces expire on the monotonic clock, so a step never+ forgets one early.+- **The home's own calls to the Admin.** Phone notifications, the wake+ notice, Pages, Slack, the team's rules and roster, and bug report status are+ signed with the measured true time while a measurement says the clock is+ 30 s or more off (`cloudSignedTimestamp`), so they still pass the Admin's+ check before the clock is set. The wake notice waits for the measurement+ the wake starts.+- **What a step forward does.** Node's timers run on the monotonic clock and+ carry on. The power loop sees a jump and runs its wake handling (the Admin+ hears the home woke). Due routines run within a minute (`server/due-timer.ts`),+ each once: its newest occurrence, the ones before closed on one counted row+ (`server/routine-catch-up.ts`). A running turn's watchdog takes a jump for a+ suspend, and the unattended-turn limit counts on the monotonic clock, so no+ turn is stopped for the hours skipped. What was written while the clock was+ behind keeps its times.+## Sleeping homes: the power read and the sleep handshakeA plan may let its home **sleep when idle**: the Admin suspends the machinediff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex a4af4cc098..9605fdb2d8 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -24,7 +24,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_CLOUD_EDGE_CLIENT_IP_HEADER", "OMB_CLOUD_EDGE_CONFIG", "OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_STORAGE","OMB_CLOUD_EDGE_TLS", "OMB_CLOUD_EDGE_TRUSTED_PROXIES", "OMB_CLOUD_EXPORT_ONLY", "OMB_CLOUD_HARDEN", "OMB_CLOUD_HOSTING_TOKEN", "OMB_CLOUD_HOSTING_URL","OMB_CLOUD_HOME", "OMB_CLOUD_IMAGE", "OMB_CLOUD_LEGACY_ORIGINS", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_MOVES",- "OMB_CLOUD_PUBLIC_HOST", "OMB_CLOUD_ROLE", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_STAGING",+ "OMB_CLOUD_PUBLIC_HOST", "OMB_CLOUD_ROLE", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_CLOCK_FD", "OMB_CLOUD_STAGING","OMB_CLOUD_STOPPED_HOLD_DAYS", "OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_LANGUAGE", "OMB_CLOUD_TEAM_NAME","OMB_CLOUD_TRUSTED_PROXIES", "OMB_CLOUD_TUNNEL_BIN", "OMB_CLOUD_TUNNEL_TOKEN", "OMB_CLOUD_VOICE_TOKEN","OMB_CLOUD_VOICE_URL", "OMB_CLOUD_X_TOKEN", "OMB_CLOUD_X_URL", "OMB_CODEX_LAUNCH_SLOTS", "OMB_CODEX_SESSION_IDLE_", "OMB_CODEX_SESSION_KEEP", "OMB_COMPANION_DIR",diff --git a/server/bot-box/env.ts b/server/bot-box/env.tsindex f6b14f44d3..7b29599568 100644--- a/server/bot-box/env.ts+++ b/server/bot-box/env.ts@@ -53,7 +53,7 @@ export const BOX_ENV_PREFIXES: readonly string[] = [* CLI's session token and server address (server/headless/client.ts) too: nothing in a box reads them, and one an* operator set on the server would otherwise pass under the engines' OPENMAUSBOT_ prefix. */export const BOX_ENV_NEVER: ReadonlySet<string> = new Set([- "OMB_LICENSE_KEY", "OMB_INSTALLATION_CREDENTIAL", "OMB_LOOPBACK_TRUST", "OMB_CLOUD_SECRETS_FD",+ "OMB_LICENSE_KEY", "OMB_INSTALLATION_CREDENTIAL", "OMB_LOOPBACK_TRUST", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_CLOCK_FD","OMB_DATA_DIR", "OMB_STATIC_DIR", "OMB_DUCKDB_DIR", "OMB_PORT", "OMB_WEBHOOK_PORT","OPENMAUSBOT_TOKEN", "OPENMAUSBOT_URL",]);diff --git a/server/cloud-clock-keeper.ts b/server/cloud-clock-keeper.tsnew file mode 100644index 0000000000..56579893cd--- /dev/null+++ b/server/cloud-clock-keeper.ts@@ -0,0 +1,125 @@+// The root supervisor's half of the home's clock (server/cloud-clock.ts): the one process allowed to set it. It measures by+// itself, from fresh HTTPS answers of independent hosts, and sets the clock only forward, only when two or more agree and say+// it is CLOCK_STEP_MS or more behind. What wakes it: the server's "check" lines (a valid signed request far from this clock,+// or a wake), and a slow look of its own (one host every CLOCK_LOOK_MS, all of them when that one says the clock is off), so+// a home whose server is down still comes right. A line is only a reason to look: anything `maus` writes there can make it+// measure at most once a minute, never choose a time.+//+// Setting it: `date -u -s @<seconds>` (clock_settime), which needs CAP_SYS_TIME. A home that runs as its own VM has its+// supervisor as root, so it has it (measured live Nov 26 2026 on the provider's smallest machine, where the provider's init+// also keeps the clock from the host's PTP clock while that works); a Docker container (a rented or a team's own server) has+// not, and those never suspend: there it logs once and only measures. No time daemon ships in the image.+import { spawnSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import type { Readable } from "node:stream";+import { CLOCK_CHECK_GAP_MS, CLOCK_MAX_STEP_MS, CLOCK_STEP_MS, clockSources, measureClock, readClock, systemClocks, type ClockClocks } from "./cloud-clock.ts";++/** The supervisor's own look, one host at a time. */+export const CLOCK_LOOK_MS = 10 * 60_000;+const CAP_SYS_TIME = 25;+const DATE = "/bin/date";++/** A capability's bit in /proc/self/status's effective set. */+export function hasEffectiveCapability(status: string, bit: number): boolean {+ const hex = /^CapEff:\s*([0-9a-f]+)$/m.exec(status)?.[1];+ return hex ? ((BigInt(`0x${hex}`) >> BigInt(bit)) & 1n) === 1n : false;+}++/** What this machine offers for time, logged once at start so the first real machine answers it: its clock source, a+ * paravirtual PTP clock, and whether this process may set the clock. */+export function clockFacts(read: (path: string) => string = (path) => { try { return readFileSync(path, "utf8"); } catch { return ""; } },+ exists: (path: string) => boolean = existsSync): { source: string; ptp: boolean; canSet: boolean } {+ return {+ source: read("/sys/devices/system/clocksource/clocksource0/current_clocksource").trim() || "unknown",+ ptp: exists("/dev/ptp0"),+ canSet: hasEffectiveCapability(read("/proc/self/status"), CAP_SYS_TIME),+ };+}++export function setSystemClock(wallMs: number): { ok: boolean; why?: string } {+ const result = spawnSync(DATE, ["-u", "-s", `@${(wallMs / 1000).toFixed(3)}`], { stdio: ["ignore", "ignore", "pipe"], encoding: "utf8", timeout: 5_000 });+ return result.status === 0 ? { ok: true } : { ok: false, why: String(result.stderr ?? "").trim().split("\n")[0] || result.error?.message || `exit ${result.status}` };+}++/** The supervisor's keeper: logs what the machine offers, checks once now, then looks every CLOCK_LOOK_MS. */+export function startClockKeeper(adminOrigin: string, log: (line: string) => void = (line) => console.log(line)) {+ const facts = clockFacts();+ log(`cloud home: clock source ${facts.source}, ${facts.ptp ? "a PTP clock at /dev/ptp0" : "no PTP clock"}, ${facts.canSet ? "may set the clock" : "can't set the clock (no CAP_SYS_TIME)"}`);+ const keeper = createClockKeeper({ origins: clockSources(adminOrigin), canSet: facts.canSet, log });+ keeper.start();+ return keeper;+}++export function createClockKeeper(options: {+ origins: readonly string[]; canSet: boolean; fetch?: typeof fetch; clocks?: ClockClocks;+ set?: (wallMs: number) => { ok: boolean; why?: string }; log: (line: string) => void;+}) {+ const clocks = options.clocks ?? systemClocks, fetcher = options.fetch ?? fetch, set = options.set ?? setSystemClock;+ let checking: Promise<void> | null = null, checkedAt = -Infinity, turn = 0, canSet = options.canSet, toldCannot = false, lastLine = "";+ const log = (line: string) => { if (line !== lastLine) { lastLine = line; options.log(line); } };++ const run = async () => {+ checkedAt = clocks.mono();+ // The true time is anchored on the monotonic clock as the measurement starts: the platform may set the wall clock meanwhile.+ const wallAt = clocks.wall(), monoAt = clocks.mono();+ const verdict = await measureClock(options.origins, fetcher, clocks);+ if (verdict.state !== "agreed") { log(`cloud home: clock not checked (${verdict.state === "disagree" ? "the hosts disagree" : "too few hosts answered"}); left as it is`); return; }+ const minutes = Math.round(Math.abs(verdict.offsetMs) / 60_000);+ if (verdict.offsetMs < CLOCK_STEP_MS) {+ log(verdict.offsetMs <= -CLOCK_STEP_MS ? `cloud home: the clock is ${minutes} min ahead; only a clock behind is set, so it is left as it is` : "cloud home: the clock is right");+ return;+ }+ if (verdict.offsetMs > CLOCK_MAX_STEP_MS) {+ log(`cloud home: the clock measured ${minutes} min behind, more than any suspend; not believed, left as it is (a restart sets it)`);+ return;+ }+ if (!canSet) {+ if (!toldCannot) { toldCannot = true; options.log(`cloud home: the clock is ${minutes} min behind and this machine can't set it (no CAP_SYS_TIME); a restart sets it`); }+ return;+ }+ // The true time now, from the anchor and the monotonic clock, never from the wall clock as it reads now (which something may+ // have set right during the measurement: adding the error to it again would leave the clock ahead). Stepped only when the+ // wall clock is still CLOCK_STEP_MS or more behind it at this moment; never backward.+ const target = wallAt + verdict.offsetMs + (clocks.mono() - monoAt);+ if (target - clocks.wall() < CLOCK_STEP_MS) { log("cloud home: the clock was set right meanwhile; left as it is"); return; }+ const result = set(target);+ lastLine = "";+ if (result.ok) options.log(`cloud home: the clock was ${minutes} min behind (${verdict.readings.length} hosts agree); set forward`);+ else { canSet = false; options.log(`cloud home: the clock is ${minutes} min behind and could not be set (${result.why}); a restart sets it`); }+ };+ const check = (): Promise<void> => {+ if (checking) return checking;+ if (clocks.mono() - checkedAt < CLOCK_CHECK_GAP_MS) return Promise.resolve();+ checking = run().catch(() => {}).finally(() => { checking = null; });+ return checking;+ };+ /** The slow look: one host, in turn; a clock off by CLOCK_STEP_MS or more there is checked against all of them. */+ const look = async () => {+ const origin = options.origins[turn++ % options.origins.length];+ if (!origin) return;+ const reading = await readClock(origin, fetcher, clocks);+ if (reading && Math.abs(reading.offsetMs) >= CLOCK_STEP_MS) await check();+ };+ return {+ check, look,+ /** "check" lines from the server's pipe; anything else on it is ignored. */+ listen(pipe: Readable) {+ let buffered = "";+ pipe.setEncoding("utf8");+ pipe.on("data", (chunk: string) => {+ buffered = (buffered + chunk).slice(-256);+ if (!buffered.includes("\n")) return;+ const lines = buffered.split("\n");+ buffered = lines.pop() ?? "";+ if (lines.some((line) => line === "check")) void check();+ });+ pipe.on("error", () => {});+ },+ start(intervalMs = CLOCK_LOOK_MS) {+ void check();+ const timer = setInterval(() => void look().catch(() => {}), intervalMs);+ timer.unref?.();+ return () => clearInterval(timer);+ },+ };+}diff --git a/server/cloud-clock-signing.test.ts b/server/cloud-clock-signing.test.tsnew file mode 100644index 0000000000..d6d2458bfb--- /dev/null+++ b/server/cloud-clock-signing.test.ts@@ -0,0 +1,79 @@+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { PHONE_PUSH_RELAY_PATHS } from "../shared/phone-push.ts";+import { CLOCK_STEP_MS, cloudSignedTimestamp, cloudSigningTime, registerCloudClock } from "./cloud-clock.ts";+import { createWokeNotifier } from "./cloud-woke.ts";+import { pagesAuthHeaders } from "./pages/access.ts";+import { cloudHomePushRequest } from "./phone-push-admin.ts";++// A home a resume left behind signs its own calls to the Admin (phone notifications, the wake notice, Pages, Slack, team rules,+// the roster) with the true time its measurement gives, so the Admin, which judges them by its own clock, doesn't refuse them+// all while the clock waits to be set. Nov 26 2026: a home 40 minutes behind for 10.5 hours.+const NOW = Date.parse("2026-11-26T12:00:00Z"), BEHIND = 40 * 60_000;+const seconds = (ms: number) => String(Math.floor(ms / 1000));+afterEach(() => { registerCloudClock(null); });++/** A clock watch that measured this clock `errorMs` off (positive: behind); `settled` resolves when the test says. */+function measured(errorMs: number | null) {+ let release: () => void = () => {};+ const pending = new Promise<void>((resolve) => { release = resolve; });+ const state = { errorMs, waiting: false };+ registerCloudClock({ woke() {}, report: () => ({ v: 1, errorMs: state.errorMs, measuredAt: null }), settled: () => (state.waiting ? pending : Promise.resolve()) });+ return { state, release };+}++describe("the time a home signs its own calls with", () => {+ it("is this clock, unless a fresh measurement says it is 30 s or more off", () => {+ expect(cloudSigningTime(NOW)).toBe(NOW);+ measured(BEHIND);+ expect(cloudSigningTime(NOW)).toBe(NOW + BEHIND);+ expect(cloudSignedTimestamp(NOW)).toBe(seconds(NOW + BEHIND));+ measured(CLOCK_STEP_MS - 1);+ expect(cloudSigningTime(NOW)).toBe(NOW);+ measured(null);+ expect(cloudSigningTime(NOW)).toBe(NOW);+ // Ahead: signed with the true time too (the Admin's clock is the one that counts).+ measured(-BEHIND);+ expect(cloudSigningTime(NOW)).toBe(NOW - BEHIND);+ });++ it("is what a phone notification, a Pages call and the wake notice carry", async () => {+ measured(BEHIND);+ const push = cloudHomePushRequest({ admin: "https://admin.example", machineId: "m1", secret: "S".repeat(43) }, PHONE_PUSH_RELAY_PATHS.send, { v: 1 }, NOW);+ expect((push!.init.headers as Record<string, string>)["x-omb-cloud-timestamp"]).toBe(seconds(NOW + BEHIND));+ expect(pagesAuthHeaders({ kind: "home", url: "https://admin.example", machineId: "m1", secret: "S".repeat(43) }, "{}", NOW)["x-omb-cloud-timestamp"]).toBe(seconds(NOW + BEHIND));+ const sent: Request[] = [];+ const notify = createWokeNotifier({ adminOrigin: "https://admin.example", machineId: "m1", secret: "S".repeat(43), now: () => NOW,+ fetcher: (async (input: string | URL | Request, init?: RequestInit) => { sent.push(new Request(input, init)); return new Response(null, { status: 204 }); }) as typeof fetch });+ notify();+ await new Promise((resolve) => setTimeout(resolve, 5));+ expect(sent.map((request) => request.headers.get("x-omb-cloud-timestamp"))).toEqual([seconds(NOW + BEHIND)]);+ });++ it("the wake notice waits for the measurement a wake starts, and is signed with what it found", async () => {+ const clock = measured(null);+ clock.state.waiting = true;+ const sent: Request[] = [];+ const notify = createWokeNotifier({ adminOrigin: "https://admin.example", machineId: "m1", secret: "S".repeat(43), now: () => NOW,+ fetcher: (async (input: string | URL | Request, init?: RequestInit) => { sent.push(new Request(input, init)); return new Response(null, { status: 204 }); }) as typeof fetch });+ notify();+ await new Promise((resolve) => setTimeout(resolve, 5));+ expect(sent).toEqual([]);+ clock.state.errorMs = BEHIND;+ clock.release();+ await new Promise((resolve) => setTimeout(resolve, 5));+ expect(sent.map((request) => request.headers.get("x-omb-cloud-timestamp"))).toEqual([seconds(NOW + BEHIND)]);+ });++ it("is used by every call the home signs for the Admin", () => {+ // Each place that sends `x-omb-cloud-timestamp` takes it from cloudSignedTimestamp; the Admin-side verifiers and tests excluded.+ const root = join(import.meta.dirname), files: string[] = [];+ const walk = (dir: string) => { for (const name of readdirSync(dir)) { const path = join(dir, name); if (statSync(path).isDirectory()) { if (name !== "node_modules") walk(path); } else if (name.endsWith(".ts") && !name.endsWith(".test.ts")) files.push(path); } };+ walk(root);+ const senders = files.filter((file) => /"x-omb-cloud-timestamp":\s*timestamp/.test(readFileSync(file, "utf8")));+ expect(senders.length).toBeGreaterThanOrEqual(8);+ const unsigned = senders.filter((file) => !/const timestamp = cloudSignedTimestamp\(/.test(readFileSync(file, "utf8")) && !file.includes(`${join("server", "testing")}`));+ expect(unsigned.map((file) => relative(root, file))).toEqual([]);+ });+});diff --git a/server/cloud-clock.test.ts b/server/cloud-clock.test.tsnew file mode 100644index 0000000000..b7a9cb1b52--- /dev/null+++ b/server/cloud-clock.test.ts@@ -0,0 +1,338 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";+import { describe, expect, it } from "vitest";+import { agree, CLOCK_FD_ENV, CLOCK_MAX_STEP_MS, CLOCK_STEP_MS, clockKicker, clockSources, createCloudClock, readClock, type ClockClocks } from "./cloud-clock.ts";+import { clockFacts, createClockKeeper, hasEffectiveCapability } from "./cloud-clock-keeper.ts";+import { CLOUD_PAIRING_SKEW_S, cloudRequestSignature, createCloudRequestVerifier } from "./cloud-home.ts";+import { createCloudPower } from "./cloud-power.ts";+import { planOccurrence } from "./routine-catch-up.ts";++const SIX_HOURS = 6 * 3_600_000;+const START = Date.parse("2026-11-25T08:00:00Z");+const ADMIN = "https://admin.example", ACCOUNTS = "https://accounts.example", RELAY = "https://relay.example";+const secret = "S".repeat(43);++/**+ * A home and the world around it. `wall` and `mono` are the home's own clocks; `truth` is the world's. A suspend moves+ * only `truth`: the home's wall and monotonic clocks both stop, which is the case a clock-jump detector can't see.+ */+function world() {+ const state = { truth: START, wall: START, mono: 1_000, skew: {} as Record<string, number>, cached: new Set<string>(), down: new Set<string>(), asked: [] as string[] };+ const clocks: ClockClocks = { wall: () => state.wall, mono: () => state.mono };+ const fetcher = (async (input: string | URL | Request) => {+ const origin = new URL(String(input)).origin;+ state.asked.push(origin);+ if (state.down.has(origin)) throw new Error("unreachable");+ const date = new Date(state.truth + (state.skew[origin] ?? 0)).toUTCString();+ return new Response(null, { status: 200, headers: { date, ...(state.cached.has(origin) ? { age: "120" } : {}) } });+ }) as typeof fetch;+ /** Time passes for everyone. */+ const pass = (ms: number) => { state.truth += ms; state.wall += ms; state.mono += ms; };+ /** Suspended for `ms`: the world moves on, the home's clocks don't. */+ const suspend = (ms: number) => { state.truth += ms; };+ let counter = 0;+ /** The Admin signs with its own (true) clock, or with `at` (a request captured then). */+ const sign = (target = "/api/cloud/health?after=0", at = state.truth) => {+ const timestamp = String(Math.floor(at / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;+ return { timestamp, nonce, signature: `v1=${cloudRequestSignature(secret, timestamp, nonce, "GET", target, "")}`, method: "GET", target, body: "" };+ };+ return { state, clocks, fetcher, pass, suspend, sign };+}++function homeClock(w: ReturnType<typeof world>) {+ const kicks: number[] = [], lines: string[] = [];+ const clock = createCloudClock({ origins: [ADMIN, ACCOUNTS, RELAY], fetch: w.fetcher, clocks: w.clocks, kick: () => kicks.push(w.state.truth), log: (line) => lines.push(line), skewS: CLOUD_PAIRING_SKEW_S });+ const verifier = (tolerant: boolean) => createCloudRequestVerifier({ secret, now: w.clocks.wall, mono: w.clocks.mono, clock, tolerant });+ return { clock, kicks, lines, health: verifier(true), pairing: verifier(false) };+}++describe("reading a clock from the outside", () => {+ it("asks the Admin first, then its own hosts, each host once", () => {+ expect(clockSources("https://admin.example/")).toEqual(["https://admin.example", "https://accounts.openmausbot.com", "https://relay1.openmausbot.com"]);+ expect(clockSources("https://accounts.openmausbot.com")).toEqual(["https://accounts.openmausbot.com", "https://relay1.openmausbot.com"]);+ });++ it("takes an answer's Date, and refuses a cached one, a slow one and one without a Date", async () => {+ const w = world();+ w.state.skew[ADMIN] = SIX_HOURS;+ expect(Math.abs((await readClock(ADMIN, w.fetcher, w.clocks))!.offsetMs - SIX_HOURS)).toBeLessThanOrEqual(500);+ w.state.cached.add(ADMIN);+ expect(await readClock(ADMIN, w.fetcher, w.clocks)).toBeNull();+ const slow = (async () => { w.state.mono += 10_000; return new Response(null, { headers: { date: new Date(w.state.truth).toUTCString() } }); }) as typeof fetch;+ expect(await readClock(ADMIN, slow, w.clocks)).toBeNull();+ expect(await readClock(ADMIN, (async () => new Response(null)) as typeof fetch, w.clocks)).toBeNull();+ expect(await readClock(ADMIN, (async () => { throw new Error("down"); }) as typeof fetch, w.clocks)).toBeNull();+ });++ it("agrees on the largest group of two or more answers within a few seconds of each other, which must hold the Admin's", () => {+ const at = (origin: string, offsetMs: number) => ({ origin, offsetMs, tripMs: 50 });+ expect(agree([at(ADMIN, SIX_HOURS)]).state).toBe("too-few");+ expect(agree([at(ADMIN, SIX_HOURS), at(ACCOUNTS, 0)]).state).toBe("disagree");+ expect(agree([at(ADMIN, SIX_HOURS), at(ACCOUNTS, SIX_HOURS + 2_000)])).toMatchObject({ state: "agreed", offsetMs: SIX_HOURS + 1_000 });+ // One host with a wrong clock is outvoted, not a veto.+ expect(agree([at(ADMIN, SIX_HOURS), at(ACCOUNTS, SIX_HOURS), at(RELAY, 0)], ADMIN)).toMatchObject({ state: "agreed", offsetMs: SIX_HOURS, readings: [at(ADMIN, SIX_HOURS), at(ACCOUNTS, SIX_HOURS)] });+ // Two hosts that are not the Admin never move the clock away from the Admin's time.+ expect(agree([at(ADMIN, 0), at(ACCOUNTS, SIX_HOURS), at(RELAY, SIX_HOURS)], ADMIN).state).toBe("disagree");+ // Two groups as large, each with the Admin's answer, saying different times: nothing.+ expect(agree([at(ACCOUNTS, -2_500), at(ADMIN, 0), at(RELAY, 2_500)], ADMIN).state).toBe("disagree");+ });+});++describe("a home a resume left behind, with no jump to notice", () => {+ it("is measured from the Admin's first signed read, keeps answering its health reads, and asks the supervisor to set the clock", async () => {+ const w = world(), home = homeClock(w);+ expect(home.health.verify(w.sign())).toEqual({ ok: true });+ w.suspend(SIX_HOURS + 60_000);+ w.pass(5_000);+ // The first read after the resume is still refused (nothing measured yet), and starts the measurement.+ expect(home.health.verify(w.sign())).toMatchObject({ ok: false, error: "stale_request" });+ await home.clock.check();+ expect(home.kicks).toHaveLength(1);+ expect(Math.abs(home.clock.report().errorMs! - (SIX_HOURS + 60_000))).toBeLessThanOrEqual(1_000);+ expect(home.clock.report().measuredAt).toBeGreaterThan(START + SIX_HOURS);+ // Then the Admin's reads pass while the clock is wrong; pairing never does.+ w.pass(60_000);+ expect(home.health.verify(w.sign())).toEqual({ ok: true });+ expect(home.pairing.verify(w.sign())).toMatchObject({ ok: false, error: "stale_request" });+ // A request signed six hours ago fits the wrong clock, and is refused now that the true time is known, by every route.+ expect(home.health.verify(w.sign(undefined, START + 60_000))).toMatchObject({ ok: false, error: "stale_request" });+ expect(home.pairing.verify(w.sign(undefined, START + 60_000))).toMatchObject({ ok: false, error: "stale_request" });+ });++ it("is set forward by the supervisor, which measures for itself, and the server then sees a wake and a right clock", async () => {+ const w = world(), home = homeClock(w), set: number[] = [], lines: string[] = [];+ const keeper = createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line),+ set: (wallMs) => { set.push(wallMs); w.state.wall = wallMs; return { ok: true }; } });+ const pipe = new PassThrough();+ keeper.listen(pipe);+ let woke = 0;+ const dir = mkdtempSync(join(tmpdir(), "omb-cloud-clock-"));+ const power = createCloudPower({ dataDir: dir, now: w.clocks.wall, broadcast: () => {}, onWoke: () => { woke += 1; }, probes: {+ turn: () => false, run: () => false, handoff: () => false, liveCall: () => false, computer: () => false, maintenance: () => false, nextDueAt: () => null } });+ try {+ w.suspend(SIX_HOURS);+ power.tick();+ expect(woke).toBe(0);+ home.health.verify(w.sign());+ await home.clock.check();+ expect(home.kicks).toHaveLength(1);+ // The server's line is only a reason to look: the supervisor measures again and sets the true time.+ pipe.write("check\n");+ await new Promise((resolve) => setImmediate(resolve));+ await keeper.check();+ expect(set).toHaveLength(1);+ expect(Math.abs(set[0]! - w.state.truth)).toBeLessThanOrEqual(1_000);+ expect(lines.at(-1)).toMatch(/360 min behind \(3 hosts agree\); set forward/);+ // A step bigger than the resume jump: cloud-power's tick calls it a wake, so the server's wake handling runs.+ expect(CLOCK_STEP_MS).toBeGreaterThan(20_000);+ power.tick();+ expect(woke).toBe(1);+ home.clock.woke();+ await home.clock.check();+ expect(Math.abs(home.clock.report().errorMs!)).toBeLessThanOrEqual(1_000);+ expect(home.health.verify(w.sign())).toEqual({ ok: true });+ } finally {+ power.close();+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("forgets no nonce when the clock is set forward: a read let through just before can't be replayed just after", async () => {+ const w = world(), home = homeClock(w);+ w.suspend(SIX_HOURS);+ home.health.verify(w.sign());+ await home.clock.check();+ const read = w.sign();+ expect(home.health.verify(read)).toEqual({ ok: true });+ w.state.wall += SIX_HOURS;+ w.pass(1_000);+ expect(home.health.verify(read)).toMatchObject({ ok: false, error: "replayed_request" });+ });+});++describe("what can't move the clock", () => {+ it("an old signed request replayed: it starts a measurement, which finds the clock right", async () => {+ const w = world(), home = homeClock(w);+ w.pass(SIX_HOURS);+ expect(home.health.verify(w.sign(undefined, START))).toMatchObject({ ok: false, error: "stale_request" });+ await home.clock.check();+ expect(home.kicks).toEqual([]);+ expect(Math.abs(home.clock.report().errorMs!)).toBeLessThanOrEqual(1_000);+ expect(home.health.verify(w.sign(undefined, START))).toMatchObject({ ok: false, error: "stale_request" });+ // And the supervisor, asked as often as anyone likes, sets nothing.+ const set: number[] = [];+ const keeper = createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: () => {}, set: (ms) => { set.push(ms); return { ok: true }; } });+ await keeper.check();+ expect(set).toEqual([]);+ });++ it("hosts that disagree: nothing is measured, set or let through", async () => {+ const w = world(), home = homeClock(w);+ w.state.skew[ADMIN] = SIX_HOURS;+ w.state.skew[RELAY] = -SIX_HOURS;+ home.health.verify(w.sign(undefined, w.state.truth + SIX_HOURS));+ await home.clock.check();+ expect(home.kicks).toEqual([]);+ expect(home.clock.report().errorMs).toBeNull();+ expect(home.health.verify(w.sign(undefined, w.state.truth + SIX_HOURS))).toMatchObject({ ok: false, error: "stale_request" });+ expect(home.lines.at(-1)).toMatch(/hosts disagree/);+ const set: number[] = [];+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: () => {}, set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ });++ it("the two other hosts agreeing without the Admin: nothing is set", async () => {+ const w = world(), set: number[] = [], lines: string[] = [];+ w.state.skew[ACCOUNTS] = SIX_HOURS;+ w.state.skew[RELAY] = SIX_HOURS;+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ expect(lines).toEqual(["cloud home: clock not checked (the hosts disagree); left as it is"]);+ });++ it("one host alone, or cached answers: too few to agree", async () => {+ const w = world(), set: number[] = [];+ w.suspend(SIX_HOURS);+ w.state.down.add(ACCOUNTS);+ w.state.cached.add(RELAY);+ const lines: string[] = [];+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ expect(lines).toEqual(["cloud home: clock not checked (too few hosts answered); left as it is"]);+ });++ it("a clock ahead is reported and never set back; the Admin's reads are judged by the measured time", async () => {+ const w = world(), home = homeClock(w), set: number[] = [], lines: string[] = [];+ w.state.wall += SIX_HOURS;+ home.health.verify(w.sign());+ await home.clock.check();+ expect(home.kicks).toEqual([]);+ expect(home.clock.report().errorMs).toBeLessThan(-SIX_HOURS + 1_000);+ expect(home.health.verify(w.sign())).toEqual({ ok: true });+ expect(home.pairing.verify(w.sign())).toMatchObject({ ok: false, error: "stale_request" });+ // Signed to fit the clock that is ahead: refused, since no such time has come yet.+ expect(home.health.verify(w.sign(undefined, w.state.wall))).toMatchObject({ ok: false, error: "stale_request" });+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ expect(lines).toEqual(["cloud home: the clock is 360 min ahead; only a clock behind is set, so it is left as it is"]);+ });++ it("one host with a wrong clock: the Admin and the other host agree, and the clock is set", async () => {+ const w = world(), set: number[] = [], lines: string[] = [];+ w.suspend(SIX_HOURS);+ w.state.skew[RELAY] = -SIX_HOURS;+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toHaveLength(1);+ expect(Math.abs(set[0]! - w.state.truth)).toBeLessThanOrEqual(1_000);+ expect(lines.at(-1)).toMatch(/360 min behind \(2 hosts agree\); set forward/);+ });++ it("a clock the platform sets right during the measurement is not stepped again (no overshoot), and a partial one gets the true time", async () => {+ // Six hours behind; the platform puts the wall clock right while the hosts are being asked.+ const w = world(), set: number[] = [], lines: string[] = [];+ w.suspend(SIX_HOURS);+ let corrected = false;+ const fetcher = (async (input: string | URL | Request, init?: RequestInit) => {+ // After every request went out, before the answers are read.+ const answer = await w.fetcher(input, init);+ await Promise.resolve();+ if (!corrected) { corrected = true; w.state.wall = w.state.truth; }+ return answer;+ }) as typeof fetch;+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ expect(lines.at(-1)).toMatch(/set right meanwhile/);+ // Corrected only part of the way (to an hour behind) meanwhile: stepped to the true time, not six hours past it.+ const p = world(), partial: number[] = [];+ p.suspend(SIX_HOURS);+ let once = false;+ const halfway = (async (input: string | URL | Request, init?: RequestInit) => {+ const answer = await p.fetcher(input, init);+ await Promise.resolve();+ if (!once) { once = true; p.state.wall = p.state.truth - 3_600_000; }+ return answer;+ }) as typeof fetch;+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: halfway, clocks: p.clocks, log: () => {}, set: (ms) => { partial.push(ms); return { ok: true }; } }).check();+ expect(partial).toHaveLength(1);+ expect(Math.abs(partial[0]! - p.state.truth)).toBeLessThanOrEqual(1_000);+ });++ it("an error larger than any suspend (two weeks) is not believed: nothing set, nothing let through on it", async () => {+ const w = world(), home = homeClock(w), set: number[] = [], lines: string[] = [];+ w.suspend(CLOCK_MAX_STEP_MS + 86_400_000);+ home.health.verify(w.sign());+ await home.clock.check();+ expect(home.kicks).toEqual([]);+ expect(home.clock.report().errorMs).toBeNull();+ expect(home.health.verify(w.sign())).toMatchObject({ ok: false, error: "stale_request" });+ expect(home.lines.at(-1)).toMatch(/more than any suspend; not believed/);+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } }).check();+ expect(set).toEqual([]);+ expect(lines.at(-1)).toMatch(/more than any suspend; not believed/);+ // Just under it: set.+ const near = world(), nearSet: number[] = [];+ near.suspend(CLOCK_MAX_STEP_MS - 3_600_000);+ await createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: true, fetch: near.fetcher, clocks: near.clocks, log: () => {}, set: (ms) => { nearSet.push(ms); return { ok: true }; } }).check();+ expect(nearSet).toHaveLength(1);+ });++ it("a machine that may not set its clock: told once, the measurement still reported", async () => {+ const w = world(), lines: string[] = [], set: number[] = [];+ w.suspend(SIX_HOURS);+ const keeper = createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: false, fetch: w.fetcher, clocks: w.clocks, log: (line) => lines.push(line), set: (ms) => { set.push(ms); return { ok: true }; } });+ await keeper.check();+ w.pass(120_000);+ await keeper.check();+ expect(set).toEqual([]);+ expect(lines).toEqual(["cloud home: the clock is 360 min behind and this machine can't set it (no CAP_SYS_TIME); a restart sets it"]);+ });++ it("measures at most once a minute, however often it is asked", async () => {+ const w = world(), home = homeClock(w);+ w.suspend(SIX_HOURS);+ for (let i = 0; i < 5; i += 1) home.health.verify(w.sign());+ await home.clock.check();+ for (let i = 0; i < 5; i += 1) home.health.verify(w.sign(undefined, START));+ await home.clock.check();+ expect(w.state.asked).toHaveLength(3);+ const keeper = createClockKeeper({ origins: [ADMIN, ACCOUNTS, RELAY], canSet: false, fetch: w.fetcher, clocks: w.clocks, log: () => {} });+ const pipe = new PassThrough();+ keeper.listen(pipe);+ pipe.write("check\ncheck\nsomething else\n2026-01-01\ncheck\n");+ await new Promise((resolve) => setImmediate(resolve));+ await keeper.check();+ expect(w.state.asked).toHaveLength(6);+ });+});++describe("after the clock is set forward six hours", () => {+ it("each routine runs once, its newest occurrence, and the ones before close on one counted row", () => {+ const hourly = { type: "interval" as const, everyMinutes: 60, anchorAt: START };+ const plan = planOccurrence({ schedule: hourly, nextRunAt: START + 60 * 60_000 }, START + SIX_HOURS + 30_000, true);+ expect(plan).toMatchObject({ scheduledFor: START + SIX_HOURS, count: 6, late: true });+ expect(plan.older).toMatchObject({ count: 5, scheduledFor: START + 60 * 60_000, fields: { status: "missed" } });+ const daily = planOccurrence({ schedule: { type: "cron", expression: "0 9 * * *", timeZone: "UTC" }, nextRunAt: Date.parse("2026-11-25T09:00:00Z") }, Date.parse("2026-11-25T14:00:00Z"), true);+ expect(daily).toMatchObject({ scheduledFor: Date.parse("2026-11-25T09:00:00Z"), count: 1, late: true });+ expect(daily.older).toBeUndefined();+ });+});++describe("the supervisor's side of the machine", () => {+ it("reads CAP_SYS_TIME from the effective set, and what the machine offers for time", () => {+ expect(hasEffectiveCapability("CapInh:\t0000000000000000\nCapEff:\t000001ffffffffff\n", 25)).toBe(true);+ expect(hasEffectiveCapability("CapEff:\t00000000a80425fb\n", 25)).toBe(false);+ const files: Record<string, string> = { "/sys/devices/system/clocksource/clocksource0/current_clocksource": "kvm-clock\n", "/proc/self/status": "CapEff:\t000001ffffffffff\n" };+ expect(clockFacts((path) => files[path] ?? "", (path) => path === "/dev/ptp0")).toEqual({ source: "kvm-clock", ptp: true, canSet: true });+ expect(clockFacts(() => "", () => false)).toEqual({ source: "unknown", ptp: false, canSet: false });+ });++ it("hands the server a pipe only through its own variable, taken out of the environment, and never a stray descriptor", () => {+ const env: NodeJS.ProcessEnv = { [CLOCK_FD_ENV]: "2" };+ expect(clockKicker(env)).toBeNull();+ expect(env[CLOCK_FD_ENV]).toBeUndefined();+ expect(clockKicker({})).toBeNull();+ });+});+diff --git a/server/cloud-clock.ts b/server/cloud-clock.tsnew file mode 100644index 0000000000..985ad85129--- /dev/null+++ b/server/cloud-clock.ts@@ -0,0 +1,222 @@+// A Cloud home's clock against the outside world (docs/cloud-pro.md, "The home's clock"). A provider that suspends a home+// and resumes it usually sets its clock on resume, and once in a while does not: the home then runs hours behind (Nov 2026:+// 6 h for 8+ h after a 6-hour suspend), the Admin's signed reads are refused as `stale_request` so it calls the Cloud down,+// and routines run hours late. Its wall clock and its monotonic clock both stopped while it was suspended, so it can't tell+// by itself; only the outside world can.+//+// The outside world here is the `Date` header of HTTPS answers from independent hosts (the Admin, the account service, a+// phone relay), read fresh each time. A signed request from the Admin whose timestamp is far from this clock is a reason to+// look, never a source: the amount always comes from two or more of those answers agreeing within CLOCK_AGREE_MS. So an+// old signed request replayed, one host with a wrong clock, or a proxy's cached answer moves nothing.+//+// Two processes use this module. The server (createCloudClock) measures when something looks off, reports the error in its+// health answer, judges the Admin's signed requests by the measured time while its clock is measured off, and asks the root+// supervisor to check (a payload-free "check" line on an inherited pipe, CLOCK_FD_ENV). The supervisor+// (server/cloud-clock-keeper.ts) measures again by itself and only then sets the system clock: nothing `maus` sends it is+// ever a time.+import { write } from "node:fs";+import { performance } from "node:perf_hooks";++/** Hosts this home reaches anyway and that keep their own clocks, besides its Admin: the account service and a phone relay. */+export const CLOCK_HOSTS = ["https://accounts.openmausbot.com", "https://relay1.openmausbot.com"] as const;+/** Errors smaller than this are left alone. Above cloud-power.ts's resume jump (20 s), so the server sees a step as a resume. */+export const CLOCK_STEP_MS = 30_000;+/** Answers must agree within this (each `Date` is whole seconds, and half the round trip is a guess). */+export const CLOCK_AGREE_MS = 3_000;+/** An answer slower than this says too little about when it was written. */+export const CLOCK_MAX_TRIP_MS = 4_000;+const CLOCK_TIMEOUT_MS = 5_000;+/** Measurements at most this often (each is one HEAD request per host). */+export const CLOCK_CHECK_GAP_MS = 60_000;+/** The most a measurement may move the clock: about the longest suspend a home could have had. A larger error is not believed+ * (a host's clock wrong, or something not a suspend), and the clock is left to a restart. A guest clock 20 to 34 days behind+ * can't measure at all anyway: the hosts' certificates are not valid yet for it (measured live Nov 26 2026). */+export const CLOCK_MAX_STEP_MS = 14 * 86_400_000;+/** A measurement is trusted this long on the monotonic clock, and never across a wake (the monotonic clock stops too). */+export const CLOCK_TRUST_MS = 10 * 60_000;+/** The supervisor's inherited pipe for "check" lines; only a Cloud home's supervisor sets it. */+export const CLOCK_FD_ENV = "OMB_CLOUD_CLOCK_FD";++export interface ClockClocks { wall(): number; mono(): number }+export const systemClocks: ClockClocks = { wall: () => Date.now(), mono: () => performance.now() };++/** One host's answer: how far its clock is ahead of this one (positive: this one is behind). */+export interface ClockReading { origin: string; offsetMs: number; tripMs: number }+export type ClockVerdict = { state: "agreed"; offsetMs: number; readings: ClockReading[] } | { state: "too-few" | "disagree"; readings: ClockReading[] };++/** The hosts to ask: this home's Admin first, then CLOCK_HOSTS, each host once. */+export function clockSources(adminOrigin: string, extra: readonly string[] = CLOCK_HOSTS): string[] {+ const seen = new Set<string>(), out: string[] = [];+ for (const origin of [adminOrigin, ...extra]) {+ let host: string;+ try { host = new URL(origin).host; } catch { continue; }+ if (seen.has(host)) continue;+ seen.add(host);+ out.push(new URL(origin).origin);+ }+ return out;+}++/** One HEAD request: null when it fails, is slow, has no usable `Date`, or came from a cache (`Age`). */+export async function readClock(origin: string, fetcher: typeof fetch, clocks: ClockClocks = systemClocks): Promise<ClockReading | null> {+ const sent = clocks.wall(), started = clocks.mono();+ let response: Response;+ try {+ response = await fetcher(`${origin}/`, { method: "HEAD", redirect: "manual", cache: "no-store", headers: { "cache-control": "no-cache" }, signal: AbortSignal.timeout(CLOCK_TIMEOUT_MS) });+ } catch { return null; }+ const tripMs = clocks.mono() - started;+ void response.body?.cancel().catch(() => {});+ const age = response.headers.get("age");+ if (age !== null && age.trim() !== "0") return null;+ const date = Date.parse(response.headers.get("date") ?? "");+ if (!Number.isFinite(date) || tripMs < 0 || tripMs > CLOCK_MAX_TRIP_MS) return null;+ // `Date` is the second it was written, rounded down: its middle, against this clock half way through the trip.+ return { origin, offsetMs: Math.round(date + 500 - (sent + tripMs / 2)), tripMs };+}++/**+ * Pure: the largest group of two or more answers all within CLOCK_AGREE_MS of each other gives the offset (its middle), so one+ * host with a wrong clock (or a slow answer) is outvoted rather than spoiling the rest. `required` (the home's Admin): the group+ * must hold its answer, so hosts that are not the Admin can never move the clock away from the Admin's time by themselves.+ * Two groups as large, or none: nothing. `readings` in the verdict: the group that agreed, else all of them.+ */+export function agree(readings: readonly ClockReading[], required?: string): ClockVerdict {+ const list = [...readings];+ if (list.length < 2) return { state: "too-few", readings: list };+ const sorted = [...list].sort((a, b) => a.offsetMs - b.offsetMs);+ let best: ClockReading[] = [], tie = false;+ for (let from = 0; from < sorted.length; from++) {+ let to = from;+ while (to + 1 < sorted.length && sorted[to + 1]!.offsetMs - sorted[from]!.offsetMs <= CLOCK_AGREE_MS) to++;+ const group = sorted.slice(from, to + 1);+ if (group.length < 2 || (required !== undefined && !group.some((reading) => reading.origin === required))) continue;+ if (group.length > best.length) { best = group; tie = false; }+ // Another group as large that is not just the same answers seen from a later start: they say different times.+ else if (group.length === best.length && !group.every((reading) => best.includes(reading))) tie = true;+ }+ if (best.length < 2 || tie) return { state: "disagree", readings: list };+ return { state: "agreed", offsetMs: Math.round((best[0]!.offsetMs + best[best.length - 1]!.offsetMs) / 2), readings: best };+}++/** `origins[0]` is the home's Admin (`clockSources`), whose answer any agreement must include. */+export async function measureClock(origins: readonly string[], fetcher: typeof fetch = fetch, clocks: ClockClocks = systemClocks): Promise<ClockVerdict> {+ const readings = await Promise.all(origins.map((origin) => readClock(origin, fetcher, clocks)));+ return agree(readings.filter((reading): reading is ClockReading => reading !== null), origins[0]);+}++/** What the health answer says about this clock (`clock`): its error when last measured and still trusted (positive: behind),+ * and when that was, in true time. Both null when nothing measured it lately. */+export interface CloudClockReport { v: 1; errorMs: number | null; measuredAt: number | null }++export interface CloudClockGate {+ /** A request with a valid signature carried this timestamp (seconds) far from this clock: measure. */+ noteSigned(timestampS: number): void;+ /** Whether a timestamp fits the measured true time (within the usual window), while this clock is measured CLOCK_STEP_MS or+ * more off; null while it is not (or nothing measured it lately), and the plain clock decides. */+ fits(timestampS: number): boolean | null;+}++/** The pipe to the supervisor (CLOCK_FD_ENV), taken out of the environment; null on any server it did not start. A write+ * never blocks the server (one at a time, asynchronous), and a failed one is dropped. */+export function clockKicker(env: NodeJS.ProcessEnv = process.env): (() => void) | null {+ const named = env[CLOCK_FD_ENV];+ if (named === undefined) return null;+ delete env[CLOCK_FD_ENV];+ const fd = Number(named);+ if (!Number.isInteger(fd) || fd < 3 || fd > 1024) return null;+ let pending = false, broken = false;+ return () => {+ if (pending || broken) return;+ pending = true;+ write(fd, "check\n", (error) => { pending = false; if (error) broken = true; });+ };+}++/**+ * The server's side. `check` measures (at most once per CLOCK_CHECK_GAP_MS, except right after a wake); an error of+ * CLOCK_STEP_MS or more behind asks the supervisor (`kick`) to set the clock. Ahead is reported and left alone: a suspend+ * only ever leaves a clock behind, and no measurement can move it backwards.+ */+export function createCloudClock(options: { origins: readonly string[]; fetch?: typeof fetch; clocks?: ClockClocks; kick?: (() => void) | null; log?: (line: string) => void; skewS: number }) {+ const clocks = options.clocks ?? systemClocks, fetcher = options.fetch ?? fetch;+ let trusted: { offsetMs: number; wall: number; mono: number } | null = null;+ let checking: Promise<void> | null = null, checkedAt = -Infinity, logged = "";+ const note = (line: string) => { if (line !== logged) { logged = line; options.log?.(line); } };++ /** The error now: the measured one, less whatever the wall clock moved beyond the monotonic clock since (a step corrects it). */+ const errorNow = (): number | null => {+ if (!trusted) return null;+ const monoSince = clocks.mono() - trusted.mono;+ if (monoSince < 0 || monoSince > CLOCK_TRUST_MS) return null;+ return Math.round(trusted.offsetMs - ((clocks.wall() - trusted.wall) - monoSince));+ };+ const run = async () => {+ checkedAt = clocks.mono();+ const verdict = await measureClock(options.origins, fetcher, clocks);+ if (verdict.state !== "agreed") {+ note(`cloud clock: not measured (${verdict.state === "disagree" ? "the hosts disagree" : "too few hosts answered"}); left as it is`);+ return;+ }+ const minutes = Math.round(Math.abs(verdict.offsetMs) / 60_000);+ if (Math.abs(verdict.offsetMs) > CLOCK_MAX_STEP_MS) {+ trusted = null;+ note(`cloud clock: ${minutes} min off, more than any suspend; not believed, left as it is (a restart sets it)`);+ return;+ }+ trusted = { offsetMs: verdict.offsetMs, wall: clocks.wall(), mono: clocks.mono() };+ if (verdict.offsetMs >= CLOCK_STEP_MS) {+ note(`cloud clock: ${minutes} min behind (${verdict.readings.length} hosts agree); asking the supervisor to set it`);+ options.kick?.();+ } else if (verdict.offsetMs <= -CLOCK_STEP_MS) note(`cloud clock: ${minutes} min ahead (${verdict.readings.length} hosts agree); left as it is`);+ else note("cloud clock: right");+ };+ const check = (force = false): Promise<void> => {+ if (checking) return checking;+ if (!force && clocks.mono() - checkedAt < CLOCK_CHECK_GAP_MS) return Promise.resolve();+ checking = run().catch(() => {}).finally(() => { checking = null; });+ return checking;+ };++ return {+ check,+ /** It woke (a resume, a boot from sleep, or the clock stepped): the monotonic clock stopped meanwhile, so the last+ * measurement no longer holds; measure again now. */+ woke() { trusted = null; void check(true); },+ /** The measurement in progress, if any. */+ settled(): Promise<void> { return checking ?? Promise.resolve(); },+ noteSigned(timestampS: number) {+ if (Math.abs(timestampS * 1000 - clocks.wall()) >= CLOCK_STEP_MS) void check();+ },+ fits(timestampS: number): boolean | null {+ const error = errorNow();+ if (error === null || Math.abs(error) < CLOCK_STEP_MS) return null;+ return Math.abs(timestampS * 1000 - (clocks.wall() + error)) <= options.skewS * 1000;+ },+ report(): CloudClockReport {+ const error = errorNow();+ return { v: 1, errorMs: error, measuredAt: error === null || !trusted ? null : trusted.wall + trusted.offsetMs };+ },+ };+}+export type CloudClock = ReturnType<typeof createCloudClock>;++/** The running home's clock watch, for cloud-power.ts's wake path and the home's own signed calls; null on any server that is+ * not a Cloud home. */+let registered: Pick<CloudClock, "woke" | "report" | "settled"> | null = null;+export function registerCloudClock(clock: Pick<CloudClock, "woke" | "report" | "settled"> | null) { registered = clock; }+export function cloudClockWoke() { registered?.woke(); }+/** Resolves once a measurement in progress is done (at once when none is), so a call signed right after a wake can use it. */+export function cloudClockSettled(): Promise<void> { return registered?.settled() ?? Promise.resolve(); }++/**+ * The time a home signs its own calls to the Admin with (phone notifications, the wake notice, Pages, Slack, team rules and the+ * roster): this clock, or the true time when a fresh measurement says this clock is CLOCK_STEP_MS or more off (the supervisor+ * has not set it yet, or can't). The Admin judges those timestamps by its own clock, so a home left behind would otherwise lose+ * them all, silently, until the clock is right.+ */+export function cloudSigningTime(at: number = Date.now()): number {+ const error = registered?.report().errorMs ?? null;+ return error !== null && Math.abs(error) >= CLOCK_STEP_MS ? at + error : at;+}+/** `cloudSigningTime` as the whole seconds a signed request's timestamp carries. */+export function cloudSignedTimestamp(at: number = Date.now()): string { return String(Math.floor(cloudSigningTime(at) / 1000)); }diff --git a/server/cloud-diagnose.test.ts b/server/cloud-diagnose.test.tsindex a1fd9418a6..5094e6a60b 100644--- a/server/cloud-diagnose.test.ts+++ b/server/cloud-diagnose.test.ts@@ -139,14 +139,14 @@ describe("the diagnose walk's budget", () => {});describe("GET /api/cloud/diagnose", () => {- function routes() {+ function routes(clock?: Parameters<typeof createCloudSignedRoutes>[0]["clock"]) {const { home, data } = homeFixture();let counter = 0;const now = () => T0;const diagnose = createCloudDiagnose({ health: health(data, now), storage: () => null, dataDir: data, home, now, uptimeS: () => ({ process: 1, machine: 2 }) });- const handle = createCloudSignedRoutes({ secret, sessions: new SessionRegistry({ file: join(data, "sessions.json"), now }), health: health(data, now), diagnose, now });- const sign = (method = "GET", key = secret) => {- const timestamp = String(Math.floor(now() / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;+ const handle = createCloudSignedRoutes({ secret, sessions: new SessionRegistry({ file: join(data, "sessions.json"), now }), health: health(data, now), diagnose, now, ...(clock ? { clock } : {}) });+ const sign = (method = "GET", key = secret, at = now()) => {+ const timestamp = String(Math.floor(at / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;return { "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudRequestSignature(key, timestamp, nonce, method, CLOUD_DIAGNOSE_PATH, "")}` };};const send = async (method: string, headers: Record<string, string>) => {@@ -171,6 +171,16 @@ describe("GET /api/cloud/diagnose", () => {expect((await send("POST", sign("POST"))).status).toBe(405);});+ it("answers the Admin while a resume left this clock behind: judged by the measured time, as health and power reads are", async () => {+ // The home measured itself 40 minutes behind (server/cloud-clock.ts); the Admin signs with the true time.+ const BEHIND = 40 * 60_000;+ const clock = { noteSigned() {}, fits: (timestampS: number) => Math.abs(timestampS * 1000 - (T0 + BEHIND)) <= 300_000, report: () => ({ v: 1 as const, errorMs: BEHIND, measuredAt: T0 + BEHIND }) };+ const { sign, send } = routes(clock);+ expect(await send("GET", sign("GET", secret, T0 + BEHIND))).toMatchObject({ answered: true, status: 200 });+ // One signed for the wrong clock is refused now that the true time is known, and says by how much.+ expect(await send("GET", sign("GET", secret, T0))).toMatchObject({ status: 401, body: { error: "stale_request", clockErrorMs: BEHIND } });+ });+it("is not a route on a server with no diagnose", async () => {const data = tempDir();const handle = createCloudSignedRoutes({ secret, sessions: new SessionRegistry({ file: join(data, "sessions.json") }), health: health(data, Date.now) });diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex aa8fba180f..b2c4a263a9 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -5,6 +5,7 @@import { spawn, spawnSync, type ChildProcess } from "node:child_process";import { chmodSync, chownSync, closeSync, existsSync, lstatSync, openSync, readFileSync, realpathSync, statSync, type Stats } from "node:fs";import { isIP } from "node:net";+import { Readable } from "node:stream";import { dirname, join, posix, resolve } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import {@@ -14,6 +15,8 @@ import {import { procHidepid } from "./bot-box/hidepid.ts";import { boxMemory, heapSizeArgs } from "./box-memory.ts";import { BROWSER_CGROUP_ENV, prepareBrowserCgroup, spawnInCgroup } from "./browser/memory-cgroup.ts";+import { CLOCK_FD_ENV } from "./cloud-clock.ts";+import { startClockKeeper } from "./cloud-clock-keeper.ts";import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";import { OOM_SCORE, protectInit, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";import { restartLine, restartPolicy } from "./restart.ts";@@ -395,11 +398,16 @@ export function codeTrustProblem(files: readonly string[], home: string, stat: (return null;}-/** Secrets go over an inherited pipe, never the environment; it is written and closed at once. */+/** The server's "check the clock" pipe (server/cloud-clock.ts), when the supervisor keeps the clock. */+const CLOCK_FD = 4;++/** Secrets go over an inherited pipe, never the environment; it is written and closed at once. `clockPipe`: one more pipe,+ * the child's descriptor 4, that the child writes "check" lines to (server/cloud-clock-keeper.ts reads them). */export function spawnWithSecrets(command: string, args: string[], env: NodeJS.ProcessEnv, secrets: Record<string, string>,- ids?: { uid: number; gid: number } | null, capture = false): ChildProcess {- const child = spawn(command, args, { env,- stdio: capture ? ["inherit", "pipe", "pipe", "pipe"] : ["inherit", "inherit", "inherit", "pipe"],+ ids?: { uid: number; gid: number } | null, capture = false, clockPipe = false): ChildProcess {+ const stdio: ("inherit" | "pipe")[] = capture ? ["inherit", "pipe", "pipe", "pipe"] : ["inherit", "inherit", "inherit", "pipe"];+ if (clockPipe) stdio.push("pipe");+ const child = spawn(command, args, { env: clockPipe ? { ...env, [CLOCK_FD_ENV]: String(CLOCK_FD) } : env, stdio,...(ids ? { uid: ids.uid, gid: ids.gid } : {}) });const pipe = child.stdio[SECRETS_FD] as NodeJS.WritableStream | null;pipe?.on("error", () => {});@@ -485,10 +493,17 @@ export function startCloudHome(processEnv: NodeJS.ProcessEnv = process.env) {if (!again?.(code, signal)) stop(true);});};+ // The clock (server/cloud-clock-keeper.ts): root keeps it right after a resume the provider left it behind on. Root only.+ const keeper = ids && process.platform === "linux" ? startClockKeeper(config.adminOrigin) : null;const policy = restartPolicy();const runServer = () => {if (stopping) return;- watch(inServerGroup(() => spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids))), (code, signal) => {+ watch(inServerGroup(() => spawnWithOomScore(OOM_SCORE.server, () => {+ const child = spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids, false, Boolean(keeper));+ const pipe = child.stdio[CLOCK_FD];+ if (keeper && pipe instanceof Readable) keeper.listen(pipe);+ return child;+ })), (code, signal) => {if (!policy.again(code, stopping, signal)) return false;console.warn(`cloud home: ${restartLine(code, policy.delayMs())}`);if (policy.delayMs() > 0) restartTimer = setTimeout(runServer, policy.delayMs());diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex 7104a7a0a7..c94deffff3 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -667,6 +667,34 @@ writeFileSync(${JSON.stringify(out)}, JSON.stringify({ secrets, env: process.env}});+// The supervisor runs on Linux only; Windows has no inherited descriptor 4 to write to.+it.skipIf(process.platform === "win32")("gives the server a pipe to the supervisor's clock keeper only when asked, which carries its kicker's check line", async () => {+ const dir = directory();+ const script = join(dir, "kick.mjs");+ writeFileSync(script, `+const { clockKicker, CLOCK_FD_ENV } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, "cloud-clock.ts")).href)});+const named = process.env[CLOCK_FD_ENV] ?? "none";+const kick = clockKicker();+kick?.(); kick?.();+process.stdout.write(named + " " + String(process.env[CLOCK_FD_ENV]));+setTimeout(() => {}, 200);+`);+ const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) };+ const run = async (clockPipe: boolean) => {+ const child = spawnWithSecrets(process.execPath, [script], env, { OMB_CLOUD_BOOTSTRAP_SECRET: secret }, undefined, true, clockPipe);+ let out = "", kicked = "";+ child.stdout?.on("data", (chunk) => { out += chunk; });+ (child.stdio[4] as NodeJS.ReadableStream | undefined)?.on("data", (chunk) => { kicked += chunk; });+ await new Promise((resolve) => child.once("close", resolve));+ return { out, kicked, fds: child.stdio.length };+ };+ const piped = await run(true);+ expect(piped.out).toBe("4 undefined");+ expect(piped.kicked).toBe("check\n");+ const plain = await run(false);+ expect(plain).toEqual({ out: "none undefined", kicked: "", fds: 4 });+});+it("captures a child's stdout and stderr when asked, and shares this process's otherwise", async () => {const dir = directory();const script = join(dir, "streams.mjs");diff --git a/server/cloud-home.ts b/server/cloud-home.tsindex 83e6a4ff34..9d1e0870af 100644--- a/server/cloud-home.ts+++ b/server/cloud-home.ts@@ -7,8 +7,10 @@ import { createHash, createHmac, timingSafeEqual } from "node:crypto";import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync } from "node:fs";import type { IncomingMessage } from "node:http";import { join } from "node:path";+import { performance } from "node:perf_hooks";import type { Surface } from "../shared/wire.ts";import { writeFileAtomic } from "./atomic.ts";+import type { CloudClockGate } from "./cloud-clock.ts";import { hostedWorkspaceConfigured } from "./enterprise.ts";import { parseMemberClaim, teamMemberEmail, teamRoleScopes, type CloudTeam } from "./cloud-team.ts";import { isLoopbackHost } from "./request-auth.ts";@@ -156,9 +158,21 @@ export function cloudPairingSignature(secret: string, timestamp: string, nonce:export type CloudRequestRefusal = "invalid_signature" | "stale_request" | "replayed_request" | "busy";export type CloudRequestVerdict = { ok: true } | { ok: false; status: 401 | 503; error: CloudRequestRefusal };-/** One route's verifier, with its own used nonces. Signature first (constant time), then clock and nonce. Nothing is logged. */-export function createCloudRequestVerifier(options: { secret: string; now?: () => number }) {+/**+ * One route's verifier, with its own used nonces. Signature first (constant time), then clock and nonce. Nothing is logged.+ *+ * `clock` (server/cloud-clock.ts): a valid signature whose timestamp is far from this clock makes the home measure its clock+ * (the timestamp itself is never taken as the time). While a measurement says this clock is off, a timestamp must also fit+ * the measured true time, so a request signed hours ago that only fits the wrong clock is refused. `tolerant`, for the+ * Admin's read-only health and power reads only: then fitting the measured true time is enough, so the Admin can still read+ * a home whose clock a resume left behind. Pairing and anything that changes the home never are.+ *+ * Nonces expire on the monotonic clock (`mono`), so a clock set forward never forgets one early. A verifier given only a+ * `now` (tests) uses it for both.+ */+export function createCloudRequestVerifier(options: { secret: string; now?: () => number; mono?: () => number; clock?: CloudClockGate | null; tolerant?: boolean }) {const now = options.now ?? Date.now;+ const mono = options.mono ?? options.now ?? (() => performance.now());const nonces = new Map<string, number>();return {verify(input: { timestamp: string | undefined; nonce: string | undefined; signature: string | undefined; method: string; target: string; body: Buffer | string }): CloudRequestVerdict {@@ -168,12 +182,15 @@ export function createCloudRequestVerifier(options: { secret: string; now?: () =const given = presented ? Buffer.from(presented, "base64url") : Buffer.alloc(expected.length);const matches = given.length === expected.length && timingSafeEqual(given, expected);if (!presented || !matches || !/^\d{1,12}$/.test(timestamp) || !/^[A-Za-z0-9_-]{16,128}$/.test(nonce)) return { ok: false, status: 401, error: "invalid_signature" };- const at = now();- if (Math.abs(at / 1000 - Number(timestamp)) > CLOUD_PAIRING_SKEW_S) return { ok: false, status: 401, error: "stale_request" };- for (const [seen, until] of nonces) if (until <= at) nonces.delete(seen);+ const at = now(), seconds = Number(timestamp);+ options.clock?.noteSigned(seconds);+ const local = Math.abs(at / 1000 - seconds) <= CLOUD_PAIRING_SKEW_S, measured = options.clock?.fits(seconds) ?? null;+ if (!(measured === null ? local : options.tolerant ? measured : local && measured)) return { ok: false, status: 401, error: "stale_request" };+ const tick = mono();+ for (const [seen, until] of nonces) if (until <= tick) nonces.delete(seen);if (nonces.has(nonce)) return { ok: false, status: 401, error: "replayed_request" };if (nonces.size >= MAX_NONCES) return { ok: false, status: 503, error: "busy" };- nonces.set(nonce, at + CLOUD_PAIRING_NONCE_MS);+ nonces.set(nonce, tick + CLOUD_PAIRING_NONCE_MS);return { ok: true };},};@@ -196,6 +213,8 @@ export function createCloudPairing(options: {memberBrowserOff?: () => boolean;/** The claim's `member.invitedBy` (additive): who invited this member, for their welcome (team-welcome.ts). */invited?: (member: string, by: string) => void;+ /** The home's clock watch (server/cloud-clock.ts): a pairing far from this clock makes it measure; never tolerant. */+ clock?: CloudClockGate | null;now?: () => number;}) {const { sessions } = options;diff --git a/server/cloud-power.ts b/server/cloud-power.tsindex add547ecc8..d6be7912c4 100644--- a/server/cloud-power.ts+++ b/server/cloud-power.ts@@ -9,6 +9,7 @@ import { readFileSync, rmSync } from "node:fs";import type { IncomingHttpHeaders, ServerResponse } from "node:http";import { join } from "node:path";import { writeFileAtomic } from "./atomic.ts";+import { cloudClockWoke } from "./cloud-clock.ts";/** Why a home is not idle, as fixed codes (the Admin keeps the latest one for its operator page). */export type CloudPowerBusy = "turn" | "run" | "handoff" | "live-call" | "computer" | "maintenance" | "recent-activity" | "recent-work" | "just-woke" | "due-soon";@@ -121,7 +122,11 @@ export function createCloudPower(options: {let wokeAt = bootedAt, lastActivityAt: number | null = null, lastWorkAt: number | null = null;/** The last wake from sleep; null while this process has only ever booted normally. */let sleptUntil: number | null = options.bootedFromSleep ? bootedAt : null;- if (options.bootedFromSleep) options.onWoke?.();+ /** A wake: the Admin hears (`onWoke`), and the home's clock is measured again (server/cloud-clock.ts): a resume may have left it+ * behind, and a clock the supervisor just set forward is a jump like a resume's. */+ // The clock first: its measurement is what the wake notice waits for before it is signed (cloud-woke.ts).+ const woke = () => { cloudClockWoke(); options.onWoke?.(); };+ if (options.bootedFromSleep) woke();/** The first request since `wokeAt` (`arrived`), and whether one came. */let wokeBy: CloudPowerReport["wokeBy"] = null, wokeSeen = false, bootWake = Boolean(options.bootedFromSleep);let sleepingSince: number | null = null, inFlight = 0;@@ -160,7 +165,7 @@ export function createCloudPower(options: {bootWake = false;sleptUntil = at;endSleep();- options.onWoke?.();+ woke();};/** Samples work (so "finished two minutes ago" needs no hook in every kind of work) and notices a resume. */const tick = () => {diff --git a/server/cloud-team-policy.ts b/server/cloud-team-policy.tsindex 7d4e45282b..7ea5fe273f 100644--- a/server/cloud-team-policy.ts+++ b/server/cloud-team-policy.ts@@ -16,6 +16,7 @@ import type { ManagedDesktopPolicy, ManagedPolicy } from "./managed-policy.ts";import { CLI_LOGIN_PATH } from "../shared/cli-login.ts";import { TEAM_PHONE_PAIRING_PATH } from "./routes/team-phone.ts";import type { SessionRegistry } from "./sessions.ts";+import { cloudSignedTimestamp } from "./cloud-clock.ts";export const TEAM_POLICY_SCHEMA = 1;/** On the Admin; must match openmaus-cloud's TEAM_POLICY_MACHINE_PATH. */@@ -176,7 +177,7 @@ export function startTeamPolicyClient(options: TeamPolicyClientOptions): TeamPol/** One signed ask, which also reports what is in force here. A failure changes nothing: what is held stays. */const ask = async (): Promise<void> => {const body = JSON.stringify({ v: 1, loaded: held ? { fingerprint: held.fingerprint, version: held.version } : null, problem });- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");let response: Response;try {response = await fetcher(`${options.adminOrigin}${TEAM_POLICY_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {diff --git a/server/cloud-team-roster.ts b/server/cloud-team-roster.tsindex c8e0719bab..4ab0fd5db6 100644--- a/server/cloud-team-roster.ts+++ b/server/cloud-team-roster.ts@@ -10,6 +10,7 @@ import { z } from "zod";import type { CloudHomeConfig } from "./cloud-home.ts";import { isTeamRole } from "./cloud-team.ts";import type { SessionRegistry } from "./sessions.ts";+import { cloudSignedTimestamp } from "./cloud-clock.ts";/** On the Admin; must match openmaus-cloud's TEAM_ROSTER_MACHINE_PATH. */export const TEAM_ROSTER_ADMIN_PATH = "/api/cloud/machines/team-member";@@ -58,7 +59,7 @@ export function startTeamRoster(options: TeamRosterOptions): TeamRoster {const emails = options.sessions.membersToVouch(TEAM_ROSTER_MAX);if (!emails.length) return;const body = JSON.stringify({ v: 1, emails });- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");let response: Response;try {response = await fetcher(`${options.adminOrigin}${TEAM_ROSTER_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {diff --git a/server/cloud-woke.ts b/server/cloud-woke.tsindex d48130aee2..10d0fb3c0b 100644--- a/server/cloud-woke.ts+++ b/server/cloud-woke.ts@@ -3,6 +3,7 @@// of this home: a desktop that lends to it stops calling while it sleeps. docs/cloud-pro.md, "Sleeping homes". An older// Admin answers 404 and nothing changes; this never retries.import { createHash, createHmac, randomBytes } from "node:crypto";+import { cloudClockSettled, cloudSignedTimestamp } from "./cloud-clock.ts";export const WOKE_ADMIN_PATH = "/api/cloud/machines/woke";const WOKE_TIMEOUT_MS = 5_000;@@ -19,11 +20,14 @@ export function createWokeNotifier(options: {let warned = false;return () => {const body = JSON.stringify({ v: 1, wokeAt: now() });- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");- void fetcher(`${adminOrigin}${WOKE_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(WOKE_TIMEOUT_MS), headers: {- accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,- "x-omb-cloud-signature": `v1=${wokeSignature(secret, machineId, timestamp, nonce, body)}`,- } }).then(async (response) => {+ // A wake starts a measurement of the clock (cloud-clock.ts): signed once it is done, with the true time if this clock is off.+ void cloudClockSettled().then(() => {+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");+ return fetcher(`${adminOrigin}${WOKE_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(WOKE_TIMEOUT_MS), headers: {+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${wokeSignature(secret, machineId, timestamp, nonce, body)}`,+ } });+ }).then(async (response) => {await response.body?.cancel().catch(() => {});if (!response.ok && response.status !== 404 && !warned) { warned = true; log?.(`cloud power: the Admin answered HTTP ${response.status} to the wake notice`); }}, (error: unknown) => {diff --git a/server/devs-report-send.ts b/server/devs-report-send.tsindex 2eb78094dc..26db82de55 100644--- a/server/devs-report-send.ts+++ b/server/devs-report-send.ts@@ -6,6 +6,7 @@ import { createHash, createHmac, randomBytes } from "node:crypto";import { z } from "zod";import { DEVS_REPORT_LIMITS, withoutContact, type DevsReportPayload } from "./devs-report.ts";+import { cloudSignedTimestamp } from "./cloud-clock.ts";export const BUG_REPORT_PATH = "/api/bug-reports";export const PRODUCTION_CLOUD_ORIGIN = "https://cloud.openmausbot.com";@@ -123,7 +124,7 @@ export const bugReportStatusEndpoint = (reportEndpoint: string): string => new Uexport async function askReportStatus(endpoint: string, question: ReportStatusQuestion, home: ReportStatusHome | null, fetcher: typeof fetch = fetch,now = Date.now): Promise<ReportStatusAnswer | null> {const body = JSON.stringify({ installId: question.installId, ids: question.ids.slice(0, BUG_REPORT_STATUS_MAX_IDS) });- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");const signed: Record<string, string> = home ? { "x-omb-cloud-machine": home.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,"x-omb-cloud-signature": `v1=${bugReportsHomeSignature(home.bootstrapSecret, home.machineId, timestamp, nonce, body)}` } : {};try {diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex 9a10769744..300b8428bd 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -4,7 +4,8 @@import type { BoxReport } from "../bot-box/box.ts";import { createCloudDiagnose } from "../cloud-diagnose.ts";import { createCloudHealth, type CloudHealth, type CloudHealthDeps } from "../cloud-health.ts";-import type { CloudHomeConfig } from "../cloud-home.ts";+import { clockKicker, clockSources, createCloudClock, registerCloudClock, type CloudClock } from "../cloud-clock.ts";+import { CLOUD_PAIRING_SKEW_S, type CloudHomeConfig } from "../cloud-home.ts";import type { CloudPower } from "../cloud-power.ts";import { createStorageHistory } from "../perf/storage-history.ts";import { createCloudSignedRoutes } from "../routes/cloud-signed.ts";@@ -32,6 +33,8 @@ export interface CloudSignedHostDeps {plan?: (cancelled: boolean) => void;/** Which plan this Cloud is on now (the Admin's signed request). */planTier?: (tier: string) => void;+ /** Tests: the clock watch to use instead of the home's own (which measures over the network and is registered for wakes). */+ clock?: CloudClock;}export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth: CloudHealth | null; cloudSigned: ReturnType<typeof createCloudSignedRoutes> | null } {@@ -41,8 +44,11 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:const health = storage && history ? { ...deps.health, storage: () => { const report = storage(); try { history.note(report); } catch {} return report; } } : deps.health;const cloudHealth = deps.cloudHome ? createCloudHealth({ ...health, box: deps.box }) : null;const diagnose = cloudHealth ? createCloudDiagnose({ health: cloudHealth, storage: storage ?? (() => null), history, dataDir: deps.health.dataDir, ...(process.env.HOME ? { home: process.env.HOME } : {}) }) : null;+ // The home's clock against its Admin and two hosts of its own (server/cloud-clock.ts); wakes reach it through cloud-power.ts.+ const clock = deps.cloudHome ? deps.clock ?? createCloudClock({ origins: clockSources(deps.cloudHome.adminOrigin), kick: clockKicker(), log: (line) => console.warn(line), skewS: CLOUD_PAIRING_SKEW_S }) : null;+ if (clock && !deps.clock) registerCloudClock(clock);const cloudSigned = deps.cloudHome && cloudHealth- ? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,+ ? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box, clock,...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}), ...(deps.cloudHome.team && deps.invited ? { invited: deps.invited } : {}), ...(deps.cloudHome.team && deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}),...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}), diagnose }): null;diff --git a/server/host/team-away.ts b/server/host/team-away.tsindex beb603b953..45861d2ed1 100644--- a/server/host/team-away.ts+++ b/server/host/team-away.ts@@ -13,6 +13,7 @@ import { personKey } from "../person-key.ts";import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "../routes/table.ts";import type { SessionRecord } from "../sessions.ts";+import { cloudSignedTimestamp } from "../cloud-clock.ts";/** On the Admin; must match openmaus-cloud's TEAM_AWAY_MACHINE_PATH. */export const TEAM_AWAY_ADMIN_PATH = "/api/cloud/machines/team-away";@@ -209,7 +210,7 @@ export function createTeamAway(deps: TeamAwayDeps) {const signedPost = async (request: AwayRequest): Promise<{ status: number; answer: z.infer<typeof answerSchema> | null }> => {const body = JSON.stringify(request);- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");const response = await fetcher(`${deps.adminOrigin}${TEAM_AWAY_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": deps.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,"x-omb-cloud-signature": `v1=${teamAwaySignature(deps.secret, deps.machineId, timestamp, nonce, body)}`,diff --git a/server/host/unattended-turns.ts b/server/host/unattended-turns.tsindex 99ca50e9d2..508d907b21 100644--- a/server/host/unattended-turns.ts+++ b/server/host/unattended-turns.ts@@ -88,7 +88,8 @@ function over(turn: Counted, limits: UnattendedLimits): Stop | undefined {}export function createUnattendedTurns(deps: UnattendedTurnDeps): UnattendedTurns {- const now = deps.now ?? Date.now;+ // Monotonic: a clock set forward (server/cloud-clock-keeper.ts) or a computer asleep is not time a turn worked.+ const now = deps.now ?? (() => performance.now());const limits = deps.limits ?? (() => unattendedLimits());const loops = createLoopGuard({ ...deps, settings: (threadId) => deps.settings(deps.unattended(threadId)) });const turns = new Map<string, Counted>();diff --git a/server/pages/access.ts b/server/pages/access.tsindex 9db327aa0b..e2c97f3945 100644--- a/server/pages/access.ts+++ b/server/pages/access.ts@@ -4,6 +4,7 @@// a desktop's main process fetches its sign-in's own pages token and hands it over on the private parent port.// Neither is ever written to config, sent to a client, or given to an engine. No Cloudflare credential is held here.import { createHash, createHmac, randomBytes } from "node:crypto";+import { cloudSignedTimestamp } from "../cloud-clock.ts";export const PAGES_TOKEN_PATH = "/api/cloud/pages/token";const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);@@ -22,7 +23,7 @@ export function pagesHomeSignature(secret: string, machineId: string, timestamp:/** The headers that prove a request to an Admin route comes from this account. */export function pagesAuthHeaders(access: PagesAccess, body: string, now = Date.now(), label = "omb-pages-v1"): Record<string, string> {if (access.kind === "desktop") return { authorization: `Bearer ${access.token}` };- const timestamp = String(Math.floor(now / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now), nonce = randomBytes(18).toString("base64url");return {"x-omb-cloud-machine": access.machineId,"x-omb-cloud-timestamp": timestamp,diff --git a/server/phone-push-admin.ts b/server/phone-push-admin.tsindex 816e99fa50..d4a3a0e6b1 100644--- a/server/phone-push-admin.ts+++ b/server/phone-push-admin.ts@@ -6,6 +6,7 @@import { createHash, createHmac, randomBytes } from "node:crypto";import { PHONE_ACTIVITY_RELAY_PATH, PHONE_PUSH_RELAY_PATHS } from "../shared/phone-push.ts";+import { cloudSignedTimestamp } from "./cloud-clock.ts";/** What a Cloud home signs with: its Admin, its machine id and its bootstrap secret (server/cloud-home.ts). */export interface CloudHomePushAccess {@@ -42,7 +43,7 @@ export function cloudHomePushRequest(access: CloudHomePushAccess, path: string,const action = CLOUD_HOME_PUSH_ACTIONS[path];if (!action) return null;const raw = JSON.stringify(body);- const timestamp = String(Math.floor(now / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now), nonce = randomBytes(18).toString("base64url");return {url: `${access.admin}${CLOUD_HOME_PUSH_ADMIN_PATH}${action}`,init: {diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex d444015213..ec52fd0c5a 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -7,6 +7,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";import type { BoxReport } from "../bot-box/box.ts";import { boxSummary } from "../cloud-health.ts";import { CLOUD_DIAGNOSE_PATH, type CloudDiagnose } from "../cloud-diagnose.ts";+import type { CloudClockGate, CloudClockReport } from "../cloud-clock.ts";import { CLOUD_HEALTH_PATH, CLOUD_PAIRING_PATH, createCloudPairing, createCloudRequestVerifier, readSignedBody } from "../cloud-home.ts";import { teamMemberEmail, type CloudTeam } from "../cloud-team.ts";import { CLOUD_TEAM_ADMIN_PATH, type TeamAdminSummary } from "../cloud-team-admin.ts";@@ -54,20 +55,30 @@ export function createCloudSignedRoutes(deps: {plan?: ((cancelled: boolean) => void) | null;/** Which plan this Cloud is on now; absent on a server that is not a Cloud home. */planTier?: ((tier: string) => void) | null;+ /** The home's clock watch (server/cloud-clock.ts); absent on a server that is not a Cloud home. */+ clock?: (CloudClockGate & { report(): CloudClockReport }) | null;/** The diagnose read (cloud-diagnose.ts); absent on a server that is not a Cloud home. */diagnose?: Pick<CloudDiagnose, "read"> | null;now?: () => number;}) {- const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, ...(deps.invited ? { invited: deps.invited } : {}), ...(deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}), now: deps.now });- const healthRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const powerReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const sleepRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const boxReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const teamAdminReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const memberLeftRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const planRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const policyNudges = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });- const diagnoseReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });+ const clock = deps.clock ?? null;+ const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, ...(deps.invited ? { invited: deps.invited } : {}), ...(deps.memberBrowserOff ? { memberBrowserOff: deps.memberBrowserOff } : {}), clock, now: deps.now });+ // Only the read-only reads the Admin manages a home by (health, power, and the diagnose read it sends when one looks wrong)+ // are tolerant of a clock measured behind (cloud-home.ts).+ const healthRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock, tolerant: true });+ const powerReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock, tolerant: true });+ const sleepRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const boxReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const teamAdminReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const memberLeftRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const planRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const policyNudges = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock });+ const diagnoseReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now, clock, tolerant: true });+ /** A refusal's body; a stale one also says this clock's measured error, when known, so the Admin can tell a clock from an attack. */+ const refusal = (error: string) => {+ const measured = error === "stale_request" ? clock?.report().errorMs ?? null : null;+ return measured === null ? { error } : { error, clockErrorMs: measured };+ };/** True when the request was one of these and has been answered. */return async ({ req, res, url, path, method }: CloudSignedRequest): Promise<boolean> => {const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;@@ -84,7 +95,7 @@ export function createCloudSignedRoutes(deps: {if (power && path === CLOUD_POWER_PATH) {if (method !== "GET") { json(res, 405, { error: "method_not_allowed" }); return true; }const verdict = powerReads.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });- if (!verdict.ok) { console.warn(`cloud power read refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }+ if (!verdict.ok) { console.warn(`cloud power read refused from ${source}: ${verdict.error}`); json(res, verdict.status, refusal(verdict.error)); return true; }const minutes = url.searchParams.get("idleMinutes");const window = minutes !== null && /^\d{1,4}$/.test(minutes) && Number(minutes) >= 1 && Number(minutes) <= 24 * 60 ? Number(minutes) * 60_000 : CLOUD_IDLE_ACTIVITY_MS;json(res, 200, power.report(window));@@ -151,7 +162,7 @@ export function createCloudSignedRoutes(deps: {if (diagnose) {if (method !== "GET") { json(res, 405, { error: "method_not_allowed" }); return true; }const verdict = diagnoseReads.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });- if (!verdict.ok) { console.warn(`cloud diagnose read refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }+ if (!verdict.ok) { console.warn(`cloud diagnose read refused from ${source}: ${verdict.error}`); json(res, verdict.status, refusal(verdict.error)); return true; }json(res, 200, await diagnose.read());return true;}@@ -167,10 +178,11 @@ export function createCloudSignedRoutes(deps: {const verdict = healthRequests.verify({ ...signed, method, target: `${path}${url.search}`, body: "" });if (!verdict.ok) {console.warn(`cloud health refused from ${source}: ${verdict.error}`);- json(res, verdict.status, { error: verdict.error });+ json(res, verdict.status, refusal(verdict.error));return true;}- json(res, 200, deps.health.report(url.searchParams.get("after")));+ const report = deps.health.report(url.searchParams.get("after"));+ json(res, 200, clock ? { ...report, clock: clock.report() } : report);return true;}if (method !== "POST") { json(res, 405, { error: "method_not_allowed" }); return true; }diff --git a/server/team-slack.ts b/server/team-slack.tsindex c8649f8bc0..6ec153399e 100644--- a/server/team-slack.ts+++ b/server/team-slack.ts@@ -11,6 +11,7 @@ import { join } from "node:path";import { z } from "zod";import { writeFileAtomic } from "./atomic.ts";+import { cloudSignedTimestamp } from "./cloud-clock.ts";/** On the Admin; must match openmaus-cloud's TEAM_SLACK_REPORT_PATH. */export const TEAM_SLACK_REPORT_PATH = "/api/cloud/machines/slack";@@ -157,7 +158,7 @@ export function createTeamSlackReporter(options: { machineId: string; adminOrigireturn async (report: TeamSlackReport): Promise<TeamSlackReportOutcome> => {const fetcher = options.fetchImpl ?? globalThis.fetch;const body = JSON.stringify({ v: 1, ...report });- const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ const timestamp = cloudSignedTimestamp(now()), nonce = randomBytes(18).toString("base64url");let response: Response;try {response = await fetcher(`${options.adminOrigin}${TEAM_SLACK_REPORT_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {