diff --git a/ai/context/operations.md b/ai/context/operations.md index e7e8ce3..0bd4ef8 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -149,7 +149,7 @@ anyone's real domain). Nothing that uses the domain was removed; it waits: |---|---| | `intent.yaml` | `BASE_DOMAIN` (every environment) and `CONSOLE_CUSTOM_DOMAIN` (`stage.lumen.app`, `prod.lumen.app`) — the parameters of the parked `infra/terraform/cloudflare-domain` | | `infra/terraform/cloudflare-domain` | `baseDomain` in its `component.yaml`, the Terraform variable's default, its README | -| `apps/api-edge/wrangler.template.jsonc` | `CONSOLE_CUSTOM_DOMAIN`, the console origin CORS allows besides the workers.dev one | +| `apps/api-edge/wrangler.template.jsonc` | `CONSOLE_CUSTOM_DOMAIN`, the console origin CORS allows besides the workers.dev one (`CONSOLE_WORKERS_DEV_SUBDOMAIN` and `CONSOLE_WORKER_PREFIX` beside it name that workers.dev one, and carry no domain) | | `apps/identity-worker/wrangler.template.jsonc` | `OAUTH_ALLOWED_CONSOLE_ORIGINS`, which lists the workers.dev console too, so sign-in works without a domain | | `apps/notifications-worker/wrangler.template.jsonc` | `EMAIL_FROM_ADDRESS`, `no-reply@mail.lumen.app` | | `apps/billing-worker/wrangler.template.jsonc` | `POLAR_SUCCESS_URL`, the fallback return after checkout | diff --git a/apps/api-edge/src/app-config.ts b/apps/api-edge/src/app-config.ts index 8d2912b..370c9db 100644 --- a/apps/api-edge/src/app-config.ts +++ b/apps/api-edge/src/app-config.ts @@ -4,6 +4,23 @@ // instance of the starter retargets one file (or, later, one generated // config) instead of hunting through handler code. Do not add behavior — // values and trivial derivations only. +// +// RUNTIME, NOT BUILD, for the console identity below. The workers.dev +// subdomain is an *account* fact: the bootstrap only learns it once the +// Cloudflare connection is read, which is after the scaffold phase has +// already written this file. A product whose edge was built from the +// scaffold's placeholder therefore shipped a CORS allowlist naming a console +// that does not exist, and every console fetch failed the preflight +// ("Failed to fetch" at the login screen) until the edge happened to be +// rebuilt. So the two values are resolved per request: +// +// 1. the Worker's `vars` (wrangler.template.jsonc), then +// 2. these constants, and — for the subdomain — additionally +// 3. the workers.dev subdomain THIS Worker is answering on. +// +// (3) is what makes the allowlist self-correcting: the edge and the console +// are deployed to one Cloudflare account, so the subdomain in the edge's own +// hostname is the console's subdomain, whatever literal the bundle carries. /** The Cloudflare account's workers.dev subdomain serving this instance. */ export const WORKERS_DEV_SUBDOMAIN = "rahulvarghesepullely"; @@ -11,7 +28,87 @@ export const WORKERS_DEV_SUBDOMAIN = "rahulvarghesepullely"; /** Worker name prefix of the console delivery (per-env: `${prefix}-${env}`). */ export const CONSOLE_WORKER_PREFIX = "lumen-web-console-next"; -/** workers.dev origin of the console for a given environment name. */ -export function consoleWorkersDevOrigin(environment: string): string { - return `https://${CONSOLE_WORKER_PREFIX}-${environment}.${WORKERS_DEV_SUBDOMAIN}.workers.dev`; +/** The environments a console deploy can serve (mirrors the console's own list). */ +export const CONSOLE_ENVIRONMENTS = ["dev", "stage", "prod"] as const; + +/** Where the console this edge trusts is deployed. */ +export interface ConsoleIdentity { + workersDevSubdomain: string; + consoleWorkerPrefix: string; +} + +/** This tree's own identity: what a deploy with no runtime `vars` serves. */ +export const DEFAULT_CONSOLE_IDENTITY: ConsoleIdentity = { + workersDevSubdomain: WORKERS_DEV_SUBDOMAIN, + consoleWorkerPrefix: CONSOLE_WORKER_PREFIX, +}; + +/** The subset of `Env` this seam reads, so it is callable with a bare object. */ +export interface ConsoleIdentityEnv { + CONSOLE_WORKERS_DEV_SUBDOMAIN?: string; + CONSOLE_WORKER_PREFIX?: string; +} + +/** The Worker `vars` that override each field at runtime. */ +export const RUNTIME_KEYS: Record = { + workersDevSubdomain: "CONSOLE_WORKERS_DEV_SUBDOMAIN", + consoleWorkerPrefix: "CONSOLE_WORKER_PREFIX", +}; + +function pick(env: ConsoleIdentityEnv, key: keyof ConsoleIdentity): string | undefined { + const value = env[RUNTIME_KEYS[key]]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; +} + +/** + * The workers.dev subdomain a host names, for the `..workers.dev` + * shape every workers.dev deploy has. A custom domain names none. + */ +export function workersDevSubdomainFromHost(host: string | null | undefined): string | undefined { + const labels = (host ?? "").toLowerCase().split(":")[0]!.split("."); + if (labels.length !== 4) return undefined; + const [worker, subdomain, workers, dev] = labels; + if (workers !== "workers" || dev !== "dev") return undefined; + if (!worker || !subdomain) return undefined; + return subdomain; +} + +/** + * workers.dev origin of the console for a given environment name, under one + * console identity. Kept for the single-identity callers and the tests. + */ +export function consoleWorkersDevOrigin( + environment: string, + identity: ConsoleIdentity = DEFAULT_CONSOLE_IDENTITY, +): string { + return `https://${identity.consoleWorkerPrefix}-${environment}.${identity.workersDevSubdomain}.workers.dev`; +} + +/** + * Every workers.dev origin the console for `environment` may answer on: one + * per subdomain this deploy knows of (the runtime var or the constant, plus + * the one the edge's own `host` names). Each entry is a complete origin — no + * wildcard, so an origin that merely *contains* one of them still fails. + */ +export function consoleWorkersDevOrigins( + environment: string, + env: ConsoleIdentityEnv = {}, + host?: string | null, +): string[] { + const consoleWorkerPrefix = + pick(env, "consoleWorkerPrefix") ?? DEFAULT_CONSOLE_IDENTITY.consoleWorkerPrefix; + const subdomains = [ + pick(env, "workersDevSubdomain") ?? DEFAULT_CONSOLE_IDENTITY.workersDevSubdomain, + workersDevSubdomainFromHost(host), + ]; + const origins: string[] = []; + for (const workersDevSubdomain of subdomains) { + if (!workersDevSubdomain) continue; + const origin = consoleWorkersDevOrigin(environment, { + workersDevSubdomain, + consoleWorkerPrefix, + }); + if (!origins.includes(origin)) origins.push(origin); + } + return origins; } diff --git a/apps/api-edge/src/cors.ts b/apps/api-edge/src/cors.ts index 00f915f..b24b82a 100644 --- a/apps/api-edge/src/cors.ts +++ b/apps/api-edge/src/cors.ts @@ -1,20 +1,19 @@ import type { Env } from "./env"; -import { consoleWorkersDevOrigin } from "./app-config"; +import { CONSOLE_ENVIRONMENTS, consoleWorkersDevOrigins } from "./app-config"; // Deploy hostnames for `apps/web-console-next` (Next.js + opennextjs/cloudflare) // under the cloudflare-workers-assets-turbo composition. Per-env naming via // `${prefix}-${env}` so the cutover keeps a stable shape across environments. -// Identity values (subdomain, worker prefix) come from `./app-config`. +// The identity behind those names (subdomain, worker prefix) is resolved per +// request by `./app-config` — from the Worker's `vars`, this tree's constants, +// and the subdomain the edge's own hostname names — so the allowlist tracks +// where the console is actually deployed rather than what the bundle was built +// with. See the header of `./app-config` for why that matters. // // Legacy `apps/web-console` (vanilla Vite, Pages) was decommissioned in Task 0083 // (custom-domain swing to web-console-next Workers). No CORS allowlist entry is // needed for the now-orphaned Pages hostnames — they are not served by any // current frontend. -const WORKERS_ORIGINS: Record = { - dev: consoleWorkersDevOrigin("dev"), - stage: consoleWorkersDevOrigin("stage"), - prod: consoleWorkersDevOrigin("prod"), -}; const LOCALHOST_RE = /^https?:\/\/localhost(:\d+)?$/; const VITE_DEV_RE = /^https?:\/\/127\.0\.0\.1(:\d+)?$/; @@ -34,7 +33,16 @@ const EXPOSED_HEADERS = [ const ALLOWED_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS"; const MAX_AGE = "86400"; -export function isAllowedOrigin(origin: string | null, env: Env): boolean { +/** The host this Worker is answering on, which names its workers.dev subdomain. */ +function requestHost(request: Request): string | null { + try { + return new URL(request.url).host; + } catch { + return null; + } +} + +export function isAllowedOrigin(origin: string | null, env: Env, host?: string | null): boolean { if (!origin) return false; if (LOCALHOST_RE.test(origin)) return true; @@ -43,15 +51,16 @@ export function isAllowedOrigin(origin: string | null, env: Env): boolean { const environment = env.ENVIRONMENT; const customDomain = env.CONSOLE_CUSTOM_DOMAIN; + if (customDomain && origin === `https://${customDomain}`) return true; + + // stage and prod each trust their OWN console only: a stage console may not + // call the prod edge. Everything else (dev, local, tests) trusts all three. if (environment === "stage" || environment === "prod") { - if (customDomain && origin === `https://${customDomain}`) return true; - if (origin === WORKERS_ORIGINS[environment]) return true; - return false; + return consoleWorkersDevOrigins(environment, env, host).includes(origin); } - if (customDomain && origin === `https://${customDomain}`) return true; - for (const workerOrigin of Object.values(WORKERS_ORIGINS)) { - if (origin === workerOrigin) return true; + for (const consoleEnvironment of CONSOLE_ENVIRONMENTS) { + if (consoleWorkersDevOrigins(consoleEnvironment, env, host).includes(origin)) return true; } return false; @@ -61,7 +70,7 @@ export function handlePreflight(request: Request, env: Env): Response | null { if (request.method !== "OPTIONS") return null; const origin = request.headers.get("origin"); - if (!isAllowedOrigin(origin, env)) { + if (!isAllowedOrigin(origin, env, requestHost(request))) { return new Response(null, { status: 204 }); } @@ -81,7 +90,7 @@ export function handlePreflight(request: Request, env: Env): Response | null { export function applyCorsHeaders(response: Response, request: Request, env: Env): Response { const origin = request.headers.get("origin"); - if (!isAllowedOrigin(origin, env)) return response; + if (!isAllowedOrigin(origin, env, requestHost(request))) return response; const headers = new Headers(response.headers); headers.set("access-control-allow-origin", origin!); diff --git a/apps/api-edge/src/env.ts b/apps/api-edge/src/env.ts index b45ee6a..462fdf1 100644 --- a/apps/api-edge/src/env.ts +++ b/apps/api-edge/src/env.ts @@ -22,6 +22,12 @@ export interface Env { RATE_LIMITER_DO?: DurableObjectNamespace; ENVIRONMENT: string; CONSOLE_CUSTOM_DOMAIN?: string; + // Where the console this edge trusts for CORS is deployed, per deploy rather + // than per build (see ./app-config). Both are plain wrangler vars, not + // secrets; when unset the Worker falls back to its compiled-in constants and, + // for the subdomain, to the one its own hostname names. + CONSOLE_WORKERS_DEV_SUBDOMAIN?: string; + CONSOLE_WORKER_PREFIX?: string; // M0 / Solo profile switch. "true" runs the single-user B2C profile (see // ./solo-mode.ts); absent or any other value keeps the full multi-tenant // baseline. Deploy-time wrangler var, not a secret. diff --git a/apps/api-edge/wrangler.template.jsonc b/apps/api-edge/wrangler.template.jsonc index 6dbe3e5..c757b79 100644 --- a/apps/api-edge/wrangler.template.jsonc +++ b/apps/api-edge/wrangler.template.jsonc @@ -13,6 +13,10 @@ "vars": { "ENVIRONMENT": "local", "CONSOLE_CUSTOM_DOMAIN": "", + // Where the console is deployed, so CORS follows the DEPLOY and not + // the build (src/app-config.ts). The rebrand rewrites both values. + "CONSOLE_WORKERS_DEV_SUBDOMAIN": "rahulvarghesepullely", + "CONSOLE_WORKER_PREFIX": "lumen-web-console-next", // M0 / Solo profile (Lumen ships single-user). Set "false" to restore the // full multi-tenant baseline. See specs/profiles/solo-m0.md. "SOLO_MODE": "true" @@ -30,6 +34,10 @@ "vars": { "ENVIRONMENT": "dev", "CONSOLE_CUSTOM_DOMAIN": "", + // Where the console is deployed, so CORS follows the DEPLOY and not + // the build (src/app-config.ts). The rebrand rewrites both values. + "CONSOLE_WORKERS_DEV_SUBDOMAIN": "rahulvarghesepullely", + "CONSOLE_WORKER_PREFIX": "lumen-web-console-next", "SOLO_MODE": "true" }, "durable_objects": { @@ -45,6 +53,10 @@ "vars": { "ENVIRONMENT": "stage", "CONSOLE_CUSTOM_DOMAIN": "stage.lumen.app", + // Where the console is deployed, so CORS follows the DEPLOY and not + // the build (src/app-config.ts). The rebrand rewrites both values. + "CONSOLE_WORKERS_DEV_SUBDOMAIN": "rahulvarghesepullely", + "CONSOLE_WORKER_PREFIX": "lumen-web-console-next", "SOLO_MODE": "true" }, "hyperdrive": [ @@ -114,6 +126,10 @@ "vars": { "ENVIRONMENT": "prod", "CONSOLE_CUSTOM_DOMAIN": "prod.lumen.app", + // Where the console is deployed, so CORS follows the DEPLOY and not + // the build (src/app-config.ts). The rebrand rewrites both values. + "CONSOLE_WORKERS_DEV_SUBDOMAIN": "rahulvarghesepullely", + "CONSOLE_WORKER_PREFIX": "lumen-web-console-next", "SOLO_MODE": "true" }, "hyperdrive": [ diff --git a/specs/components/01-edge-api.md b/specs/components/01-edge-api.md index d610989..789a27d 100644 --- a/specs/components/01-edge-api.md +++ b/specs/components/01-edge-api.md @@ -137,6 +137,33 @@ in the allowlist alongside the custom domain so SSR previews work without DNS. Legacy `lumen-web-console-{env}.pages.dev` Pages origins were removed from the allowlist in Task 0083 when `apps/web-console` was decommissioned. +### Where the console's workers.dev origin comes from + +Not from the build. `apps/api-edge/src/app-config.ts` resolves the console's +worker prefix and workers.dev subdomain per request, from three sources: + +1. the Worker's `vars` — `CONSOLE_WORKER_PREFIX`, + `CONSOLE_WORKERS_DEV_SUBDOMAIN` (`wrangler.template.jsonc`, per environment); +2. the constants compiled into the bundle (what a deploy with no `vars` gets); +3. for the subdomain only, **the one this Worker's own hostname names**. + +(3) exists because the workers.dev subdomain is an account fact the bootstrap +learns only after the scaffold phase has already written the constants into the +bundle. A product shipped with the placeholder still in its edge: every +preflight from the real console came back without +`access-control-allow-origin`, so the login screen read "Failed to fetch" +against a healthy API. The edge and the console are deployed to one Cloudflare +account, so the subdomain in the edge's own hostname is the console's — and +reading it there makes the allowlist correct whatever the bundle was built +with. + +This widens nothing: each source yields one complete origin, matched whole, and +`stage` still refuses the `prod` console (and the reverse). A custom-domain edge +host names no workers.dev subdomain, so (3) contributes nothing there. +`tests/platform-limits/src/console-origin-agreement.test.ts` guards the other +half — the identity worker's `OAUTH_ALLOWED_CONSOLE_ORIGINS`, an open-redirect +guard that is deliberately literal and cannot self-correct. + The custom domain origin is read from the `CONSOLE_CUSTOM_DOMAIN` environment variable (set in `wrangler.jsonc` per environment, sourced from `intent.yaml` environment-level `env` declarations). This ensures domain names are never diff --git a/tests/api-edge/src/cors.test.ts b/tests/api-edge/src/cors.test.ts index 34280d9..5db2035 100644 --- a/tests/api-edge/src/cors.test.ts +++ b/tests/api-edge/src/cors.test.ts @@ -1,5 +1,11 @@ import { handlePreflight, applyCorsHeaders, isAllowedOrigin } from "@api-edge/cors"; -import { consoleWorkersDevOrigin } from "@api-edge/app-config"; +import { + CONSOLE_WORKER_PREFIX, + WORKERS_DEV_SUBDOMAIN, + consoleWorkersDevOrigin, + consoleWorkersDevOrigins, + workersDevSubdomainFromHost, +} from "@api-edge/app-config"; import type { Env } from "@api-edge/env"; const stageEnv: Env = { ENVIRONMENT: "stage", CONSOLE_CUSTOM_DOMAIN: "stage.lumen.app" }; @@ -310,4 +316,134 @@ describe("api-edge cors", () => { expect(res.headers.get("access-control-allow-origin")).toBe("http://localhost:5173"); }); }); + + // ── The console identity is a DEPLOY fact, not a build fact ────────────── + // + // Regression: a product's edge was built during the scaffold phase, before + // the bootstrap had read the Cloudflare connection, so its bundle carried a + // placeholder workers.dev subdomain. The console deployed to the account's + // real subdomain, every preflight from it came back without + // `access-control-allow-origin`, and the login screen showed "Failed to + // fetch" against a perfectly healthy API. The allowlist now reads the + // subdomain off the edge's OWN hostname as well, so a stale bundle still + // trusts the console it is deployed beside. + describe("console identity resolved per deploy", () => { + // Derived from the seam, never written out: the rebrand rewrites every + // baseline identity literal in this file, so a hard-coded "live" subdomain + // would collapse onto the constant in a fork and stop testing anything. + const LIVE_SUBDOMAIN = `${WORKERS_DEV_SUBDOMAIN}-elsewhere`; + const RENAMED_CONSOLE_PREFIX = `${CONSOLE_WORKER_PREFIX}-renamed`; + const edgeHost = (environment: string) => `api-${environment}.${LIVE_SUBDOMAIN}.workers.dev`; + const consoleOrigin = (environment: string, prefix = CONSOLE_WORKER_PREFIX) => + `https://${prefix}-${environment}.${LIVE_SUBDOMAIN}.workers.dev`; + + describe("workersDevSubdomainFromHost", () => { + it("reads the subdomain out of a workers.dev host", () => { + expect(workersDevSubdomainFromHost(edgeHost("stage"))).toBe(LIVE_SUBDOMAIN); + }); + + it("ignores a port", () => { + expect(workersDevSubdomainFromHost(`${edgeHost("stage")}:8787`)).toBe(LIVE_SUBDOMAIN); + }); + + it("names no subdomain for a custom domain or a malformed host", () => { + // A custom domain, i.e. not `..workers.dev`. + expect(workersDevSubdomainFromHost("api.example.net")).toBeUndefined(); + expect(workersDevSubdomainFromHost("no-subdomain.workers.dev")).toBeUndefined(); + expect(workersDevSubdomainFromHost("a.b.c.workers.dev")).toBeUndefined(); + expect(workersDevSubdomainFromHost("evil.com")).toBeUndefined(); + expect(workersDevSubdomainFromHost(null)).toBeUndefined(); + expect(workersDevSubdomainFromHost(undefined)).toBeUndefined(); + }); + }); + + it("allows the console on the subdomain the edge itself answers on", () => { + // The bundle's constant still says the baseline's subdomain. + expect(isAllowedOrigin(consoleOrigin("stage"), stageEnv)).toBe(false); + expect(isAllowedOrigin(consoleOrigin("stage"), stageEnv, edgeHost("stage"))).toBe(true); + }); + + it("still allows the console named by the bundle's own constant", () => { + expect(isAllowedOrigin(STAGE_WORKER_ORIGIN, stageEnv, edgeHost("stage"))).toBe(true); + }); + + it("allows the console named by the runtime vars", () => { + const env: Env = { + ENVIRONMENT: "stage", + CONSOLE_WORKERS_DEV_SUBDOMAIN: LIVE_SUBDOMAIN, + CONSOLE_WORKER_PREFIX: RENAMED_CONSOLE_PREFIX, + }; + const origin = consoleOrigin("stage", RENAMED_CONSOLE_PREFIX); + expect(isAllowedOrigin(origin, env)).toBe(true); + // The prefix var applies to the host-derived subdomain too, which is how + // a console renamed after the edge was built is still trusted. + expect( + isAllowedOrigin( + origin, + { ENVIRONMENT: "stage", CONSOLE_WORKER_PREFIX: RENAMED_CONSOLE_PREFIX }, + edgeHost("stage"), + ), + ).toBe(true); + }); + + it("treats a blank var as unset", () => { + const env: Env = { + ENVIRONMENT: "stage", + CONSOLE_WORKERS_DEV_SUBDOMAIN: " ", + CONSOLE_WORKER_PREFIX: "", + }; + expect(isAllowedOrigin(STAGE_WORKER_ORIGIN, env)).toBe(true); + }); + + it("keeps stage and prod apart on the derived subdomain", () => { + expect(isAllowedOrigin(consoleOrigin("prod"), stageEnv, edgeHost("stage"))).toBe(false); + expect(isAllowedOrigin(consoleOrigin("stage"), prodEnv, edgeHost("prod"))).toBe(false); + expect(isAllowedOrigin(consoleOrigin("prod"), prodEnv, edgeHost("prod"))).toBe(true); + }); + + it("widens to one origin only — no wildcard on the derived subdomain", () => { + expect(isAllowedOrigin(`${consoleOrigin("stage")}.evil.com`, stageEnv, edgeHost("stage"))).toBe(false); + expect(isAllowedOrigin(`https://evil.${LIVE_SUBDOMAIN}.workers.dev`, stageEnv, edgeHost("stage"))).toBe(false); + expect(isAllowedOrigin(`https://${LIVE_SUBDOMAIN}.workers.dev`, stageEnv, edgeHost("stage"))).toBe(false); + expect(isAllowedOrigin(`${consoleOrigin("stage")}:8080`, stageEnv, edgeHost("stage"))).toBe(false); + expect(isAllowedOrigin(consoleOrigin("stage").replace("https://", "http://"), stageEnv, edgeHost("stage"))).toBe(false); + }); + + it("derives nothing from a custom-domain edge host", () => { + expect(isAllowedOrigin(consoleOrigin("stage"), stageEnv, "api.example.net")).toBe(false); + // …and the custom-domain console is still trusted there. + expect(isAllowedOrigin("https://stage.lumen.app", stageEnv, "api.example.net")).toBe(true); + }); + + it("offers both subdomains, deduped, and only those", () => { + expect(consoleWorkersDevOrigins("stage", stageEnv, edgeHost("stage"))).toEqual([ + STAGE_WORKER_ORIGIN, + consoleOrigin("stage"), + ]); + expect(consoleWorkersDevOrigins("stage", { CONSOLE_WORKERS_DEV_SUBDOMAIN: LIVE_SUBDOMAIN }, edgeHost("stage"))).toEqual([ + consoleOrigin("stage"), + ]); + expect(consoleWorkersDevOrigins("stage")).toEqual([STAGE_WORKER_ORIGIN]); + }); + + it("preflights the live console origin through the deployed edge host", () => { + const req = new Request(`https://${edgeHost("stage")}/v1/auth/login/start`, { + method: "OPTIONS", + headers: { origin: consoleOrigin("stage") }, + }); + const res = handlePreflight(req, stageEnv); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBe(consoleOrigin("stage")); + expect(res!.headers.get("access-control-allow-credentials")).toBe("true"); + }); + + it("answers the live console origin with CORS headers on a real response", () => { + const req = new Request(`https://${edgeHost("stage")}/v1/auth/login/start`, { + method: "POST", + headers: { origin: consoleOrigin("stage") }, + }); + const res = applyCorsHeaders(Response.json({ data: {} }), req, stageEnv); + expect(res.headers.get("access-control-allow-origin")).toBe(consoleOrigin("stage")); + }); + }); }); diff --git a/tests/platform-limits/src/console-origin-agreement.test.ts b/tests/platform-limits/src/console-origin-agreement.test.ts new file mode 100644 index 0000000..5615499 --- /dev/null +++ b/tests/platform-limits/src/console-origin-agreement.test.ts @@ -0,0 +1,131 @@ +/** + * The workers.dev subdomain must be ONE value across the repository. + * + * It is the only piece of this product's identity that is an *account* fact: + * every other name (the repo slug, the product name, the worker prefixes) is + * known the moment the repository is created, but the Cloudflare account's + * workers.dev subdomain is only known once the Cloudflare connection is read. + * The bootstrap therefore writes a PLACEHOLDER first and corrects it later, + * and each phase only rewrites the files of the component it is building. + * + * So a component built before the correction keeps the placeholder, and + * nothing fails: both halves typecheck, deploy, and answer /health. What + * breaks is only the cross-origin contract between the console and the + * fleet — and only in a browser: + * + * - `apps/api-edge` (CORS allowlist) — the console's preflight comes back + * without `access-control-allow-origin`, so every call from the console + * fails as "Failed to fetch". The login screen shows it first. + * - `apps/identity-worker` (`OAUTH_ALLOWED_CONSOLE_ORIGINS`) — the open- + * redirect guard refuses the console's own `returnTo`, so OAuth sign-in + * dead-ends after the provider hands the user back. + * + * Both shipped that way on a product born from this baseline (2026-10-26): + * the edge named `test-` while the console was deployed on the real + * account subdomain. The edge now reads the subdomain off its own hostname + * too (`apps/api-edge/src/app-config.ts`), which repairs CORS whatever the + * bundle says — but the identity-worker's allowlist is an open-redirect + * guard, deliberately literal, and nothing but agreement can save it. + * + * Hence this guard: if two places name different subdomains, one of them is + * a leftover placeholder, and a browser-only failure is already in the + * repository. Setting the subdomain is one substitution across every file + * (`node tooling/rebrand/rebrand.mjs --values `), never one component. + */ + +import { readFileSync } from "node:fs"; +import { execFileSync } from "node:child_process"; +import { join } from "node:path"; + +const REPO_ROOT = join(process.cwd(), "..", ".."); + +// `..workers.dev`, the only shape workers.dev serves. +const WORKERS_DEV_RE = /\b([a-z0-9][a-z0-9-]*)\.([a-z0-9][a-z0-9-]*)\.workers\.dev\b/g; + +// Subdomains of OTHER people's accounts, which this product only calls. +const FOREIGN_SUBDOMAINS = new Set([ + "oruncloud", // the Orun control plane (intent.yaml `backendUrl`) +]); + +// Where this product's own identity is written: the component trees and the +// deployment intent, runbooks included — a runbook naming a host nobody can +// reach is the same leftover. The top-level `docs/` and `specs/` narrate the +// BASELINE and are left out; they are not this product's configuration. +const SEARCH_PATHS = [ + "apps", + "packages", + "infra", + "tooling", + "intent.yaml", + "blueprint.yaml", +]; + +function trackedFiles(): string[] { + return execFileSync("git", ["ls-files", "-z", "--", ...SEARCH_PATHS], { + cwd: REPO_ROOT, + encoding: "utf-8", + maxBuffer: 32 * 1024 * 1024, + }) + .split("\0") + .filter(Boolean); +} + +interface Mention { + file: string; + subdomain: string; + host: string; +} + +function mentions(): Mention[] { + const found: Mention[] = []; + for (const file of trackedFiles()) { + let contents: string; + try { + contents = readFileSync(join(REPO_ROOT, file), "utf-8"); + } catch { + continue; // a submodule or a symlink to nowhere; nothing to read + } + for (const match of contents.matchAll(WORKERS_DEV_RE)) { + const subdomain = match[2]!; + if (FOREIGN_SUBDOMAINS.has(subdomain)) continue; + found.push({ file, subdomain, host: match[0] }); + } + } + return found; +} + +describe("workers.dev subdomain agreement", () => { + const found = mentions(); + + it("is named somewhere, so this guard is guarding something", () => { + expect(found.length).toBeGreaterThan(0); + }); + + it("is the same subdomain everywhere it is named", () => { + const bySubdomain = new Map(); + for (const { file, subdomain } of found) { + const files = bySubdomain.get(subdomain) ?? []; + if (!files.includes(file)) files.push(file); + bySubdomain.set(subdomain, files); + } + + if (bySubdomain.size > 1) { + const report = [...bySubdomain.entries()] + .sort((a, b) => b[1].length - a[1].length) + .map(([subdomain, files]) => + ` ${subdomain}.workers.dev\n${files.map((f) => ` ${f}`).join("\n")}`, + ) + .join("\n"); + throw new Error( + "This repository names more than one workers.dev subdomain. One of them is a " + + "leftover bootstrap placeholder, and the console cannot reach the fleet it " + + "names: CORS and the OAuth return-to guard both compare origins literally.\n" + + "Set the subdomain across EVERY file at once — " + + "`node tooling/rebrand/rebrand.mjs --values ` — not per component.\n\n" + + report, + ); + } + + expect([...bySubdomain.keys()]).toHaveLength(1); + }); +});