Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Control plane: a self-hosted server keeps its tunnel under the old-phone cutoff (#5357)
Milind Soni62ea04ce1c2e
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.mdindex cb4608ac43..3f87a77017 100644--- a/cloudflare/control-plane/README.md+++ b/cloudflare/control-plane/README.md@@ -632,7 +632,7 @@ old one; no identifiers) answers:### Releasing tunnelsA running desktop keeps its connector up, so idle reclaim never sees its tunnel as idle. These rules give tunnels back-once the relay has replaced them. Each switch is off in `wrangler.jsonc`; all need migration `0015`. The cron only+once the relay has replaced them. Each switch is off in `wrangler.jsonc`; all need migrations `0015` and `0016`. The cron onlymarks rows `deleting` (at most 20 a run, every reason together) and the cleanup sweep removes them; the row and itshostname stay, so a later provisioning call returns the same address.@@ -672,6 +672,19 @@ hostname stay, so a later provisioning call returns the same address.removal still refused as connected after its rounds does not count as waiting: it backs off (5 minutes up to 24hours) and retries while the sweep and the marking go on. A marked row is a final delete: its owner is answered`409 endpoint_busy` until the sweep has removed it.+- **Self-hosted servers.** A server (`openmausbot serve --tunnel`, a fleet container with `OMB_INSTALLATION_CREDENTIAL`)+ has no phone relay of its own: its tunnel is its public address (web UI, the desktop app's connection to it,+ webhooks). Provisioning never answers a server `relay_capable` (no `retired`, no `full`; at the limit it gets+ `503 endpoint_capacity`), and the cron never marks a server's tunnel for `relay_proven` or `legacy_cutoff`. The+ version cutoff still applies (`426`, and `min_version`). A server that uses the relay and does not ask for a tunnel+ simply has none. An installation is a server when it says so: optional `kind: "desktop" | "server"` on+ `POST /v1/installations`, `POST .../self/endpoint` and `POST .../self/relay-token`, stored in `installations.kind`+ (migration `0016`; the latest report wins). The request schemas are strict, so this Worker must accept `kind` before+ any client release sends it. An installation that has never said is judged by what every release up to 0.1.152+ does: the desktop reports `legacyDevices` whenever its companion runs and asks for relay tokens, a server does+ neither. So `POST .../endpoint` without `legacyDevices`, from an installation with no `relay_adoption` row, is+ treated as a server. A desktop that has never asked for a relay token and provisions while its companion is off is+ treated the same way, and gets a tunnel as before the cutoff.- **Coming back.** `POST /v1/installations/self/endpoint` creates a tunnel again, with the same hostname, when thedesktop reports an old phone (outside the cutoff), or the relay cannot carry it: `RELAY_DISABLED: "1"`, a lower`RELAY_ROLLOUT_PERCENT`, or `relay_blocked_at`. With the relay switched off the cron releases nothing on the@@ -696,7 +709,7 @@ hostname stay, so a later provisioning call returns the same address.the last two days below `TUNNEL_MIN_APP_VERSION`, or below `RELAY_CAPABLE_MIN_VERSION` while no minimum is set. `capacity.reclaim.preview` is`{ "offlineDays": 1, "eligible": 37 }` once every account has finished a full pass at the preview period (about 50minutes per 1,000 tunnels), and `eligible: null` until then.-- **Order.** Apply migration `0015` and deploy with everything off. Read `tunnelRelease`. Raise+- **Order.** Apply migrations `0015` and `0016` and deploy with everything off. Read `tunnelRelease`. Raise`RELAY_TUNNEL_RELEASE_PERCENT` 10, 50, 100. After the desktop release that explains the cutoff is out, set`TUNNEL_REASON_MIN_VERSION` to that release, then raise `TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT` 10, then 100, and lastset `TUNNEL_MIN_APP_VERSION`.diff --git a/cloudflare/control-plane/migrations/0016_installation_kind.sql b/cloudflare/control-plane/migrations/0016_installation_kind.sqlnew file mode 100644index 0000000000..8f1f7437e5--- /dev/null+++ b/cloudflare/control-plane/migrations/0016_installation_kind.sql@@ -0,0 +1,4 @@+-- What an installation is, as it says itself: the desktop app or a self-hosted server (`openmausbot serve`, a fleet+-- container). NULL until a client reports it; the control plane then tells them apart by what each release sends.+-- A server's tunnel is its public address, so the relay rules that end tunnels never apply to one.+ALTER TABLE installations ADD COLUMN kind TEXT CHECK (kind IS NULL OR kind IN ('desktop', 'server'));diff --git a/cloudflare/control-plane/src/endpoints.ts b/cloudflare/control-plane/src/endpoints.tsindex 1671f846f0..4c746d44eb 100644--- a/cloudflare/control-plane/src/endpoints.ts+++ b/cloudflare/control-plane/src/endpoints.ts@@ -24,8 +24,12 @@ import {import { errorResponse, HTTPError, json, readOptionalBoundedJSON } from "./http";import {printableVersion,+ installationKindSchema,+ type InstallationKind,+ recordInstallationKind,recordReportedAppVersion,requireInstallation,+ storedInstallationKind,requireInstallationAndRead,} from "./installations";import { idleTunnelReason } from "./tunnel-activity";@@ -245,15 +249,26 @@ 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(),+ kind: installationKindSchema.optional(),});-/** POST may carry `{ "appVersion": "0.1.103", "legacyDevices": 1 }`, or no body. */-async function provisionRequest(request: Request): Promise<{ appVersion: string | null; legacyDevices: number | null }> {+interface ProvisionRequest {+ appVersion: string | null;+ kind: InstallationKind | null;+ legacyDevices: number | null;+}++/** POST may carry `{ "appVersion": "0.1.103", "legacyDevices": 1, "kind": "desktop" }`, or no body. */+async function provisionRequest(request: Request): Promise<ProvisionRequest> {const body = await readOptionalBoundedJSON(request);- if (body === undefined) return { appVersion: null, legacyDevices: null };+ if (body === undefined) return { appVersion: null, kind: null, legacyDevices: null };const parsed = provisionRequestSchema.safeParse(body);if (!parsed.success) throw new HTTPError(400, "invalid_request");- return { appVersion: parsed.data.appVersion ?? null, legacyDevices: parsed.data.legacyDevices ?? null };+ return {+ appVersion: parsed.data.appVersion ?? null,+ kind: parsed.data.kind ?? null,+ legacyDevices: parsed.data.legacyDevices ?? null,+ };}/** Why a relay-capable desktop goes without a tunnel. The code stays `relay_capable`, which every such desktop@@ -1210,10 +1225,11 @@ export async function provisionManagedEndpoint(): Promise<Response> {const installation = await requireInstallation(request, env);await enforceEndpointRateLimit(env, installation.installation_id, "reconcile_endpoint");- const { appVersion: reportedVersion, legacyDevices } = await provisionRequest(request);+ const { appVersion: reportedVersion, kind: reportedKind, legacyDevices } = await provisionRequest(request);if (reportedVersion !== null && reportedVersion !== installation.app_version) {await recordReportedAppVersion(env, installation.installation_id, reportedVersion);}+ if (reportedKind !== null) await recordInstallationKind(env, installation.installation_id, reportedKind);const allocation = allocationFor(env, config, reportedVersion ?? installation.app_version);const existing = await endpointRow(env, installation.installation_id);const policy = readTunnelPolicy(env);@@ -1221,12 +1237,18 @@ export async function provisionManagedEndpoint(if (belowMinimum(policy, reportedVersion ?? installation.app_version)) throw new HTTPError(426, "update_required");// The relay first: a desktop it can carry gets a tunnel only for an old phone, and only while old phones may// still hold one. A desktop the relay cannot carry (an older release, the relay off, outside the rollout,- // blocked) falls through to a tunnel, as before the relay existed.+ // blocked) falls through to a tunnel, as before the relay existed. So does a self-hosted server: its tunnel is+ // its public address, so it is never answered relay_capable. One that does not say what it is is known by what+ // every released server does: it reports no phones and has never asked for a relay token.let standing: RelayStanding | null = null;+ let kind: InstallationKind | null | undefined = reportedKind ?? undefined;const onRelay = async () => {if (!relayCapableVersion(policy, reportedVersion)) return null;+ if (kind === undefined) kind = await storedInstallationKind(env, installation.installation_id);+ if (kind === "server") return null;standing ??= await relayStanding(env, installation.installation_id);- return standing.serves ? standing : null;+ if (!standing.serves) return null;+ return kind === null && legacyDevices === null && !standing.asked ? null : standing;};if (policy.legacyCutoffPercent > 0) {const relay = await onRelay();diff --git a/cloudflare/control-plane/src/installations.ts b/cloudflare/control-plane/src/installations.tsindex 12c6ec4884..534f9a6b97 100644--- a/cloudflare/control-plane/src/installations.ts+++ b/cloudflare/control-plane/src/installations.ts@@ -47,11 +47,17 @@ function printableString(maxLength: number) {const printableName = printableString(80);export const printableVersion = printableString(64);+/** The desktop app, or a self-hosted server (`openmausbot serve`, a fleet container). Optional on every request+ * that carries it: accepted here before any client sends it, since the request schemas are strict. */+export const installationKindSchema = z.enum(["desktop", "server"]);+export type InstallationKind = z.infer<typeof installationKindSchema>;+const createInstallationSchema = z.strictObject({name: printableName,clientInstanceId: z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),platform: z.enum(["darwin", "windows", "linux"]),appVersion: printableVersion.optional(),+ kind: installationKindSchema.optional(),});const INSTALLATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;@@ -175,10 +181,11 @@ export async function createInstallation(request: Request, env: Env, auth: Contrconst credential = await newCredential(now);try {await env.DB.batch([+ // `kind` is written only when sent, so registration does not depend on migration 0016.env.DB.prepare(`INSERT INTO installations- (id, owner_user_id, client_instance_id, display_name, platform, app_version, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ (id, owner_user_id, client_instance_id, display_name, platform, app_version, created_at, updated_at${parsed.data.kind ? ", kind" : ""})+ VALUES (?, ?, ?, ?, ?, ?, ?, ?${parsed.data.kind ? ", ?" : ""})`,).bind(installationId,session.user.id,@@ -188,6 +195,7 @@ export async function createInstallation(request: Request, env: Env, auth: Contrparsed.data.appVersion ?? null,now,now,+ ...(parsed.data.kind ? [parsed.data.kind] : []),),env.DB.prepare(`INSERT INTO installation_credentials@@ -393,6 +401,21 @@ export async function recordReportedAppVersion().bind(appVersion, installationId).run();}+/** Stores the kind a client reported. Best effort: without migration 0016 nothing is stored. */+export async function recordInstallationKind(env: Env, installationId: string, kind: InstallationKind): Promise<void> {+ await env.DB.prepare(+ "UPDATE installations SET kind = ? WHERE id = ? AND revoked_at IS NULL AND kind IS NOT ?",+ ).bind(kind, installationId, kind).run().catch(() => undefined);+}++/** The kind the installation last reported, or null: none reported, or no migration 0016. */+export async function storedInstallationKind(env: Env, installationId: string): Promise<InstallationKind | null> {+ const row = await env.DB.prepare("SELECT kind FROM installations WHERE id = ?")+ .bind(installationId).first<{ kind: string | null }>().catch(() => null);+ const parsed = installationKindSchema.safeParse(row?.kind);+ return parsed.success ? parsed.data : null;+}+export async function installationSelf(request: Request, env: Env): Promise<Response> {const installation = await requireInstallation(request, env);return json({diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.tsindex f1fbff06bd..0535543e91 100644--- a/cloudflare/control-plane/src/relay.ts+++ b/cloudflare/control-plane/src/relay.ts@@ -4,7 +4,7 @@import { z } from "zod";import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";-import { recordReportedAppVersion, requireInstallation } from "./installations";+import { installationKindSchema, recordInstallationKind, recordReportedAppVersion, requireInstallation } from "./installations";const HOUR_MS = 60 * 60 * 1_000;export const RELAY_TOKEN_TTL_S = 12 * 60 * 60;@@ -23,6 +23,7 @@ const requestSchema = z.strictObject({e2e: z.number().int().min(0).max(100),legacy: z.number().int().min(0).max(100),}),+ kind: installationKindSchema.optional(),});export interface RelaySettings {@@ -275,24 +276,27 @@ export interface RelayStanding {bucket: number | null;/** It also holds a relay token from the last two days: the relay is what it is using. */proven: boolean;+ /** It has asked for a relay token at least once (a `relay_adoption` row), which no released server does. True+ * when that cannot be read, so a desktop is never taken for a server. */+ asked: boolean;}/** `relayAdmits` for one installation, making its host id if it has none. A database that cannot answer (a Worker* ahead of migration 0012) reads as served and unproven, which is what a relay-capable desktop got before. */export async function relayStanding(env: Env, installationId: string, now = Date.now()): Promise<RelayStanding> {const settings = await readRelaySettings(env);- if (!settings) return { serves: false, bucket: null, proven: false };+ if (!settings) return { serves: false, bucket: null, proven: false, asked: true };let host: { hostId: string; blocked: boolean };try {host = await hostIdFor(env, installationId);} catch {- return { serves: true, bucket: null, proven: false };+ return { serves: true, bucket: null, proven: false, asked: true };}const { admitted, bucket } = await relayAdmits(settings, { installationId, hostId: host.hostId, blocked: host.blocked });- if (!admitted) return { serves: false, bucket, proven: false };+ if (!admitted) return { serves: false, bucket, proven: false, asked: true };const adoption = await env.DB.prepare("SELECT token_at FROM relay_adoption WHERE installation_id = ?")- .bind(installationId).first<{ token_at: number | null }>().catch(() => null);- return { serves: true, bucket, proven: (adoption?.token_at ?? 0) >= now - RELAY_FRESH_MS };+ .bind(installationId).first<{ token_at: number | null }>().catch(() => undefined);+ return { serves: true, bucket, proven: (adoption?.token_at ?? 0) >= now - RELAY_FRESH_MS, asked: adoption !== null };}export async function issueRelayToken(request: Request, env: Env): Promise<Response> {@@ -305,6 +309,7 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respoif (parsed.data.appVersion !== installation.app_version) {await recordReportedAppVersion(env, installation.installation_id, parsed.data.appVersion).catch(() => undefined);}+ if (parsed.data.kind) await recordInstallationKind(env, installation.installation_id, parsed.data.kind);const [limited] = await env.DB.batch([limitStatement(env, installation.installation_id, now)]);if (limited?.meta.changes === 0) {const response = errorResponse(429, "rate_limited");diff --git a/cloudflare/control-plane/src/tunnel-release.ts b/cloudflare/control-plane/src/tunnel-release.tsindex 46748b91df..50adefe1f1 100644--- a/cloudflare/control-plane/src/tunnel-release.ts+++ b/cloudflare/control-plane/src/tunnel-release.ts@@ -91,6 +91,10 @@ const HELD_TUNNEL_SQL = `e.status = 'ready'/** The relay gave this computer a token lately. */const RELAY_SERVED_SQL = "a.token_at IS NOT NULL AND a.token_at >= ?";+/** Not a self-hosted server by its own report: a server's tunnel is its public address, so the relay never replaces+ * it. Only the version cutoff applies to one. Needs migration 0016; without it nothing is released. */+const NOT_SERVER_SQL = "i.kind IS NOT 'server'";+/** Every paired phone has used the encrypted connection (a phone that has* never dials the tunnel again), none is an old phone, and that has held for* the whole wait. Binds: fresh cutoff twice, then the wait cutoff. */@@ -116,15 +120,15 @@ interface VersionRow {}/** Held tunnels by desktop version, with how many of each the relay serves- * and how many are proven on it. Throws without migration 0015. */+ * and how many are proven on it. Throws without migrations 0015 and 0016. */async function heldByVersion(env: Env, config: ControlPlaneConfig, policy: TunnelPolicy, now: number): Promise<VersionRow[]> {const fresh = now - RELAY_FRESH_MS;const found = await env.DB.prepare(`SELECT COALESCE(i.app_version, '') AS version,COUNT(*) AS tunnels,COALESCE(SUM(CASE WHEN ${SEEN_LATELY_SQL} THEN 1 ELSE 0 END), 0) AS seen,- COALESCE(SUM(CASE WHEN ${RELAY_SERVED_SQL} THEN 1 ELSE 0 END), 0) AS relay_served,- COALESCE(SUM(CASE WHEN ${RELAY_PROVEN_SQL} THEN 1 ELSE 0 END), 0) AS proven+ COALESCE(SUM(CASE WHEN ${NOT_SERVER_SQL} AND ${RELAY_SERVED_SQL} THEN 1 ELSE 0 END), 0) AS relay_served,+ COALESCE(SUM(CASE WHEN ${NOT_SERVER_SQL} AND ${RELAY_PROVEN_SQL} THEN 1 ELSE 0 END), 0) AS provenFROM installation_endpoints eJOIN installations i ON i.id = e.installation_idLEFT JOIN relay_adoption a ON a.installation_id = e.installation_id@@ -171,7 +175,7 @@ export function forgetTunnelRelease(): void {/** Counts only, for /healthz: the switches as set, and what each would clear* now, so the numbers can be read before a switch is turned. Read at most- * every five minutes per isolate; left out without migration 0015. */+ * every five minutes per isolate; left out without migrations 0015 and 0016. */export async function tunnelReleaseHealth(env: Env, config: ControlPlaneConfig, now = Date.now()): Promise<JSONValue | null> {if (healthMemo && now - healthMemo.at < HEALTH_MEMO_MS) return healthMemo.value;const policy = readTunnelPolicy(env);@@ -243,7 +247,7 @@ export async function releaseTunnels(try {rows = await heldByVersion(env, config, policy, now);} catch {- // Migration 0015 is not applied yet: nothing is released.+ // Migration 0015 or 0016 is not applied yet: nothing is released.return null;}const summary: ReleaseSummary = {@@ -301,7 +305,7 @@ export async function releaseTunnels(if (policy.minAppVersion !== null) {await run("min_version", `${VERSION_IN_SQL} AND ${SEEN_LATELY_SQL}`, [below, now - SEEN_FRESH_MS]);}- const servedGuard = `${VERSION_IN_SQL} AND i.relay_blocked_at IS NULL`;+ const servedGuard = `${VERSION_IN_SQL} AND i.relay_blocked_at IS NULL AND ${NOT_SERVER_SQL}`;if (relay && policy.legacyCutoffPercent > 0) {await run("legacy_cutoff", `${servedGuard} AND ${RELAY_SERVED_SQL}`, [capable, fresh], inside(policy.legacyCutoffPercent));}diff --git a/cloudflare/control-plane/test/managed-endpoints.test.ts b/cloudflare/control-plane/test/managed-endpoints.test.tsindex 0e7fede4a6..3c37521d74 100644--- a/cloudflare/control-plane/test/managed-endpoints.test.ts+++ b/cloudflare/control-plane/test/managed-endpoints.test.ts@@ -3698,7 +3698,7 @@ async function computerWithTunnel(type Computer = Awaited<ReturnType<typeof computerWithTunnel>>;/** The desktop's hourly relay-token request, which carries its phone counts. */-async function reportPhones(worker: TestWorker, computer: Computer, devices: { e2e: number; legacy: number }, vars = relayVars()) {+async function reportPhones(worker: TestWorker, computer: Pick<Computer, "appVersion" | "credential">, devices: { e2e: number; legacy: number }, vars = relayVars()) {const response = await call(worker, "/v1/installations/self/relay-token", {body: { appVersion: computer.appVersion, devices },env: { ...env, ...vars } as unknown as Env,@@ -4297,3 +4297,196 @@ describe("removing a tunnel whose computer is online", () => {expect(connectionCleanups(cloudflare, endpoint.tunnel.id)).toHaveLength(1);});});++describe("self-hosted servers keep their tunnel", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ forgetTunnelRelease();+ });++ /** Tonight's switches: the old-phone cutoff on everyone, the reason from 0.1.152, the minimum at 0.1.145. */+ const live = (extra: Record<string, string> = {}) => relayVars({+ TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: "100",+ TUNNEL_REASON_MIN_VERSION: "0.1.152",+ TUNNEL_MIN_APP_VERSION: "0.1.145",+ RELAY_TUNNEL_RELEASE_PERCENT: "100",+ RELAY_TUNNEL_RELEASE_DAYS: "1",+ ...extra,+ });++ /** `openmausbot serve --tunnel` and `openmausbot login`: registration as any client sends it, `kind` only when given. */+ async function register(worker: TestWorker, accountToken: string, clientInstanceId: string, appVersion: string, kind?: string) {+ const response = await call(worker, "/v1/installations", {+ body: { clientInstanceId, name: "home-server", platform: "linux", appVersion, ...(kind ? { kind } : {}) },+ method: "POST",+ token: accountToken,+ });+ expect(response.status).toBe(201);+ const created = await response.json<{ credential: string; installation: { id: string } }>();+ return { appVersion, credential: created.credential, id: created.installation.id };+ }++ /** What every released server and fleet container sends: its version and nothing else, unless `kind` is given. */+ const provision = (worker: TestWorker, credential: string, body: Record<string, unknown> | undefined, vars = live()) =>+ call(worker, "/v1/installations/self/endpoint", {+ ...(body ? { body } : {}),+ env: { ...env, ...vars } as unknown as Env,+ method: "POST",+ token: credential,+ });++ const storedKind = async (id: string) => (await env.DB.prepare("SELECT kind FROM installations WHERE id = ?")+ .bind(id).first<{ kind: string | null }>())?.kind ?? null;++ it("gives a server that does not say what it is a tunnel under the cutoff, and the capacity answer at the limit", async () => {+ const cloudflare = new FakeCloudflare();+ const worker = createWorker(cloudflare.fetch);+ const owner = await signIn(worker, "[email protected]");+ const server = await register(worker, owner.token, "server-unlabelled", "0.1.152");+ const fleet = await register(worker, owner.token, "fleet-unlabelled", "0.1.150");++ for (const each of [server, fleet]) {+ const response = await provision(worker, each.credential, { appVersion: each.appVersion });+ expect(response.status).toBe(200);+ const body = await response.json<{ connectorToken: string; endpoint: { url: string } }>();+ expect(body.connectorToken).toBe(CONNECTOR_TOKEN);+ // And again, now that it holds one.+ expect((await provision(worker, each.credential, { appVersion: each.appVersion })).status).toBe(200);+ }+ // No body at all, as a server with no version would send.+ const bare = await register(worker, owner.token, "server-bare", "0.1.152");+ expect((await provision(worker, bare.credential, undefined)).status).toBe(200);++ // At the limit: the 503 it retries on, never relay_capable "full".+ const late = await register(worker, owner.token, "server-late", "0.1.152");+ cloudflare.providerErrors.set("create_tunnel", 1_045);+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ const full = await provision(worker, late.credential, { appVersion: "0.1.152" });+ expect(full.status).toBe(503);+ await expect(full.json()).resolves.toEqual({ error: "endpoint_capacity" });++ // The minimum version still applies.+ const old = await register(worker, owner.token, "server-old", "0.1.140");+ const refused = await provision(worker, old.credential, { appVersion: "0.1.140" });+ expect(refused.status).toBe(426);+ });++ it("stores the kind a client reports, and a server is never answered relay_capable even once it uses the relay", async () => {+ const cloudflare = new FakeCloudflare();+ const worker = createWorker(cloudflare.fetch);+ const owner = await signIn(worker, "[email protected]");+ const server = await register(worker, owner.token, "server-labelled", "0.1.153", "server");+ expect(await storedKind(server.id)).toBe("server");+ // Uses the relay (a relay token, phones reported) and sends what a desktop would: still a tunnel.+ expect(await reportPhones(worker, server, { e2e: 1, legacy: 0 }, live())).toBe(200);+ for (const body of [{ appVersion: "0.1.153", legacyDevices: 0 }, { appVersion: "0.1.153", legacyDevices: 2 }, { appVersion: "0.1.153" }]) {+ const response = await provision(worker, server.credential, body);+ expect(response.status).toBe(200);+ }++ // Reported later, on provisioning or with a relay token; the latest report wins.+ const later = await register(worker, owner.token, "server-later", "0.1.153");+ expect(await storedKind(later.id)).toBeNull();+ expect((await provision(worker, later.credential, { appVersion: "0.1.153", kind: "server" })).status).toBe(200);+ expect(await storedKind(later.id)).toBe("server");+ const relayToken = (kind: unknown) => call(worker, "/v1/installations/self/relay-token", {+ body: { appVersion: "0.1.153", devices: { e2e: 0, legacy: 0 }, kind },+ env: { ...env, ...live() } as unknown as Env,+ method: "POST",+ token: later.credential,+ });+ expect((await relayToken("desktop")).status).toBe(200);+ expect(await storedKind(later.id)).toBe("desktop");+ expect((await relayToken("server")).status).toBe(200);+ expect(await storedKind(later.id)).toBe("server");+ expect((await relayToken("robot")).status).toBe(400);+ expect((await provision(worker, later.credential, { appVersion: "0.1.153", kind: "robot" })).status).toBe(400);+ const badRegistration = await call(worker, "/v1/installations", {+ body: { clientInstanceId: "server-bad-kind", name: "x", platform: "linux", appVersion: "0.1.153", kind: "robot" },+ method: "POST",+ token: owner.token,+ });+ expect(badRegistration.status).toBe(400);+ });++ it("never marks a server's tunnel for the relay release or the cutoff, but the minimum version still removes it", async () => {+ const cloudflare = new FakeCloudflare();+ const worker = createWorker(cloudflare.fetch);+ const owner = await signIn(worker, "[email protected]");+ const server = await register(worker, owner.token, "server-cron", "0.1.153", "server");+ expect((await provision(worker, server.credential, { appVersion: "0.1.153" }, relayVars())).status).toBe(200);+ expect(await reportPhones(worker, server, { e2e: 1, legacy: 0 })).toBe(200);+ await clearSince(server.id, 5);+ const desktop = await computerWithTunnel(worker, cloudflare, owner.token, "server-cron-desktop");+ expect(await reportPhones(worker, desktop, { e2e: 1, legacy: 0 })).toBe(200);+ await clearSince(desktop.id, 5);+ vi.spyOn(console, "log").mockImplementation(() => undefined);++ expect(await releaseHealth(worker, live())).toMatchObject({+ relayProven: { eligible: 1 },+ legacyPhoneCutoff: { eligible: 0 },+ });+ await runScheduledCleanup(worker, live());+ expect((await endpointState(desktop.id)).status).toBe("deleted");+ expect((await endpointState(server.id)).status).toBe("ready");+ expect((await provision(worker, server.credential, { appVersion: "0.1.153" })).status).toBe(200);++ // Below the minimum a server is treated as any installation.+ const old = await register(worker, owner.token, "server-cron-old", "0.1.140", "server");+ expect((await provision(worker, old.credential, { appVersion: "0.1.140" }, relayVars())).status).toBe(200);+ await runScheduledCleanup(worker, live());+ expect((await endpointState(old.id)).status).toBe("deleted");+ expect((await endpointState(server.id)).status).toBe("ready");+ });++ it("answers every desktop exactly as before", async () => {+ const cloudflare = new FakeCloudflare();+ const worker = createWorker(cloudflare.fetch);+ const owner = await signIn(worker, "[email protected]");+ const answer = async (response: Response) => ({ status: response.status, body: response.status === 200 ? "endpoint" : await response.json() });+ const relayDesktop = async (name: string) => {+ const installation = await createInstallation(worker, owner.token, name, "0.1.152");+ const computer = { appVersion: "0.1.152", credential: installation.credential, id: installation.installation.id };+ expect(await reportPhones(worker, computer, { e2e: 1, legacy: 0 }, live())).toBe(200);+ return computer;+ };+ const retired = { status: 409, body: { error: "relay_capable", tunnel: "retired" } };++ // On the relay, no tunnel: no old phone, old phones, the companion not running (no count), or saying it is a desktop.+ const none = await relayDesktop("desktop-none");+ expect(await answer(await provision(worker, none.credential, { appVersion: "0.1.152", legacyDevices: 0 })))+ .toEqual({ status: 409, body: { error: "relay_capable" } });+ const phones = await relayDesktop("desktop-phones");+ expect(await answer(await provision(worker, phones.credential, { appVersion: "0.1.152", legacyDevices: 2 }))).toEqual(retired);+ const companionOff = await relayDesktop("desktop-companion-off");+ expect(await answer(await provision(worker, companionOff.credential, { appVersion: "0.1.152" }))).toEqual(retired);+ const saysDesktop = await createInstallation(worker, owner.token, "desktop-says-so", "0.1.152");+ expect(await answer(await provision(worker, saysDesktop.credential, { appVersion: "0.1.152", kind: "desktop" }))).toEqual(retired);++ // Holding a tunnel: kept while the relay has not carried it lately, given up once it has.+ const holding = await computerWithTunnel(worker, cloudflare, owner.token, "desktop-holding", "0.1.152");+ expect(await answer(await provision(worker, holding.credential, { appVersion: "0.1.152", legacyDevices: 2 }))).toEqual({ status: 200, body: "endpoint" });+ expect(await reportPhones(worker, holding, { e2e: 0, legacy: 2 }, live())).toBe(200);+ expect(await answer(await provision(worker, holding.credential, { appVersion: "0.1.152", legacyDevices: 2 }))).toEqual(retired);++ // Cutoff off: an old phone gets a tunnel, none does not; at the limit a release that reads the reason pairs over+ // the relay and an older one keeps the 503.+ const off = live({ TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: "0" });+ const fresh = await relayDesktop("desktop-cutoff-off");+ expect(await answer(await provision(worker, fresh.credential, { appVersion: "0.1.152", legacyDevices: 0 }, off)))+ .toEqual({ status: 409, body: { error: "relay_capable" } });+ expect(await answer(await provision(worker, fresh.credential, { appVersion: "0.1.152", legacyDevices: 1 }, off))).toEqual({ status: 200, body: "endpoint" });+ cloudflare.providerErrors.set("create_tunnel", 1_045);+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ const atLimit = await relayDesktop("desktop-at-limit");+ expect(await answer(await provision(worker, atLimit.credential, { appVersion: "0.1.152", legacyDevices: 1 }, off)))+ .toEqual({ status: 409, body: { error: "relay_capable", tunnel: "full" } });+ const older = await createInstallation(worker, owner.token, "desktop-older", "0.1.151");+ expect(await answer(await provision(worker, older.credential, { appVersion: "0.1.151", legacyDevices: 1 }, off)))+ .toEqual({ status: 503, body: { error: "endpoint_capacity" } });+ // Below the minimum.+ const old = await createInstallation(worker, owner.token, "desktop-old", "0.1.140");+ expect(await answer(await provision(worker, old.credential, { appVersion: "0.1.140", legacyDevices: 0 })))+ .toEqual({ status: 426, body: { error: "update_required" } });+ });+});