Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(control-plane): cut D1 round trips, cache config/keys, and avoid N+1 cron scans
milind-sonie0aea1b31c46
diff --git a/cloudflare/control-plane/src/config.ts b/cloudflare/control-plane/src/config.tsindex 0250a1e283..78fae37f20 100644--- a/cloudflare/control-plane/src/config.ts+++ b/cloudflare/control-plane/src/config.ts@@ -94,36 +94,41 @@ function boundedIntegerVar(fallback: number,minimum: number,maximum: number,+ onInvalid?: () => void,): number {if (value === undefined || value === null || value === "") return fallback;const text = typeof value === "number" ? String(value) : value;const parsed = typeof text === "string" && /^[0-9]{1,9}$/.test(text.trim()) ? Number(text.trim()) : Number.NaN;if (!Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {// A tuning value must never take sign-in and pairing down: use the default.+ onInvalid?.();console.error(JSON.stringify({ message: "invalid capacity setting; using the default", setting: label, minimum, maximum, fallback }));return fallback;}return parsed;}-function reclaimMode(value: unknown): TunnelReclaimMode {+function reclaimMode(value: unknown, onInvalid?: () => void): TunnelReclaimMode {// Unset or invalid: observe only. Reclaiming is switched on deliberately.if (value === "on" || value === "observe") return value;if (value !== undefined && value !== null && value !== "") {+ onInvalid?.();console.error(JSON.stringify({ message: "invalid OMB_TUNNEL_RECLAIM; observing only", allowed: ["on", "observe"] }));}return "observe";}-/** Optional tuning variables, each with a safe default. */-export function readCapacityConfig(env: Partial<Record<string, unknown>>): CapacityConfig {- return {+function parseCapacityConfig(env: Partial<Record<string, unknown>>): { config: CapacityConfig; valid: boolean } {+ let valid = true;+ const markInvalid = () => { valid = false; };+ const config: CapacityConfig = {cleanupSweepLimit: boundedIntegerVar(env.OMB_CLEANUP_SWEEP_LIMIT,"OMB_CLEANUP_SWEEP_LIMIT",DEFAULT_CLEANUP_SWEEP_LIMIT,1,MAX_CLEANUP_SWEEP_LIMIT,+ markInvalid,),dnsRecordLimit: boundedIntegerVar(env.OMB_DNS_RECORD_LIMIT,@@ -131,6 +136,7 @@ export function readCapacityConfig(env: Partial<Record<string, unknown>>): CapacDEFAULT_DNS_RECORD_LIMIT,1,10_000_000,+ markInvalid,),offlineReclaimMs: boundedIntegerVar(env.OMB_TUNNEL_OFFLINE_RECLAIM_DAYS,@@ -138,8 +144,9 @@ export function readCapacityConfig(env: Partial<Record<string, unknown>>): CapacDEFAULT_OFFLINE_RECLAIM_DAYS,MIN_OFFLINE_RECLAIM_DAYS,365,+ markInvalid,) * DAY_MS,- reclaimMode: reclaimMode(env.OMB_TUNNEL_RECLAIM),+ reclaimMode: reclaimMode(env.OMB_TUNNEL_RECLAIM, markInvalid),reclaimPreviewMs: env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === undefined || env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === null|| env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === ""? null@@ -149,6 +156,7 @@ export function readCapacityConfig(env: Partial<Record<string, unknown>>): Capac0,MIN_OFFLINE_RECLAIM_DAYS,365,+ markInvalid,) * DAY_MS || null,tunnelLimit: boundedIntegerVar(env.OMB_TUNNEL_LIMIT,@@ -156,8 +164,15 @@ export function readCapacityConfig(env: Partial<Record<string, unknown>>): CapacDEFAULT_TUNNEL_LIMIT,1,10_000_000,+ markInvalid,),};+ return { config, valid };+}++/** Optional tuning variables, each with a safe default. */+export function readCapacityConfig(env: Partial<Record<string, unknown>>): CapacityConfig {+ return parseCapacityConfig(env).config;}function exactHTTPSOrigin(value: string, label: string): string {@@ -214,31 +229,25 @@ const endpointAccountSchema = z.strictObject({newEndpoints: z.boolean().optional(),});-/**- * CLOUDFLARE_ENDPOINT_ACCOUNTS: a JSON array (a wrangler.jsonc JSON var, or the- * same JSON as a string or a secret) of `{ accountId, zoneId,- * companionHostSuffix, apiTokenSecret, tunnelLimit?, dnsRecordLimit?,- * minAppVersion?, newEndpoints? }`. A bad entry never throws: it is dropped and- * reported as a redacted issue code, and endpoints tied to it refuse to act.- */-export function readEndpointAccounts(+function parseEndpointAccounts(env: Partial<Record<string, unknown>>,primary: EndpointAccount,-): { accounts: EndpointAccount[]; issues: string[] } {+): { accounts: EndpointAccount[]; issues: string[]; tokenSecrets: Array<[string, string]> } {const raw = env.CLOUDFLARE_ENDPOINT_ACCOUNTS;- if (raw === undefined || raw === null || raw === "") return { accounts: [], issues: [] };+ if (raw === undefined || raw === null || raw === "") return { accounts: [], issues: [], tokenSecrets: [] };let entries: unknown = raw;if (typeof raw === "string") {try {entries = JSON.parse(raw);} catch {- return { accounts: [], issues: ["accounts_json"] };+ return { accounts: [], issues: ["accounts_json"], tokenSecrets: [] };}}- if (!Array.isArray(entries)) return { accounts: [], issues: ["accounts_json"] };+ if (!Array.isArray(entries)) return { accounts: [], issues: ["accounts_json"], tokenSecrets: [] };const accounts: EndpointAccount[] = [];const issues: string[] = [];+ const tokenSecrets: Array<[string, string]> = [];const used = {accountIds: new Set([primary.accountId]),suffixes: new Set([primary.companionHostSuffix]),@@ -280,6 +289,7 @@ export function readEndpointAccounts(used.accountIds.add(accountId);used.zoneIds.add(zoneId);used.suffixes.add(companionHostSuffix);+ tokenSecrets.push([parsed.data.apiTokenSecret, apiToken.data]);accounts.push({accountId,apiToken: apiToken.data,@@ -291,10 +301,82 @@ export function readEndpointAccounts(zoneId,});}+ return { accounts, issues, tokenSecrets };+}++/**+ * CLOUDFLARE_ENDPOINT_ACCOUNTS: a JSON array (a wrangler.jsonc JSON var, or the+ * same JSON as a string or a secret) of `{ accountId, zoneId,+ * companionHostSuffix, apiTokenSecret, tunnelLimit?, dnsRecordLimit?,+ * minAppVersion?, newEndpoints? }`. A bad entry never throws: it is dropped and+ * reported as a redacted issue code, and endpoints tied to it refuse to act.+ */+export function readEndpointAccounts(+ env: Partial<Record<string, unknown>>,+ primary: EndpointAccount,+): { accounts: EndpointAccount[]; issues: string[] } {+ const { accounts, issues } = parseEndpointAccounts(env, primary);return { accounts, issues };}+interface CachedConfig {+ betterAuthSecret: unknown;+ emailFrom: unknown;+ betterAuthUrl: unknown;+ allowedOrigins: unknown;+ accountId: unknown;+ zoneId: unknown;+ apiToken: unknown;+ hostSuffix: unknown;+ cleanupSweepLimit: unknown;+ dnsRecordLimit: unknown;+ offlineReclaimDays: unknown;+ reclaimMode: unknown;+ reclaimPreviewDays: unknown;+ tunnelLimit: unknown;+ endpointAccountsRaw: string | null | undefined;+ extraTokens: ReadonlyArray<readonly [string, string]>;+ config: ControlPlaneConfig;+}++let cachedConfig: CachedConfig | null = null;++function matchesCachedConfig(+ cached: CachedConfig,+ env: Env,+ vars: Partial<Record<string, unknown>>,+): boolean {+ if (+ cached.betterAuthSecret !== env.BETTER_AUTH_SECRET+ || cached.emailFrom !== env.EMAIL_FROM+ || cached.betterAuthUrl !== env.BETTER_AUTH_URL+ || cached.allowedOrigins !== env.ALLOWED_ORIGINS+ || cached.accountId !== env.CLOUDFLARE_ACCOUNT_ID+ || cached.zoneId !== env.CLOUDFLARE_ZONE_ID+ || cached.apiToken !== env.CLOUDFLARE_API_TOKEN+ || cached.hostSuffix !== env.COMPANION_HOST_SUFFIX+ || cached.cleanupSweepLimit !== vars.OMB_CLEANUP_SWEEP_LIMIT+ || cached.dnsRecordLimit !== vars.OMB_DNS_RECORD_LIMIT+ || cached.offlineReclaimDays !== vars.OMB_TUNNEL_OFFLINE_RECLAIM_DAYS+ || cached.reclaimMode !== vars.OMB_TUNNEL_RECLAIM+ || cached.reclaimPreviewDays !== vars.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS+ || cached.tunnelLimit !== vars.OMB_TUNNEL_LIMIT+ || cached.endpointAccountsRaw !== vars.CLOUDFLARE_ENDPOINT_ACCOUNTS+ ) {+ return false;+ }+ for (const [name, value] of cached.extraTokens) {+ if (vars[name] !== value) return false;+ }+ return true;+}+export function readConfig(env: Env): ControlPlaneConfig {+ const vars = env as unknown as Partial<Record<string, unknown>>;+ if (cachedConfig && matchesCachedConfig(cachedConfig, env, vars)) {+ return cachedConfig.config;+ }+if (!secretSchema.safeParse(env.BETTER_AUTH_SECRET).success) {throw new Error("BETTER_AUTH_SECRET must contain at least 32 characters");}@@ -328,8 +410,8 @@ export function readConfig(env: Env): ControlPlaneConfig {throw new Error("COMPANION_HOST_SUFFIX must be a lowercase DNS suffix");}- const vars = env as unknown as Partial<Record<string, unknown>>;- const capacity = readCapacityConfig(vars);+ const capacityParsed = parseCapacityConfig(vars);+ const capacity = capacityParsed.config;const primary: EndpointAccount = {accountId: env.CLOUDFLARE_ACCOUNT_ID.toLowerCase(),apiToken: env.CLOUDFLARE_API_TOKEN,@@ -340,9 +422,9 @@ export function readConfig(env: Env): ControlPlaneConfig {tunnelLimit: capacity.tunnelLimit,zoneId: env.CLOUDFLARE_ZONE_ID.toLowerCase(),};- const extra = readEndpointAccounts(vars, primary);+ const extra = parseEndpointAccounts(vars, primary);- return {+ const config: ControlPlaneConfig = {authBaseURL,allowedOrigins,capacity,@@ -351,4 +433,35 @@ export function readConfig(env: Env): ControlPlaneConfig {endpointAccounts: [primary, ...extra.accounts],endpointAccountIssues: extra.issues,};++ // Cache only valid, issue-free configs backed by immutable primitive env vars,+ // so invalid settings always keep logging and mutable array fixtures re-parse.+ const rawAccounts = vars.CLOUDFLARE_ENDPOINT_ACCOUNTS;+ if (+ capacityParsed.valid+ && extra.issues.length === 0+ && (rawAccounts === undefined || rawAccounts === null || typeof rawAccounts === "string")+ ) {+ cachedConfig = {+ betterAuthSecret: env.BETTER_AUTH_SECRET,+ emailFrom: env.EMAIL_FROM,+ betterAuthUrl: env.BETTER_AUTH_URL,+ allowedOrigins: env.ALLOWED_ORIGINS,+ accountId: env.CLOUDFLARE_ACCOUNT_ID,+ zoneId: env.CLOUDFLARE_ZONE_ID,+ apiToken: env.CLOUDFLARE_API_TOKEN,+ hostSuffix: env.COMPANION_HOST_SUFFIX,+ cleanupSweepLimit: vars.OMB_CLEANUP_SWEEP_LIMIT,+ dnsRecordLimit: vars.OMB_DNS_RECORD_LIMIT,+ offlineReclaimDays: vars.OMB_TUNNEL_OFFLINE_RECLAIM_DAYS,+ reclaimMode: vars.OMB_TUNNEL_RECLAIM,+ reclaimPreviewDays: vars.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS,+ tunnelLimit: vars.OMB_TUNNEL_LIMIT,+ endpointAccountsRaw: rawAccounts,+ extraTokens: extra.tokenSecrets,+ config,+ };+ }++ return config;}diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.tsindex f35440c08f..e348233a15 100644--- a/cloudflare/control-plane/src/index.ts+++ b/cloudflare/control-plane/src/index.ts@@ -69,6 +69,7 @@ async function canonicalAuthResponse(response: Response): Promise<Response> {async function route(request: Request,+ url: URL,env: Env,ctx: ExecutionContext,config: ControlPlaneConfig,@@ -76,11 +77,11 @@ async function route(cloudflareFetch: CloudflareFetch,pushFetch: typeof fetch,) {- const url = new URL(request.url);if (request.method === "OPTIONS") return preflight(request, config);- if (url.pathname.startsWith("/api/auth/")) {- const limited = await limitedOTPResponse(request, env);+ const { pathname } = url;+ if (pathname.startsWith("/api/auth/")) {+ const limited = await limitedOTPResponse(request, env, url);if (limited) return limited;const auth = createAuth(env, ctx, config, requestId);const response = await auth.handler(request);@@ -89,7 +90,7 @@ async function route(// other 4xx sweeps.if (request.method === "POST"- && url.pathname === SIGN_IN_OTP_PATH+ && pathname === SIGN_IN_OTP_PATH&& response.status !== 429&& response.status < 500) {@@ -104,9 +105,12 @@ async function route(return canonicalAuthResponse(response);}- const auth = createAuth(env, ctx, config, requestId);- if (request.method === "GET" && url.pathname === "/v1/me") {- const session = await accountSession(request, auth);+ // Installation-authenticated and Cloud-home push routes never use Better Auth;+ // instantiate it lazily only for account-session routes.+ const getAuth = () => createAuth(env, ctx, config, requestId);++ if (request.method === "GET" && pathname === "/v1/me") {+ const session = await accountSession(request, getAuth());if (!session) throw new HTTPError(401, "unauthorized");return json({user: {@@ -117,16 +121,16 @@ async function route(},});}- if (request.method === "GET" && url.pathname === "/v1/installations") {- return listInstallations(request, env, auth);+ if (request.method === "GET" && pathname === "/v1/installations") {+ return listInstallations(request, env, getAuth());}- if (request.method === "POST" && url.pathname === "/v1/installations") {- return createInstallation(request, env, auth);+ if (request.method === "POST" && pathname === "/v1/installations") {+ return createInstallation(request, env, getAuth());}- if (request.method === "GET" && url.pathname === "/v1/installations/self") {+ if (request.method === "GET" && pathname === "/v1/installations/self") {return installationSelf(request, env);}- if (url.pathname === "/v1/installations/self/endpoint") {+ if (pathname === "/v1/installations/self/endpoint") {if (request.method === "GET") return getManagedEndpoint(request, env);if (request.method === "POST") {return provisionManagedEndpoint(request, env, config, cloudflareFetch, requestId);@@ -136,36 +140,36 @@ async function route(}}- if (request.method === "POST" && url.pathname === "/v1/installations/self/relay-token") {+ if (request.method === "POST" && pathname === "/v1/installations/self/relay-token") {return issueRelayToken(request, env);}- if (request.method === "POST" && url.pathname === "/v1/installations/self/push/register") {+ if (request.method === "POST" && pathname === "/v1/installations/self/push/register") {return registerPushDevice(request, env);}- if (request.method === "POST" && url.pathname === "/v1/installations/self/push/unregister") {+ if (request.method === "POST" && pathname === "/v1/installations/self/push/unregister") {return unregisterPushDevice(request, env);}- if (request.method === "POST" && url.pathname === "/v1/installations/self/push/send") {+ if (request.method === "POST" && pathname === "/v1/installations/self/push/send") {return sendPush(request, env, pushFetch, requestId);}- if (request.method === "POST" && url.pathname === "/v1/installations/self/push/activity") {+ if (request.method === "POST" && pathname === "/v1/installations/self/push/activity") {return sendActivityPush(request, env, pushFetch, requestId);}// A Cloud home's push calls, relayed by the Admin (push-cloud-homes.ts): its shared secret, not an installation.- const cloudHome = url.pathname.match(CLOUD_HOME_PUSH_ROUTE);+ const cloudHome = pathname.match(CLOUD_HOME_PUSH_ROUTE);if (cloudHome) {return routeCloudHomePush(request, env, pushFetch, requestId, cloudHome[1]!, cloudHome[2]!);}- const rotate = url.pathname.match(ROTATE_ROUTE);+ const rotate = pathname.match(ROTATE_ROUTE);if (request.method === "POST" && rotate) {- return rotateInstallationCredential(request, rotate[1], env, auth);+ return rotateInstallationCredential(request, rotate[1], env, getAuth());}- const installation = url.pathname.match(INSTALLATION_ROUTE);+ const installation = pathname.match(INSTALLATION_ROUTE);if (request.method === "DELETE" && installation) {- const response = await revokeInstallation(request, installation[1], env, auth);+ const response = await revokeInstallation(request, installation[1], env, getAuth());ctx.waitUntil(cleanupEndpointForInstallation(env,config,@@ -202,9 +206,11 @@ export function createWorker(// `ok` keeps meaning "this Worker is correctly configured"; desktops// 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);- const release = await tunnelReleaseHealth(env, healthConfig).catch(() => null);+ const [capacity, adoption, release] = await Promise.all([+ capacityHealth(env, healthConfig, ctx).catch(() => null),+ relayAdoption(env).catch(() => null),+ tunnelReleaseHealth(env, healthConfig).catch(() => null),+ ]);return secureResponse(json({ok: true,service: "openmausbot-control-plane",@@ -223,7 +229,7 @@ export function createWorker(}const boundedRequest = await withBoundedRequestBody(request);return secureResponse(- await route(boundedRequest, env, ctx, config, requestId, cloudflareFetch, pushFetch),+ await route(boundedRequest, url, env, ctx, config, requestId, cloudflareFetch, pushFetch),request,config,requestId,diff --git a/cloudflare/control-plane/src/installations.ts b/cloudflare/control-plane/src/installations.tsindex 534f9a6b97..1693241fa1 100644--- a/cloudflare/control-plane/src/installations.ts+++ b/cloudflare/control-plane/src/installations.ts@@ -5,6 +5,8 @@ import type { ControlPlaneAuth } from "./auth";import { accountSession } from "./auth";import { HTTPError, json, readBoundedJSON } from "./http";+const UTF8 = new TextEncoder();+interface InstallationRow {id: string;client_instance_id: string;@@ -20,7 +22,7 @@ interface OwnedInstallationRow extends InstallationRow {revoked_at: number | null;}-interface InstallationCredentialRow {+export interface InstallationCredentialRow {installation_id: string;lookup_id: string;secret_hash: string;@@ -105,7 +107,7 @@ function fromHex(value: string): Uint8Array | null {}export async function sha256(value: string): Promise<string> {- return hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));+ return hex(await crypto.subtle.digest("SHA-256", UTF8.encode(value)));}async function newCredential(createdAt: number) {@@ -343,11 +345,51 @@ async function authenticateInstallation(request: Request, env: Env): Promise<Insconst expected = fromHex(row.secret_hash);if (!expected) return null;- const actual = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(bearer)));+ const actual = new Uint8Array(await crypto.subtle.digest("SHA-256", UTF8.encode(bearer)));if (!timingSafeEqual(actual, expected)) return null;return row;}+/** Authenticates the installation without writing the check-in yet, so callers+ * that need extra statements in the check-in batch can compose them in one round trip. */+export async function requireAuthenticatedInstallation(+ request: Request,+ env: Env,+): Promise<InstallationCredentialRow> {+ const installation = await authenticateInstallation(request, env);+ if (!installation) throw new HTTPError(401, "unauthorized");+ return installation;+}++/** The credential + installation check-in writes, optionally updating `app_version`+ * in the same row write when the caller reports a newer release. */+export function checkInStatements(+ env: Env,+ installation: InstallationCredentialRow,+ now: number,+ reportedAppVersion?: string,+): D1PreparedStatement[] {+ const updateInstallation = reportedAppVersion !== undefined && reportedAppVersion !== installation.app_version+ ? env.DB.prepare(+ `UPDATE installations+ SET last_seen_at = ?, app_version = ?+ WHERE id = ? AND revoked_at IS NULL`,+ ).bind(now, reportedAppVersion, installation.installation_id)+ : env.DB.prepare(+ `UPDATE installations+ SET last_seen_at = ?+ WHERE id = ? AND revoked_at IS NULL`,+ ).bind(now, installation.installation_id);+ return [+ env.DB.prepare(+ `UPDATE installation_credentials+ SET last_used_at = ?+ WHERE lookup_id = ? AND revoked_at IS NULL`,+ ).bind(now, installation.lookup_id),+ updateInstallation,+ ];+}+export async function requireInstallation(request: Request,env: Env,@@ -362,22 +404,10 @@ export async function requireInstallationAndRead<T>(env: Env,read: ((installationId: string) => D1PreparedStatement) | null,): Promise<{ installation: InstallationCredentialRow; row: T | null }> {- const installation = await authenticateInstallation(request, env);- if (!installation) throw new HTTPError(401, "unauthorized");+ const installation = await requireAuthenticatedInstallation(request, env);const now = Date.now();- const statements = [- env.DB.prepare(- `UPDATE installation_credentials- SET last_used_at = ?- WHERE lookup_id = ? AND revoked_at IS NULL`,- ).bind(now, installation.lookup_id),- env.DB.prepare(- `UPDATE installations- SET last_seen_at = ?- WHERE id = ? AND revoked_at IS NULL`,- ).bind(now, installation.installation_id),- ];+ const statements = checkInStatements(env, installation, now);// After the writes: a batch is one transaction, so a failed read rolls the// check-in back with it.if (read) statements.push(read(installation.installation_id));diff --git a/cloudflare/control-plane/src/otp-rate-limit.ts b/cloudflare/control-plane/src/otp-rate-limit.tsindex 90961ee770..810dba715a 100644--- a/cloudflare/control-plane/src/otp-rate-limit.ts+++ b/cloudflare/control-plane/src/otp-rate-limit.ts@@ -6,23 +6,36 @@ const OTP_SEND_PATH = "/api/auth/email-otp/send-verification-otp";const RECIPIENT_WINDOW_MS = 15 * 60 * 1_000;const RECIPIENT_MAX_ATTEMPTS = 3;const RETENTION_MS = 24 * 60 * 60 * 1_000;+const UTF8 = new TextEncoder();const recipientSchema = z.object({email: z.string().trim().min(1).max(254).toLowerCase(),});+let cachedHmacKey: { secret: string; key: Promise<CryptoKey> } | null = null;++function hmacKeyFor(secret: string): Promise<CryptoKey> {+ if (!cachedHmacKey || cachedHmacKey.secret !== secret) {+ cachedHmacKey = {+ secret,+ key: crypto.subtle.importKey(+ "raw",+ UTF8.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ ),+ };+ }+ return cachedHmacKey.key;+}+function hex(bytes: ArrayBuffer): string {return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");}async function recipientKey(email: string, secret: string): Promise<string> {- const key = await crypto.subtle.importKey(- "raw",- new TextEncoder().encode(secret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- return hex(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(email)));+ const key = await hmacKeyFor(secret);+ return hex(await crypto.subtle.sign("HMAC", key, UTF8.encode(email)));}async function normalizedRecipient(request: Request): Promise<string | null> {@@ -38,9 +51,9 @@ async function normalizedRecipient(request: Request): Promise<string | null> {* Returns Better Auth's generic success response only when the recipient limit* is exhausted. Invalid requests keep flowing to Better Auth for validation.*/-export async function limitedOTPResponse(request: Request, env: Env): Promise<Response | null> {- const url = new URL(request.url);- if (request.method !== "POST" || url.pathname !== OTP_SEND_PATH) return null;+export async function limitedOTPResponse(request: Request, env: Env, url?: URL): Promise<Response | null> {+ const pathname = (url ?? new URL(request.url)).pathname;+ if (request.method !== "POST" || pathname !== OTP_SEND_PATH) return null;const email = await normalizedRecipient(request);if (!email) return null;diff --git a/cloudflare/control-plane/src/push-cloud-homes.ts b/cloudflare/control-plane/src/push-cloud-homes.tsindex ac57344598..e58f1c2edf 100644--- a/cloudflare/control-plane/src/push-cloud-homes.ts+++ b/cloudflare/control-plane/src/push-cloud-homes.ts@@ -37,6 +37,8 @@ export const CLOUD_HOME_SEND_LIMIT = 200;const FLEET_SENDS: PushLimit = { owner: FLEET_ID, action: "push_send", limit: CLOUD_HOME_FLEET_SEND_LIMIT };const FLEET_REGISTERS: PushLimit = { owner: FLEET_ID, action: "push_register", limit: CLOUD_HOME_FLEET_REGISTER_LIMIT };+const UTF8 = new TextEncoder();+const secretDigestCache = new Map<string, Uint8Array>();export function cloudHomePushSecrets(env: Env): string[] {const vars = env as unknown as Partial<Record<string, unknown>>;@@ -47,7 +49,17 @@ export function cloudHomePushSecrets(env: Env): string[] {}async function digest(value: string): Promise<Uint8Array> {- return new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));+ return new Uint8Array(await crypto.subtle.digest("SHA-256", UTF8.encode(value)));+}++async function cachedSecretDigest(secret: string): Promise<Uint8Array> {+ let cached = secretDigestCache.get(secret);+ if (!cached) {+ cached = await digest(secret);+ if (secretDigestCache.size >= 8) secretDigestCache.clear();+ secretDigestCache.set(secret, cached);+ }+ return cached;}/** The Admin's bearer, compared in constant time with each configured secret (every one is compared). No secret set:@@ -58,7 +70,7 @@ export async function requireCloudHomeRelay(request: Request, env: Env): Promiseconst bearer = request.headers.get("authorization")?.match(/^Bearer\s+([^\s]+)$/i)?.[1] ?? "";const given = await digest(bearer);let matched = false;- for (const secret of secrets) matched = timingSafeEqual(given, await digest(secret)) || matched;+ for (const secret of secrets) matched = timingSafeEqual(given, await cachedSecretDigest(secret)) || matched;if (!bearer || !matched) throw new HTTPError(401, "unauthorized");}diff --git a/cloudflare/control-plane/src/push-fcm.ts b/cloudflare/control-plane/src/push-fcm.tsindex b4301adc54..d96c5ee53f 100644--- a/cloudflare/control-plane/src/push-fcm.ts+++ b/cloudflare/control-plane/src/push-fcm.ts@@ -1,5 +1,4 @@// Firebase Cloud Messaging, HTTP v1: the Android half of the phone push relay.-import { sha256 } from "./installations";export interface FcmConfig {projectId: string;@@ -17,30 +16,45 @@ const ACCESS_TOKEN_MARGIN_MS = 5 * 60 * 1_000;const ASSERTION_LIFETIME_SECONDS = 60 * 60;const FCM_TIMEOUT_MS = 10_000;export const FCM_TTL = "86400s";+export const FCM_TIMEOUT = FCM_TIMEOUT_MS;+const UTF8 = new TextEncoder();const PROJECT_ID = /^[a-z][a-z0-9-]{4,61}[a-z0-9]$/;const CLIENT_EMAIL = /^[A-Za-z0-9._%+-]{1,128}@[A-Za-z0-9.-]{1,128}\.iam\.gserviceaccount\.com$/;const PEM = /^-----BEGIN PRIVATE KEY-----\n[\s\S]+\n-----END PRIVATE KEY-----$/;+let cachedFcmConfig: { raw: unknown; config: FcmConfig | null } | null = null;+/** `FCM_SERVICE_ACCOUNT`: the service-account JSON file Firebase gives, whole. */export function readFcmConfig(env: Env): FcmConfig | null {const raw = (env as unknown as Partial<Record<string, unknown>>).FCM_SERVICE_ACCOUNT;- if (typeof raw !== "string" || !raw.trim()) return null;- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch {- return null;+ if (cachedFcmConfig && cachedFcmConfig.raw === raw) return cachedFcmConfig.config;++ let config: FcmConfig | null = null;+ if (typeof raw === "string" && raw.trim()) {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ parsed = null;+ }+ if (parsed && typeof parsed === "object") {+ const file = parsed as Record<string, unknown>;+ const { project_id: projectId, client_email: clientEmail, private_key: rawKey } = file;+ if (+ typeof projectId === "string" && PROJECT_ID.test(projectId)+ && typeof clientEmail === "string" && CLIENT_EMAIL.test(clientEmail)+ && typeof rawKey === "string"+ ) {+ const privateKey = rawKey.replace(/\\n/g, "\n").trim();+ if (PEM.test(privateKey)) {+ config = { projectId, clientEmail, privateKey };+ }+ }+ }}- if (!parsed || typeof parsed !== "object") return null;- const file = parsed as Record<string, unknown>;- const { project_id: projectId, client_email: clientEmail, private_key: rawKey } = file;- if (typeof projectId !== "string" || !PROJECT_ID.test(projectId)) return null;- if (typeof clientEmail !== "string" || !CLIENT_EMAIL.test(clientEmail)) return null;- if (typeof rawKey !== "string") return null;- const privateKey = rawKey.replace(/\\n/g, "\n").trim();- if (!PEM.test(privateKey)) return null;- return { projectId, clientEmail, privateKey };+ cachedFcmConfig = { raw, config };+ return config;}function base64url(bytes: ArrayBuffer | Uint8Array): string {@@ -58,11 +72,14 @@ function pemBytes(pem: string): Uint8Array<ArrayBuffer> {}interface CachedAccess {- fingerprint: string;+ projectId: string;+ clientEmail: string;+ privateKey: string;expiresAt: number;token: string;}let cachedAccess: CachedAccess | null = null;+let cachedFcmKey: { privateKey: string; key: CryptoKey } | null = null;export function forgetFcmAccessToken(): void {cachedAccess = null;@@ -70,26 +87,36 @@ export function forgetFcmAccessToken(): void {/** RS256 per RFC 7518 §3.3, the OAuth 2.0 JWT bearer grant (RFC 7523) Google's service accounts use. */export async function fcmAssertion(config: FcmConfig, now: number): Promise<string> {- const key = await crypto.subtle.importKey("pkcs8", pemBytes(config.privateKey), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);- const encoder = new TextEncoder();+ let key: CryptoKey;+ if (cachedFcmKey && cachedFcmKey.privateKey === config.privateKey) {+ key = cachedFcmKey.key;+ } else {+ key = await crypto.subtle.importKey("pkcs8", pemBytes(config.privateKey), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);+ cachedFcmKey = { privateKey: config.privateKey, key };+ }const iat = Math.floor(now / 1_000);- const header = base64url(encoder.encode(JSON.stringify({ alg: "RS256", typ: "JWT" })));- const claims = base64url(encoder.encode(JSON.stringify({+ const header = base64url(UTF8.encode(JSON.stringify({ alg: "RS256", typ: "JWT" })));+ const claims = base64url(UTF8.encode(JSON.stringify({iss: config.clientEmail,scope: FCM_SCOPE,aud: GOOGLE_TOKEN_URL,iat,exp: iat + ASSERTION_LIFETIME_SECONDS,})));- const signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, key, encoder.encode(`${header}.${claims}`));+ const signature = await crypto.subtle.sign({ name: "RSASSA-PKCS1-v1_5" }, key, UTF8.encode(`${header}.${claims}`));return `${header}.${claims}.${base64url(signature)}`;}export type FcmAccess = { kind: "ok"; token: string } | { kind: "credentials" | "failed"; status: number; reason: string };export async function fcmAccessToken(config: FcmConfig, pushFetch: typeof fetch, now: number): Promise<FcmAccess> {- const fingerprint = `${config.projectId}:${config.clientEmail}:${await sha256(config.privateKey)}`;- if (cachedAccess && cachedAccess.fingerprint === fingerprint && cachedAccess.expiresAt - ACCESS_TOKEN_MARGIN_MS > now) {+ if (+ cachedAccess+ && cachedAccess.expiresAt - ACCESS_TOKEN_MARGIN_MS > now+ && cachedAccess.projectId === config.projectId+ && cachedAccess.clientEmail === config.clientEmail+ && cachedAccess.privateKey === config.privateKey+ ) {return { kind: "ok", token: cachedAccess.token };}let assertion: string;@@ -113,7 +140,13 @@ export async function fcmAccessToken(config: FcmConfig, pushFetch: typeof fetch,const answer = await response.json<{ access_token?: unknown; expires_in?: unknown; error?: unknown }>().catch(() => null);if (response.status === 200 && typeof answer?.access_token === "string" && answer.access_token) {const lifetime = typeof answer.expires_in === "number" && Number.isFinite(answer.expires_in) ? answer.expires_in : 3_600;- cachedAccess = { fingerprint, expiresAt: now + lifetime * 1_000, token: answer.access_token };+ cachedAccess = {+ projectId: config.projectId,+ clientEmail: config.clientEmail,+ privateKey: config.privateKey,+ expiresAt: now + lifetime * 1_000,+ token: answer.access_token,+ };return { kind: "ok", token: answer.access_token };}const reason = typeof answer?.error === "string" ? answer.error.slice(0, 64) : "";@@ -148,5 +181,3 @@ export function fcmTokenIsDead(error: FcmError): boolean {export function fcmSendUrl(config: FcmConfig): string {return `${FCM_HOST}/v1/projects/${config.projectId}/messages:send`;}--export const FCM_TIMEOUT = FCM_TIMEOUT_MS;diff --git a/cloudflare/control-plane/src/push.ts b/cloudflare/control-plane/src/push.tsindex 2d46f20dcc..337b9ef84f 100644--- a/cloudflare/control-plane/src/push.ts+++ b/cloudflare/control-plane/src/push.ts@@ -46,6 +46,7 @@ const APNS_EXPIRATION_SECONDS = 24 * 60 * 60;/** APNs wants a provider token refreshed no more than every 20 and at least every 60 minutes. */export const APNS_TOKEN_WINDOW_MS = 50 * 60 * 1_000;const APNS_TIMEOUT_MS = 10_000;+const UTF8 = new TextEncoder();const KEY_OR_TEAM_ID = /^[A-Z0-9]{10}$/;const BUNDLE_ID = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;@@ -116,24 +117,61 @@ export const sendSchema = z.strictObject({});export type PushSendRequest = z.infer<typeof sendSchema>;+interface CachedApnsConfig {+ keyId: unknown;+ teamId: unknown;+ bundleId: unknown;+ rawKey: unknown;+ environments: unknown;+ config: ApnsConfig | null;+}+let cachedApnsConfig: CachedApnsConfig | null = null;+export function readApnsConfig(env: Env): ApnsConfig | null {const vars = env as unknown as Partial<Record<string, unknown>>;+ if (+ cachedApnsConfig+ && cachedApnsConfig.keyId === vars.APNS_KEY_ID+ && cachedApnsConfig.teamId === vars.APNS_TEAM_ID+ && cachedApnsConfig.bundleId === vars.APNS_BUNDLE_ID+ && cachedApnsConfig.rawKey === vars.APNS_PRIVATE_KEY+ && cachedApnsConfig.environments === vars.APNS_ENVIRONMENTS+ ) {+ return cachedApnsConfig.config;+ }++ let config: ApnsConfig | null = null;const keyId = vars.APNS_KEY_ID;const teamId = vars.APNS_TEAM_ID;const bundleId = vars.APNS_BUNDLE_ID;const rawKey = vars.APNS_PRIVATE_KEY;- if (typeof keyId !== "string" || !KEY_OR_TEAM_ID.test(keyId)) return null;- if (typeof teamId !== "string" || !KEY_OR_TEAM_ID.test(teamId)) return null;- if (typeof bundleId !== "string" || bundleId.length > 155 || !BUNDLE_ID.test(bundleId)) return null;- if (typeof rawKey !== "string") return null;- // `wrangler secret put` from a file keeps the newlines; a pasted value may carry them escaped.- const privateKey = rawKey.replace(/\\n/g, "\n").trim();- if (!/^-----BEGIN PRIVATE KEY-----\n[\s\S]+\n-----END PRIVATE KEY-----$/.test(privateKey)) return null;- const listed = typeof vars.APNS_ENVIRONMENTS === "string" && vars.APNS_ENVIRONMENTS.trim()- ? vars.APNS_ENVIRONMENTS.split(",").map((value) => value.trim())- : ["production"];- if (!listed.every((value) => value === "production" || value === "sandbox")) return null;- return { keyId, teamId, privateKey, bundleId, environments: new Set(listed as ApnsEnvironment[]) };+ if (+ typeof keyId === "string" && KEY_OR_TEAM_ID.test(keyId)+ && typeof teamId === "string" && KEY_OR_TEAM_ID.test(teamId)+ && typeof bundleId === "string" && bundleId.length <= 155 && BUNDLE_ID.test(bundleId)+ && typeof rawKey === "string"+ ) {+ // `wrangler secret put` from a file keeps the newlines; a pasted value may carry them escaped.+ const privateKey = rawKey.replace(/\\n/g, "\n").trim();+ if (/^-----BEGIN PRIVATE KEY-----\n[\s\S]+\n-----END PRIVATE KEY-----$/.test(privateKey)) {+ const listed = typeof vars.APNS_ENVIRONMENTS === "string" && vars.APNS_ENVIRONMENTS.trim()+ ? vars.APNS_ENVIRONMENTS.split(",").map((value) => value.trim())+ : ["production"];+ if (listed.every((value) => value === "production" || value === "sandbox")) {+ config = { keyId, teamId, privateKey, bundleId, environments: new Set(listed as ApnsEnvironment[]) };+ }+ }+ }++ cachedApnsConfig = {+ keyId: vars.APNS_KEY_ID,+ teamId: vars.APNS_TEAM_ID,+ bundleId: vars.APNS_BUNDLE_ID,+ rawKey: vars.APNS_PRIVATE_KEY,+ environments: vars.APNS_ENVIRONMENTS,+ config,+ };+ return config;}function base64url(bytes: ArrayBuffer | Uint8Array): string {@@ -151,11 +189,14 @@ function pemBytes(pem: string): Uint8Array<ArrayBuffer> {}interface CachedToken {- fingerprint: string;+ teamId: string;+ keyId: string;+ privateKey: string;window: number;jwt: string;}let cachedToken: CachedToken | null = null;+let cachedApnsKey: { privateKey: string; key: CryptoKey } | null = null;export function forgetApnsToken(): void {cachedToken = null;@@ -164,21 +205,33 @@ export function forgetApnsToken(): void {/** ES256 per RFC 7518 §3.4 is the raw r‖s signature WebCrypto returns. */export async function apnsProviderToken(config: ApnsConfig, now = Date.now()): Promise<string> {const window = Math.floor(now / APNS_TOKEN_WINDOW_MS);- const fingerprint = `${config.teamId}:${config.keyId}:${await sha256(config.privateKey)}`;- if (cachedToken && cachedToken.fingerprint === fingerprint && cachedToken.window === window) return cachedToken.jwt;- const key = await crypto.subtle.importKey(- "pkcs8",- pemBytes(config.privateKey),- { name: "ECDSA", namedCurve: "P-256" },- false,- ["sign"],- );- const encoder = new TextEncoder();- const header = base64url(encoder.encode(JSON.stringify({ alg: "ES256", kid: config.keyId })));- const claims = base64url(encoder.encode(JSON.stringify({ iss: config.teamId, iat: Math.floor((window * APNS_TOKEN_WINDOW_MS) / 1_000) })));- const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, encoder.encode(`${header}.${claims}`));+ if (+ cachedToken+ && cachedToken.window === window+ && cachedToken.teamId === config.teamId+ && cachedToken.keyId === config.keyId+ && cachedToken.privateKey === config.privateKey+ ) {+ return cachedToken.jwt;+ }+ let key: CryptoKey;+ if (cachedApnsKey && cachedApnsKey.privateKey === config.privateKey) {+ key = cachedApnsKey.key;+ } else {+ key = await crypto.subtle.importKey(+ "pkcs8",+ pemBytes(config.privateKey),+ { name: "ECDSA", namedCurve: "P-256" },+ false,+ ["sign"],+ );+ cachedApnsKey = { privateKey: config.privateKey, key };+ }+ const header = base64url(UTF8.encode(JSON.stringify({ alg: "ES256", kid: config.keyId })));+ const claims = base64url(UTF8.encode(JSON.stringify({ iss: config.teamId, iat: Math.floor((window * APNS_TOKEN_WINDOW_MS) / 1_000) })));+ const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, UTF8.encode(`${header}.${claims}`));const jwt = `${header}.${claims}.${base64url(signature)}`;- cachedToken = { fingerprint, window, jwt };+ cachedToken = { teamId: config.teamId, keyId: config.keyId, privateKey: config.privateKey, window, jwt };return jwt;}@@ -304,19 +357,42 @@ function limitStatement(env: Env, store: PushStore, ownerId: string, action: str).bind(ownerId, action, now, now, cutoff, cutoff, cutoff, limit);}-/** Takes one from every window, or from none: with several, all are read before any is taken, so a request refused by one- * limit does not spend another. */+/** Takes one from every window, or from none: with several, SQLite evaluates the+ * `NOT EXISTS` guard against the table before applying any row insert/update in+ * one D1 round trip, so a request refused by one limit does not spend another. */async function takeLimits(env: Env, store: PushStore, limits: PushLimit[], now: number): Promise<boolean> {- if (limits.length > 1) {- const full = await env.DB.prepare(- `SELECT COUNT(*) AS full FROM ${store.limits}- WHERE window_started_at > ? AND (${limits.map(() => `(${store.owner} = ? AND action = ? AND attempts >= ?)`).join(" OR ")})`,- ).bind(now - HOUR_MS, ...limits.flatMap(({ owner, action, limit }) => [owner, action, limit]))- .first<{ full: number }>();- if (full?.full) return false;+ if (limits.length === 0) return true;+ if (limits.length === 1) {+ const { owner, action, limit } = limits[0]!;+ const result = await limitStatement(env, store, owner, action, limit, now).run();+ return result.meta.changes > 0;}- const taken = await env.DB.batch(limits.map(({ owner, action, limit }) => limitStatement(env, store, owner, action, limit, now)));- return !taken.some((result) => result.meta.changes === 0);+ const cutoff = now - HOUR_MS;+ const rows = limits.map(() => "SELECT ? AS owner, ? AS action").join(" UNION ALL ");+ const fullChecks = limits.map(() => `(${store.owner} = ? AND action = ? AND attempts >= ?)`).join(" OR ");+ const result = await env.DB.prepare(+ `INSERT INTO ${store.limits}+ (${store.owner}, action, window_started_at, attempts, updated_at)+ SELECT v.owner, v.action, ?, 1, ?+ FROM (${rows}) v+ WHERE NOT EXISTS (+ SELECT 1 FROM ${store.limits}+ WHERE window_started_at > ? AND (${fullChecks})+ )+ ON CONFLICT(${store.owner}, 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`,+ ).bind(+ now,+ now,+ ...limits.flatMap(({ owner, action }) => [owner, action]),+ cutoff,+ ...limits.flatMap(({ owner, action, limit }) => [owner, action, limit]),+ cutoff,+ cutoff,+ ).run();+ return result.meta.changes === limits.length;}export async function registerPushDevice(request: Request, env: Env): Promise<Response> {diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.tsindex 0535543e91..5ed7b347f0 100644--- a/cloudflare/control-plane/src/relay.ts+++ b/cloudflare/control-plane/src/relay.ts@@ -4,7 +4,12 @@import { z } from "zod";import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";-import { installationKindSchema, recordInstallationKind, recordReportedAppVersion, requireInstallation } from "./installations";+import {+ checkInStatements,+ installationKindSchema,+ recordInstallationKind,+ requireAuthenticatedInstallation,+} from "./installations";const HOUR_MS = 60 * 60 * 1_000;export const RELAY_TOKEN_TTL_S = 12 * 60 * 60;@@ -16,6 +21,7 @@ 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 UTF8 = new TextEncoder();const requestSchema = z.strictObject({appVersion: z.string().regex(VERSION),@@ -70,37 +76,81 @@ const listVar = (value: unknown): string[] =>let cachedKey: { secret: string; key: Promise<CryptoKey> } | null = null;+interface CachedRelaySettings {+ disabled: unknown;+ secret: unknown;+ kid: unknown;+ nodes: unknown;+ americasNodes: unknown;+ rolloutPercent: unknown;+ allowInstallations: unknown;+ settings: RelaySettings | null;+}++let cachedSettings: CachedRelaySettings | 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;+ if (+ cachedSettings+ && cachedSettings.disabled === vars.RELAY_DISABLED+ && cachedSettings.secret === vars.RELAY_TOKEN_SIGNING_KEY+ && cachedSettings.kid === vars.RELAY_TOKEN_KID+ && cachedSettings.nodes === vars.RELAY_NODES+ && cachedSettings.americasNodes === vars.RELAY_NODES_AMERICAS+ && cachedSettings.rolloutPercent === vars.RELAY_ROLLOUT_PERCENT+ && cachedSettings.allowInstallations === vars.RELAY_ALLOW_INSTALLATIONS+ ) {+ return cachedSettings.settings;}- 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))),++ let settings: RelaySettings | null = null;+ if (vars.RELAY_DISABLED !== "1") {+ 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 && nodes.every((node) => RELAY_HOST.test(node))) {+ 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;+ }+ settings = {+ 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))),+ };+ }+ }++ cachedSettings = {+ disabled: vars.RELAY_DISABLED,+ secret: vars.RELAY_TOKEN_SIGNING_KEY,+ kid: vars.RELAY_TOKEN_KID,+ nodes: vars.RELAY_NODES,+ americasNodes: vars.RELAY_NODES_AMERICAS,+ rolloutPercent: vars.RELAY_ROLLOUT_PERCENT,+ allowInstallations: vars.RELAY_ALLOW_INSTALLATIONS,+ settings,};+ return settings;}/** 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)]));+ const encoded = UTF8.encode(node);+ const input = new Uint8Array(hostId.length + encoded.length);+ input.set(hostId);+ input.set(encoded, hostId.length);+ const digest = await sha256(input);return { node, score: new DataView(digest.buffer).getBigUint64(0) };}));const americas = continent !== null && AMERICAS.has(continent);@@ -124,8 +174,8 @@ export async function mintRelayToken(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)));+ const body = b64u(UTF8.encode(payload));+ const signature = new Uint8Array(await crypto.subtle.sign({ name: "Ed25519" }, signingKey, UTF8.encode(body)));return `${body}.${b64u(signature)}`;}@@ -146,12 +196,13 @@ function limitStatement(env: Env, installationId: string, now: number) {interface RelayRow {relay_host_id: string | null;relay_blocked_at: number | null;+ kind?: string | 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 }> {+async function hostIdFor(env: Env, installationId: string, existing?: RelayRow | null): 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();+ let row = existing !== undefined ? existing : 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)@@ -188,13 +239,16 @@ interface RelayUse {/** A token is minted for this request. */token: boolean;now: number;+ /** Optional `UPDATE installations SET kind = ?` to fold into the same D1 batch when kind changed. */+ kindStatement?: D1PreparedStatement | null;}/**- * Records a request in `relay_adoption` and, once per installation per UTC day and kind, adds 1 to `relay_daily`: `seen`- * (asked), `token` (got one), `e2e` (reported end-to-end phones), `new` (asked for the first time). Each count runs before- * the row is written, in one batch, so it reads the row as the previous request left it. Without migration 0014 the- * daily counts are skipped and only the adoption row is written, as before. False when neither could be written.+ * Records a request in `relay_adoption` (including `legacy_clear_at` from migration 0015) and, once per installation+ * per UTC day and kind, adds 1 to `relay_daily`: `seen` (asked), `token` (got one), `e2e` (reported end-to-end phones),+ * `new` (asked for the first time). Each count runs before the row is written, in one batch, so it reads the row as+ * the previous request left it. Gracefully falls back when migration 0015 or 0014 has not been applied yet. False when+ * none of the schemas could be written (pre-0012).*/async function recordUse(env: Env, use: RelayUse): Promise<boolean> {const day = new Date(use.now).toISOString().slice(0, 10);@@ -206,7 +260,36 @@ async function recordUse(env: Env, use: RelayUse): Promise<boolean> {SELECT ?1, ?2, 1 WHERE NOT EXISTS (SELECT 1 FROM relay_adoption WHERE installation_id = ?3${since ? ` AND ${since} >= ?4` : ""})ON CONFLICT (day, kind) DO UPDATE SET installs = installs + 1`,).bind(day, kind, use.installationId, ...(since ? [dayStart] : []));- const write = env.DB.prepare(+ const dailyBumps = [+ bump("new"),+ bump("seen", "updated_at"),+ ...(use.token ? [bump("token", "token_at")] : []),+ ...(use.e2e > 0 ? [bump("e2e", "e2e_at")] : []),+ ];+ const tokenAt = use.token ? use.now : null;+ const e2eAt = use.e2e > 0 ? use.now : null;+ // Migration 0015+: `legacy_clear_at` is kept while `legacy_devices = 0` and cleared by any old phone,+ // folded into the same batch so steady-state requests save an extra D1 round trip.+ const writeWithLegacyClear = env.DB.prepare(+ `INSERT INTO relay_adoption+ (installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at, first_seen_at, token_at, e2e_at, legacy_clear_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8, CASE WHEN ?4 > 0 THEN NULL ELSE ?6 END)+ 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,+ first_seen_at = COALESCE(first_seen_at, excluded.first_seen_at),+ token_at = COALESCE(excluded.token_at, token_at), e2e_at = COALESCE(excluded.e2e_at, e2e_at),+ legacy_clear_at = CASE WHEN excluded.legacy_devices > 0 THEN NULL ELSE COALESCE(relay_adoption.legacy_clear_at, excluded.updated_at) END`,+ ).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now, tokenAt, e2eAt);+ const fullBatch = [+ ...dailyBumps,+ writeWithLegacyClear,+ ...(use.kindStatement ? [use.kindStatement] : []),+ ];+ if (await env.DB.batch(fullBatch).then(() => true, () => false)) return true;++ // Fallback for pre-0015 databases (has `relay_daily` from 0014, no `legacy_clear_at` yet).+ const writeWithoutLegacyClear = env.DB.prepare(`INSERT INTO relay_adoption(installation_id, app_version, e2e_devices, legacy_devices, continent, updated_at, first_seen_at, token_at, e2e_at)VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8)@@ -215,16 +298,10 @@ async function recordUse(env: Env, use: RelayUse): Promise<boolean> {legacy_devices = excluded.legacy_devices, continent = excluded.continent, updated_at = excluded.updated_at,first_seen_at = COALESCE(first_seen_at, excluded.first_seen_at),token_at = COALESCE(excluded.token_at, token_at), e2e_at = COALESCE(excluded.e2e_at, e2e_at)`,- ).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now,- use.token ? use.now : null, use.e2e > 0 ? use.now : null);- const statements = [- bump("new"),- bump("seen", "updated_at"),- ...(use.token ? [bump("token", "token_at")] : []),- ...(use.e2e > 0 ? [bump("e2e", "e2e_at")] : []),- write,- ];- if (await env.DB.batch(statements).then(() => true, () => false)) return true;+ ).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now, tokenAt, e2eAt);+ if (await env.DB.batch([...dailyBumps, writeWithoutLegacyClear]).then(() => true, () => false)) return true;++ // Fallback for pre-0014 databases (only `relay_adoption` from 0012).if (!dailyWarned) {dailyWarned = true;console.error(JSON.stringify({ message: "relay daily counts not written; apply migration 0014", errorCode: "relay_daily_schema" }));@@ -238,16 +315,6 @@ async function recordUse(env: Env, use: RelayUse): Promise<boolean> {).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now).run().then(() => true, () => false);}-/** Since when this installation has reported no old phone: kept while the count stays 0, cleared by any old phone.- * The tunnel release waits on it (`tunnel-release.ts`). Skipped without migration 0015, and the release stays off. */-async function recordLegacyClear(env: Env, use: Pick<RelayUse, "installationId" | "legacy" | "now">): Promise<void> {- await env.DB.prepare(- `UPDATE relay_adoption- SET legacy_clear_at = CASE WHEN ?2 > 0 THEN NULL ELSE COALESCE(legacy_clear_at, ?3) END- WHERE installation_id = ?1`,- ).bind(use.installationId, use.legacy, use.now).run().catch(() => undefined);-}-/** The relay gave the computer a token this recently: tokens are renewed hourly while the relay is in use, so two* days covers a night off and a sleeping laptop. */export const RELAY_FRESH_MS = 2 * 24 * HOUR_MS;@@ -299,28 +366,73 @@ export async function relayStanding(env: Env, installationId: string, now = Datereturn { serves: true, bucket, proven: (adoption?.token_at ?? 0) >= now - RELAY_FRESH_MS, asked: adoption !== null };}+function rateLimited(): Response {+ const response = errorResponse(429, "rate_limited");+ response.headers.set("retry-after", "60");+ return response;+}+export async function issueRelayToken(request: Request, env: Env): Promise<Response> {- const installation = await requireInstallation(request, env);+ // Parse before D1 so valid requests can fold check-in, app_version, rate limit,+ // and relay host lookup into one batch, while still returning 401 before 400.const parsed = requestSchema.safeParse(await readBoundedJSON(request).catch(() => null));- if (!parsed.success) throw new HTTPError(400, "invalid_request");+ const installation = await requireAuthenticatedInstallation(request, env);const now = Date.now();- // The one request every relay-capable desktop makes each hour: it keeps the stored release current, so a desktop- // that updated itself is never judged by the version it registered with.- if (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");- response.headers.set("retry-after", "60");- return response;+ if (!parsed.success) {+ await env.DB.batch(checkInStatements(env, installation, now));+ throw new HTTPError(400, "invalid_request");}++ // The one request every relay-capable desktop makes each hour: keep the stored+ // release current in the same check-in write so a self-updated desktop is never+ // judged by the version it registered with.+ const checkIn = checkInStatements(env, installation, now, parsed.data.appVersion);+ const limit = limitStatement(env, installation.installation_id, now);const settings = await readRelaySettings(env);- if (!settings) return unavailable();+ if (!settings) {+ const results = await env.DB.batch([...checkIn, limit]);+ if (parsed.data.kind) await recordInstallationKind(env, installation.installation_id, parsed.data.kind);+ if (results[checkIn.length]?.meta.changes === 0) return rateLimited();+ return unavailable();+ }++ let limited: D1Result | undefined;+ let hostRow: RelayRow | null = null;+ let hasKindColumn = true;+ try {+ const results = await env.DB.batch([+ ...checkIn,+ limit,+ env.DB.prepare("SELECT relay_host_id, relay_blocked_at, kind FROM installations WHERE id = ?")+ .bind(installation.installation_id),+ ]);+ limited = results[checkIn.length];+ hostRow = (results[checkIn.length + 1]?.results[0] as RelayRow | undefined) ?? null;+ } catch {+ hasKindColumn = false;+ try {+ // Pre-0016 database: has `relay_host_id` / `relay_blocked_at` (0012), no `kind` yet.+ const results = await env.DB.batch([+ ...checkIn,+ limit,+ env.DB.prepare("SELECT relay_host_id, relay_blocked_at FROM installations WHERE id = ?")+ .bind(installation.installation_id),+ ]);+ limited = results[checkIn.length];+ hostRow = (results[checkIn.length + 1]?.results[0] as RelayRow | undefined) ?? null;+ } catch {+ // Pre-0012 database: keep check-in and rate limiting working, relay stays off.+ const results = await env.DB.batch([...checkIn, limit]);+ if (results[checkIn.length]?.meta.changes === 0) return rateLimited();+ return relaySchemaMissing();+ }+ }++ if (limited?.meta.changes === 0) return rateLimited();+let host: { hostId: string; blocked: boolean };try {- host = await hostIdFor(env, installation.installation_id);+ host = await hostIdFor(env, installation.installation_id, hostRow);} catch (error) {if (error instanceof HTTPError) throw error;return relaySchemaMissing();@@ -331,6 +443,10 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respoconst hostBytes = fromB64u(hostId) as Uint8Array;const included = !blocked && (settings.allowInstallations.has(installation.installation_id)|| (await rolloutBucket(hostBytes)) < settings.rolloutPercent);+ const kindStatement = parsed.data.kind && hasKindColumn && hostRow?.kind !== parsed.data.kind+ ? env.DB.prepare("UPDATE installations SET kind = ? WHERE id = ? AND revoked_at IS NULL AND kind IS NOT ?")+ .bind(parsed.data.kind, installation.installation_id, parsed.data.kind)+ : null;// Counted for every relay-capable desktop, in the rollout or not: the tunnel path retires on these numbers.const counted = await recordUse(env, {installationId: installation.installation_id,@@ -340,9 +456,9 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respocontinent: region,token: included,now,+ kindStatement,});if (!counted) return relaySchemaMissing();- await recordLegacyClear(env, { installationId: installation.installation_id, legacy: parsed.data.devices.legacy, now });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);diff --git a/cloudflare/control-plane/src/tunnel-capacity.ts b/cloudflare/control-plane/src/tunnel-capacity.tsindex 5cf18af7e7..393ae128d2 100644--- a/cloudflare/control-plane/src/tunnel-capacity.ts+++ b/cloudflare/control-plane/src/tunnel-capacity.ts@@ -57,8 +57,18 @@ const CAPACITY_HEALTH_CACHE_PATH = "/__internal/healthz-capacity-row/v2";interface ScanEndpointRow {installation_id: string;tunnel_name: string;+ tunnel_id: string | null;+ status: string;+ lease_expires_at: number | null;+ updated_at: number;+ last_reconciled_at: number | null;+ inst_id: string | null;+ inst_revoked_at: number | null;+ inst_last_seen_at: number | null;}+const RECLAIMABLE_STATUSES: ReadonlySet<string> = new Set(["ready", "error", "provisioning"]);+export interface TunnelScanSummary {dnsRecordCount: number | null;/** Idle tunnels that also passed every D1 guard (marked when mode is on). */@@ -202,13 +212,14 @@ export async function releaseCleanedCapacity(await forgetCachedCapacity(config);}-// The D1 side of "has been seen recently" lives only here, so the same SQL-// decides both the observe-mode count and the real mark, and a concurrent-// reconcile, revocation, or installation check-in that lands between the-// provider read and the write always wins. A row is only ever matched to a-// tunnel listed in its own account. A 'provisioning' row qualifies only once-// its request's lease has expired and nothing has touched the row for the-// whole quiet period, so a provisioning still under way is never cut.+// The D1 side of "has been seen recently" lives in `RECLAIM_GUARD_SQL` (which+// guards the atomic UPDATE so a concurrent reconcile, revocation, or check-in+// always wins) and is mirrored in `rowMatchesReclaimGuard` for the batched+// scan read so observe/preview counts and ineligible rows avoid N+1 D1 queries.+// A row is only ever matched to a tunnel listed in its own account. A+// 'provisioning' row qualifies only once its request's lease has expired and+// nothing has touched the row for the whole quiet period, so a provisioning+// still under way is never cut.const RECLAIM_GUARD_SQL = `installation_id = ?AND provider_account = ?AND tunnel_name = ?@@ -224,6 +235,25 @@ const RECLAIM_GUARD_SQL = `installation_id = ?AND COALESCE(i.last_seen_at, i.created_at) <= ?)`;+function rowMatchesReclaimGuard(+ row: ScanEndpointRow,+ tunnelId: string,+ reason: IdleReason,+ policy: IdlePolicy,+ now: number,+): boolean {+ const quietCutoff = now - quietPeriodMs(reason, policy);+ return (row.tunnel_id === null || row.tunnel_id === tunnelId)+ && RECLAIMABLE_STATUSES.has(row.status)+ && (row.lease_expires_at === null || row.lease_expires_at <= now)+ && row.updated_at <= quietCutoff+ && (row.last_reconciled_at ?? 0) <= quietCutoff+ && row.inst_id !== null+ && row.inst_revoked_at === null+ && row.inst_last_seen_at !== null+ && row.inst_last_seen_at <= quietCutoff;+}+function reclaimGuardBindings(account: EndpointAccount,row: ScanEndpointRow,@@ -245,21 +275,6 @@ function reclaimGuardBindings(];}-async function reclaimEligible(- env: Env,- account: EndpointAccount,- row: ScanEndpointRow,- tunnelId: string,- reason: IdleReason,- policy: IdlePolicy,- now: number,-): Promise<boolean> {- const found = await env.DB.prepare(- `SELECT 1 AS eligible FROM installation_endpoints WHERE ${RECLAIM_GUARD_SQL}`,- ).bind(...reclaimGuardBindings(account, row, tunnelId, reason, policy, now)).first<{ eligible: number }>();- return found !== null;-}-async function markIdleEndpoint(env: Env,account: EndpointAccount,@@ -429,14 +444,21 @@ async function scanAccount());// Only rows this account acts on: a row whose hostname is not one opaque label// under the account's suffix is never touched, so its tunnel is unmatched.+ // Join `installations` here so reclaim eligibility for preview and observe+ // checks is evaluated from this single D1 read instead of up to 200 per-tunnel+ // queries.const rows = new Map<string, ScanEndpointRow>();if (managed.length > 0) {const found = await env.DB.prepare(- `SELECT installation_id, tunnel_name- FROM installation_endpoints- WHERE provider_account = ?- AND ${opaqueHostnameSQL("hostname", "?")}- AND tunnel_name IN (SELECT value FROM json_each(?))`,+ `SELECT e.installation_id, e.tunnel_name, e.tunnel_id, e.status,+ e.lease_expires_at, e.updated_at, e.last_reconciled_at,+ i.id AS inst_id, i.revoked_at AS inst_revoked_at,+ COALESCE(i.last_seen_at, i.created_at) AS inst_last_seen_at+ FROM installation_endpoints e+ LEFT JOIN installations i ON i.id = e.installation_id+ WHERE e.provider_account = ?+ AND ${opaqueHostnameSQL("e.hostname", "?")}+ AND e.tunnel_name IN (SELECT value FROM json_each(?))`,).bind(account.accountId,account.companionHostSuffix,@@ -467,15 +489,16 @@ async function scanAccount(const previewReason = previewPolicy ? idleTunnelReason(tunnel.activity, now, previewPolicy) : null;if (previewPolicy && previewReason- && await reclaimEligible(env, account, row, tunnel.id, previewReason, previewPolicy, now)+ && rowMatchesReclaimGuard(row, tunnel.id, previewReason, previewPolicy, now)) {previewEligible += 1;}const reason = idleTunnelReason(tunnel.activity, now, policy);if (!reason) continue;idle[reason] += 1;+ if (!rowMatchesReclaimGuard(row, tunnel.id, reason, policy, now)) continue;if (config.capacity.reclaimMode !== "on") {- if (await reclaimEligible(env, account, row, tunnel.id, reason, policy, now)) eligible += 1;+ eligible += 1;continue;}if (budget.marks <= 0) continue;@@ -748,9 +771,12 @@ export async function capacityHealth(ctx: ExecutionContext,now = Date.now(),): Promise<JSONValue> {- const pool = poolHealth(config, await cachedSnapshots(env, config, ctx), now);+ const [snapshots, dryRun] = await Promise.all([+ cachedSnapshots(env, config, ctx),+ reclaimPreview(env, config, now),+ ]);+ const pool = poolHealth(config, snapshots, now);const only = pool.accounts.length === 1 ? pool.accounts[0] : undefined;- const dryRun = await reclaimPreview(env, config, now);const preview: Record<string, JSONValue> = dryRun === null ? {} : { preview: dryRun };if (only) {return {diff --git a/cloudflare/control-plane/src/tunnel-release.ts b/cloudflare/control-plane/src/tunnel-release.tsindex 50adefe1f1..0582b22169 100644--- a/cloudflare/control-plane/src/tunnel-release.ts+++ b/cloudflare/control-plane/src/tunnel-release.ts@@ -254,68 +254,78 @@ export async function releaseTunnels(marked: { legacy_cutoff: 0, min_version: 0, relay_proven: 0 },preview: preview(rows, policy),};- // Never more waiting for cleanup than one sweep removes: while the sweep is- // failing or rate-limited its queue stays full and nothing more is marked,- // so no owner is left with a row it cannot take back. A forced removal- // whose tunnel was still connected after its cleanup rounds is not a failing- // sweep: it backs off and retries on its own, and does not hold the queue.- const queued = await env.DB.prepare(- `SELECT COUNT(*) AS count FROM installation_endpoints e- WHERE e.status = 'deleting' AND ${ACTED_ON_ENDPOINT_SQL}- AND NOT (e.reclaim_requested_at IS NULL AND COALESCE(e.last_error_code, '') IN (SELECT value FROM json_each(?)))`,- ).bind(actedOnAccounts(config), STILL_CONNECTED_CODES).first<{ count: number }>();- let budget = Math.max(0, Math.min(RELEASE_MARK_LIMIT, config.capacity.cleanupSweepLimit) - (queued?.count ?? 0));- const fresh = now - RELAY_FRESH_MS;- const versions = rows.map((row) => row.version);- const below = JSON.stringify(versions.filter((each) => belowMinimum(policy, each)));- const capable = JSON.stringify(versions.filter((each) => relayCapableVersion(policy, each) && !belowMinimum(policy, each)));- // With the relay switched off, or a computer outside its rollout, nobody is- // moved onto it: the same `relayAdmits` provisioning answers by, so a tunnel- // provisioning would hand back is never marked.- const relay = await readRelaySettings(env);- const inside = (percent: number) => async (row: Candidate) => {- const { admitted, bucket } = await relayAdmits(relay, { installationId: row.installation_id, hostId: row.relay_host_id, blocked: false });- return admitted && bucket !== null && bucket < percent;- };- const run = async (reason: ReleaseReason, guard: string, bindings: unknown[], admit?: (row: Candidate) => Promise<boolean>) => {- if (budget <= 0) return;- const found = await env.DB.prepare(- `SELECT e.installation_id, i.relay_host_id- FROM installation_endpoints e- JOIN installations i ON i.id = e.installation_id- LEFT JOIN relay_adoption a ON a.installation_id = e.installation_id- WHERE ${HELD_TUNNEL_SQL}- AND (e.lease_expires_at IS NULL OR e.lease_expires_at <= ?)- AND ${guard}- ORDER BY e.updated_at ASC, e.installation_id ASC- LIMIT ?`,- ).bind(actedOnAccounts(config), now, ...bindings, admit ? PROVEN_SCAN_LIMIT : budget)- .all<Candidate>();- for (const row of found.results) {- if (budget <= 0) break;- if (admit && !(await admit(row))) continue;- if (await mark(env, config, row.installation_id, guard, bindings, now)) {- budget -= 1;- summary.marked[reason] += 1;+ const anyRelaySwitch = policy.legacyCutoffPercent > 0 || policy.releasePercent > 0;+ if (policy.minAppVersion !== null || anyRelaySwitch) {+ // Never more waiting for cleanup than one sweep removes: while the sweep is+ // failing or rate-limited its queue stays full and nothing more is marked,+ // so no owner is left with a row it cannot take back. A forced removal+ // whose tunnel was still connected after its cleanup rounds is not a failing+ // sweep: it backs off and retries on its own, and does not hold the queue.+ const queued = await env.DB.prepare(+ `SELECT COUNT(*) AS count FROM installation_endpoints e+ WHERE e.status = 'deleting' AND ${ACTED_ON_ENDPOINT_SQL}+ AND NOT (e.reclaim_requested_at IS NULL AND COALESCE(e.last_error_code, '') IN (SELECT value FROM json_each(?)))`,+ ).bind(actedOnAccounts(config), STILL_CONNECTED_CODES).first<{ count: number }>();+ let budget = Math.max(0, Math.min(RELEASE_MARK_LIMIT, config.capacity.cleanupSweepLimit) - (queued?.count ?? 0));+ if (budget > 0) {+ const fresh = now - RELAY_FRESH_MS;+ const versions = rows.map((row) => row.version);++ const run = async (reason: ReleaseReason, guard: string, bindings: unknown[], admit?: (row: Candidate) => Promise<boolean>) => {+ if (budget <= 0) return;+ const found = await env.DB.prepare(+ `SELECT e.installation_id, i.relay_host_id+ FROM installation_endpoints e+ JOIN installations i ON i.id = e.installation_id+ LEFT JOIN relay_adoption a ON a.installation_id = e.installation_id+ WHERE ${HELD_TUNNEL_SQL}+ AND (e.lease_expires_at IS NULL OR e.lease_expires_at <= ?)+ AND ${guard}+ ORDER BY e.updated_at ASC, e.installation_id ASC+ LIMIT ?`,+ ).bind(actedOnAccounts(config), now, ...bindings, admit ? PROVEN_SCAN_LIMIT : budget)+ .all<Candidate>();+ for (const row of found.results) {+ if (budget <= 0) break;+ if (admit && !(await admit(row))) continue;+ if (await mark(env, config, row.installation_id, guard, bindings, now)) {+ budget -= 1;+ summary.marked[reason] += 1;+ }+ }+ };++ if (policy.minAppVersion !== null) {+ const below = JSON.stringify(versions.filter((each) => belowMinimum(policy, each)));+ await run("min_version", `${VERSION_IN_SQL} AND ${SEEN_LATELY_SQL}`, [below, now - SEEN_FRESH_MS]);+ }+ if (budget > 0 && anyRelaySwitch) {+ // With the relay switched off, or a computer outside its rollout, nobody is+ // moved onto it: the same `relayAdmits` provisioning answers by, so a tunnel+ // provisioning would hand back is never marked.+ const relay = await readRelaySettings(env);+ if (relay) {+ const capable = JSON.stringify(versions.filter((each) => relayCapableVersion(policy, each) && !belowMinimum(policy, each)));+ const inside = (percent: number) => async (row: Candidate) => {+ const { admitted, bucket } = await relayAdmits(relay, { installationId: row.installation_id, hostId: row.relay_host_id, blocked: false });+ return admitted && bucket !== null && bucket < percent;+ };+ const servedGuard = `${VERSION_IN_SQL} AND i.relay_blocked_at IS NULL AND ${NOT_SERVER_SQL}`;+ if (policy.legacyCutoffPercent > 0) {+ await run("legacy_cutoff", `${servedGuard} AND ${RELAY_SERVED_SQL}`, [capable, fresh], inside(policy.legacyCutoffPercent));+ }+ if (policy.releasePercent > 0) {+ await run(+ "relay_proven",+ `${servedGuard} AND ${RELAY_PROVEN_SQL}`,+ [capable, fresh, fresh, now - policy.releaseMs],+ inside(policy.releasePercent),+ );+ }+ }}}- };-- 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 AND ${NOT_SERVER_SQL}`;- if (relay && policy.legacyCutoffPercent > 0) {- await run("legacy_cutoff", `${servedGuard} AND ${RELAY_SERVED_SQL}`, [capable, fresh], inside(policy.legacyCutoffPercent));- }- if (relay && policy.releasePercent > 0) {- await run(- "relay_proven",- `${servedGuard} AND ${RELAY_PROVEN_SQL}`,- [capable, fresh, fresh, now - policy.releaseMs],- inside(policy.releasePercent),- );}console.log(JSON.stringify({diff --git a/cloudflare/control-plane/test/push.test.ts b/cloudflare/control-plane/test/push.test.tsindex 485f809de9..55a84cf2ce 100644--- a/cloudflare/control-plane/test/push.test.ts+++ b/cloudflare/control-plane/test/push.test.ts@@ -19,6 +19,39 @@ const TOKEN_B = "b2".repeat(32);type TestWorker = ReturnType<typeof createWorker>;+const RAW_STATEMENT = Symbol("raw-statement");+function countD1Trips(baseEnv: Env): { env: Env; getTrips: () => number; reset: () => void } {+ let trips = 0;+ const wrap = (statement: D1PreparedStatement): D1PreparedStatement => new Proxy(statement, {+ get(target, property) {+ if (property === RAW_STATEMENT) return target;+ if (property === "bind") return (...values: unknown[]) => wrap(target.bind(...values));+ if (property === "first" || property === "all" || property === "run" || property === "raw") {+ return (...args: unknown[]) => {+ trips += 1;+ return (target[property] as (...rest: unknown[]) => unknown).apply(target, args);+ };+ }+ const value: unknown = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ const db = new Proxy(baseEnv.DB, {+ get(target, property) {+ if (property === "prepare") return (sql: string) => wrap(target.prepare(sql));+ if (property === "batch") {+ return (statements: D1PreparedStatement[]) => {+ trips += 1;+ return target.batch(statements.map((each) => (each as unknown as Record<symbol, D1PreparedStatement>)[RAW_STATEMENT] ?? each));+ };+ }+ const value: unknown = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ return { env: { ...baseEnv, DB: db } as Env, getTrips: () => trips, reset: () => { trips = 0; } };+}+interface ApnsCall {url: string;headers: Record<string, string>;@@ -157,6 +190,18 @@ describe("phone push relay", () => {expect(apns.calls).toHaveLength(1);});+ it("enforces both send rate limits in one D1 round trip (4 total for a push send)", async () => {+ const key = await apnsKey();+ const testEnv = await pushEnv(key.privateKeyPem);+ const apns = fakeApns();+ const worker = createWorker(fetch, apns.fetch);+ const { credential } = await installation(worker, testEnv, "[email protected]");+ expect((await register(worker, testEnv, credential)).status).toBe(200);+ const counted = countD1Trips(testEnv);+ expect((await send(worker, counted.env, credential)).status).toBe(202);+ expect(counted.getTrips()).toBe(4);+ });+it("signs an ES256 provider token and sends a content-free alert", async () => {const key = await apnsKey();const testEnv = await pushEnv(key.privateKeyPem);diff --git a/cloudflare/control-plane/test/relay.test.ts b/cloudflare/control-plane/test/relay.test.tsindex b850a4c8a1..41f2ef7712 100644--- a/cloudflare/control-plane/test/relay.test.ts+++ b/cloudflare/control-plane/test/relay.test.ts@@ -22,6 +22,39 @@ function relayEnv(extra: Record<string, string> = {}): Env {return { ...env, RELAY_TOKEN_SIGNING_KEY: b64u(seed), RELAY_ROLLOUT_PERCENT: "100", ...extra } as unknown as Env;}+const RAW_STATEMENT = Symbol("raw-statement");+function countD1Trips(baseEnv: Env): { env: Env; getTrips: () => number; reset: () => void } {+ let trips = 0;+ const wrap = (statement: D1PreparedStatement): D1PreparedStatement => new Proxy(statement, {+ get(target, property) {+ if (property === RAW_STATEMENT) return target;+ if (property === "bind") return (...values: unknown[]) => wrap(target.bind(...values));+ if (property === "first" || property === "all" || property === "run" || property === "raw") {+ return (...args: unknown[]) => {+ trips += 1;+ return (target[property] as (...rest: unknown[]) => unknown).apply(target, args);+ };+ }+ const value: unknown = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ const db = new Proxy(baseEnv.DB, {+ get(target, property) {+ if (property === "prepare") return (sql: string) => wrap(target.prepare(sql));+ if (property === "batch") {+ return (statements: D1PreparedStatement[]) => {+ trips += 1;+ return target.batch(statements.map((each) => (each as unknown as Record<symbol, D1PreparedStatement>)[RAW_STATEMENT] ?? each));+ };+ }+ const value: unknown = Reflect.get(target, property, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ return { env: { ...baseEnv, DB: db } as Env, getTrips: () => trips, reset: () => { trips = 0; } };+}+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}`);@@ -116,6 +149,16 @@ describe("relay host tokens", () => {expect(first.nodes).toEqual(await orderNodes(fromB64u(first.hostId), { nodes: ["relay1.openmausbot.com", "relay2.openmausbot.com"], americasNodes: new Set() }, null));});+ it("issues a steady-state token refresh in 3 D1 round trips", async () => {+ const { credential } = await installation("[email protected]");+ const counted = countD1Trips(relayEnv());+ // First call assigns relay_host_id; second call is the steady-state hourly refresh.+ expect((await ask(counted.env, credential)).status).toBe(200);+ counted.reset();+ expect((await ask(counted.env, credential)).status).toBe(200);+ expect(counted.getTrips()).toBe(3);+ });+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);