Skip to content

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

control plane: MausBot Relay host tokens

milind-soni37793e3eba8b
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.md
index fa82a58e72..85585cbeb3 100644
--- a/cloudflare/control-plane/README.md
+++ b/cloudflare/control-plane/README.md
@@ -67,6 +67,7 @@ any new account row. Apply `0011` before deploying a Worker on Better Auth
| `POST` | `/v1/installations/self/push/register` | installation credential |
| `POST` | `/v1/installations/self/push/unregister` | installation credential |
| `POST` | `/v1/installations/self/push/send` | installation credential |
+| `POST` | `/v1/installations/self/relay-token` | installation credential |
Installation registration requires a stable `clientInstanceId`, a display
`name`, and a `platform` of `darwin`, `windows`, or `linux`; `appVersion` is
@@ -584,6 +585,49 @@ the same Cloudflare user share its 1,200 requests per five minutes. On
Workers Free, four accounts with `OMB_CLEANUP_SWEEP_LIMIT` 4 use the whole
50-subrequest budget, hence at most three extra accounts.
+### MausBot Relay
+
+Phones reach a desktop through MausBot Relay, end-to-end encrypted: the relay passes sealed bytes and can't open them
+(`companion/src/e2e/README.md`). This Worker only lets a computer onto the relay. It mints a 12-hour host token signed
+with Ed25519; the relay holds only the public key and checks tokens offline, so it can't mint one itself.
+
+`POST /v1/installations/self/relay-token` with the installation credential and
+`{"appVersion":"0.1.150","devices":{"e2e":2,"legacy":1}}` (counts of paired phones on the encrypted connection and on the
+old one; no identifiers) answers:
+
+| Status | Body | When |
+| --- | --- | --- |
+| 200 | `{token, hostId, nodes, expiresAt, refreshAfter}` (times in ms) | this computer is in the rollout |
+| 503 | `relay_unavailable` | no signing key yet, `RELAY_DISABLED` on, outside the rollout, or blocked (`relay_blocked_at`). The desktop stays on Wi-Fi and Tailscale |
+| 401 | `unauthorized` | the installation credential is invalid or expired |
+| 429 | `rate_limited` | more than 60 an hour |
+
+- **Host id.** 16 random bytes made once per installation (`installations.relay_host_id`, unique). Phones learn it at
+ pairing; it never changes.
+- **Token.** `b64u(payload) "." b64u(Ed25519 signature over the first part)`, payload
+ `{"v":1,"kid","hid","iid","iat","exp"}` in that order, `exp = iat + 12 h`. The desktop refreshes after an hour.
+ Minted tokens match the V8 test vector byte for byte.
+- **Nodes.** Ordered by rendezvous hash, highest `SHA256(hostId ‖ node)[0:8]` first, so each computer prefers one node
+ and load splits evenly. A node listed in `RELAY_NODES_AMERICAS` goes first for a request whose `cf.continent` is NA or
+ SA.
+- **Rollout.** `RELAY_ROLLOUT_PERCENT` admits a computer when `SHA256(hostId)[0:2] mod 100` is below it, so a computer
+ stays in as the number grows; `RELAY_ALLOW_INSTALLATIONS` admits named installations (the team) at any percentage.
+- **Adoption.** Every request records its counts in `relay_adoption`, in the rollout or not; `/healthz` reports
+ `relayAdoption: {e2eDevices, legacyDevices, installs}` over the last 30 days. The tunnel path retires on these numbers.
+- **Tunnels.** From `RELAY_CAPABLE_MIN_VERSION`, a desktop at that version or later that reports `legacyDevices: 0` gets
+ `409 relay_capable` instead of a new tunnel. An endpoint it already holds keeps working.
+
+Setup, once:
+
+1. `wrangler d1 migrations apply DB --config wrangler.jsonc` (0012).
+2. Make a key pair: a 32-byte Ed25519 seed for this Worker, its public key for the relay's `RELAY_TOKEN_KEYS`
+ (`{"k1":"<b64u public key>"}`). `wrangler secret put RELAY_TOKEN_SIGNING_KEY --config wrangler.jsonc` with the seed as
+ base64url. It is deliberately not in `secrets.required`: until it exists every request answers 503.
+3. Admit the team with `RELAY_ALLOW_INSTALLATIONS`, then raise `RELAY_ROLLOUT_PERCENT` 10, 50, 100 while watching the
+ relay alerts. `RELAY_DISABLED: "1"` turns every token off at once; tokens already issued expire within 12 hours.
+4. To rotate, give the relay both public keys, set `RELAY_TOKEN_KID` and the new secret, deploy, then drop the old key
+ from the relay after 12 hours.
+
### HighLevel OAuth relay
OpenMausBot's native HighLevel (GoHighLevel, and white-labels such as Growably)
diff --git a/cloudflare/control-plane/migrations/0012_relay.sql b/cloudflare/control-plane/migrations/0012_relay.sql
new file mode 100644
index 0000000000..9d1f9bffb3
--- /dev/null
+++ b/cloudflare/control-plane/migrations/0012_relay.sql
@@ -0,0 +1,19 @@
+-- MausBot Relay: each installation gets one stable relay host id the first time it asks for a relay token, and the
+-- adoption counts that gate retiring the tunnel path. The counts carry no device identifiers.
+ALTER TABLE installations ADD COLUMN relay_host_id TEXT;
+ALTER TABLE installations ADD COLUMN relay_blocked_at INTEGER;
+
+CREATE UNIQUE INDEX installations_relay_host_id_uidx
+ ON installations(relay_host_id)
+ WHERE relay_host_id IS NOT NULL;
+
+CREATE TABLE relay_adoption (
+ installation_id TEXT PRIMARY KEY REFERENCES installations(id) ON DELETE CASCADE,
+ app_version TEXT NOT NULL CHECK (length(app_version) BETWEEN 1 AND 32),
+ e2e_devices INTEGER NOT NULL CHECK (e2e_devices BETWEEN 0 AND 100),
+ legacy_devices INTEGER NOT NULL CHECK (legacy_devices BETWEEN 0 AND 100),
+ continent TEXT CHECK (continent IS NULL OR length(continent) = 2),
+ updated_at INTEGER NOT NULL
+);
+
+CREATE INDEX relay_adoption_updated_idx ON relay_adoption(updated_at);
diff --git a/cloudflare/control-plane/src/endpoints.ts b/cloudflare/control-plane/src/endpoints.ts
index 53322e3ae1..ccf43d2ee7 100644
--- a/cloudflare/control-plane/src/endpoints.ts
+++ b/cloudflare/control-plane/src/endpoints.ts
@@ -11,6 +11,7 @@ import type { ControlPlaneConfig, EndpointAccount } from "./config";
import {
ACTED_ON_ENDPOINT_SQL,
actedOnAccounts,
+ appVersionAtLeast,
chooseNewEndpointAccount,
endpointAccountFor,
neverReady,
@@ -235,15 +236,27 @@ async function shouldLeave(allocation: Allocation, account: EndpointAccount): Pr
return rejectionActive(snapshot, now) || scannedFull(account, snapshot, now);
}
-const provisionRequestSchema = z.strictObject({ appVersion: printableVersion.optional() });
+const provisionRequestSchema = z.strictObject({
+ appVersion: printableVersion.optional(),
+ /** Paired phones that can't use the encrypted connection yet; only they still need a tunnel. */
+ legacyDevices: z.number().int().min(0).max(100).optional(),
+});
-/** POST may carry `{ "appVersion": "0.1.103" }`, or no body. */
-async function reportedAppVersion(request: Request): Promise<string | null> {
+/** POST may carry `{ "appVersion": "0.1.103", "legacyDevices": 1 }`, or no body. */
+async function provisionRequest(request: Request): Promise<{ appVersion: string | null; legacyDevices: number | null }> {
const body = await readOptionalBoundedJSON(request);
- if (body === undefined) return null;
+ if (body === undefined) return { appVersion: null, legacyDevices: null };
const parsed = provisionRequestSchema.safeParse(body);
if (!parsed.success) throw new HTTPError(400, "invalid_request");
- return parsed.data.appVersion ?? null;
+ return { appVersion: parsed.data.appVersion ?? null, legacyDevices: parsed.data.legacyDevices ?? null };
+}
+
+/** A desktop that reaches its phones through the relay gets no new tunnel unless an old phone still needs one.
+ * Off until RELAY_CAPABLE_MIN_VERSION names the first release that can. */
+function relayCapableWithoutLegacy(env: Env, appVersion: string | null, legacyDevices: number | null): boolean {
+ const minimum = (env as unknown as Partial<Record<string, unknown>>).RELAY_CAPABLE_MIN_VERSION;
+ return typeof minimum === "string" && /^[0-9]+\.[0-9]+\.[0-9]+$/.test(minimum)
+ && legacyDevices === 0 && appVersionAtLeast(appVersion, minimum);
}
async function enforceEndpointRateLimit(
@@ -1159,13 +1172,15 @@ export async function provisionManagedEndpoint(
): Promise<Response> {
const installation = await requireInstallation(request, env);
await enforceEndpointRateLimit(env, installation.installation_id, "reconcile_endpoint");
- const reportedVersion = await reportedAppVersion(request);
+ const { appVersion: reportedVersion, legacyDevices } = await provisionRequest(request);
if (reportedVersion !== null && reportedVersion !== installation.app_version) {
await recordReportedAppVersion(env, installation.installation_id, reportedVersion);
}
const allocation = allocationFor(env, config, reportedVersion ?? installation.app_version);
+ const existing = await endpointRow(env, installation.installation_id);
+ if (!existing && relayCapableWithoutLegacy(env, reportedVersion, legacyDevices)) throw new HTTPError(409, "relay_capable");
// Only a new row chooses its account; an existing one keeps its own.
- const row = await endpointRow(env, installation.installation_id)
+ const row = existing
?? await ensureEndpointRow(env, installation.installation_id, await newEndpointAccount(config, allocation));
const account = endpointAccountFor(config, row);
if (!account) {
diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.ts
index d5808ff997..45d84ed2d9 100644
--- a/cloudflare/control-plane/src/index.ts
+++ b/cloudflare/control-plane/src/index.ts
@@ -21,6 +21,7 @@ import {
sweepHighLevelFlows,
} from "./highlevel";
import { registerPushDevice, sendPush, unregisterPushDevice } from "./push";
+import { issueRelayToken, relayAdoption } from "./relay";
import { capacityHealth, reportEndpointAccountProblems, scanTunnelCapacity } from "./tunnel-capacity";
import {
createInstallation,
@@ -141,6 +142,10 @@ async function route(
}
}
+ if (request.method === "POST" && url.pathname === "/v1/installations/self/relay-token") {
+ return issueRelayToken(request, env);
+ }
+
if (request.method === "POST" && url.pathname === "/v1/installations/self/push/register") {
return registerPushDevice(request, env);
}
@@ -211,10 +216,12 @@ export function createWorker(
// gate hosted sign-in on it. Provider capacity is reported beside it
// so a full quota never hides sign-in, recovery, or local pairing.
const capacity = await capacityHealth(env, healthConfig, ctx).catch(() => null);
+ const adoption = await relayAdoption(env).catch(() => null);
return secureResponse(json({
ok: true,
service: "openmausbot-control-plane",
...(capacity === null ? {} : { capacity }),
+ ...(adoption === null ? {} : { relayAdoption: adoption }),
}), request, null, requestId);
}
diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.ts
new file mode 100644
index 0000000000..0119f26834
--- /dev/null
+++ b/cloudflare/control-plane/src/relay.ts
@@ -0,0 +1,227 @@
+// MausBot Relay host tokens: `POST /v1/installations/self/relay-token`. The relay checks them offline with the public
+// key only, so this Worker's secret is the one thing that can let a computer onto the relay. Wire format: the
+// companion's e2e README, section 9 ("Relay token" and "Control plane endpoint").
+import { z } from "zod";
+
+import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";
+import { requireInstallation } from "./installations";
+
+const HOUR_MS = 60 * 60 * 1_000;
+export const RELAY_TOKEN_TTL_S = 12 * 60 * 60;
+export const RELAY_REFRESH_AFTER_S = 60 * 60;
+export const RELAY_TOKEN_LIMIT = 60;
+const ADOPTION_WINDOW_MS = 30 * 24 * HOUR_MS;
+const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
+const KID = /^k[0-9]{1,3}$/;
+const VERSION = /^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/;
+const UUIDISH = /^[0-9a-f-]{36}$/;
+const AMERICAS = new Set(["NA", "SA"]);
+
+const requestSchema = z.strictObject({
+ appVersion: z.string().regex(VERSION),
+ devices: z.strictObject({
+ e2e: z.number().int().min(0).max(100),
+ legacy: z.number().int().min(0).max(100),
+ }),
+});
+
+export interface RelaySettings {
+ kid: string;
+ signingKey: CryptoKey;
+ /** Every node, in no particular order. */
+ nodes: readonly string[];
+ /** Nodes ranked first for a computer in the Americas. */
+ americasNodes: ReadonlySet<string>;
+ rolloutPercent: number;
+ allowInstallations: ReadonlySet<string>;
+}
+
+const b64u = (bytes: Uint8Array): string => {
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+};
+
+function fromB64u(text: string): Uint8Array | null {
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;
+ try {
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4));
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
+ return b64u(bytes) === text ? bytes : null;
+ } catch {
+ return null;
+ }
+}
+
+const sha256 = async (bytes: Uint8Array): Promise<Uint8Array> => new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(bytes)));
+
+/** WebCrypto takes an Ed25519 private key only as PKCS#8: the RFC 8410 prefix, then the 32-byte seed. */
+export async function importSigningSeed(seed: Uint8Array): Promise<CryptoKey> {
+ if (seed.length !== 32) throw new Error("an Ed25519 seed is 32 bytes");
+ const der = new Uint8Array(48);
+ der.set([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]);
+ der.set(seed, 16);
+ return crypto.subtle.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
+}
+
+const listVar = (value: unknown): string[] =>
+ typeof value === "string" ? value.split(",").map((entry) => entry.trim()).filter(Boolean) : [];
+
+let cachedKey: { secret: string; key: Promise<CryptoKey> } | null = null;
+
+/** Null while the relay is off: no signing secret, no nodes, or the kill switch. Never throws on a bad value. */
+export async function readRelaySettings(env: Env): Promise<RelaySettings | null> {
+ const vars = env as unknown as Partial<Record<string, unknown>>;
+ if (vars.RELAY_DISABLED === "1") return null;
+ const secret = vars.RELAY_TOKEN_SIGNING_KEY;
+ const kid = typeof vars.RELAY_TOKEN_KID === "string" ? vars.RELAY_TOKEN_KID : "k1";
+ const nodes = listVar(vars.RELAY_NODES);
+ const seed = typeof secret === "string" ? fromB64u(secret.trim()) : null;
+ if (!seed || seed.length !== 32 || !KID.test(kid) || nodes.length === 0 || nodes.length > 4) return null;
+ if (!nodes.every((node) => RELAY_HOST.test(node))) return null;
+ const percent = Number(vars.RELAY_ROLLOUT_PERCENT ?? "0");
+ let cached = cachedKey;
+ if (!cached || cached.secret !== secret) {
+ cached = { secret: secret as string, key: importSigningSeed(seed) };
+ cachedKey = cached;
+ }
+ return {
+ kid,
+ signingKey: await cached.key,
+ nodes,
+ americasNodes: new Set(listVar(vars.RELAY_NODES_AMERICAS).filter((node) => nodes.includes(node))),
+ rolloutPercent: Number.isInteger(percent) && percent >= 0 && percent <= 100 ? percent : 0,
+ allowInstallations: new Set(listVar(vars.RELAY_ALLOW_INSTALLATIONS).filter((id) => UUIDISH.test(id))),
+ };
+}
+
+/** Rendezvous order: highest `SHA256(hostId ‖ node)[0:8]` first, so each computer prefers one node and load splits
+ * evenly. A node marked for the Americas goes first for a computer there. */
+export async function orderNodes(hostId: Uint8Array, settings: Pick<RelaySettings, "nodes" | "americasNodes">, continent: string | null): Promise<string[]> {
+ const scored = await Promise.all(settings.nodes.map(async (node) => {
+ const digest = await sha256(new Uint8Array([...hostId, ...new TextEncoder().encode(node)]));
+ return { node, score: new DataView(digest.buffer).getBigUint64(0) };
+ }));
+ const americas = continent !== null && AMERICAS.has(continent);
+ return scored
+ .sort((a, b) => {
+ const regional = Number(americas && settings.americasNodes.has(b.node)) - Number(americas && settings.americasNodes.has(a.node));
+ return regional || (a.score === b.score ? 0 : a.score > b.score ? -1 : 1);
+ })
+ .map((entry) => entry.node);
+}
+
+/** The percentage bucket of a host: stable, so a computer stays in or out as the rollout grows. */
+export async function rolloutBucket(hostId: Uint8Array): Promise<number> {
+ const digest = await sha256(hostId);
+ return new DataView(digest.buffer).getUint16(0) % 100;
+}
+
+/** Field order is part of the format: the signature covers exactly these bytes. */
+export async function mintRelayToken(
+ claims: { kid: string; hid: string; iid: string; iat: number; exp: number },
+ signingKey: CryptoKey,
+): Promise<string> {
+ const payload = JSON.stringify({ v: 1, kid: claims.kid, hid: claims.hid, iid: claims.iid, iat: claims.iat, exp: claims.exp });
+ const body = b64u(new TextEncoder().encode(payload));
+ const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, signingKey, new TextEncoder().encode(body)));
+ return `${body}.${b64u(signature)}`;
+}
+
+function limitStatement(env: Env, installationId: string, now: number) {
+ const cutoff = now - HOUR_MS;
+ return env.DB.prepare(
+ `INSERT INTO installation_action_rate_limits
+ (installation_id, action, window_started_at, attempts, updated_at)
+ VALUES (?, 'relay_token', ?, 1, ?)
+ ON CONFLICT(installation_id, action) DO UPDATE SET
+ window_started_at = CASE WHEN window_started_at <= ? THEN excluded.window_started_at ELSE window_started_at END,
+ attempts = CASE WHEN window_started_at <= ? THEN 1 ELSE attempts + 1 END,
+ updated_at = excluded.updated_at
+ WHERE window_started_at <= ? OR attempts < ?`,
+ ).bind(installationId, now, now, cutoff, cutoff, cutoff, RELAY_TOKEN_LIMIT);
+}
+
+interface RelayRow {
+ relay_host_id: string | null;
+ relay_blocked_at: number | null;
+}
+
+/** Made once per installation; the unique index settles a race between two first requests. */
+async function hostIdFor(env: Env, installationId: string): Promise<{ hostId: string; blocked: boolean }> {
+ const read = () => env.DB.prepare("SELECT relay_host_id, relay_blocked_at FROM installations WHERE id = ?").bind(installationId).first<RelayRow>();
+ let row = await read();
+ if (row && !row.relay_host_id) {
+ await env.DB.prepare("UPDATE installations SET relay_host_id = ? WHERE id = ? AND relay_host_id IS NULL")
+ .bind(b64u(crypto.getRandomValues(new Uint8Array(16))), installationId)
+ .run();
+ row = await read();
+ }
+ if (!row?.relay_host_id) throw new HTTPError(500, "internal_error");
+ return { hostId: row.relay_host_id, blocked: row.relay_blocked_at !== null };
+}
+
+const unavailable = () => errorResponse(503, "relay_unavailable");
+
+export async function issueRelayToken(request: Request, env: Env): Promise<Response> {
+ const installation = await requireInstallation(request, env);
+ const parsed = requestSchema.safeParse(await readBoundedJSON(request).catch(() => null));
+ if (!parsed.success) throw new HTTPError(400, "invalid_request");
+ const now = Date.now();
+ const [limited] = await env.DB.batch([limitStatement(env, installation.installation_id, now)]);
+ if (limited?.meta.changes === 0) {
+ const response = errorResponse(429, "rate_limited");
+ response.headers.set("retry-after", "60");
+ return response;
+ }
+ const settings = await readRelaySettings(env);
+ if (!settings) return unavailable();
+ const { hostId, blocked } = await hostIdFor(env, installation.installation_id);
+ const continent = (request as Request & { cf?: { continent?: unknown } }).cf?.continent;
+ const region = typeof continent === "string" && /^[A-Z]{2}$/.test(continent) ? continent : null;
+ // Counted for every relay-capable desktop, in the rollout or not: the tunnel path retires on these numbers.
+ await env.DB.prepare(
+ `INSERT INTO relay_adoption (installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(installation_id) DO UPDATE SET
+ app_version = excluded.app_version, e2e_devices = excluded.e2e_devices,
+ legacy_devices = excluded.legacy_devices, continent = excluded.continent, updated_at = excluded.updated_at`,
+ ).bind(installation.installation_id, parsed.data.appVersion, parsed.data.devices.e2e, parsed.data.devices.legacy, region, now).run();
+ if (blocked) return unavailable();
+ const hostBytes = fromB64u(hostId) as Uint8Array;
+ const included = settings.allowInstallations.has(installation.installation_id)
+ || (await rolloutBucket(hostBytes)) < settings.rolloutPercent;
+ if (!included) return unavailable();
+ const iat = Math.floor(now / 1000);
+ const token = await mintRelayToken({ kid: settings.kid, hid: hostId, iid: installation.installation_id, iat, exp: iat + RELAY_TOKEN_TTL_S }, settings.signingKey);
+ return json({
+ token,
+ hostId,
+ nodes: await orderNodes(hostBytes, settings, region),
+ expiresAt: (iat + RELAY_TOKEN_TTL_S) * 1000,
+ refreshAfter: (iat + RELAY_REFRESH_AFTER_S) * 1000,
+ });
+}
+
+const ADOPTION_MEMO_MS = 5 * 60 * 1_000;
+
+export type RelayAdoption = {
+ e2eDevices: number;
+ legacyDevices: number;
+ installs: number;
+};
+
+let adoptionMemo: { at: number; value: RelayAdoption } | null = null;
+
+/** Sums only, for /healthz: how far the encrypted connection has replaced the tunnel. Read at most every five
+ * minutes per isolate, since desktops call /healthz often. */
+export async function relayAdoption(env: Env, now = Date.now()): Promise<RelayAdoption> {
+ if (adoptionMemo && now - adoptionMemo.at < ADOPTION_MEMO_MS) return adoptionMemo.value;
+ const row = await env.DB.prepare(
+ `SELECT COALESCE(SUM(e2e_devices), 0) AS e2e, COALESCE(SUM(legacy_devices), 0) AS legacy, COUNT(*) AS installs
+ FROM relay_adoption WHERE updated_at > ?`,
+ ).bind(now - ADOPTION_WINDOW_MS).first<{ e2e: number; legacy: number; installs: number }>();
+ const value = { e2eDevices: row?.e2e ?? 0, legacyDevices: row?.legacy ?? 0, installs: row?.installs ?? 0 };
+ adoptionMemo = { at: now, value };
+ return value;
+}
diff --git a/cloudflare/control-plane/test/control-plane.test.ts b/cloudflare/control-plane/test/control-plane.test.ts
index bbcc564a1a..280053f4f4 100644
--- a/cloudflare/control-plane/test/control-plane.test.ts
+++ b/cloudflare/control-plane/test/control-plane.test.ts
@@ -294,6 +294,7 @@ describe("control-plane migrations and health", () => {
providerRejectedAt: null,
reclaim: { mode: "on", pending: 0 },
},
+ relayAdoption: { e2eDevices: 0, legacyDevices: 0, installs: 0 },
});
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("access-control-allow-origin")).toBeNull();
@@ -304,7 +305,8 @@ describe("control-plane migrations and health", () => {
const first = await call("/healthz");
const second = await call("/healthz");
await expect(second.json()).resolves.toEqual(await first.json());
- expect(prepare).toHaveBeenCalledTimes(1);
+ expect(prepare.mock.calls.filter(([sql]) => !sql.includes("relay_adoption"))).toHaveLength(1);
+ expect(prepare.mock.calls.filter(([sql]) => sql.includes("relay_adoption")).length).toBeLessThanOrEqual(1);
// The public response stays uncached; only the internal copy expires on
// its own, which bounds how far the report can trail D1.
expect(second.headers.get("cache-control")).toBe("no-store");
@@ -395,6 +397,13 @@ describe("control-plane migrations and health", () => {
OMB_TUNNEL_RECLAIM: env.OMB_TUNNEL_RECLAIM,
OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: env.OMB_TUNNEL_OFFLINE_RECLAIM_DAYS,
OMB_CLEANUP_SWEEP_LIMIT: env.OMB_CLEANUP_SWEEP_LIMIT,
+ RELAY_NODES: env.RELAY_NODES,
+ RELAY_NODES_AMERICAS: env.RELAY_NODES_AMERICAS,
+ RELAY_TOKEN_KID: env.RELAY_TOKEN_KID,
+ RELAY_ROLLOUT_PERCENT: env.RELAY_ROLLOUT_PERCENT,
+ RELAY_ALLOW_INSTALLATIONS: env.RELAY_ALLOW_INSTALLATIONS,
+ RELAY_DISABLED: env.RELAY_DISABLED,
+ RELAY_CAPABLE_MIN_VERSION: env.RELAY_CAPABLE_MIN_VERSION,
BETTER_AUTH_SECRET: "too-short",
};
const request = new Request(`${BASE_URL}/healthz`);
diff --git a/cloudflare/control-plane/test/managed-endpoints.test.ts b/cloudflare/control-plane/test/managed-endpoints.test.ts
index b7d1f985ec..88795c4b6d 100644
--- a/cloudflare/control-plane/test/managed-endpoints.test.ts
+++ b/cloudflare/control-plane/test/managed-endpoints.test.ts
@@ -3370,6 +3370,7 @@ describe("managed endpoints in several Cloudflare accounts", () => {
},
],
},
+ relayAdoption: { e2eDevices: 0, legacyDevices: 0, installs: 0 },
});
for (const secret of [
PRIMARY_ACCOUNT,
diff --git a/cloudflare/control-plane/test/relay.test.ts b/cloudflare/control-plane/test/relay.test.ts
new file mode 100644
index 0000000000..36f4e45527
--- /dev/null
+++ b/cloudflare/control-plane/test/relay.test.ts
@@ -0,0 +1,192 @@
+import { env } from "cloudflare:workers";
+import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";
+import { describe, expect, it } from "vitest";
+
+import vectors from "../../../companion/src/e2e/vectors/v1.json";
+import { createAuth } from "../src/auth";
+import { readConfig } from "../src/config";
+import { createWorker } from "../src/index";
+import { importSigningSeed, mintRelayToken, orderNodes, RELAY_TOKEN_LIMIT, rolloutBucket } from "../src/relay";
+
+const BASE_URL = "https://auth.openmausbot.test";
+const hex = (text: string) => Uint8Array.from(text.match(/../g)!.map((pair) => Number.parseInt(pair, 16)));
+const b64u = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+const fromB64u = (text: string) => Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4)), (c) => c.charCodeAt(0));
+
+type TestWorker = ReturnType<typeof createWorker>;
+const worker = createWorker((async () => new Response('{"success":false,"errors":[]}', { status: 500 })) as typeof fetch);
+const seed = crypto.getRandomValues(new Uint8Array(32));
+
+function relayEnv(extra: Record<string, string> = {}): Env {
+ return { ...env, RELAY_TOKEN_SIGNING_KEY: b64u(seed), RELAY_ROLLOUT_PERCENT: "100", ...extra } as unknown as Env;
+}
+
+async function call(testEnv: Env, path: string, options: { body?: unknown; token?: string; method?: string; via?: TestWorker } = {}) {
+ const headers = new Headers();
+ if (options.token) headers.set("authorization", `Bearer ${options.token}`);
+ if (options.body !== undefined) headers.set("content-type", "application/json");
+ const request = new Request(`${BASE_URL}${path}`, {
+ method: options.method ?? "POST",
+ headers,
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
+ });
+ const ctx = createExecutionContext();
+ const response = await (options.via ?? worker).fetch(request, testEnv, ctx);
+ await waitOnExecutionContext(ctx);
+ return response;
+}
+
+async function installation(email: string) {
+ const ctx = createExecutionContext();
+ const auth = createAuth(env, ctx, readConfig(env), crypto.randomUUID());
+ const otp = await auth.api.createVerificationOTP({ body: { email, type: "sign-in" } });
+ await waitOnExecutionContext(ctx);
+ const signedIn = await call(env, "/api/auth/sign-in/email-otp", { body: { email, name: "Relay owner", otp } });
+ const accountToken = signedIn.headers.get("set-auth-token")!;
+ const created = await call(env, "/v1/installations", {
+ token: accountToken,
+ body: { clientInstanceId: crypto.randomUUID(), name: "Test computer", platform: "darwin" },
+ });
+ const body = await created.json<{ credential: string; installation: { id: string } }>();
+ return { credential: body.credential, id: body.installation.id };
+}
+
+const ask = (testEnv: Env, credential: string, devices = { e2e: 1, legacy: 0 }) =>
+ call(testEnv, "/v1/installations/self/relay-token", { token: credential, body: { appVersion: "0.1.150", devices } });
+
+interface Issued {
+ token: string;
+ hostId: string;
+ nodes: string[];
+ expiresAt: number;
+ refreshAfter: number;
+}
+
+async function verify(token: string, publicKey: CryptoKey) {
+ const [body, signature] = token.split(".");
+ const ok = await crypto.subtle.verify({ name: "Ed25519" }, publicKey, fromB64u(signature), new TextEncoder().encode(body));
+ return { ok, claims: JSON.parse(new TextDecoder().decode(fromB64u(body))) as Record<string, unknown> };
+}
+
+async function publicKeyOf(seedBytes: Uint8Array): Promise<CryptoKey> {
+ const pair = await crypto.subtle.importKey("pkcs8", new Uint8Array([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20, ...seedBytes]), { name: "Ed25519" }, true, ["sign"]);
+ const jwk = await crypto.subtle.exportKey("jwk", pair);
+ return crypto.subtle.importKey("jwk", { kty: "OKP", crv: "Ed25519", x: jwk.x }, { name: "Ed25519" }, true, ["verify"]);
+}
+
+describe("relay host tokens", () => {
+ it("are byte for byte the V8 vector token, so every relay that passes V8 accepts them", async () => {
+ const key = await importSigningSeed(hex(vectors.V8.seed));
+ expect(await mintRelayToken(vectors.V8.claims, key)).toBe(vectors.V8.token);
+ const publicKey = await publicKeyOf(hex(vectors.V8.seed));
+ expect(b64u(new Uint8Array(await crypto.subtle.exportKey("raw", publicKey)))).toBe(vectors.V8.publicKeyB64u);
+ });
+
+ it("are refused without an installation credential", async () => {
+ expect((await call(relayEnv(), "/v1/installations/self/relay-token", { body: { appVersion: "0.1.150", devices: { e2e: 0, legacy: 0 } } })).status).toBe(401);
+ });
+
+ it("answer 503 relay_unavailable until the signing key exists, and while the kill switch is on", async () => {
+ const { credential } = await installation("[email protected]");
+ for (const testEnv of [env, relayEnv({ RELAY_DISABLED: "1" }), relayEnv({ RELAY_NODES: "relay.example.com" })]) {
+ const response = await ask(testEnv, credential);
+ expect(response.status).toBe(503);
+ expect(await response.json()).toEqual({ error: "relay_unavailable" });
+ }
+ });
+
+ it("mint a 12 h token for a stable host id, with the node order and the refresh time", async () => {
+ const { credential, id } = await installation("[email protected]");
+ const before = Math.floor(Date.now() / 1000);
+ const first = await (await ask(relayEnv(), credential)).json<Issued>();
+ const second = await (await ask(relayEnv(), credential)).json<Issued>();
+ expect(second.hostId).toBe(first.hostId);
+ expect(fromB64u(first.hostId)).toHaveLength(16);
+ const { ok, claims } = await verify(first.token, await publicKeyOf(seed));
+ expect(ok).toBe(true);
+ expect(Object.keys(claims)).toEqual(["v", "kid", "hid", "iid", "iat", "exp"]);
+ expect(claims).toMatchObject({ v: 1, kid: "k1", hid: first.hostId, iid: id });
+ expect(claims.exp).toBe((claims.iat as number) + 43_200);
+ expect(claims.iat as number).toBeGreaterThanOrEqual(before);
+ expect(first.expiresAt).toBe((claims.exp as number) * 1000);
+ expect(first.refreshAfter).toBe(((claims.iat as number) + 3600) * 1000);
+ expect(first.nodes).toEqual(await orderNodes(fromB64u(first.hostId), { nodes: ["relay1.openmausbot.com", "relay2.openmausbot.com"], americasNodes: new Set() }, null));
+ });
+
+ it("admit by rollout bucket, or by name, and never a blocked installation", async () => {
+ const { credential, id } = await installation("[email protected]");
+ const outside = await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: "0" }), credential);
+ expect(outside.status).toBe(503);
+ const named = await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: "0", RELAY_ALLOW_INSTALLATIONS: `other,${id}` }), credential);
+ expect(named.status).toBe(200);
+ const { hostId } = await named.json<Issued>();
+ const bucket = await rolloutBucket(fromB64u(hostId));
+ expect((await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: String(bucket) }), credential)).status).toBe(503);
+ expect((await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: String(bucket + 1) }), credential)).status).toBe(200);
+ await env.DB.prepare("UPDATE installations SET relay_blocked_at = ? WHERE id = ?").bind(Date.now(), id).run();
+ expect((await ask(relayEnv(), credential)).status).toBe(503);
+ });
+
+ it(`allow ${RELAY_TOKEN_LIMIT} requests an hour per installation`, async () => {
+ const { credential } = await installation("[email protected]");
+ for (let index = 0; index < RELAY_TOKEN_LIMIT; index += 1) expect((await ask(relayEnv(), credential)).status).toBe(200);
+ const limited = await ask(relayEnv(), credential);
+ expect(limited.status).toBe(429);
+ expect(limited.headers.get("retry-after")).toBe("60");
+ });
+
+ it("refuse a request body outside the schema", async () => {
+ const { credential } = await installation("[email protected]");
+ for (const body of [{ appVersion: "0.1.150" }, { appVersion: "x", devices: { e2e: 0, legacy: 0 } }, { appVersion: "0.1.150", devices: { e2e: 0, legacy: 0, extra: 1 } }]) {
+ expect((await call(relayEnv(), "/v1/installations/self/relay-token", { token: credential, body })).status).toBe(400);
+ }
+ });
+
+ it("report adoption sums on /healthz, with no identifiers", async () => {
+ const { credential } = await installation("[email protected]");
+ await ask(relayEnv({ RELAY_ROLLOUT_PERCENT: "0" }), credential, { e2e: 2, legacy: 1 });
+ const health = await (await call(relayEnv(), "/healthz", { method: "GET" })).json<{ relayAdoption: Record<string, number> }>();
+ expect(Object.keys(health.relayAdoption).sort()).toEqual(["e2eDevices", "installs", "legacyDevices"]);
+ expect(health.relayAdoption.e2eDevices).toBeGreaterThanOrEqual(2);
+ expect(health.relayAdoption.legacyDevices).toBeGreaterThanOrEqual(1);
+ });
+});
+
+describe("node order", () => {
+ const nodes = ["relay1.openmausbot.com", "relay2.openmausbot.com", "relay3.openmausbot.com"];
+
+ it("is the rendezvous hash: highest SHA256(hostId ‖ node)[0:8] first", async () => {
+ const hostId = crypto.getRandomValues(new Uint8Array(16));
+ const scores = await Promise.all(nodes.map(async (node) => {
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array([...hostId, ...new TextEncoder().encode(node)])));
+ return { node, score: [...digest.subarray(0, 8)].map((byte) => byte.toString(16).padStart(2, "0")).join("") };
+ }));
+ const expected = scores.sort((a, b) => (a.score < b.score ? 1 : -1)).map((entry) => entry.node);
+ expect(await orderNodes(hostId, { nodes, americasNodes: new Set() }, "EU")).toEqual(expected);
+ });
+
+ it("puts an Americas node first for a computer in the Americas only", async () => {
+ const hostId = crypto.getRandomValues(new Uint8Array(16));
+ const settings = { nodes, americasNodes: new Set(["relay3.openmausbot.com"]) };
+ expect((await orderNodes(hostId, settings, "SA"))[0]).toBe("relay3.openmausbot.com");
+ expect(await orderNodes(hostId, settings, "EU")).toEqual(await orderNodes(hostId, { nodes, americasNodes: new Set() }, null));
+ });
+});
+
+describe("tunnels for relay-capable desktops", () => {
+ it("are refused with 409 relay_capable when no old phone needs one, once the release is named", async () => {
+ const { credential } = await installation("[email protected]");
+ const gated = { ...env, RELAY_CAPABLE_MIN_VERSION: "0.1.150" } as unknown as Env;
+ const refused = await call(gated, "/v1/installations/self/endpoint", { token: credential, body: { appVersion: "0.1.151", legacyDevices: 0 } });
+ expect(refused.status).toBe(409);
+ expect(await refused.json()).toEqual({ error: "relay_capable" });
+ for (const [testEnv, body] of [
+ [gated, { appVersion: "0.1.151", legacyDevices: 1 }],
+ [gated, { appVersion: "0.1.149", legacyDevices: 0 }],
+ [gated, { appVersion: "0.1.151" }],
+ [env, { appVersion: "0.1.151", legacyDevices: 0 }],
+ ] as const) {
+ expect((await call(testEnv, "/v1/installations/self/endpoint", { token: credential, body })).status).not.toBe(409);
+ }
+ });
+});
diff --git a/cloudflare/control-plane/wrangler.jsonc b/cloudflare/control-plane/wrangler.jsonc
index af58d84113..19f872d3aa 100644
--- a/cloudflare/control-plane/wrangler.jsonc
+++ b/cloudflare/control-plane/wrangler.jsonc
@@ -71,7 +71,21 @@
// HighLevel Marketplace app exactly.
"HIGHLEVEL_CLIENT_ID": "6ad0c3b87999ff4de949c785-mv9n5v73",
"HIGHLEVEL_REDIRECT_URL": "https://accounts.openmausbot.com/v1/highlevel/callback",
- "HIGHLEVEL_SCOPES": "contacts.readonly contacts.write opportunities.readonly opportunities.write conversations.readonly locations.readonly calendars.readonly calendars/events.readonly users.readonly"
+ "HIGHLEVEL_SCOPES": "contacts.readonly contacts.write opportunities.readonly opportunities.write conversations.readonly locations.readonly calendars.readonly calendars/events.readonly users.readonly",
+ // MausBot Relay (README "MausBot Relay"). Host tokens are signed with RELAY_TOKEN_SIGNING_KEY (b64u of a 32-byte
+ // Ed25519 seed, `wrangler secret put`), deliberately not in secrets.required: until it exists the endpoint answers
+ // 503 relay_unavailable and desktops stay on Wi-Fi and Tailscale. The relay holds only the matching public key.
+ // RELAY_ROLLOUT_PERCENT (0-100) admits computers by a stable hash of their host id; RELAY_ALLOW_INSTALLATIONS
+ // (comma-separated installation ids) admits a few by name; RELAY_DISABLED "1" turns every token off.
+ "RELAY_NODES": "relay1.openmausbot.com,relay2.openmausbot.com",
+ "RELAY_NODES_AMERICAS": "",
+ "RELAY_TOKEN_KID": "k1",
+ "RELAY_ROLLOUT_PERCENT": "0",
+ "RELAY_ALLOW_INSTALLATIONS": "",
+ "RELAY_DISABLED": "0",
+ // The first desktop release that reaches phones through the relay. From it, a desktop with no old phones paired
+ // gets 409 relay_capable instead of a new tunnel. Empty: never refused.
+ "RELAY_CAPABLE_MIN_VERSION": ""
},
"secrets": {
"required": ["BETTER_AUTH_SECRET", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_TOKEN_MAUSBOT_SI"]