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/schemaexporttenant-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_idFK cascade,domaintext UNIQUE (lowercase, punycode-normalized),status(pending_dns → verifying → active | error),verification_token,verified_at,last_checked_at,last_error,is_sample, timestamps. - RLS:
organizationsstays outside RLS (existing control-plane posture); writes are gated app-layer bysuperAdminProcedure.org_domainsgets a standard org-scoped policy. Host lookup (which runs with NO org context, asyng_app) goes through a SECURITY DEFINER locator — same pattern aspublic-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.tskeeps JWT/session parsing lightweight. A request-memoized resolvergetRequestTenant()(apps/web/src/server/tenant-host.ts) readsx-forwarded-host/host, normalizes, and classifies:- platform host (
msocloud.netapex,www., the legacy${DOMAIN},NEXTAUTH_URLhost) → current behavior, unchanged; <sub>.${TENANT_BASE_DOMAIN}→ org byorganizations.subdomain(active orgs only);- anything else → active
org_domainsrow via the locator; - unknown host → tenant-not-found page (404), no data.
- platform host (
- 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.tsresolves 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
createContextand the dashboard/admin RSC layouts overrideactiveOrgIdwith the host org after a membership check (super admin exempt); non-members get "no access to this workspace".POST /api/auth/switch-orgis rejected on tenant hosts — the domain fixes the org. - Cookies stay host-only (NextAuth default): sessions on
a.msocloud.netnever leak tob.msocloud.netor to white-label hosts. This is the isolation property, not a bug. TENANT_BASE_DOMAINenv (prodmsocloud.net, opt-in locallocalhostsoacme.localhost:3000works in a browser with zero DNS setup).- Local/dev kill-switch:
TENANT_HOSTS_DISABLED(same posture asTOKEN_REFRESH_DISABLED). Explicit"true"/"false"wins; otherwise disabled wheneverNODE_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 onNEXTAUTH_URL. Day-to-daylocalhost:3000feature work never touches multi-host routing; setTENANT_HOSTS_DISABLED=falseonly to exercise ADR 0016 locally.
3. Auth on tenant hosts
- NextAuth v5
trustHost: true(prod compose already setsAUTH_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 toNEXTAUTH_URL. Never trust an arbitrary Host header for URL construction — validate against the tenant allowlist first. - WebAuthn: RP-ID stays host-derived (
passkey.tsalready readsx-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/signinwithoutsso/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 (auditauth.sso.handoff), else the form with?sso=0. Explicit sign-out lands on/auth/signin?sso=0so 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 constant1hint;Domain=.<TENANT_BASE_DOMAIN>,Secure,HttpOnly,SameSite=Lax, 14 d, re-issued after 24 h) now carriesv1.<iat>.<tag>.<seal>:tag = HMAC(k1, userId),seal = HMAC(k2, "v1.<iat>.<tag>"), both keys derived fromSESSION_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-handoffsets 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 withsso=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: 1only when its sign-in wrote the anchor. A session withoutanc, or any browser holding the legacy value1, 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 anancsession 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.netcookie, 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 withsso=tried, because/api/auth/ssorefuses cross-site starts. - IdP.
/api/internal/idp/sessionanswers 401 when the anchor contradicts the session or anancsession has no anchor, so a satellite app never sees an identity the browser has dropped; a pre-anchor session is answered as before./sidand/claimsnever read it. - Rollback.
IDENTITY_ANCHOR_ENFORCE=0keeps writing and adopting anchors but never revokes or redirects; it logsidentity_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.
- Identity anchor. The base-domain cookie
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.netissued 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, bearerTRAEFIK_CONFIG_TOKEN, no org data, only active custom domains) that renders dynamic config: one router per active custom domain (Host(...),certresolver=myresolverHTTP-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 modewildcard= the script only ensures the wildcard/apex records exist (idempotent).per-recordmode 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 theverification_token; reachability = CNAME/A resolves to<sub>.msocloud.netor the LB. Checked from a worker job (external I/O outside RLS scope), status transitions recorded onorg_domains, re-checked periodically whilepending_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 mutationssuperAdminProcedure, rate-limited, audit-logged (admin.organization.domain.*), withdiffBefore/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":
site_settings.site_namecolumn default + the scattered fallbacks (site-identity.tsDEFAULT_SITE_IDENTITY,routers/site-identity.ts,site-identity-form.tsx,sidebar.tsxfallback,global-error.tsx).- i18n values (
common.appName, landing hero/loop/pillars/diagrams, signin tagline, permissions preset title, siteIdentity help) in bothvianden— copy written around the MSO framing (Marketing Systems OS), per §38/§62 no-slop rules. - 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 directNEXTAUTH_URLreads. start-prod.shtopology guards (WEBAUTHN exact-match) are relaxed to allowlist-aware;verify-prod-compose.mjslearns the new labels.- Legacy
ucip-blo.younetco.comkeeps working as a platform host until BLO is migrated toblueocean.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 envTRAEFIK_HOST_RULE— existing hosts must set it in.env.prodon their next redeploy (fail-loud atdocker compose config).