Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
103 changes: 100 additions & 3 deletions apps/api-edge/src/app-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,111 @@
// 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";

/** 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<keyof ConsoleIdentity, keyof ConsoleIdentityEnv> = {
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 `<worker>.<subdomain>.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;
}
41 changes: 25 additions & 16 deletions apps/api-edge/src/cors.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
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+)?$/;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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 });
}

Expand All @@ -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!);
Expand Down
6 changes: 6 additions & 0 deletions apps/api-edge/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions apps/api-edge/wrangler.template.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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": {
Expand All @@ -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": [
Expand Down Expand Up @@ -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": [
Expand Down
27 changes: 27 additions & 0 deletions specs/components/01-edge-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading