Skip to content

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

control plane: the relay stays off quietly on a database without migration 0012

milind-soni21eb8878ebf9
diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.ts
index 0119f26834..66d2d10f7d 100644
--- a/cloudflare/control-plane/src/relay.ts
+++ b/cloudflare/control-plane/src/relay.ts
@@ -163,6 +163,16 @@ async function hostIdFor(env: Env, installationId: string): Promise<{ hostId: st
const unavailable = () => errorResponse(503, "relay_unavailable");
+let schemaWarned = false;
+/** A Worker deployed before migration 0012 must keep pairing and health working: the relay just stays off. */
+function relaySchemaMissing(): Response {
+ if (!schemaWarned) {
+ schemaWarned = true;
+ console.error(JSON.stringify({ message: "relay tables missing; apply migration 0012", errorCode: "relay_schema" }));
+ }
+ return 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));
@@ -176,17 +186,25 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respo
}
const settings = await readRelaySettings(env);
if (!settings) return unavailable();
- const { hostId, blocked } = await hostIdFor(env, installation.installation_id);
+ let host: { hostId: string; blocked: boolean };
+ try {
+ host = await hostIdFor(env, installation.installation_id);
+ } catch (error) {
+ if (error instanceof HTTPError) throw error;
+ return relaySchemaMissing();
+ }
+ const { hostId, blocked } = host;
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(
+ const counted = 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();
+ ).bind(installation.installation_id, parsed.data.appVersion, parsed.data.devices.e2e, parsed.data.devices.legacy, region, now).run().then(() => true, () => false);
+ if (!counted) return relaySchemaMissing();
if (blocked) return unavailable();
const hostBytes = fromB64u(hostId) as Uint8Array;
const included = settings.allowInstallations.has(installation.installation_id)
@@ -211,17 +229,23 @@ export type RelayAdoption = {
installs: number;
};
-let adoptionMemo: { at: number; value: RelayAdoption } | null = null;
+let adoptionMemo: { at: number; value: RelayAdoption | null } | null = null;
+
+/** Test-only. */
+export function forgetRelayAdoption(): void {
+ adoptionMemo = 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> {
+ * minutes per isolate, since desktops call /healthz often; a failed read (no migration 0012 yet) is remembered too,
+ * as null, and /healthz leaves the field out. */
+export async function relayAdoption(env: Env, now = Date.now()): Promise<RelayAdoption | null> {
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 };
+ ).bind(now - ADOPTION_WINDOW_MS).first<{ e2e: number; legacy: number; installs: number }>().then((found) => found, () => undefined);
+ const value = row === undefined ? null : { 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/relay.test.ts b/cloudflare/control-plane/test/relay.test.ts
index 36f4e45527..dbba8c3163 100644
--- a/cloudflare/control-plane/test/relay.test.ts
+++ b/cloudflare/control-plane/test/relay.test.ts
@@ -1,12 +1,12 @@
import { env } from "cloudflare:workers";
-import { createExecutionContext, waitOnExecutionContext } from "cloudflare:test";
+import { applyD1Migrations, createExecutionContext, createScheduledController, 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";
+import { forgetRelayAdoption, 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)));
@@ -190,3 +190,51 @@ describe("tunnels for relay-capable desktops", () => {
}
});
});
+
+describe("a Worker deployed before migration 0012", () => {
+ it("keeps health, pairing endpoints and the cron working, and the relay off", async () => {
+ const db = env.MIGRATION_DB;
+ const relayMigration = env.TEST_MIGRATIONS.findIndex((migration) => migration.name.startsWith("0012_"));
+ expect(relayMigration).toBeGreaterThan(0);
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, relayMigration));
+ const oldEnv = { ...relayEnv({ RELAY_CAPABLE_MIN_VERSION: "0.1.150" }), DB: db } as unknown as Env;
+
+ const now = Date.now();
+ const lookup = b64u(crypto.getRandomValues(new Uint8Array(16)));
+ const credential = `omb_install_${lookup}.${b64u(crypto.getRandomValues(new Uint8Array(32)))}`;
+ const secretHash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credential)))]
+ .map((byte) => byte.toString(16).padStart(2, "0")).join("");
+ const installationId = crypto.randomUUID();
+ await db.batch([
+ db.prepare('INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)').bind("old-user", "Old", "[email protected]", now, now),
+ db.prepare("INSERT INTO installations (id, owner_user_id, client_instance_id, display_name, platform, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
+ .bind(installationId, "old-user", crypto.randomUUID(), "Old computer", "darwin", now, now),
+ db.prepare("INSERT INTO installation_credentials (id, installation_id, lookup_id, secret_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)")
+ .bind(crypto.randomUUID(), installationId, lookup, secretHash, now, now + 3_600_000),
+ ]);
+
+ forgetRelayAdoption();
+ const health = await call(oldEnv, "/healthz", { method: "GET" });
+ expect(health.status).toBe(200);
+ const body = await health.json<Record<string, unknown>>();
+ expect(body).toMatchObject({ ok: true, service: "openmausbot-control-plane" });
+ expect(body).not.toHaveProperty("relayAdoption");
+
+ const token = await ask(oldEnv, credential);
+ expect(token.status).toBe(503);
+ expect(await token.json()).toEqual({ error: "relay_unavailable" });
+
+ const refused = await call(oldEnv, "/v1/installations/self/endpoint", { token: credential, body: { appVersion: "0.1.151", legacyDevices: 0 } });
+ expect(refused.status).toBe(409);
+ for (const body of [{ appVersion: "0.1.151", legacyDevices: 1 }, { appVersion: "0.1.149" }]) {
+ const response = await call(oldEnv, "/v1/installations/self/endpoint", { token: credential, body });
+ expect(response.status).not.toBe(500);
+ expect(await response.json()).not.toEqual({ error: "internal_error" });
+ }
+
+ const ctx = createExecutionContext();
+ worker.scheduled(createScheduledController(), oldEnv, ctx);
+ await waitOnExecutionContext(ctx);
+ expect((await call(oldEnv, "/v1/installations/self", { token: credential, method: "GET" })).status).toBe(200);
+ });
+});