Skip to content
MSO CloudDocumentation

ADR 0016 — MSO Cloud: per-org subdomains, white-label domains, and the product rename

On this page
  • Status: Accepted (2026-07-21)
  • Deciders: Operator (Tien Le) + platform architecture
  • Relates to: ADR 0007 (demo posture), §66 (RLS context), §7 (route security), docs/SECURITY.md (trusted proxy)

Context#

The product is renamed UCIP → MSO Cloud and moves to the domain msocloud.net (Cloudflare-managed zone). Each organization gains a tenant address:

  • <subdomain>.msocloud.net — chosen at org creation, changeable only by super admin.
  • Later, a white-label domain owned by the customer (e.g. insights.customer.vn), CNAME'd to the org's <subdomain>.msocloud.net, from which their users sign in.

Production ingress is an externally-managed Traefik on the balancer Docker network (not in this repo); the app is wired to it purely via container labels. Today the stack is single-host (Host(${DOMAIN}), one cert resolver myresolver), org identity is purely cookie/session-based (yng_active_org + session callback), and no host-header→org resolution exists anywhere.

Decision#

1. Data model

  • organizations.subdomain — varchar(63), nullable, UNIQUE. Validation lives in ONE shared module (@yng/schema export tenant-domain.ts): RFC-1035 label regex ^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$ (1-63 chars, as RFC-1035 allows — the original {1,61} middle run refused every two-character label), plus a reserved list (www, api, app, admin, auth, mail, cdn, static, assets, status, docs, help, blog, dev, staging, demo, sso, login, mso, cloud, …).
  • New table org_domains (white-label): id, org_id FK cascade, domain text UNIQUE (lowercase, punycode-normalized), status (pending_dns → verifying → active | error), verification_token, verified_at, last_checked_at, last_error, is_sample, timestamps.
  • RLS: organizations stays outside RLS (existing control-plane posture); writes are gated app-layer by superAdminProcedure. org_domains gets a standard org-scoped policy. Host lookup (which runs with NO org context, as yng_app) goes through a SECURITY DEFINER locator — same pattern as public-share-locator.sql: app_locate_tenant_host(host) returns (org_id, kind) for an active subdomain or active custom domain; app_list_active_custom_domains() feeds the Traefik endpoint.

2. Host → tenant resolution (app layer)

  • proxy.ts keeps JWT/session parsing lightweight. A request-memoized resolver getRequestTenant() (apps/web/src/server/tenant-host.ts) reads x-forwarded-host/host, normalizes, and classifies:
    • platform host (msocloud.net apex, www., the legacy ${DOMAIN}, NEXTAUTH_URL host) → current behavior, unchanged;
    • <sub>.${TENANT_BASE_DOMAIN} → org by organizations.subdomain (active orgs only);
    • anything else → active org_domains row via the locator;
    • unknown host → tenant-not-found page (404), no data.
  • Amendment 2026-10-19: Next.js 16 proxy runs in Node.js and requires absolute redirect Locations. For a signed-out protected request on a custom domain only, server/sign-in-redirect.ts resolves ownership through the existing tenant-host locator before emitting an absolute same-host sign-in URL. Unknown domains return 404 and lookup failures return 503, without a redirect or protected response. Platform/subdomain redirects and authenticated requests add no custom-domain query. No process-wide domain cache is introduced; revocation follows the locator's current answer. Relative callback paths remain sanitized and sessions remain host-only.
  • Org pinning: on a tenant host the effective org IS the host's org. Enforced at the consumption layer, not the cookie: tRPC createContext and the dashboard/admin RSC layouts override activeOrgId with the host org after a membership check (super admin exempt); non-members get "no access to this workspace". POST /api/auth/switch-org is rejected on tenant hosts — the domain fixes the org.
  • Cookies stay host-only (NextAuth default): sessions on a.msocloud.net never leak to b.msocloud.net or to white-label hosts. This is the isolation property, not a bug.
  • TENANT_BASE_DOMAIN env (prod msocloud.net, opt-in local localhost so acme.localhost:3000 works in a browser with zero DNS setup).
  • Local/dev kill-switch: TENANT_HOSTS_DISABLED (same posture as TOKEN_REFRESH_DISABLED). Explicit "true"/"false" wins; otherwise disabled whenever NODE_ENV !== 'production'. When disabled, getRequestTenant() always returns platform, resolveOrgWorkspaceUrl() returns null (no post-login / dashboard bounce to a subdomain), and Edge sign-in/admin helpers stay on NEXTAUTH_URL. Day-to-day localhost:3000 feature work never touches multi-host routing; set TENANT_HOSTS_DISABLED=false only to exercise ADR 0016 locally.

3. Auth on tenant hosts

  • NextAuth v5 trustHost: true (prod compose already sets AUTH_TRUST_HOST=true).
  • Base URLs become host-derived. Magic-link emails, OAuth callbacks and PDF export origins currently hardcode NEXTAUTH_URL; a helper (requestBaseUrl()) prefers the validated request host (platform, *.${TENANT_BASE_DOMAIN}, or an active custom domain) and falls back to NEXTAUTH_URL. Never trust an arbitrary Host header for URL construction — validate against the tenant allowlist first.
  • WebAuthn: RP-ID stays host-derived (passkey.ts already reads x-forwarded-host); the prod exact-match guard is relaxed to an allowlist (legacy ${DOMAIN}, *.${TENANT_BASE_DOMAIN}, active custom domains). Passkeys are inherently per-RP: a passkey enrolled on one tenant host only works there — documented, accepted.
  • Amendment 2026-09-04: switching org to a workspace host hands the session over through the magic-link token; a signed-in user never sees the sign-in form on the target host.
  • Amendment 2026-10-31: a workspace SUBDOMAIN sign-in page (/auth/signin without sso/error) redirects once to <platform>/api/auth/sso?returnHost=…; if the platform host holds a session for a member or super admin, it returns the same single-use handoff token (audit auth.sso.handoff), else the form with ?sso=0. Explicit sign-out lands on /auth/signin?sso=0 so it is not undone. Custom white-label domains are never handed a session. Cookies stay host-only. Why: back/typed navigation from the platform host to a workspace host read as "logged out".
  • Amendment 2026-11-03 (§191): one browser holds one identity on every host. Host-only sessions let one browser be user A on the platform host and user B on workspace hosts at the same time; the SSO handoff only ran where a host had NO session, so a stale session for B survived and B's identity changed customer data. Decision:
    • Identity anchor. The base-domain cookie msocloud_platform_session (formerly the constant 1 hint; Domain=.<TENANT_BASE_DOMAIN>, Secure, HttpOnly, SameSite=Lax, 14 d, re-issued after 24 h) now carries v1.<iat>.<tag>.<seal>: tag = HMAC(k1, userId), seal = HMAC(k2, "v1.<iat>.<tag>"), both keys derived from SESSION_SECRET. No id, email or sid in clear. Every sign-in sets it (the Auth.js jwt callback covers password, magic link, passkey and LDAP; OIDC, Google, SSO and org-switch handoffs all consume a magic-link token; /api/auth/idp-handoff sets it explicitly). Sign-out (events.signOut) clears it.
    • Enforcement. On the platform host and <slug>.<base>: anchor = session user → OK; anchor names another user (or fails its seal) → the session callback revokes the sid and returns no user, and a page request goes through /api/auth/reconcile, which deletes the host's session cookie and, on a workspace subdomain, starts the SSO handoff from the platform host (which mints the anchor's user and returns to the same path); on the platform host it shows the sign-in form. Anchor absent (signed out elsewhere) → revoke and the form with sso=0. API/RSC fetches get 401 until the next page request reconciles. A reconcile that already handed off in the last 60 s (msocloud_anchor_hop) ends on the form: at most one handoff, two hops.
    • Deploy bridge (adoption, never a mass sign-out). A token claims anc: 1 only when its sign-in wrote the anchor. A session without anc, or any browser holding the legacy value 1, is ADOPTED: the platform host re-issues the anchor from its own session; a workspace host asks the platform host once (/api/auth/sso?probe=1&tag=<user tag>) without dropping its session. A different user there replaces it (the incident case); the same user or nobody returns to /api/auth/reconcile, which writes the anchor from the local session. Only an anc session whose anchor is absent reads as "signed out elsewhere". A sign-in over another user's live session revokes that session's sid.
    • Custom domains (exception). A white-label domain cannot read or write a .msocloud.net cookie, so its session is not checked against the anchor and a sign-out there does not clear it. It is only entered from the platform host through the org-switch handoff with the current user; the magic-link consume replaces whatever session that host held. A switch from a custom domain into an anchored host re-anchors the browser to that user (the latest sign-in wins). A cross-site entry (an email link) to a contradicted workspace ends on the form with sso=tried, because /api/auth/sso refuses cross-site starts.
    • IdP. /api/internal/idp/session answers 401 when the anchor contradicts the session or an anc session has no anchor, so a satellite app never sees an identity the browser has dropped; a pre-anchor session is answered as before. /sid and /claims never read it.
    • Rollback. IDENTITY_ANCHOR_ENFORCE=0 keeps writing and adopting anchors but never revokes or redirects; it logs identity_anchor_would_revoke {hostKind, state} instead. The reconcile route is limited to 600 requests a minute per client IP; over it, a session the anchor does not contradict is kept and anchored.

4. Edge / TLS / DNS

  • Cloudflare zone msocloud.net: ONE wildcard record *.msocloud.net + apex/www, DNS-only (grey cloud), pointing at the production LB. Grey-cloud is deliberate: customer CNAMEs (insights.customer.vn → sub.msocloud.net) would break against a proxied (orange) target for a non-Enterprise plan, and Traefik must terminate TLS to serve white-label certs. (Cloudflare-for-SaaS is the future upgrade path if edge WAF/CDN per custom hostname is ever needed.)
  • Subdomain certs: one wildcard certificate *.msocloud.net + msocloud.net issued by Traefik via DNS-01 (Cloudflare API token scoped to the zone). No per-org DNS or cert work at org creation — creating an org is a pure DB write.
  • White-label certs: Traefik HTTP provider polls a token-protected app endpoint (GET /api/edge/traefik-dynamic, bearer TRAEFIK_CONFIG_TOKEN, no org data, only active custom domains) that renders dynamic config: one router per active custom domain (Host(...), certresolver=myresolver HTTP-01) → the existing web service. Adding a verified domain therefore auto-provisions routing + cert with zero manual Traefik edits; the app is the single source of truth.
  • Cloudflare API client (scripts/infra/ensure-cloudflare-dns.ts + worker job): env-gated (CLOUDFLARE_API_TOKEN, CLOUDFLARE_ZONE_ID, CLOUDFLARE_DNS_MODE= wildcard|per-record|off). Default mode wildcard = the script only ensures the wildcard/apex records exist (idempotent). per-record mode additionally upserts/deletes explicit <sub> records on subdomain change — executed via the durable job outbox (§66a), never inside an RLS transaction, never blocking the admin mutation.
  • Domain verification: ownership = TXT _msocloud-verify.<domain> containing the verification_token; reachability = CNAME/A resolves to <sub>.msocloud.net or the LB. Checked from a worker job (external I/O outside RLS scope), status transitions recorded on org_domains, re-checked periodically while pending_dns/verifying.

5. Super-admin surface

  • Org drawer (/admin/orgs): subdomain field on create + edit (suggested from slug), white-label domain panel (add → shows required DNS records → verify → active / error with reason → remove). All mutations superAdminProcedure, rate-limited, audit-logged (admin.organization.domain.*), with diffBefore/diffAfter.
  • Org list shows the tenant URL; org admins can SEE their domain (read-only) in org settings but cannot change it.

6. Product rename UCIP → MSO Cloud

Displayed name has three sources; all move to "MSO Cloud":

  1. site_settings.site_name column default + the scattered fallbacks (site-identity.ts DEFAULT_SITE_IDENTITY, routers/site-identity.ts, site-identity-form.tsx, sidebar.tsx fallback, global-error.tsx).
  2. i18n values (common.appName, landing hero/loop/pillars/diagrams, signin tagline, permissions preset title, siteIdentity help) in both vi and en — copy written around the MSO framing (Marketing Systems OS), per §38/§62 no-slop rules.
  3. Email/auth strings: magic-link subject, WebAuthn RP_NAME, docs footer. TOTP issuer changes affect only NEW enrollments (accepted).

Never renamed: @yng/* package names, root package/dir name, org slugs (ucip-mso-demo), health service id yng-ucip-web, MCP server name yng-ucip, container names, DB identifiers, plugin ids, sample-data fixtures asserted by e2e. Docs corpus (154 files) is a separate later pass; docs/MSO-UCIP-Roadmap/ path is build-script-referenced and stays.

Consequences#

  • Org creation stays instant (wildcard DNS + wildcard cert = no external calls).
  • The app becomes multi-host: every URL builder must go through requestBaseUrl(); a future audit can ratchet direct NEXTAUTH_URL reads.
  • start-prod.sh topology guards (WEBAUTHN exact-match) are relaxed to allowlist-aware; verify-prod-compose.mjs learns the new labels.
  • Legacy ucip-blo.younetco.com keeps working as a platform host until BLO is migrated to blueocean.msocloud.net (operator-scheduled; not part of this change).
  • Traefik host config gains two things (documented in docs/runbooks/tenant-domains.md): the DNS-01 resolver for the wildcard + the HTTP provider pointing at the app endpoint. The compose template adds a tenant router pair driven by the REQUIRED env TRAEFIK_HOST_RULE — existing hosts must set it in .env.prod on their next redeploy (fail-loud at docker compose config).