Skip to content

Dispatch & published apps ​

Path: services/dispatch
Role: Route traffic to Workers-for-Platforms user Workers; mint per-request identity; realtime; AppRpc.

Responsibilities ​

  • Host / path routing to published scripts in a dispatch namespace
  • Dual-accept auth patterns (app-scoped capability tokens, internal guard, public policy cache — verify current code)
  • Strip inbound cookies / guard / spoofed context; mint fresh x-brilliant-context
  • RealtimeDO — per-app collection invalidation over WebSocket
  • AppRpc — platform → published app RPC for workflows (see docs/wiki/modules/template-apprpc.md)
  • PlatformData entrypoint — platform SQL hop to per-workspace data workers (not public /a/ paths). Replaced on main by #516 (not deployed yet): a stateless PlatformData gateway (src/access/gateway.ts) admits every request against current control-plane permissions and routes to one collection DO per collection (src/do/collection.ts). See Permissions & app data.

App enablement & tombstones (APP_POLICIES) ​

Control plane (writer) and dispatch (reader) share one KV key contract for kill switches and deleted apps. Keys live in the APP_POLICIES binding.

SignalKey helper (@brilliant/capabilities)FormatMeaning
Disabled (kill switch)disabledAppKey(name)app:<name.toLowerCase()>:disabledKey present (any value) → app must not serve (403 App Disabled). Absent → enabled.
Deleted (tombstone)deletedAppKey(name)app:<name.toLowerCase()>:deletedKey present → treat as deleted (edge may keep the script for minutes after delete).

Rules that must stay true:

  • Always lowercase the app id / script name in the key. Writers and readers go only through disabledAppKey / deletedAppKey (packages/capabilities/src/app-policy-keys.ts). Do not inline app:${id}:disabled — mixed-case ids used to keep serving after a kill switch (#224).
  • Presence is the signal; do not interpret the JSON/string value for enablement.
  • Control plane writes both the app id and script name when they differ (disable, clear, tombstone). Dispatch’s isAppEnabled / isAppDeleted use the same helpers (services/dispatch/src/policy.ts).
  • Enablement fails open if APP_POLICIES is missing or the KV read throws (see contract enablement-fails-open in code).

Landed in #250 (merged; closes #224, #219).

Security notes ​

  • Generated apps decode context JWTs without verifying them, trusting that dispatch/conductor are sole ingress. Exposing a user Worker directly would break that assumption.
  • Platform (not the model-written app) is the enforcement boundary (formerly stated in root CONTRACTS, removed in #592).
  • Historical gaps (policy not consulted at edge, enforcement in wrong bundle layer) are documented in ARCHITECTURE / GOTCHAS — confirm current behaviour in code before writing runbooks.

Template demos (#358, merged with #345) ​

Dispatch serves 30-minute template demos on demo.<studio domain>/<versionId>/ (side envs: /demo/<versionId>/). It turns a version-bound demo JWT into an HttpOnly path-scoped cookie, injects synthetic admin context + countdown / Install banner, loads tpl-<versionId> from the demos WFP namespace, and forwards only x-brilliant-demo-token to the demo script. Published /a/ paths never load the demo module.

Full design (token claims, demo-data DO, Turnstile, rollout): Template demos.

Published apps zone (#412, merged) ​

Landed in #412 (merged 2026-10-04 by yoni-monday; closes #407; part of #305). Pulumi routes published-app traffic on a dedicated zone, not a wildcard under studio/site:

EnvZoneRoute
Stagingbrilliant-app.rocks*.brilliant-app.rocks/* → brilliant-dispatch
Prodbrilliant-app.ai*.brilliant-app.ai/* → brilliant-dispatch

Security rationale and Pulumi pieces (originless wildcard DNS, origins.apps, isolation contract): Hosting — Published apps zone.

Host mode: <script>.<apps-domain> (#413, merged) ​

Landed in #413 (merged 2026-10-04 by yoni-monday; part of #408 — issue stays open until staging checks; part of #305). Needs #412 (merged) infra apply first — without origins.apps, APPS_DOMAIN stays unset and behaviour is unchanged.

Symptom it fixes: every published app is served from one shared origin (brilliant-dispatch.<account>.workers.dev/a/<script>/), so any app can read another app’s cookies, localStorage, and service worker. With APPS_DOMAIN set, each app gets its own subdomain of the apps domain.

ModeWhenPublished URL shape
HostAPPS_DOMAIN set (from origins.apps, https:// stripped)https://<script>.<apps-domain>/a/<script>/
Path (unchanged)Side envs, or APPS_DOMAIN unsetShared dispatch host + /a/<script>/…

Dispatch behaviour (when APPS_DOMAIN is set) ​

ConcernRule
Host resolution<label>.<APPS_DOMAIN> resolves to that app. Apex, reserved labels, nested labels (a.b.<apps>), and lookalikes (x.<apps>.evil.com, x.not<apps>) are refused. Old brilliant.lighting / generic 3-label fallbacks are gone.
Shared-host redirectPage navigation or iframe to /a/<script>/… on a path-mode host (shared workers.dev or apps apex) → 308 to https://<script>.<apps>/a/<script>/… (query kept). Fetches, XHR, and WebSocket upgrades on the shared host still serve. Invalid host-label ids → 404.
Platform domainsPLATFORM_DOMAINS = comma-separated studio + site hostnames. Host equals or under one → 421 for every path (before routing; match on a dot boundary).
CookiesApp cookies from dispatch are host-only (no Domain attribute) — guest set/clear, token-exchange redirect, sign-in redirect.

Control plane / SPA (same PR) ​

PieceBehaviour
Published urlhttps://<script>.<APPS_DOMAIN>/a/<script>/ when set (publish, rollback, MCP publish, admin rollback via src/lib/app-url.ts)
isValidAppReturnToOnly that app’s id or script as one label under APPS_DOMAIN; path mode only on DISPATCH_HOST; since #1015 https only, except http on localhost, 127.0.0.1 and *.localhost
SPA live URLgetLiveAppUrl / realtime prefer VITE_LIVE_APP_DOMAIN (from rendered control-plane vars); else dispatch URL; no hard-coded brilliant.lighting
RenderAPPS_DOMAIN for dispatch + control plane from origins.apps; PLATFORM_DOMAINS + CONTROL_PLANE_URL (from origins.studio) for dispatch

Contracts added: platform-domains-never-serve-apps, shared-host-never-serves-app-documents, app-cookies-are-host-only, app-return-to-is-own-host, apps-domain-only-from-origins-apps.

Not verified on real staging yet (code on main; needs #412 infra apply so origins.apps exists): host mode load on <script>.brilliant-app.rocks, old-link 308, app sign-in round-trip, localStorage isolation between two apps. Scripts that send Accept: text/html or Sec-Fetch-Dest: document to ${dispatchUrl}/a/<id>/ will see a 308 once host mode is live.

No control-plane origin guess (#447, open) ​

Open #447 (closes #443): dispatch does not fall back to brilliant.lighting or retired monday-vibe-stg studio hosts. Missing CONTROL_PLANE_URL fails (contract control-plane-origin-never-guessed). Dispatch still derives brilliant-control-plane[-<env>] from its own workers.dev host. The 421 guard for preview.brilliant.lighting (and contract preview-host-not-dispatch-404) is deleted — that host is in the dead zone.

Host-mode apps-domain rules above already refuse old brilliant.lighting / generic 3-label fallbacks (#413). Full table: Hosting — no lighting fallbacks.

Public host at /: <host-label>.<apps-domain>/ (#994, merged) ​

PR #994 "Serve published apps at a public host and at /" (opened 2026-10-16 22:36 IDT by yoni-monday, branch friendly-app-hosts; merged 2026-10-17 09:32 IDT by yoni-monday, merge cd675e63, final head 3216707c) is the next step after host mode (#413). On an env with APPS_DOMAIN (staging and prod), a publish is built with base / and served at https://<host-label>.<apps-domain>/, for example https://notes.brilliant-app.rocks/. The Worker script name stays internal.

PieceBehaviour with #994
Host labelNew column apps.host_label (migration 0054_app_host_label, unique index apps_host_label_unique), derived from the app's display name: lowercase, hyphens, max 48 chars before a suffix. Claimed inside the create transaction under a Postgres advisory lock, checked against every tenant's host labels and script names. A collision takes the next suffix (notes-2, notes-3, … up to 50 tries, then a random suffix) instead of failing the create or overwriting another app's dispatch record. Reserved platform labels and UUID-shaped labels (which would collide with another app's app:<id> policy key) are skipped. An existing app with no label claims one on its first root publish.
Root flagNew column apps.serves_at_root (default false). The control plane sets it from the conductor's report that the build used base /, not from the request. A retried publish keeps the label it already claimed, so the URL does not move.
Policy recordAppPolicyRecord gains optional hostLabel and servesAtRoot. Once an app serves at root, the policy (and icon) KV record is also written under the host label, so <host-label>.<apps-domain> resolves.
DispatchFor a root app in host mode, /a/<name>/foo and /foo are both forwarded to the Worker as /foo. A page navigation on the old <script> host or under /a/<name>/ gets a 308 to https://<host-label>.<apps-domain>/<path> (query kept); fetches, XHR and WebSockets are forwarded without a redirect. Apps whose record has no servesAtRoot still get the prefixed /a/<script>/… forward.
Already-live appsKeep https://<script>.<apps-domain>/a/<script>/ until their next publish. After that republish, the old URL redirects to the public host.
RollbackOn an apps-domain env, rollback rebuilds at / from the workspace app list's publish_base, even when the request body omits base_path, so a rollback cannot put the prefix back under a root Worker.
Side envsNo apps domain, so apps stay at /a/<script>/ and never set the flag.
SuspensionDispatch's publishedAppEnabled (src/policy.ts) checks the disabled flag under the request host and the app id and script name from the policy record, so a legacy app suspended under its id or script name stays 403 App Disabled after it claims a public host.
Sign-in return-toValidated against the app's script host and, once it has one, its public host label, on APPS_DOMAIN only.

Deploy order: dispatch, then the control plane, then the conductor. The conductor builds at / only when asked (base_path: "/"). Studio publish sends it; an agent publish reads publish_base: "/" from GET /internal/workspaces/:id/apps instead. See Conductor — root publish base (#994) and Control plane — public host label (#994).

Test plan in the PR (unchecked at merge): publish a new app on staging and open https://<name>.brilliant-app.rocks/; confirm an app not yet republished still loads at its old /a/<script>/ URL; republish it and confirm the old URL redirects; create two same-named apps in different tenants and confirm the second is <name>-2; roll back a root-published app and confirm assets load at /.

Staging e2e follow-up: #994 turned the staging deploy e2e red, because step 4 only accepted /a/<script>/. PR #1006 (merged 2026-10-17 14:17 IDT) makes it accept https://<label>.<apps-domain>/ and open that URL. See Verify & ship: staging e2e accepts a root publish URL (#1006).

App icons and favicons ​

Landed in PR #781 (merged 2026-10-11). Every app gets an automatic icon drawn from its own design style.

  • Rendering: packages/app-icon/ (renderAppIcon) draws a deterministic marble SVG with a lowercase Bowlby One initial. Look knobs: the STONE table and blur in packages/app-icon/src/render.ts.
  • Capture: at turn end the conductor reads :root tokens from apps/<dir>/src/styles.css, derives a palette, and POSTs /internal/workspaces/:id/apps/:appId/icon-colors only when it changed (never starts a container; failures are logged skips).
  • Storage: the control plane sanitizes colors (max 4, 64 chars), stores them in nullable apps.icon_colors (migration 0042), and overwrites the KV record app:<id>:icon {name, iconColors}. The access record app:<id> is untouched and still written only by ingest inside the publish fence, so icons can never change who may open an app. Retirement deletes icon keys.
  • Serving: dispatch serves GET /__icon.svg (reads only app:<id>:icon, same admission as the app's pages, strict CSP, 5 min browser cache), and injects <link rel="icon"> before </head> on any successful HTML GET that has no icon link of its own.
  • Studio: listApps returns iconColors; <AppIcon> renders as a data-URI <img> in sidebar rows (status dot on the corner), Browse, launcher cards, recents, and hover cards.
  • The agent prompt says not to add a favicon unless asked. Follow-ups: #767 (PNG icons for iOS/PWA), #768 (draft-preview favicon), #769 (header/app switcher/non-Latin/dark).

App login return_to must be https (#1015, merged) ​

PR #1015 (merged 2026-10-18 17:23 IDT by yoni-monday, merge 49dddd9e) tightens isValidAppReturnTo (apps/control-plane/src/auth/app-return.ts). The app-login callback appends a 7-day brilliant_token to return_to, so plain http would leak it. Now http is accepted only for localhost, 127.0.0.1 and *.localhost. Every other host, including the public app host (<app>.<APPS_DOMAIN>), the dispatch host and *.dispatch.local, must be https, or the login answers invalid_return_to. The host and path rules are unchanged (the app's own one-label host, or /a/<id>/ on the dispatch host).

Edge cases the tests pin (apps/control-plane/test/auth-redirect.test.ts): lookalikes like localhost.evil.com and 127.0.0.1.evil.com are not loopback; trailing-dot hosts (localhost.) and IPv6 [::1] are rejected; http://localhost@evil.com/ is evil.com and rejected, while http://evil.com@localhost/a/<id>/ is localhost with the app path and stays allowed. The same PR makes the apps zone HTTPS-only with HSTS: Hosting & Pulumi — apps zone HSTS (#1015).