Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a moved Cloud's bots where they are when its address changes (#5029)
Milind Soni63afb28a03a2
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex 385d3107bd..f1d6f9dd26 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1259,6 +1259,21 @@ feeds the pairing lockout, never authorization. Apart from `/api/health`,Caddy answers only for the machine's own name (`OMB_PUBLIC_URL`) and refusesany other `Host`.+**A home that moved to another provider.** Its old address (say+`<app>.fly.dev`) is served by a forwarder that proxies to the new one and+rewrites `Host` to the new name, so the edge's host matcher, and in+`OMB_CLOUD_EDGE_TLS` mode the certificate it serves for that name, already+match: the edge is not widened for the old name. What still names the old+address is the `Origin` of a page or client on it (a browser tab, a device+paired by code straight to it), which the server's same-origin checks would+refuse. `OMB_CLOUD_LEGACY_ORIGINS` lists those old origins, and the server+counts exactly those as its own besides its `Host`'s: for cookie sessions,+a browser sign-in's changes, WebSockets, the event stream and the viewers.+`X-Forwarded-Host` is never read. Requests through the forwarder reach the+edge from the forwarder's address, so in `OMB_CLOUD_EDGE_TLS` mode they share+one pairing lockout unless the forwarder is named in+`OMB_CLOUD_TRUSTED_PROXIES`. New pairing links name the new address.+### On your own server: how people reach itA home on a server of its owner's (Team on your own server) runs the same@@ -1357,6 +1372,7 @@ never echoes a secret.| `OMB_CLOUD_ADMIN_URL` | secret | The Cloud origin, exact `https://`, e.g. `https://cloud.openmausbot.com`. || `OMB_CLOUD_BOOTSTRAP_SECRET` | secret | 43 base64url characters (256 bits): the key the Admin signs pairing requests with. || `OMB_PUBLIC_URL` | env | The machine's exact `https://` origin, `https://<app>.fly.dev`. |+| `OMB_CLOUD_LEGACY_ORIGINS` | env | Optional, only for a home that moved to another provider: the exact `https://` origins it answered at before, comma-separated (at most 8, never a loopback name), e.g. `https://<app>.fly.dev`. |- The machine must not also carry `OMB_ADMIN_URL`, `OMB_ADMIN_WORKSPACE` or`OMB_ADMIN_MEMBERSHIP`: a Cloud home is a personal server with pairing codes@@ -1888,6 +1904,14 @@ token (`Authorization: Bearer omc_…`). Contract version 1 adds:Optional, additive fields the app reads when the Admin sends them (an Adminwithout them works as before; a malformed one is dropped, never the machine):+- `cloud.formerOrigins: string[]`, and the same beside each `clouds[].origin`+ and each `teams[].machine.origin`: the addresses that Cloud answered at+ before it moved to another provider (`electron/cloud-home.mjs`+ `parseFormerOrigins`; each a valid `https://` origin, never its `origin`+ now; anything else is left out). The desktop knows My Cloud again by them+ and by its id in `clouds[]`, so a computer whose bots moved to it follows it+ to its new address instead of reading the move as My Cloud ending; see+ [This computer's bots move to your Cloud](#this-computers-bots-move-to-your-cloud).- `cloud.setup: {step, slow}` while `setting_up` (`step` is `reserving`,`storage`, `starting` or `checking`): the app shows the same four steps asthe Cloud page, and says when setup is slow.@@ -2342,6 +2366,16 @@ all arrived, and freezes this computer's copy so nothing runs in two placesBackups. [docs/verification/cloud-send.md](verification/cloud-send.md) has thetests.+The move's journal names the Cloud by its address and, once the session lists+it, by its id (the person's own Cloud in `clouds[]` at My Cloud's address).+When My Cloud moves to another provider, the verified session gives it a new+`origin` and lists the old one in `formerOrigins`: the same id, or the+journal's address among those, is the same Cloud, so the journal follows it+to the new address and the move goes on, or stays done, there. The window+opens it there, and its saved place moves with it. A Cloud with another id+whose former addresses don't include the journal's is another Cloud, and+ends the move as before.+## Security summary- The server never listens on the network; only Caddy does, and nothing itdiff --git a/electron/cloud-home.d.mts b/electron/cloud-home.d.mtsindex e7e3f96d7d..f7b4855fb0 100644--- a/electron/cloud-home.d.mts+++ b/electron/cloud-home.d.mts@@ -6,6 +6,8 @@ export type CloudUnreachableCause = "host" | "no_answer";export interface CloudMachine {status: CloudMachineStatus;origin?: string;+ /** The addresses it answered at before it moved to another provider, when the Admin says: never its `origin`. */+ formerOrigins?: string[];/** While setting up, when the Admin says: the step it is at, and whether it is slow. */setup?: { step: CloudSetupStep; slow?: true };/** A failed setup's next automatic try, when the Admin says. */@@ -127,6 +129,7 @@ export declare const CLOUD_UNREACHABLE_CAUSES: readonly CloudUnreachableCause[];export declare const INSTALLATION_ID: RegExp;export declare function parseCloudPower(input: unknown): import("./cloud-power.mjs").CloudPower | null;export declare function parseCloudSummary(input: unknown): CloudMachine | null;+export declare function parseFormerOrigins(input: unknown, origin: string | null): string[];export type CloudTeamRole = "owner" | "admin" | "member";/** A team this account is in, from the verified session: its Cloud as the Admin describes it, null while it has none. */export interface CloudTeam { id: string; name: string; role: CloudTeamRole; machine: CloudMachine | null }diff --git a/electron/cloud-home.mjs b/electron/cloud-home.mjsindex dca67884d3..a3f0bd8758 100644--- a/electron/cloud-home.mjs+++ b/electron/cloud-home.mjs@@ -27,6 +27,15 @@ export function homeOrigin(value) {}}+const MAX_FORMER_ORIGINS = 8;+/** A Cloud's `formerOrigins` beside its `origin` (contract v1, additive; absent from an older Admin): the addresses it+ * answered at before it moved to another provider. Each a valid home origin, once, never its address now; anything else is+ * left out, never the Cloud. */+export function parseFormerOrigins(input, origin) {+ if (!Array.isArray(input)) return [];+ return [...new Set(input.slice(0, MAX_FORMER_ORIGINS).map(homeOrigin).filter(former => former && former !== origin))];+}+export const CLOUD_SETUP_STEPS = Object.freeze(["reserving", "storage", "starting", "checking"]);export const CLOUD_UNREACHABLE_CAUSES = Object.freeze(["host", "no_answer"]);const GB = 1024 ** 3;@@ -67,7 +76,8 @@ export function parseCloudSummary(input) {const power = parseCloudPower(input.power);const homecoming = record(input.hold) ? parseHomecoming(input.hold.homecoming) : null;const hold = record(input.hold) && moment(input.hold.until) ? { until: input.hold.until, ...(homecoming ? { homecoming } : {}) } : null;- return { status, ...(origin ? { origin } : {}), ...(setup ? { setup } : {}), ...(retryAt ? { retryAt } : {}), ...(disk ? { disk } : {}), ...(unreachable ? { unreachable } : {}), ...(power ? { power } : {}),+ const formerOrigins = parseFormerOrigins(input.formerOrigins, origin);+ return { status, ...(origin ? { origin } : {}), ...(formerOrigins.length ? { formerOrigins } : {}), ...(setup ? { setup } : {}), ...(retryAt ? { retryAt } : {}), ...(disk ? { disk } : {}), ...(unreachable ? { unreachable } : {}), ...(power ? { power } : {}),...(input.moves === true ? { moves: true } : {}), ...(hold ? { hold } : {}) };}diff --git a/electron/cloud-list.d.mts b/electron/cloud-list.d.mtsindex 337198e175..a73ec87c5c 100644--- a/electron/cloud-list.d.mts+++ b/electron/cloud-list.d.mts@@ -12,6 +12,8 @@ export interface CloudListEntry {runsOn: "cloud" | "server";status: CloudListStatus;origin: string | null;+ /** The addresses it answered at before it moved to another provider, when the Admin says: never its `origin`. */+ formerOrigins?: string[];/** A Team or Business Cloud: the team behind its People. */teamId: string | null;/** The account's oldest open Cloud of its own: My Cloud. */@@ -58,6 +60,9 @@ export declare const CLOUD_ID: RegExp;export declare const CLOUD_NAME_LIMIT: number;export declare function cleanCloudListName(value: unknown): string | null;export declare function ownCloud(cloud: CloudListEntry | null | undefined): boolean;+/** My Cloud as the verified session names it: its address, its id in the list, and the addresses it had before a move to+ * another provider. */+export declare function myCloudOf(state: unknown): { origin: string | null; id: string | null; formerOrigins: string[] } | null;export declare function signedInServers(clouds: CloudListEntry[] | null | undefined): CloudListEntry[];export declare function releaseVersion(value: unknown): string | null;export declare function olderRelease(version: unknown, latest: unknown): boolean;diff --git a/electron/cloud-list.mjs b/electron/cloud-list.mjsindex 486cd0fba3..cb17f281b1 100644--- a/electron/cloud-list.mjs+++ b/electron/cloud-list.mjs@@ -1,6 +1,6 @@// The verified session's `clouds` (contract v1, additive): every Cloud this person owns and every team's Cloud they are// in, the account's primary Cloud first. Only the Admin lists a Cloud; a page never names one.-import { CLOUD_SETUP_STEPS, homeOrigin, parseCloudPower } from "./cloud-home.mjs";+import { CLOUD_SETUP_STEPS, homeOrigin, parseCloudPower, parseFormerOrigins } from "./cloud-home.mjs";import environments from "./environments.cjs";export const MAX_CLOUDS = 20;@@ -63,9 +63,10 @@ function parseCloudEntry(input) {// list (an Admin with Remove from list says so only for one of their own, in no team, that ended or was never paid for).const deleteAfter = DEAD.includes(input.status) && Number.isSafeInteger(input.deleteAfter) && input.deleteAfter > 0 ? input.deleteAfter : null;const removable = input.removable === true && DEAD.includes(input.status) && managed && input.role === "owner" && teamId === null;+ const formerOrigins = parseFormerOrigins(input.formerOrigins, origin);return { id: input.id, name, color: Object.hasOwn(CLOUD_SWATCH_COLORS, input.color) ? input.color : null, role: input.role,tier: typeof input.tier === "string" && TIER.test(input.tier) ? input.tier : null, runsOn: input.runsOn, status: input.status, origin, teamId,- primary: input.primary, managed, ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}), ...(power ? { power } : {}),+ primary: input.primary, managed, ...(formerOrigins.length ? { formerOrigins } : {}), ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}), ...(power ? { power } : {}),...(deleteAfter ? { deleteAfter } : {}), ...(removable ? { removable: true } : {}) };}@@ -149,6 +150,17 @@ export function parseCloudRenewal(clouds) {renewsAt: Number.isSafeInteger(own.renewsAt) && own.renewsAt > 0 ? own.renewsAt : null, endsAt, keptDays: kept, ...(team ? { team } : {}) };}+/** My Cloud as the verified session names it, for knowing it again after it moved to another provider: its address, its id+ * (the person's own Cloud the list has at that address; null without one), and every address it had before+ * (`formerOrigins`, the summary's and the list's). Null while the session names no My Cloud. */+export function myCloudOf(state) {+ const machine = state?.status === "connected" ? state.machine : null;+ if (!machine) return null;+ const origin = machine.origin ?? null;+ const listed = origin && Array.isArray(state.clouds) ? state.clouds.find(cloud => ownCloud(cloud) && cloud.origin === origin) ?? null : null;+ return { origin, id: listed?.id ?? null, formerOrigins: [...new Set([...(machine.formerOrigins ?? []), ...(listed?.formerOrigins ?? [])])] };+}+/** Every Cloud of the person's own besides the primary (My Cloud): each a place of its own, as a team's Cloud is. */export function otherOwnClouds(clouds) {return Array.isArray(clouds) ? clouds.filter(cloud => ownCloud(cloud) && !cloud.primary) : [];@@ -188,15 +200,21 @@ export function ownCloudPlaces(clouds) {}/** The saved places once the session says where the account's own machine is: the place listed as home at another- * address was My Cloud before this one. It leaves the list when the session's list has it as ended, or not at all;- * otherwise (still one of the person's Clouds, or an Admin without the list) it stays, as a place of its own. */+ * address was My Cloud before this one, unless that address is one My Cloud had before it moved to another provider: then+ * the place moves to My Cloud's address with it, keeping its id, name and colour (while none is saved there yet). Another+ * Cloud's leaves the list when the session's list has it as ended, or not at all; otherwise (still one of the person's+ * Clouds, or an Admin without the list) it stays, as a place of its own. */export function withoutOldCloudHome(saved, state) {const machine = state?.status === "connected" ? state.machine : null;if (!machine?.origin || machine.status === "provisioning") return saved;- const clouds = state.clouds;+ const clouds = state.clouds, former = myCloudOf(state)?.formerOrigins ?? [];let next = saved;for (const entry of saved.environments) {if (entry.home !== true || entry.origin === machine.origin) continue;+ if (former.includes(entry.origin) && !next.environments.some(other => other.origin === machine.origin)) {+ next = { ...next, environments: next.environments.map(candidate => (candidate.id === entry.id ? { ...candidate, origin: machine.origin } : candidate)) };+ continue;+ }const listed = Array.isArray(clouds) ? clouds.find(cloud => cloud.origin === entry.origin) ?? null : null;if (Array.isArray(clouds) && (!listed || cloudState(listed) === "ended")) { next = environments.withoutEnvironment(next, entry.id); continue; }const { home: _home, ...rest } = entry;diff --git a/electron/cloud-provider-move.node-test.mjs b/electron/cloud-provider-move.node-test.mjsnew file mode 100644index 0000000000..343d5d5f8e--- /dev/null+++ b/electron/cloud-provider-move.node-test.mjs@@ -0,0 +1,188 @@+import assert from "node:assert/strict";+import test from "node:test";++import { parseCloudSummary } from "./cloud-home.mjs";+import { myCloudOf, parseCloudList, withoutOldCloudHome } from "./cloud-list.mjs";+import { homeOf } from "./home-window.mjs";+import { createOneHome } from "./one-home.mjs";+import { oneHomeCloud } from "./one-home-main.mjs";++// My Cloud moves to another provider: the same Cloud (its id) answers at a new address, and the Admin lists the old one+// among its `formerOrigins`. A computer whose bots moved to it keeps them there, follows it, and never brings them back,+// which would run them in two places; a Cloud that truly is another still ends the move as before. Every side is faked;+// nothing reaches the network or the disk.+const OLD = "https://omb-u-1a2b3c4d5e6f.fly.dev", NEW = "https://omb-u-1a2b3c4d5e6f.homes.example", OTHER = "https://omb-u-other.homes.example";+const reply = (status, body = {}) => ({ ok: status < 400, status, body });++function computer({ journal, cloud = {}, admin = {} }) {+ const w = {+ journal, admin, asked: [], opened: [], logged: [],+ server: { marker: { frozen: true, cloud: OLD }, thaws: [], frozenFor: [] },+ cloud: { origin: NEW, account: "acct-1", machine: NEW, ready: true, moves: true, ended: false, paid: true, verified: true, ...cloud },+ };+ w.home = createOneHome({+ journal: { read: () => structuredClone(w.journal), write: (value) => { w.journal = structuredClone(value); } },+ cloud: () => ({ ...w.cloud }),+ gone: async (origin) => { w.asked.push(origin); return w.admin[origin] ?? null; },+ send: { move: async () => {}, check: async () => ({ ok: true }), switches: () => ({}), snapshot: () => ({ running: null }) },+ local: {+ async freeze(origin) { w.server.frozenFor.push(origin); w.server.marker = { frozen: true, cloud: origin }; return { frozen: true }; },+ async unfreeze(options) { w.server.thaws.push(options ?? null); w.server.marker = { frozen: false }; },+ frozen: async () => Boolean(w.server.marker.frozen),+ marker: async () => structuredClone(w.server.marker),+ json: async (route) => (route.startsWith("/api/bots") ? { bots: [] } : { items: [], conversations: [], automations: [] }),+ call: async () => reply(200),+ },+ session: async () => ({ call: async () => reply(200, { v: 1 }), close: async () => {} }),+ openHome: () => w.opened.push("cloud"),+ openLocal: () => w.opened.push("local"),+ lastInput: () => 0,+ version: "0.1.151",+ now: () => 2_000_000,+ log: (line) => w.logged.push(line),+ timers: { set: () => ({}), clear: () => {} },+ });+ return w;+}++const movedTo = (origin, extra = {}) => ({ origin, account: "acct-1", machine: origin, ...extra });+const doneTo = (cloud) => ({ v: 1, phase: "done", cloud, startedAt: 1_000, doneAt: 1_500, frozenAt: 1_400, version: "0.1.151", lent: true });++test("a done move keyed by the Cloud's id follows it to its new address and stays done: nothing comes home, nothing is asked", async () => {+ const w = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: { id: "c-home" } });+ await w.home.kick();+ assert.equal(w.journal.phase, "done");+ assert.deepEqual(w.journal.cloud, movedTo(NEW, { id: "c-home" }));+ assert.deepEqual([w.server.thaws, w.opened, w.asked], [[], [], []], "the freeze stays, the window stays, the Admin isn't asked whether it is gone");+ assert.equal(w.server.marker.frozen, true);+ assert.equal(w.logged.filter((line) => line.includes("new address")).length, 1);+ await w.home.kick();+ assert.deepEqual([w.journal.phase, w.journal.cloud.origin, w.server.thaws], ["done", NEW, []], "and on every run after");+});++test("a journal from before ids were kept is known again by the address the Cloud had before, and keeps its id from then on", async () => {+ const w = computer({ journal: doneTo(movedTo(OLD)), cloud: { id: "c-home", formerOrigins: [OLD] } });+ await w.home.kick();+ assert.equal(w.journal.phase, "done");+ assert.deepEqual(w.journal.cloud, movedTo(NEW, { id: "c-home" }));+ assert.deepEqual([w.server.thaws, w.opened], [[], []]);+ const without = computer({ journal: doneTo(movedTo(OLD)), cloud: { formerOrigins: [OLD] } });+ await without.home.kick();+ assert.deepEqual(without.journal.cloud, movedTo(NEW), "an Admin that lists no id: the address alone, and no id is made up");+});++test("a move under way follows the Cloud too, so the freeze names its new address", async () => {+ const w = computer({ journal: { v: 1, phase: "wait", cloud: movedTo(OLD), startedAt: 1_000 }, cloud: { id: "c-home", formerOrigins: [OLD] } });+ w.server.marker = { frozen: false };+ await w.home.kick();+ assert.deepEqual(w.server.frozenFor, [NEW]);+ assert.equal(w.journal.cloud.origin, NEW);+ assert.equal(w.journal.phase, "done");+});++test("the id is kept once the session lists it, even before the Cloud ever moves", async () => {+ const w = computer({ journal: doneTo(movedTo(NEW)), cloud: { id: "c-home" } });+ await w.home.kick();+ assert.deepEqual(w.journal.cloud, movedTo(NEW, { id: "c-home" }));+ const fresh = computer({ journal: null, cloud: { id: "c-home" } });+ fresh.server.marker = { frozen: false };+ await fresh.home.kick();+ assert.equal(fresh.journal.cloud.id, "c-home", "a new move keeps the id from its start");+});++test("a Cloud that truly is another still counts as ended: a move not switched yet stops, and a done one comes home on the Admin's word", async () => {+ // Another id, another address, and the journal's address not among the ones it had before.+ const other = { origin: OTHER, machine: OTHER, id: "c-other", formerOrigins: ["https://omb-u-other.fly.dev"] };+ const moving = computer({ journal: { v: 1, phase: "copy", cloud: movedTo(OLD, { id: "c-home" }), startedAt: 1_000 }, cloud: other });+ moving.server.marker = { frozen: false };+ await moving.home.kick();+ assert.equal(moving.journal, null, "the move to the old Cloud stops: nothing runs there yet");+ const done = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: other, admin: { [OLD]: "deleted" } });+ await done.home.kick();+ assert.deepEqual(done.asked, [OLD], "the Admin is asked about the Cloud this computer moved to, at its own address");+ assert.equal(done.journal.phase, "back");+ assert.equal(done.journal.gone, "deleted");+ assert.deepEqual(done.server.thaws, [{ automations: "off" }]);+ const waiting = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: other });+ await waiting.home.kick();+ assert.deepEqual([waiting.journal.phase, waiting.journal.cloud.origin, waiting.server.thaws], ["done", OLD, []], "no word from the Admin: it stays, and is not followed");+ const sameAddress = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: { origin: OTHER, machine: OTHER, id: "c-other" }, admin: { [OLD]: "ended" } });+ await sameAddress.home.kick();+ assert.equal(sameAddress.journal.gone, "ended", "an id of its own is no sign of being the same Cloud");+ const twoIds = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: { ...other, formerOrigins: [OLD] }, admin: { [OLD]: "deleted" } });+ await twoIds.home.kick();+ assert.equal(twoIds.journal.gone, "deleted", "an old address listed for a Cloud with another known id never makes it this journal's");+});++test("the same Cloud that moved and then ended still brings this computer home, as My Cloud ending always has", async () => {+ const w = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud: { id: "c-home", ended: true, ready: false } });+ await w.home.kick();+ assert.equal(w.journal.cloud.origin, NEW, "its things come home from where it is now");+ assert.equal(w.journal.phase, "back");+ assert.deepEqual(w.server.thaws, [null]);+});++test("nobody else's word moves a journal: a session not verified, or another account's", async () => {+ for (const cloud of [{ id: "c-home", formerOrigins: [OLD], verified: false }, { id: "c-home", formerOrigins: [OLD], account: "acct-2" }]) {+ const w = computer({ journal: doneTo(movedTo(OLD, { id: "c-home" })), cloud });+ await w.home.kick();+ assert.equal(w.journal.cloud.origin, OLD, JSON.stringify(cloud));+ assert.deepEqual(w.server.thaws, [], JSON.stringify(cloud));+ }+});++test("a freeze with no journal that names the Cloud's old address is My Cloud's, never asked about as another", async () => {+ const w = computer({ journal: null, cloud: { id: "c-home", formerOrigins: [OLD] }, admin: { [OLD]: "deleted" } });+ await w.home.kick();+ assert.deepEqual([w.asked, w.server.thaws], [[], []]);+});++const session = ({ machine = {}, clouds } = {}) => ({+ status: "connected", account: { id: "acct-1" }, entitlement: { status: "active" },+ machine: { status: "ready", origin: NEW, ...machine },+ ...(clouds ? { clouds } : {}),+});+const listed = (over = {}) => ({ id: "c-home", name: "My Cloud", color: null, role: "owner", tier: "pro", runsOn: "cloud", status: "ready", origin: NEW, teamId: null, primary: true, managed: true, ...over });++test("the Admin's formerOrigins are read beside a Cloud's origin, strictly, and an Admin without them reads as before", () => {+ assert.deepEqual(parseCloudSummary({ state: "ready", origin: NEW, formerOrigins: [OLD, OLD, NEW, "http://omb-u-x.fly.dev", `${OLD}/path`, 7, null] }),+ { status: "ready", origin: NEW, formerOrigins: [OLD] });+ assert.deepEqual(parseCloudSummary({ state: "ready", origin: NEW }), { status: "ready", origin: NEW });+ for (const formerOrigins of [OLD, {}, [], ["nope"]]) assert.deepEqual(parseCloudSummary({ state: "ready", origin: NEW, formerOrigins }), { status: "ready", origin: NEW }, JSON.stringify(formerOrigins));+ const [entry] = parseCloudList([{ ...listed(), formerOrigins: [OLD, "ftp://x.example"] }]);+ assert.deepEqual(entry.formerOrigins, [OLD]);+ assert.equal("formerOrigins" in parseCloudList([listed()])[0], false);+});++test("My Cloud's identity: its id from the list at its address, and every address it had before, the summary's and the list's", () => {+ assert.deepEqual(myCloudOf(session({ machine: { formerOrigins: [OLD] }, clouds: [listed({ formerOrigins: ["https://omb-u-older.fly.dev"] })] })),+ { origin: NEW, id: "c-home", formerOrigins: [OLD, "https://omb-u-older.fly.dev"] });+ assert.deepEqual(myCloudOf(session({ clouds: [listed({ origin: OTHER })] })), { origin: NEW, id: null, formerOrigins: [] }, "an id only from the Cloud at its address");+ assert.deepEqual(myCloudOf(session({ clouds: [listed({ role: "member" })] })).id, null, "never a team's");+ assert.equal(myCloudOf({ status: "unavailable", machine: { status: "ready", origin: NEW } }), null, "only a verified session's word");+ const cloud = oneHomeCloud(session({ machine: { formerOrigins: [OLD] }, clouds: [listed()] }));+ assert.deepEqual([cloud.id, cloud.formerOrigins, cloud.origin], ["c-home", [OLD], NEW]);+});++test("the window opens My Cloud at its new address for a journal or a freeze kept at its old one, and nothing else changes", () => {+ const state = session({ machine: { formerOrigins: [OLD] }, clouds: [listed()] });+ assert.deepEqual(homeOf({ journal: doneTo(movedTo(OLD)), state }), { kind: "cloud", origin: NEW });+ assert.deepEqual(homeOf({ journal: doneTo(movedTo(OLD, { id: "c-home" })), state: session({ clouds: [listed()] }) }), { kind: "cloud", origin: NEW }, "by id alone");+ assert.deepEqual(homeOf({ frozenCloud: OLD, state }), { kind: "cloud", origin: NEW }, "a freeze with no journal is not another account's");+ assert.deepEqual(homeOf({ journal: doneTo(movedTo(OLD)), state: session({ machine: { hold: { until: 9 }, formerOrigins: [OLD] } }) }), { kind: "computer" }, "it ended: home is this computer");+ assert.deepEqual(homeOf({ journal: doneTo(movedTo(OLD)), state: session({ machine: { origin: OTHER }, clouds: [listed({ origin: OTHER, id: "c-other" })] }) }), { kind: "cloud", origin: OLD },+ "another Cloud: the one moved to opens, as before");+ assert.deepEqual(homeOf({ journal: doneTo(movedTo(OLD)), state: { ...state, account: { id: "acct-2" } } }), { kind: "cloud", origin: NEW, otherAccount: true },+ "another account's Cloud is never this journal's");+});++test("My Cloud's saved place moves to its new address with it, keeping its id, name and colour", () => {+ const garage = { id: "garage", kind: "remote", name: "Garage", origin: "https://garage.example" };+ const saved = { environments: [{ id: "home", kind: "remote", name: "Anagama", color: "teal", origin: OLD, home: true }, garage], activeId: "home" };+ const moved = withoutOldCloudHome(saved, session({ machine: { formerOrigins: [OLD] }, clouds: [listed()] }));+ assert.deepEqual(moved.environments, [{ id: "home", kind: "remote", name: "Anagama", color: "teal", origin: NEW, home: true }, garage]);+ assert.equal(moved.activeId, "home");+ const already = { ...saved, environments: [...saved.environments, { id: "new", kind: "remote", name: "My Cloud", origin: NEW, home: true }] };+ assert.deepEqual(withoutOldCloudHome(already, session({ machine: { formerOrigins: [OLD] }, clouds: [listed()] })).environments.map((entry) => entry.id), ["garage", "new"],+ "one already saved at the new address stays the only one");+});diff --git a/electron/home-window.mjs b/electron/home-window.mjsindex aac2865a91..87e05f6eec 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -9,10 +9,10 @@// shown place's verified origin, nothing else. A team is only ever one the Admin's session lists, paired through the// Admin's team pairing (its claims are the Admin's), never an address a page supplied.import { cloudHomeConnectUrl, cloudSetupOf, cloudUnreachableCause, cloudUnreachableText, machineSetup, readyCloudOrigin } from "./cloud-home.mjs";-import { cloudMachine, cloudState, otherOwnClouds, ownCloud } from "./cloud-list.mjs";+import { cloudMachine, cloudState, myCloudOf, otherOwnClouds, ownCloud } from "./cloud-list.mjs";import { asleepAnswer, BACKGROUND_HEADERS, openSleepingCloud, SIGNED_IN_MS } from "./cloud-power.mjs";import nativeText from "./native-text.cjs";-import { awayIn, parseJournal } from "./one-home.mjs";+import { awayIn, parseJournal, sameCloud } from "./one-home.mjs";export const HOME_SCREEN_PATH = "/home";/** The look at an awake My Cloud before the window moves there: under 3 s, so the offline screen shows within 3 s. */@@ -65,6 +65,14 @@ const DEFAULT_TIMERS = {const originOf = (url) => { try { return new URL(url).origin; } catch { return null; } };+/** The Cloud this computer moved to, at the address the verified session gives My Cloud now when My Cloud is that Cloud by+ * its id or by an address it had before it moved to another provider, for the journal's own account; as kept otherwise. */+function followedCloud(kept, state) {+ const mine = myCloudOf(state);+ if (!mine?.origin || !kept.origin || mine.origin === kept.origin || (kept.account && kept.account !== state.account?.id)) return kept;+ return sameCloud(mine, kept) ? { ...kept, origin: mine.origin } : kept;+}+/*** Who the window opens. `journal`: one-home.json read back; `frozenCloud`: this computer's freeze marker when there is no* journal (its Cloud's origin, or true when it names none); `state`: the MausBot Cloud sign-in's state. An ended My Cloud@@ -73,9 +81,10 @@ const originOf = (url) => { try { return new URL(url).origin; } catch { return n* @returns {{ kind: "computer" } | { kind: "cloud", origin: string } | { kind: "signin", other?: true }}*/export function homeOf({ journal = null, frozenCloud = null, state = null }) {- const moved = journal ? (awayIn(journal) ? journal.cloud : null)+ const kept = journal ? (awayIn(journal) ? journal.cloud : null): frozenCloud ? { origin: typeof frozenCloud === "string" ? frozenCloud : null, account: null } : null;- if (!moved) return { kind: "computer" };+ if (!kept) return { kind: "computer" };+ const moved = followedCloud(kept, state);const connected = state?.status === "connected";const signedInNow = state?.account?.id ?? null;// This computer moved to another account's Cloud: its frozen copy stays frozen, and this account's own Cloud is what opens.diff --git a/electron/one-home-main.mjs b/electron/one-home-main.mjsindex 7f8760bee7..815714756a 100644--- a/electron/one-home-main.mjs+++ b/electron/one-home-main.mjs@@ -14,6 +14,7 @@ import { createMoveSession } from "./move-session.mjs";import { createMoveStatusReport, moveStatus } from "./move-status.mjs";import { createHomeAgain } from "./one-home-again.mjs";import { awayIn, createOneHome, parseJournal, underWay } from "./one-home.mjs";+import { myCloudOf } from "./cloud-list.mjs";import { teamPlan } from "./cloud-team-plan.mjs";import { installTeamMove } from "./team-move-main.mjs";import nativeText from "./native-text.cjs";@@ -43,9 +44,11 @@ export function oneHomeCloud(state) {if (typeof account !== "string" || !account) return null;const connected = state.status === "connected", machine = connected ? state.machine ?? null : null;const trialOn = ["active", "ending"].includes(state.trial?.state ?? "");- const homecoming = machine?.hold?.homecoming ?? null;+ const homecoming = machine?.hold?.homecoming ?? null, mine = myCloudOf(state);return {origin: machine?.origin ?? null,+ ...(mine?.id ? { id: mine.id } : {}),+ ...(mine?.formerOrigins.length ? { formerOrigins: mine.formerOrigins } : {}),account,machine: machine?.origin ?? null,ready: connected && machine?.status === "ready" && Boolean(machine.origin),diff --git a/electron/one-home.d.mts b/electron/one-home.d.mtsindex 96725c7d56..125d233587 100644--- a/electron/one-home.d.mts+++ b/electron/one-home.d.mts@@ -39,6 +39,10 @@ export interface OneHomeCloud {signIn?: string;/** The Admin answered this sign-in just now (connected), so its word on the person's Clouds counts. */verified?: boolean;+ /** Its id in the session's list of Clouds, which the journal keeps, so the Cloud is known again at a new address. */+ id?: string;+ /** The addresses it answered at before it moved to another provider: a journal kept at one of them is this Cloud's. */+ formerOrigins?: string[];}type Answer = { ok: boolean; status: number; body: any };@@ -52,6 +56,8 @@ export function parseJournal(value: unknown): Record<string, any> | null;export function rateLimited(error: unknown): boolean;/** Home is My Cloud by this journal. */export function awayIn(journal: Record<string, any> | null | undefined): boolean;+/** `cloud` is the Cloud kept as `kept`: the same address, the same id, or one of its former addresses. */+export function sameCloud(cloud: { origin: string | null; id?: string | null; formerOrigins?: string[] }, kept: { origin: string; id?: string }): boolean;export function parseKeep(value: unknown): { on: boolean };/** This computer's bots are on their way home and past turning back. */export function underWay(journal: Record<string, any> | null | undefined): boolean;diff --git a/electron/one-home.mjs b/electron/one-home.mjsindex 50247a46e4..de0d794283 100644--- a/electron/one-home.mjs+++ b/electron/one-home.mjs@@ -93,9 +93,15 @@ const tagged = (message, code, extra = {}) => Object.assign(new Error(message),const errorText = (error) => (typeof error?.errorKey === "string" && error.errorKey.startsWith("serverError.")? { errorKey: error.errorKey, errorParams: record(error.errorParams) ? error.errorParams : {} } : { errorKey: undefined, errorParams: undefined });-/** The session's My Cloud is known to be another Cloud than the one at `origin`. A held Cloud that names no address gives no- * sign of being another, so it is taken for that one. */-const anotherCloud = (cloud, origin) => cloud.origin !== origin && !(cloud.ended && !cloud.origin);+/** The session's Cloud (`cloud`: its address, id and `formerOrigins`) is the one kept as `kept` (a journal's Cloud: its+ * address, and its id once known): the same address, the same id, or an address the Cloud had before it moved to another+ * provider, unless both ids are known and differ. A journal from before ids were kept is known again by that last one. */+export const sameCloud = (cloud, kept) => cloud.origin === kept.origin || (Boolean(cloud.id) && cloud.id === kept.id)+ || (Array.isArray(cloud.formerOrigins) && cloud.formerOrigins.includes(kept.origin) && !(cloud.id && kept.id && cloud.id !== kept.id));++/** The session's My Cloud is known to be another Cloud than `kept`. A held Cloud that names no address gives no sign of being+ * another, so it is taken for that one. */+const anotherCloud = (cloud, kept) => !sameCloud(cloud, kept) && !(cloud.ended && !cloud.origin);/** A journal read back, kept to its known shape; null when there is none. */export function parseJournal(value) {@@ -157,7 +163,7 @@ export function arrivedCounts(here, there) {* @param {{* journal: { read(): unknown, write(value: unknown): void },* cloud(): null | { origin: string | null, account: string, machine: string | null, ready: boolean, moves: boolean, ended: boolean, paid: boolean,- * homecoming?: { installationId: string, name: string }, signIn?: string, verified?: boolean },+ * homecoming?: { installationId: string, name: string }, signIn?: string, verified?: boolean, id?: string, formerOrigins?: string[] },* send: { move(options?: { final?: boolean }): Promise<unknown>, check(): Promise<{ ok: boolean }>, switches(): Record<string, boolean>, snapshot(): any },* local: { freeze(origin: string): Promise<{ frozen: true } | { busy: string, what?: string }>, unfreeze(options?: { automations?: "off" }): Promise<void>, frozen(): Promise<boolean>, json(route: string): Promise<any>,* call(method: string, route: string, body?: unknown): Promise<{ ok: boolean, status: number, body: any }>, forget?(): Promise<void>,@@ -481,10 +487,10 @@ export function createOneHome(deps) {* this app kept no journal of it. Never a server of the person's own (`place`), nor one another account moved to. */async function frozenFor(journal, cloud) {if (!cloud?.verified || !deps.gone) return null;- if (journal && (awayIn(journal) || journal.phase === "home-again")) return anotherCloud(cloud, journal.cloud.origin) ? journal : null;+ if (journal && (awayIn(journal) || journal.phase === "home-again")) return anotherCloud(cloud, journal.cloud) ? journal : null;if (journal && journal.phase !== "back") return null;const marker = await deps.local.marker?.().catch(() => null);- if (!marker?.frozen || marker.place || typeof marker.cloud !== "string" || marker.cloud === cloud.origin) return null;+ if (!marker?.frozen || marker.place || typeof marker.cloud !== "string" || sameCloud(cloud, { origin: marker.cloud })) return null;return { v: 1, cloud: { origin: marker.cloud, account: cloud.account, machine: marker.cloud }, startedAt: now() };}@@ -503,11 +509,22 @@ export function createOneHome(deps) {* nor takes a top-up by that word, and a move not yet switched over stops as it does when My Cloud ends (nothing runs* there yet). Only a verified session's word, for the journal's own account. */function judged(cloud, journal) {- if (!cloud?.verified || !journal || journal.phase === "back" || cloud.account !== journal.cloud.account || !anotherCloud(cloud, journal.cloud.origin)) return cloud;+ if (!cloud?.verified || !journal || journal.phase === "back" || cloud.account !== journal.cloud.account || !anotherCloud(cloud, journal.cloud)) return cloud;const { homecoming: _, ...rest } = cloud;return awayIn(journal) || journal.phase === "home-again" ? { ...rest, ready: false, ended: false } : { ...rest, ended: true };}+ /** The Cloud this journal moved to, by a verified session's word for its own account, answers at a new address now (it+ * moved to another provider), or its id is known now: the journal follows it there and keeps its id, so the move goes+ * on, or stays done, at that address, and the old one is never read as My Cloud having ended. */+ function followed(journal, cloud) {+ if (!journal || journal.phase === "back" || !cloud?.verified || !cloud.origin || cloud.account !== journal.cloud.account || !sameCloud(cloud, journal.cloud)) return journal;+ const id = cloud.id || journal.cloud.id;+ if (cloud.origin === journal.cloud.origin && id === journal.cloud.id) return journal;+ if (cloud.origin !== journal.cloud.origin) log("one home: the Cloud this computer moved to answers at a new address; the move follows it there");+ return write({ ...journal, cloud: { ...journal.cloud, origin: cloud.origin, machine: cloud.machine ?? cloud.origin, ...(id ? { id } : {}) } });+ }+/** My Cloud ended: this computer is home again at once, as it was at the move, then brings back what was done there. */async function homeAgain(journal) {let next = journal;@@ -635,8 +652,9 @@ export function createOneHome(deps) {async function run() {noted = null;- let journal = read();- const said = deps.cloud(), cloud = judged(said, journal);+ const said = deps.cloud();+ let journal = followed(read(), said);+ const cloud = judged(said, journal);// A move left off while My Cloud was away goes on as soon as it is back, unless it failed frozen: that waits its hour.const cameBack = cloud?.ready === true && wasReady === false;wasReady = cloud ? cloud.ready : null;@@ -663,7 +681,8 @@ export function createOneHome(deps) {// local environment) nothing starts or counts as failing, and it looks again in a minute.if (deps.ownCopy?.() === false) { noted = "local_unavailable"; if (!heldOff) log("one home: the move waits until this computer's own copy runs"); heldOff = true; later(MINUTE); return; }heldOff = false;- journal = write({ v: 1, phase: "copy", cloud: { origin: cloud.origin, account: cloud.account, machine: cloud.machine, ...(cloud.name ? { name: cloud.name } : {}) }, startedAt: now() });+ journal = write({ v: 1, phase: "copy", cloud: { origin: cloud.origin, account: cloud.account, machine: cloud.machine, ...(cloud.id ? { id: cloud.id } : {}), ...(cloud.name ? { name: cloud.name } : {}) },+ startedAt: now() });}if (journal.thaw && !(await thaw(journal))) return;journal = read() ?? journal;diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 1331bc5285..89443e1033 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -38,6 +38,8 @@ const SERVER_ENV_NAMES = new Set(["OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_IMAGE", "OMB_PUBLIC_URL", "OMB_WEBHOOK_PUBLIC_URL","OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_NAME", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_AI_URL", "OMB_CLOUD_X_URL", "OMB_TTS_DEFAULT_VOICE","OMB_COMPOSIO_BROKER_URL",+ // The addresses a home answered at before it moved to another provider, which still forward to it.+ "OMB_CLOUD_LEGACY_ORIGINS",// The bot box switch (server/bot-box/detect.ts): the Admin may turn a home's box off for support."OMB_BOT_BOX",// An ended Cloud started only for its owner's export: the server runs frozen (server/move-freeze.ts).diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.tsindex c8cfaedfed..9a62b7c54a 100644--- a/server/cloud-home.test.ts+++ b/server/cloud-home.test.ts@@ -48,14 +48,35 @@ it("is off on every ordinary server and desktop", () => {it("reads the Admin's contract", () => {expect(cloudHomeConfiguration(contract())).toEqual({- role: "home", team: null, machineId, adminOrigin: "https://cloud.example.test", publicOrigin: "https://omb-u-1a2b3c4d5e6f.fly.dev", bootstrapSecret: secret, warnings: [],+ role: "home", team: null, machineId, adminOrigin: "https://cloud.example.test", publicOrigin: "https://omb-u-1a2b3c4d5e6f.fly.dev", legacyOrigins: [], bootstrapSecret: secret,+ warnings: [],});expect(cloudHomeConfiguration(contract({ OMB_CLOUD_ADMIN_URL: "https://cloud.example.test/" }))!.adminOrigin).toBe("https://cloud.example.test");});+it("reads the addresses a moved home answered at before, exactly and once each, without its own", () => {+ const legacy = (value: string) => cloudHomeConfiguration(contract({ OMB_CLOUD_LEGACY_ORIGINS: value }))!.legacyOrigins;+ expect(legacy("https://omb-u-old.fly.dev")).toEqual(["https://omb-u-old.fly.dev"]);+ expect(legacy(" https://omb-u-old.fly.dev/ , https://older.example.test,https://omb-u-old.fly.dev,https://omb-u-1a2b3c4d5e6f.fly.dev ,"))+ .toEqual(["https://omb-u-old.fly.dev", "https://older.example.test"]);+ expect(legacy("")).toEqual([]);+});++it.each([+ ["an http origin", "http://omb-u-old.fly.dev"],+ ["an origin with a path", "https://omb-u-old.fly.dev/app"],+ ["an origin with credentials", "https://user:[email protected]"],+ ["a host that is not written as its origin", "https://OMB-U-OLD.fly.dev"],+ ["a loopback name", "https://localhost"],+ ["a loopback address", "https://127.0.0.1:8443"],+ ["too many", Array.from({ length: 9 }, (_, at) => `https://old-${at}.example.test`).join(",")],+])("refuses to start with %s as a former address", (_why, value) => {+ expect(() => cloudHomeConfiguration(contract({ OMB_CLOUD_LEGACY_ORIGINS: value }))).toThrow(/Cloud home configuration is invalid: .*OMB_CLOUD_LEGACY_ORIGINS/);+});+it("ignores a platform gateway's settings with one warning, whatever they hold, and never serves them", () => {const all = cloudHomeConfiguration(withGateway())!;- expect(Object.keys(all).sort()).toEqual(["adminOrigin", "bootstrapSecret", "machineId", "publicOrigin", "role", "team", "warnings"]);+ expect(Object.keys(all).sort()).toEqual(["adminOrigin", "bootstrapSecret", "legacyOrigins", "machineId", "publicOrigin", "role", "team", "warnings"]);expect(all.warnings).toEqual(["ignoring OMB_HOSTED_MODEL_URL, OMB_HOSTED_MODEL_TOKEN, OMB_HOSTED_MODELS: Cloud Pro includes no AI; people sign in with their own Claude or ChatGPT account, or an API key"]);for (const stray of [{ OMB_HOSTED_MODEL_TOKEN: token }, { OMB_HOSTED_MODEL_TOKEN: "sk-ant-api03-platform-key" }, { OMB_HOSTED_MODELS: "{not json" },{ OMB_HOSTED_MODEL_URL: "https://gateway.attacker.test/v1" }, { OMB_HOSTED_MODELS: "" }]) {@@ -405,6 +426,13 @@ it("hands the server the Admin's export-only switch, so an ended Cloud started fexpect(cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_CLOUD_EXPORT_ONLY: "1" }, "/data").server).toMatchObject({ OMB_CLOUD_EXPORT_ONLY: "1" });});+it("hands the server the addresses a moved home answered at before, and never its edge", () => {+ const env = contract({ PATH: "/usr/bin", OMB_CLOUD_LEGACY_ORIGINS: "https://omb-u-old.fly.dev" });+ const children = cloudHomeChildEnvironments(cloudHomeConfiguration(env)!, env, "/data");+ expect(children.server).toMatchObject({ OMB_CLOUD_LEGACY_ORIGINS: "https://omb-u-old.fly.dev" });+ expect(children.edge).not.toHaveProperty("OMB_CLOUD_LEGACY_ORIGINS");+});+it("gives the server only an allow-listed environment: a secret added later, a test's key or anything unknown never reaches it", () => {const config = cloudHomeConfiguration(contract())!;const env = { ...contract(), PATH: "/usr/bin", LANG: "C.UTF-8", LC_ALL: "C.UTF-8", NODE_ENV: "production", OMB_STATIC_DIR: "/app/dist",diff --git a/server/cloud-home.ts b/server/cloud-home.tsindex 7fee3c7a3b..f1b8418dfd 100644--- a/server/cloud-home.ts+++ b/server/cloud-home.ts@@ -11,6 +11,7 @@ import type { Surface } from "../shared/wire.ts";import { writeFileAtomic } from "./atomic.ts";import { hostedWorkspaceConfigured } from "./enterprise.ts";import { parseMemberClaim, teamRoleScopes, type CloudTeam } from "./cloud-team.ts";+import { isLoopbackHost } from "./request-auth.ts";import { formatPairingCode, type SessionRegistry } from "./sessions.ts";/** Any of these switches the server into Cloud home mode; then all are required. */@@ -42,6 +43,10 @@ export interface CloudHomeConfig {machineId: string;adminOrigin: string;publicOrigin: string;+ /** The addresses this home answered at before a move to another provider (OMB_CLOUD_LEGACY_ORIGINS), each an exact https+ * origin. The old address forwards here with Host rewritten to `publicOrigin`'s name, so a page or client still on it+ * sends that address as its Origin, which counts as this home's own. Empty for a home that never moved. */+ legacyOrigins: string[];bootstrapSecret: string;warnings: string[];}@@ -66,6 +71,18 @@ function exactHttpsOrigin(raw: string | undefined, name: string): string {return url.origin;}+export const MAX_LEGACY_ORIGINS = 8;++/** OMB_CLOUD_LEGACY_ORIGINS, comma-separated: exact https origins only, never a loopback name (a loopback Origin means this+ * machine), at most MAX_LEGACY_ORIGINS; this home's own address among them is dropped. */+function legacyOrigins(raw: string | undefined, publicOrigin: string): string[] {+ const entries = (raw ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);+ if (entries.length > MAX_LEGACY_ORIGINS) invalid(`OMB_CLOUD_LEGACY_ORIGINS names more than ${MAX_LEGACY_ORIGINS} origins`);+ const origins = entries.map((entry) => exactHttpsOrigin(entry, "every OMB_CLOUD_LEGACY_ORIGINS entry"));+ if (origins.some((origin) => isLoopbackHost(new URL(origin).host))) invalid("OMB_CLOUD_LEGACY_ORIGINS must not name a loopback address");+ return [...new Set(origins)].filter((origin) => origin !== publicOrigin);+}+/** Null on any machine that is not a Cloud home; throws, so the server refuses to start, on a partial or invalid one. */export function cloudHomeConfiguration(env: NodeJS.ProcessEnv = process.env): CloudHomeConfig | null {if (!cloudHomeConfigured(env)) return null;@@ -78,12 +95,13 @@ export function cloudHomeConfiguration(env: NodeJS.ProcessEnv = process.env): Clif (!/^[A-Za-z0-9][A-Za-z0-9_-]{2,127}$/.test(machineId)) invalid("OMB_CLOUD_MACHINE_ID must be the Admin's machine id (letters, digits, dashes)");const adminOrigin = exactHttpsOrigin(env.OMB_CLOUD_ADMIN_URL, "OMB_CLOUD_ADMIN_URL");const publicOrigin = exactHttpsOrigin(env.OMB_PUBLIC_URL, "OMB_PUBLIC_URL");+ const legacy = legacyOrigins(env.OMB_CLOUD_LEGACY_ORIGINS, publicOrigin);const bootstrapSecret = env.OMB_CLOUD_BOOTSTRAP_SECRET ?? "";if (!/^[A-Za-z0-9_-]{43,128}$/.test(bootstrapSecret)) invalid("OMB_CLOUD_BOOTSTRAP_SECRET must be at least 256 bits of base64url");const warnings: string[] = [];const ignored = CLOUD_IGNORED_KEYS.filter((key) => env[key] !== undefined);if (ignored.length) warnings.push(`ignoring ${ignored.join(", ")}: Cloud Pro includes no AI; people sign in with their own Claude or ChatGPT account, or an API key`);- return { role, team, machineId, adminOrigin, publicOrigin, bootstrapSecret, warnings };+ return { role, team, machineId, adminOrigin, publicOrigin, legacyOrigins: legacy, bootstrapSecret, warnings };}const TEAM_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;diff --git a/server/cloud-legacy-origin.e2e.test.ts b/server/cloud-legacy-origin.e2e.test.tsnew file mode 100644index 0000000000..bf48d03e80--- /dev/null+++ b/server/cloud-legacy-origin.e2e.test.ts@@ -0,0 +1,126 @@+// A Cloud home that moved to another provider, asked the way its old address's forwarder asks: Host rewritten to the+// home's new name, the browser's own Origin (the old address) kept. With OMB_CLOUD_LEGACY_ORIGINS naming that address, a+// browser signed in there goes on working; any other Origin is refused as before, and a malformed list stops the home.+import { randomBytes } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { mkdirSync, mkdtempSync } from "node:fs";+import { request } from "node:http";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, expect, it, vi } from "vitest";+import { cloudPairingSignature } from "./cloud-home.ts";+import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { freePortBlock } from "./testing/ports.ts";++const SERVER_DIR = dirname(fileURLToPath(import.meta.url));+const NEW_HOST = "omb-u-0a1b2c3d4e5f.homes.example", OLD = "https://omb-u-0a1b2c3d4e5f.fly.dev";+const secret = randomBytes(32).toString("base64url");+// Anything but loopback fails here, so the home reaches nothing outside the test.+const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;+const homes: string[] = [];+let child: ChildProcess | undefined;+let base = "", log = "", cookie = "";++async function launch(legacy: string, port: number): Promise<{ child: ChildProcess; output: () => string }> {+ const home = mkdtempSync(join(tmpdir(), "omb-cloud-legacy-origin-"));+ homes.push(home);+ const dataDir = join(home, ".openmausbot");+ mkdirSync(dataDir, { recursive: true });+ let output = "";+ const started = spawn(process.execPath, ["--import", offline, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: {+ PATH: process.env.PATH, HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir, OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1),+ OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: "5c9e3d2f-0b8a-4f7e-9d6c-2b3c4d5e6f70", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${NEW_HOST}`, OMB_CLOUD_LEGACY_ORIGINS: legacy,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ started.stdout?.on("data", (chunk) => { output += chunk; });+ started.stderr?.on("data", (chunk) => { output += chunk; });+ return { child: started, output: () => output };+}++/** Through the forwarder: the home's new name as Host, the edge's own forwarding headers, and X-Forwarded-Host naming the+ * old address, which the home must never read. */+const forwarded = (origin: string, extra: Record<string, string> = {}) => ({+ host: NEW_HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "x-forwarded-host": new URL(OLD).host, origin, ...extra,+});++/** Headers sent exactly as given: fetch would put its own Host in place of the forwarder's. */+function raw(method: string, path: string, headers: Record<string, string>, body?: string) {+ return new Promise<{ status: number; cookie: string; body: any }>((resolve, reject) => {+ const target = new URL(path, base);+ const sent = request({ hostname: target.hostname, port: target.port, path: target.pathname, method, headers }, (res) => {+ let text = "";+ res.setEncoding("utf8");+ res.on("data", (chunk) => { text += chunk; });+ res.on("end", () => {+ let parsed: any = null;+ try { parsed = JSON.parse(text); } catch {}+ resolve({ status: res.statusCode ?? 0, cookie: String(res.headers["set-cookie"]?.[0] ?? "").split(";")[0]!, body: parsed });+ });+ });+ sent.on("error", reject);+ sent.end(body);+ });+}++async function call(method: string, path: string, origin: string) {+ const { status, body } = await raw(method, path, forwarded(origin, { cookie, ...(method === "GET" ? {} : { "content-type": "application/json" }) }), method === "GET" ? undefined : "{}");+ return { status, body };+}++beforeAll(async () => {+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const port = await freePortBlock([0, 1]);+ base = `http://127.0.0.1:${port}`;+ const launched = await launch(`${OLD},https://omb-u-older.example.test`, port);+ child = launched.child;+ const deadline = Date.now() + 25_000;+ for (;;) {+ log = launched.output();+ if (child.exitCode !== null) throw new Error(`the server exited:\n${log}`);+ try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {}+ if (Date.now() > deadline) throw new Error(`the server did not start:\n${log}`);+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ // The Admin's signed pairing request, then a browser redeeming its code into its own cookie at the old address.+ const body = JSON.stringify({ label: "Chrome on Mac", ttlSeconds: 300 });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const granted = await raw("POST", "/api/cloud/pairing", {+ host: NEW_HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`,+ }, body);+ const paired = await raw("POST", "/api/auth/pair", forwarded(OLD, { "content-type": "application/json" }), JSON.stringify({ code: granted.body.code, cookie: true }));+ expect(paired.status, launched.output().slice(-2000)).toBe(200);+ cookie = paired.cookie;+ expect(cookie).toMatch(/^omb_session_\d+_\w+=omb_sess_/);+}, 60_000);++afterAll(async () => {+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ for (const home of homes) await removeTempDir(home);+ vi.restoreAllMocks();+});++it("takes a browser on the old address as its own, and refuses every other Origin as before", async () => {+ expect((await call("GET", "/api/bots", OLD)).status, log.slice(-2000)).toBe(200);+ expect((await call("POST", "/api/notifications/read-all", OLD)).status).toBe(200);+ expect((await call("GET", "/api/bots", "https://omb-u-older.example.test")).status).toBe(200);+ expect((await call("GET", "/api/bots", `https://${NEW_HOST}`)).status).toBe(200);+ for (const origin of ["https://evil.example", "https://omb-u-other.fly.dev", OLD.replace("https:", "http:")]) {+ const refused = await call("POST", "/api/notifications/read-all", origin);+ expect(refused, origin).toEqual({ status: 403, body: { error: "forbidden: cross-origin request" } });+ }+}, 60_000);++it("refuses to start with a former address that is not an exact https origin", async () => {+ const port = await freePortBlock([0, 1]);+ const bad = await launch("http://omb-u-0a1b2c3d4e5f.fly.dev", port);+ await new Promise<void>((resolve) => { if (bad.child.exitCode !== null) resolve(); else bad.child.once("exit", () => resolve()); });+ expect(bad.child.exitCode).not.toBe(0);+ expect(bad.output()).toMatch(/Cloud home configuration is invalid: every OMB_CLOUD_LEGACY_ORIGINS entry must be an exact https origin/);+}, 60_000);diff --git a/server/index.ts b/server/index.tsindex ec8c7232b4..bb50591773 100644--- a/server/index.ts+++ b/server/index.ts@@ -543,7 +543,7 @@ import {resolveRequestAuth,parseCookies,serializeSessionCookie,- sessionCookieName, ownerOrAdmin,+ sessionCookieName, ownerOrAdmin, acceptLegacyOrigins,} from "./request-auth.ts";import { cookieMaxAgeSeconds, formatPairingCode, pairingRequest, SessionRegistry, type SessionRecord } from "./sessions.ts";import { ThreadStarters } from "./thread-starters.ts";@@ -697,7 +697,7 @@ const CLOUD_HOME = cloudHomeConfiguration(CLOUD_ENV);const CLOUD_TEAM = CLOUD_HOME?.team ?? null, CLOUD_PERSONAL = CLOUD_HOME !== null && CLOUD_TEAM === null, TEAM_LABEL = CLOUD_TEAM ? { label: CLOUD_TEAM.name } : {};/** The language set on this server, else (on a Team Cloud) the team's default from the Admin. threadLanguage: the one a line in a conversation is written in, its one person's, else the place's (server/server-lines.ts). */const appLanguage = (): string | undefined => cfg.language ?? CLOUD_TEAM?.language; const personLanguages = createPersonLanguages({ dataDir: DATA_DIR, configured: appLanguage, privateTo: (threadId) => teamHost.privateTo(threadId) }); const threadLanguage = personLanguages.forThread; setConversationLanguage(threadLanguage);-if (CLOUD_HOME) repairMovedWorkspacePaths(DATA_DIR);+if (CLOUD_HOME) { repairMovedWorkspacePaths(DATA_DIR); acceptLegacyOrigins(CLOUD_HOME.legacyOrigins); }if (CLOUD_PERSONAL) sessions.requireAdmin(userError("serverError.cloud.personal"));const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null || ownHome.here(); const ownerLends = () => ownerLendingEnabled(cfg) && ownHome.takesMove(); const botLending = () => lendingEnabled() || (ownerLends() && sharedComputers.anyLent()); // ownerLends: a server only its one owner signs in to (own-home.ts) takes that owner's computer by default, never anyone else's (routes/shared-computers.ts); the desktop asks its person first, and the public description stays as it was.const CLOUD_HOME_LENDER = "cloud-home";diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 0b01c579c1..87b1b68e67 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -5,6 +5,7 @@ import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {+ acceptLegacyOrigins,BROWSER_SIGN_IN,clearSessionCookie,fromBrowser,@@ -445,6 +446,41 @@ describe("resolveRequestAuth", () => {expect(csrf.error).toBe("forbidden: cross-origin request");});+ it("takes a moved Cloud home's configured former address as its own, and no other, whatever X-Forwarded-Host says", () => {+ const token = pairedToken();+ const { credential } = sessions.openPairing({ browser: true, owner: "[email protected]" });+ const browser = sessions.exchange({ code: credential, label: "Chrome on Mac", source: "1.2.3.4", browser: true });+ if (!browser.ok) throw new Error(browser.error);+ // What the old address's forwarder sends: Host rewritten to this home's name, the page's own Origin kept.+ const forwarded = (origin: string, cookie = token, extra: Record<string, string> = {}) => ({+ host: "omb-u-1.homes.example", "x-forwarded-proto": "https", "x-forwarded-for": "203.0.113.9", "x-forwarded-host": "omb-u-1.fly.dev",+ cookie: `${cookieName}=${cookie}`, origin, ...extra,+ });+ const page = { "sec-fetch-site": "same-origin", "sec-fetch-dest": "empty" };+ try {+ acceptLegacyOrigins(["https://omb-u-1.fly.dev"]);+ expect(resolve(forwarded("https://omb-u-1.fly.dev"), "/api/bots", "POST").auth?.kind).toBe("session");+ expect(resolve(forwarded("https://OMB-U-1.fly.dev "), "/api/bots", "POST").auth?.kind).toBe("session");+ expect(resolve(forwarded("https://omb-u-1.fly.dev", browser.token, page), "/api/bots", "POST").auth?.kind).toBe("session");+ expect(resolve(forwarded("https://omb-u-1.fly.dev"), "/api/events").auth?.kind).toBe("session");+ expect(isSameOrigin(request({ host: "omb-u-1.homes.example", "x-forwarded-proto": "https", origin: "https://omb-u-1.fly.dev", upgrade: "websocket" }))).toBe(true);+ expect(provesSameOrigin(request({ host: "omb-u-1.homes.example", "x-forwarded-proto": "https", origin: "https://omb-u-1.fly.dev" }))).toBe(true);+ // Only the exact origin: not another app on the same provider, its http twin, a port, or a name X-Forwarded-Host gives.+ for (const origin of ["https://omb-u-2.fly.dev", "http://omb-u-1.fly.dev", "https://omb-u-1.fly.dev:8443", "https://evil.example"]) {+ const refused = resolve(forwarded(origin), "/api/bots", "POST");+ expect(refused, origin).toMatchObject({ auth: null, status: 403, error: "forbidden: cross-origin request" });+ }+ expect(isSameOrigin(request({ host: "omb-u-1.homes.example", "x-forwarded-proto": "https", "x-forwarded-host": "evil.example", origin: "https://evil.example" }))).toBe(false);+ // Never loopback trust: the former address is a remote page's, so a request with no session is still refused.+ expect(resolve({ host: "127.0.0.1:8799", origin: "https://omb-u-1.fly.dev" }).auth).toBeNull();+ } finally {+ acceptLegacyOrigins([]);+ }+ const unconfigured = resolve(forwarded("https://omb-u-1.fly.dev"), "/api/bots", "POST");+ expect(unconfigured).toMatchObject({ auth: null, status: 403, error: "forbidden: cross-origin request" });+ expect(isSameOrigin(request({ host: "omb-u-1.homes.example", "x-forwarded-proto": "https", "x-forwarded-host": "omb-u-1.fly.dev", origin: "https://omb-u-1.fly.dev" }))).toBe(false);+ });+it("lets a browser sign-in's session make changes only when the browser says the request is its own page's", () => {const { credential } = sessions.openPairing({ browser: true, owner: "[email protected]" });const signedIn = sessions.exchange({ code: credential, label: "Chrome on Mac", source: "1.2.3.4", browser: true });diff --git a/server/request-auth.ts b/server/request-auth.tsindex 8a2100bccb..b4e677282d 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -203,11 +203,21 @@ export function ipcPeer(req: IncomingMessage): boolean {return Boolean(socket) && socket.remoteAddress === undefined && socket.remoteFamily === undefined;}+let legacyOrigins: ReadonlySet<string> = new Set();++/** A Cloud home that moved to another provider (OMB_CLOUD_LEGACY_ORIGINS): its old address forwards here with Host+ * rewritten to this home's own name, so a page or client still on the old address sends that address as its Origin.+ * Security: only these exact origins count as this server's own besides its Host's; X-Forwarded-Host, which any client+ * writes, is never read. */+export function acceptLegacyOrigins(origins: readonly string[]): void {+ legacyOrigins = new Set(origins);+}+export function isSameOrigin(req: IncomingMessage): boolean {const origin = headerValue(req.headers.origin);if (!origin) return true;- const own = requestOrigin(req);- return own !== null && origin.trim().toLowerCase() === own;+ const own = requestOrigin(req), presented = origin.trim().toLowerCase();+ return own !== null && (presented === own || legacyOrigins.has(presented));}/** The desktop window's session adds the owner header to every request for this server, whichever page in it asks, and