Skip to content
MSO CloudDocumentation

Tenant domains runbook (ADR 0016 — MSO Cloud)

On this page

Operator reference for org subdomains (<sub>.msocloud.net) and customer white-label domains (insights.customer.vn). Design: ADR 0016. Host classification: apps/web/src/server/tenant-host.ts. WebAuthn per-host RP: apps/web/src/auth/passkey.ts.


Local development (default: off)#

Multi-host routing is disabled outside production by default (TENANT_HOSTS_DISABLED, same kill-switch pattern as TOKEN_REFRESH_DISABLED). Plain http://localhost:3000 keeps cookie/session org selection; post-login and dashboard never redirect to *.localhost.

./scripts/start-dev.sh writes both kill-switches into .env when missing (never overwrites an explicit false), and fails boot if a signed-out GET / redirects onto *.localhost. ./scripts/stop-dev.sh is unchanged — volumes preserved by default.

Goal Env
Day-to-day feature work on localhost Leave unset (or TENANT_HOSTS_DISABLED=true) — start-dev.sh ensures this
Exercise <sub>.localhost:3000 locally TENANT_HOSTS_DISABLED=false (+ optional TENANT_BASE_DOMAIN=localhost)
Emergency single-host rollback in prod TENANT_HOSTS_DISABLED=true (then redeploy)

Admin can still assign org subdomains in /admin/orgs while the kill-switch is on — that only writes organizations.subdomain; Host → org pinning stays inert until the switch is off.


(a) One-time Cloudflare setup#

  1. Create (or reuse) the msocloud.net zone in Cloudflare, DNS-only plan is fine.

  2. Mint an API token: Zone → DNS → Edit, scoped to that one zone only. Never a Global API Key.

  3. Set in .env.prod (see the "MSO Cloud tenant domains" section of .env.prod.example):

    TENANT_BASE_DOMAIN=msocloud.net
    CLOUDFLARE_API_TOKEN=<the token>
    CLOUDFLARE_ZONE_ID=<zone id, from the Cloudflare dashboard overview page>
    CLOUDFLARE_ORIGIN_TARGET=<production LB IPv4, or a hostname>
    
  4. Dry-run the ensure script (default; makes no changes):

    pnpm tsx scripts/infra/ensure-cloudflare-dns.ts
    

    Review the printed plan, then apply:

    pnpm tsx scripts/infra/ensure-cloudflare-dns.ts --apply
    

    This ensures exactly 3 records: apex, www, and *.msocloud.net. Existing records keep their current proxy status; new platform records default to proxied. The optional --proxy or --dns-only flags change all three managed records together; do not use blanket --proxy --apply on this production deployment because www must stay DNS-only for large uploads. Use the default preserve mode for routine convergence, and review the per-record plan before --apply. Conflicting flags fail without writing. On a fresh deployment, create the DNS-only www exception explicitly before running the ensure script.

    Before proxying the platform wildcard, review white-label CNAME chains. A customer CNAME to a proxied hostname in another Cloudflare account can produce Error 1014. Use an explicitly DNS-only origin/CNAME target for that path, or onboard the hostname through Cloudflare for SaaS; a certificate for *.msocloud.net does not cover the customer hostname. Preserve the white-label Host route and its own origin certificate. DNS-01 certificate validation is independent of the platform proxy status.

    Production white-label onboarding uses origin.msocloud.net as its stable DNS-only CNAME target. Preserve explicit legacy CNAME targets such as blueocean.msocloud.net and unilever.msocloud.net as DNS-only records: an explicit record takes precedence over the proxied *.msocloud.net wildcard. Neither these origin records nor assets.msocloud.net are managed by this three-record ensure script. assets.msocloud.net is proxied and serves public hashed Next static assets; HTML, login, API and tenant routing stay on each requested hostname.

  5. The token is never logged by the script or printed in its output.

Production proxy policy

Hostname Cloudflare proxy Purpose
msocloud.net Proxied Public apex ingress
*.msocloud.net Proxied New tenant subdomains inherit edge ingress
assets.msocloud.net Proxied Public hashed /_next/static/* assets for all app and white-label pages
www.msocloud.net DNS-only Canonical app/admin host; keeps backup uploads up to 2 GiB off the Cloudflare request-body limit
origin.msocloud.net DNS-only Stable CNAME target for new white-label domains
blueocean.msocloud.net, unilever.msocloud.net DNS-only Explicit legacy white-label CNAME targets; override the proxied wildcard

Cloudflare Free/Pro proxy upload limits are 100 MB per request, so proxying the canonical admin host would reject supported large backup uploads before they reach the app. Static assets still use the proxied assets host when HTML and uploads go directly through www or a DNS-only white-label host. Do not point customer white-label CNAMEs at the proxied wildcard; use origin.msocloud.net and retain each customer hostname's own Traefik route and certificate. See Cloudflare upload limits.

Manual Cloudflare settings (Cloudflare Free dashboard checklist)#

The deployment API token has Zone → DNS → Edit permissions only (never zone settings, cache rules, or SaaS hostnames). Apply these Cloudflare Free dashboard settings once on the msocloud.net zone:

  1. SSL/TLS → Overview: select Full (strict). Origin certificates must remain valid; keep the Traefik DNS-01 resolver and renewal credentials configured. See Full (strict).
  2. Speed → Optimization → Protocol / Network: confirm HTTP/3 (with QUIC) is ON, 0-RTT Connection Resumption is ON, Brotli is ON, and Early Hints is ON (all included on Cloudflare Free).
  3. Caching → Tiered Cache: enable Smart Tiered Cache (free on Cloudflare Free) so APAC/Vietnam PoP misses fill through an upper-tier PoP instead of multiplying origin hits to France.
  4. Scrape Shield → Email Address Obfuscation: turn OFF. Email Obfuscation injects email-decode.min.js, which conflicts with strict nonce CSP and is the only reason responses carry Cache-Control: no-transform.
  5. Caching → Cache Rules:
    • Rule 1 (Static assets): match http.host eq "assets.msocloud.net" and starts_with(http.request.uri.path, "/_next/static/") → Eligible for cache, Respect origin TTL (public, max-age=31536000, immutable).
    • Rule 2 (Optional — Unlocked public shares): match starts_with(http.request.uri.path, "/share/") and not any(http.request.cookies.names[*] contains "yng_share_pw_") and not any(http.request.cookies.names[*] contains "session-token") → Eligible for cache, Respect origin (public, s-maxage=60).
    • Rule 3 (Dynamic bypass): match starts_with(http.request.uri.path, "/api/") or starts_with(http.request.uri.path, "/auth/") or starts_with(http.request.uri.path, "/admin") or starts_with(http.request.uri.path, "/dashboards/") → Bypass cache. Do not use a site-wide Cache Everything rule and never override private or no-store. See Create a cache rule.
  6. Optional free upgrades on Cloudflare Free:
    • Cloudflare for SaaS (up to 100 Custom Hostnames free): point fallback origin to origin.msocloud.net to bring customer white-label domains onto Cloudflare edge without Error 1014.
    • Cloudflare R2 (10 GB/month storage + 0 egress fees free): target store for retiring the single-request 2 GiB backup upload on www.msocloud.net via multipart/presigned upload so www.msocloud.net can later be proxied too.
  7. Post-change verification: verify DNS proxy states (dig +short @1.1.1.1 msocloud.net, probe.msocloud.net, assets.msocloud.net return Cloudflare IPs while www.msocloud.net and origin.msocloud.net return 37.187.147.65), check a hashed asset twice for cf-cache-status: HIT, confirm content-encoding: br and alt-svc: h3 on https://msocloud.net/, and confirm zero Set-Cookie on https://msocloud.net/privacy.

(b) Host Traefik additions#

The externally-managed Traefik instance (not in this repo) needs two static-config additions. On this host Traefik takes them as command flags in /opt/apps/balancer/docker-compose.mso.yml (--certificatesresolvers.cloudflare.*, --providers.http.*), not as a YAML file; the YAML below shows the same settings. Full label wiring for the app side lives in docker-compose.prod.yml.example; this section is what changes on the Traefik host itself.

1. A DNS-01 certificate resolver that can prove the *.msocloud.net wildcard SAN (HTTP-01 cannot issue wildcards):

certificatesResolvers:
  cloudflare:
    acme:
      email: ops@younetgroup.com
      storage: /letsencrypt/acme-cloudflare.json
      dnsChallenge:
        provider: cloudflare
        delayBeforeCheck: 30

The Traefik process needs CF_DNS_API_TOKEN=<a Zone:DNS:Edit token> in its own environment (separate from this app's CLOUDFLARE_API_TOKEN — Traefik talks to Cloudflare directly for the ACME challenge; the app never does).

2. An HTTP provider polling this app's dynamic-config endpoint for white-label domains:

providers:
  http:
    # The app container over the shared `balancer` network — NOT the public
    # origin. The endpoint gates on `isInternalOnlyRequest()`: a poll that
    # crossed Traefik/Cloudflare carries `x-real-ip`/`cf-*` and gets a 404,
    # the same answer an unconfigured deployment gives.
    endpoint: 'http://yng-ucip-web-prod:3000/api/edge/traefik-dynamic'
    headers:
      Authorization: 'Bearer <TRAEFIK_CONFIG_TOKEN value>'
    pollInterval: '30s'

yng-ucip-web-prod is the alias web publishes on the balancer network in docker-compose.prod.yml.example; a deployment's own compose may name it differently (this host's docker-compose.prod.yml publishes msocloud-web-prod, and its TRAEFIK_DYNAMIC_SERVICE_URL default matches) — use the alias your compose file declares. Traefik shares that network, so the poll is a cleartext container-to-container hop. A Traefik still pointed at https://<platform-host>/api/edge/traefik-dynamic will log 404s and drop every white-label router it had learned — change the provider block before deploying, not after.

Set TRAEFIK_CONFIG_TOKEN (openssl rand -hex 32) in .env.prod to match. Unset = the endpoint 404s and this provider block has nothing to poll — safe to add ahead of time.

Set TRAEFIK_HOST_RULE in .env.prod (required — see docker-compose.prod.yml.example's header for why) to the rule matching every tenant host on THIS zone, e.g.:

TRAEFIK_HOST_RULE=Host(`msocloud.net`) || Host(`www.msocloud.net`) || HostRegexp(`^[a-z0-9-]+\.msocloud\.net$`)

Traefik v2 syntax note: the HostRegexp matcher above is native-regex (Traefik v3). Traefik v2 used mustache-style capture groups instead — HostRegexp(\{subdomain:[a-z0-9-]+}.msocloud.net`)`. If the host Traefik is still on v2, translate before pasting.

(c) Org subdomain flow (instant)#

Creating or renaming an org's subdomain (super admin only, /admin/orgs) is a pure DB write — no DNS, no cert, no Traefik reload. The wildcard DNS record + wildcard cert already cover every possible label. The org is reachable at <subdomain>.msocloud.net as soon as the write commits.

(d) White-label flow end-to-end#

  1. Admin adds the domain — /admin/orgs → org → white-label domain panel → enter insights.customer.vn. Row is created status='pending_dns' with a random verification_token; the panel shows the required DNS records.
  2. Customer creates DNS records on their own zone:
    • TXT _msocloud-verify.insights.customer.vn → the verification token (ownership proof).
    • DNS-only CNAME insights.customer.vn → the target shown by the admin panel (origin.msocloud.net in production). Existing DNS-only tenant targets remain supported.
  3. Verify — use the admin panel verification action. External DNS checks run outside the RLS transaction: TXT proves ownership, and the CNAME or dedicated-origin address proves reachability. Both confirmed → status='active'. A failed check is recorded in last_error; retry after DNS propagation. Do not use shared Cloudflare edge addresses as origin proof.
  4. Traefik picks it up — the next /api/edge/traefik-dynamic poll (≤ pollInterval, e.g. 30s) sees the new active row and adds a router for Host(insights.customer.vn), pointing at the shared yng-mso-web-dynamic service — the SAME app containers as everything else.
  5. Cert auto-issues — that router's tls.certresolver is the ordinary HTTP-01 resolver (myresolver by default), since a single exact hostname doesn't need DNS-01. No manual cert work.
  6. Customer users sign in directly at https://insights.customer.vn — the app resolves the host to the org via app_locate_org_by_custom_domain (SECURITY DEFINER locator, packages/schema/sql/tenant-host-locator.sql) and pins that org for the whole request. Passkeys enrolled on a white-label domain are disabled in v1 (passkey.ts) — surfaced as a clear in-app message, not a silent RP mismatch.

(e) Rollback#

  • Disable white-label routing without touching DNS: unset TRAEFIK_CONFIG_TOKEN on the app (or remove the HTTP provider block on Traefik). The endpoint 404s; Traefik's provider naturally drops the routers it previously learned from it on its next poll failure/removal.
  • Disable one customer domain: flip its org_domains.status away from active (or delete the row) via /admin/orgs. It drops off app_list_active_custom_domains() and Traefik removes that router on the next poll — no redeploy.
  • Disable org subdomains entirely: this is the wildcard DNS record + cert; there is no per-org toggle. To fully roll back ADR 0016 routing, remove the TRAEFIK_HOST_RULE-driven router labels (or unset TRAEFIK_HOST_RULE, which fails compose validation by design — re-copy a prior template revision instead of leaving it unset on a live host).
  • DNS is separately reversible: ensure-cloudflare-dns.ts only ever converges toward the desired state; deleting the wildcard/apex/www records is a manual Cloudflare-dashboard action, intentionally not exposed as a script flag.
  • The legacy single-host ${DOMAIN} router (yng-ucip-web-http/-https) is untouched by any of the above — it keeps working throughout, including for hosts that never adopt msocloud.net.

CDN console diagnostics#

Dynamic chunk preload hints must carry the same crossOrigin mode as the runtime script loader. Next 16.4.6 omits that value in its lazy-dynamic preload component; patches/next@16.4.6.patch reads the client-reference manifest for both JS hints and CSS links. scripts/next-dynamic-preload-crossorigin.test.mjs exercises the installed dependency through test:scripts; retain the patch until an upstream version passes that guard without it.

Dynamic app responses add Cache-Control: no-transform while retaining their privacy/cache directives. This prevents Cloudflare Email Address Obfuscation from rewriting those responses, so email-decode.min.js does not conflict with nonce-based CSP. Next's built-in compression also skips responses carrying no-transform; keeping that header therefore requires scoped origin compression in Traefik. Keep CSP intact; public hashed static assets retain their immutable CDN caching.

Compress dynamic responses without changing their cache policy

The tracked Compose defaults leave this response middleware disabled for hosts that have not installed it. Before opting in to msocloud-response@file, copy infra/traefik/msocloud-response.yml into the balancer's watched file-provider directory. On this host that is /opt/apps/balancer/dynamic/msocloud-response.yml. The middleware must exist before application routers reference it; otherwise Traefik rejects those routers. Do not replace the balancer's other dynamic configuration.

The supplied middleware compresses eligible responses of at least 1,024 bytes, preferring br then gzip, and excludes text/event-stream (so SSE is not buffered) plus already-compressed binary/font/media MIME types (font/woff2, font/woff, image/avif, image/webp, image/jpeg, image/png, image/gif, image/x-icon, video/mp4, video/webm, video/iso.segment, audio/mp4, application/zip, application/gzip, application/zstd). Verified live on www.msocloud.net/ (2026-11-23): switching encodings from [gzip, br] to [br, gzip] reduced HTML transfer from 37,539 B (gzip) to 24,521 B (br, -34.7%) and stopped re-compressing font/woff2. While responses retain Cache-Control: no-transform (until Email Obfuscation is turned off in the Cloudflare dashboard), modern browsers (Accept-Encoding: zstd, br, gzip) receive origin Brotli directly through Cloudflare (11.5 KB on /privacy), while rare gzip-only clients receive uncompressed HTML cleanly without corruption. Guard: apps/web/src/__tests__/traefik-response-middleware.test.ts.

After installing the file, set TRAEFIK_RESPONSE_MIDDLEWARE=msocloud-response@file. Both platform HTTPS routers append it to their fixed retry middleware; white-label routers from the HTTP provider use it directly. Without these opt-in settings, platform routers retain their retry middleware and white-label routers omit the response middleware. The middleware performs compression only: it does not overwrite Cache-Control, add cache eligibility to HTML/API responses, or remove no-transform. Public-share TTLs, private responses and immutable static assets keep their existing policies. The assets hostname's dedicated static router remains separately scoped.

Verify both direct-origin and public-edge GET requests with normal browser Accept-Encoding: gzip, br. Check Content-Encoding, actual transferred bytes, privacy/cache directives and Vary: Accept-Encoding, then verify SSE emits its first event promptly without compression. Repeat a hashed static request to confirm CDN HIT behavior. Compare cold and warm browser waterfalls for authenticated dashboards, including API time, JS execution and cross-origin DNS/TLS setup. Lower ping alone does not establish faster API/database work or chart rendering.

On this deployment, a white-label HTML response dropped from roughly 53 KB uncompressed to 12.3 KB transferred after the scoped middleware was applied; this is a payload observation, not an end-to-end dashboard performance guarantee.

Live verification covers console warnings as well as failed requests and page errors. Check a proxied /privacy response containing contact emails: it should contain neither data-cfemail nor email-decode.min.js, and its cache policy should retain no-transform. Authenticated conditional widgets require a signed-in browser check; a clean anonymous signin page alone does not cover them.