AladiaDocs

Domain and email

Slices (b) and (c) of Domain and email: the shared ownership TXT, the Site track (tenant, storefront, bucket CORS) and the Email track (EU subuser, DKIM, required DMARC, test email): how they're built, what to configure and in what order.

Status: built on branch feat/custom-domain-wizard (05/10/2026), not released. Owner-approved spec of 05/10 ("Domain and email", points 1–8). Plan: docs/CUSTOM_DOMAIN_EMAIL_PLAN.md (L1, L9, §9, §11, §12, §17 D2). Slice (a), sender and reply-to, is on its own branch: Email sender and reply-to. User guide: Domain and email. Paths are relative to backend/ and web-next/.

1. Shape

One settings section, two independent tracks on the same school domain, each with its own records, verification and status, activable at different times; a summary on top (domainSummary: "Site: … · Email: …").

PartRecordsStatus
Ownership (shared)TXT _aladia.<domain> = aladia-verify=<token>verified once, valid for both tracks; without it neither track calls Vercel or SendGrid
SiteCNAME app (or the chosen subdomain) → the project CNAME from Vercel, or A on @ for the bare domain with a www CNAME; _vercel TXT only when Vercel asks. Several domains per workspace: §1 bispending → verifying → active; 7 days broken → misconfigured; 30 days → removed from Vercel
Email3 SendGrid CNAMEs on mail.<domain> (em…, s1._domainkey.mail, s2._domainkey.mail); DMARC requiredaccount_pending, pending, verifying, verified, failed
  • Token: sha256("aladia-custom-domain:<orgId>:<root>"), 32 hex. Deterministic, so the previews show the real value without writing. No secret needed: whoever reads it still can't write it into someone else's DNS, and each workspace gets a different value.
  • Sender: <Academy name> <notification@mail.<domain>>. The mail subdomain is the default and stays fixed unless changed from the advanced option; never the root; never a no-reply local part.
  • DMARC is required for the Email track: _dmarc.mail.<domain>, or the root _dmarc.<domain> whose sp= (or p=) covers the subdomain, with a valid policy (at least p=none). When missing, the exact TXT to add is shown (v=DMARC1; p=none; rua=mailto:<reply-to>;).
  • Reserved: aladia.io, vercel.app, vercel.com always; aladia.ai and istitutoformativoaladia.it only for the workspaces in CUSTOM_DOMAIN_RESERVED_OWNERS; mailbox providers (gmail, outlook, libero…).

1 bis. Site domains: bare domain and "Change domain"

Owner decision of 08/10/2026. Branch feat/custom-domain-apex-change.

Model. The old customDomain (one domain) is replaced by organizations.siteDomains[] (OrganizationCustomDomainDocument with a role): same fields as before (records, status, Vercel, SSL, 7/30 days, backoff) plus:

FieldWhat
roleactive = the site domain (at most one; until its status is active the site stays on <slug>.aladia.io); next = the new domain of a change, being verified (at most one); redirect = redirects to the site domain
apexbare domain (school.com): A record on @ (IP from recommendedIPv4 of /v6/domains/:d/config, fallback 76.76.21.21) instead of the CNAME
companionOfwww.<domain>, ALWAYS connected with the bare domain (redirect role, www CNAME); comes and goes with its domain
vercelRedirectthe redirect set on Vercel (read back on every domain GET): the sync is idempotent
redirectingSincesince when it redirects (after the swap)
ownershipthe ownership (_aladia TXT) of ITS root when it isn't domainOwnership's: change to another domain with the email left on the first one

Pure rules in apps/profile/…/site-domains.rules.ts: promoteNext (the swap), redirectTarget/desiredRedirect (every redirect ALWAYS points to the active domain, only once it's on Vercel: Vercel only accepts a project domain as target), arrangeOwnerships (domainOwnership = email root if any, else the site domain's, else the new one's; other roots on the domains using them; redirects need none; a verified ownership moves, never gets recreated: the token is deterministic), removableAlone.

Flow.

  1. First connection (PUT …/custom-domain { domain, subdomain?, apex? } with the site not live): the chosen domain is active; with apex also www.<domain> as redirect (companionOf). The previous one, never live, leaves Vercel.
  2. Change domain (same route, with the active domain already ACTIVE and a different host): the new one comes in as next (plus its www when bare) NEXT TO the old one, which stays the site. On another root ownership is verified again (the new root's TXT in ownership); the email stays on its own. A previous change to another host is cancelled; a redirecting host can become next again.
  3. Check (check, cron and "Check again"): ownership of every root → due domains in the order active, next, redirect (a redirect goes on Vercel only after its target: POST /v10/projects/:p/domains { name, redirect, redirectStatusCode: 308 }) → swap when the next is ACTIVE (DNS + Vercel verified + TLS probe): the next becomes active, the old one redirect → sync of the Vercel redirects (PATCH /v9/projects/:p/domains/:d { redirect, redirectStatusCode: 308 }, null for those that must not redirect). No DELETE and re-create. Idempotent: a second run makes no Vercel writes.
  4. When the new one goes live: "… is live" email to the Owner (as today) and WorkspaceOriginsNotifier.domainActive: bucket CORS and Stripe payment method domain (Apple Pay/Google Pay) registered on the academy account. redirects send no email; after 30 days of broken DNS they leave Vercel and the list.
  5. Removals: DELETE …/custom-domain/hosts/:host removes a redirect (any time) or the next with its www (cancels the change); the active domain → 409. DELETE …/custom-domain removes everything (the site goes back to <slug>.aladia.io).

What follows the site domain (the live active domain):

WhereWhat
Tenant resolution (workspace-address.service.ts resolveCustomDomain)the active answers with its host; a redirect answers redirectTo = site domain with redirectStatus: 308, the next with 307 (temporary, never cached by browsers: it becomes the site soon). proxy.ts (tenantRedirect in lib/tenant.ts) redirects keeping path and query: it covers the time before the Vercel redirect is set
Trusted origins (activeDomains)only the live active; the /_api proxy answers 404 on a redirecting domain
Canonical, OG, previews (lib/tenant-metadata)tenant.host = site domain
Email links and sender (mail-identity.ts, MailTenantService)siteHost = active domain; from a redirecting domain the host is the redirectTo
Stripe Apple Pay/Google Pay, bucket CORSdomainActive of the new one at the swap
Product SSO (workspaceHosts)accepted aud: <slug>.aladia.io, the site domain and, while they exist, the redirecting domains (not the www ones)
Email domain (mail.<root>)does NOT change; if the site root changes the Email track flags it (emailOnOtherRoot) until it's set up again

Session. Cookies (__Host-accessToken) are per domain: after the swap people signed in on the old one sign in once more on the new one. A one-time cross-domain session handoff doesn't exist yet (the auth.aladia.io one-time code is in plan §5.2, not built): documented limit, shown in the wizard.

UI (custom-domain-section.tsx): rows with a "⋯" menu (DropdownMenu): site domain (Change domain, Open, Remove the custom domain), new domain ("New domain" badge, Cancel the change, with its steps and records), redirecting domains ("Redirects to …" badge, Open, Delete); a ConfirmDialog for every removal. Wizard with a "Main domain" / "Subdomain" RadioGroup, a warning about the website being replaced (existing from the preview) and, on a change, the consequences (redirect, signing in again, product SSO if on, email sender).

Migration scripts/migrations/2026-10-site-domains.js (PHASE=plan, then PHASE=apply): customDomain → siteDomains: [{ ...customDomain, role: 'active' }], partial multikey unique index siteDomains.domain_unique, sparse siteDomains.nextCheckAt and siteDomains.status, then the customDomain.* indexes are dropped. Stops if a host is in two workspaces. Behaviour unchanged.

Tests: tests/unit/custom-domain-change.spec.ts (rules; bare domain with www 308; change from app. to the bare domain with swap, PATCH and idempotence; change to another root with new TXT and email left behind; cancel; deleting a redirect; refusal on the site domain; email links on the new one), workspace-address.spec.ts (308/307 for domains that aren't the site), lib/tenant.test.mjs (tenantRedirect), lib/custom-domain.test.mjs (siteRows, canChange, removableAlone). Vercel and DNS are always fake.

2. Code

FileWhat
apps/profile/src/app/organization-branding/custom-domain.rules.tspure rules: validation, token, records, DNS evaluation with seenValue, DMARC, status, backoff, 7/30 days, limits, zone file
apps/profile/…/custom-domain.service.tsownership, Site (preview, set, remove), Email (preview, set, remove, test), check of the three parts, instructions, sweep
apps/profile/…/site-domains.rules.tspure rules of the site domains: roles, swap, redirect target, ownership per root (§1 bis)
apps/profile/…/custom-domain.sweep.ts@Cron every 5 min with Murlock (custom-domains:sweep), 25 workspaces per run
apps/profile/…/dns-checker.tsdns.promises.Resolver on 1.1.1.1 and 8.8.8.8, TLS probe with SNI
apps/profile/…/vercel-domains.client.tsVercel REST: GET /v6/domains/:d/config?projectIdOrName before adding, add, get, verify, remove
apps/profile/…/sendgrid-domains.client.ts@sendgrid/client, EU host, on-behalf-of: <subuser>: subusers probe and creation, domain authentication, validation, test send
libs/common/src/common/custom-domain/dns-providers.tsprovider from NS + deep link (Squarespace, Aruba, Register.it, GoDaddy, Cloudflare, Google Cloud DNS, OVH, Namecheap, Vercel)
libs/common/src/common/custom-domain/trusted-custom-domains.tsactive domains as trusted origins (CORS, Origin check, websocket), reloaded every minute by the gateway
apps/gateway/…/organization-branding/custom-domain.controller.tsorganizations/:id/custom-domain and organizations/:id/email-domain, flag custom-domain, assertFeature (custom_domain, school_email_domain)
apps/gateway/…/course/marketplace/marketplace-storefront.controller.tspublic storefront of the site's workspace
apps/storage/src/app/buckets/buckets.service.ts (ensureOwnerOrigins)site origin in the CORS of every bucket of the workspace
web-next/components/settings/domain/custom-domain-section.tsxthe section (track prop: Site in Settings > Domain, Email in Settings > Email), the two tracks and the wizard
web-next/lib/tenant.ts, lib/tenant-resolve.ts, proxy.tstenant on verified custom domains (resolveTenant, per-instance cache 60/30 s)
web-next/app/brand-icon/[file]/route.tsxper-host favicon (favicon.png, 64 px) and apple-touch-icon.png (180 px): the workspace logo cropped square (PNG/JPEG redrawn with next/og, other formats passed through), otherwise 307 to Aladia's /icon.svg; one-hour Cache-Control, Vercel's cache keys on host. The path has a dot, so proxy.ts skips it
web-next/components/tenant/ (tenant-mark, auth-brand, tenant-title), components/shell/guest-shell.tsxworkspace brand in the guest header, sign-in and invitations; tab title (tenantTitle: "· Aladia" → name). The root layout stays static: no headers()

3. Routes

RouteWhat
POST …/custom-domain/preview { domain, subdomain, apex? }ownership TXT, A/CNAME (and www CNAME with the bare domain), provider, change (it's a change), existing (what the host answers today); no writes
PUT …/custom-domain { domain, subdomain, apex? }save the Site (and the ownership if new), first check; with the site already live on another host it's "Change domain" (§1 bis)
POST …/custom-domain/verify"Check again": ownership + both tracks, 10/h, asks Vercel to verify
POST …/custom-domain/instructions { to, track?, domain? }"Send to your IT", 5/day, from the saved track or the preview
DELETE …/custom-domainremove every site domain (always allowed)
DELETE …/custom-domain/hosts/:hostremove a redirecting domain or cancel the change (the new one with its www); the site domain → 409
POST …/email-domain/preview { domain, sender, subdomain? }sender, ownership, DMARC, accountReady
PUT …/email-domainsave the Email track, first check
POST …/email-domain/test { to }"Send a test email" from the subuser, 5/h, only when verified
POST …/email-domain/verify, …/instructions, DELETE …/email-domainas for the Site
GET /v2/public/tenants/resolve?host=also resolves ACTIVE custom domains (same lock and brand as <slug>.aladia.io)
GET /v2/public/storefront, /public/storefront/categoriesthe site's published showcase and visible categories, for guests too

POST /courses/search on a site (x-aladia-tenant) stays in that workspace's catalog, for guests and non-members.

4. Email track and SendGrid

  • One subuser per academy (aladia-<orgId>), created when GET /v3/subusers answers, on the dedicated IP (SENDGRID_SUBUSER_IPS if set, else the first of GET /v3/ips). The IP region is read from GET /v3/send_ips/ips/:ip?include_region=true: the subuser is created only on an EU IP; a us IP or a region SendGrid doesn't report stays account_pending with the reason shown (never guessed). A 401/403 means account review pending or a key without subusers.*: account_pending too.
  • IP warmup: before the first subuser, if is_auto_warmup is false, it's turned on with PATCH /v3/send_ips/ips/:ip {is_auto_warmup: true}, but only when the parent doesn't send from that IP (is_parent_assigned false): warming up a shared IP would throttle every Aladia email. With a shared IP the log says so and the step is manual: SENDGRID_AUTO_WARMUP=force, or Settings > IP Addresses > the IP > Automated warmup in SendGrid.
  • Hosts: account calls (subusers, IPs) on api.sendgrid.com; subuser calls (domain authentication, test send) on the host of the subuser's region (api.eu.sendgrid.com for EU, stored in emailSending.subuserRegion). To confirm on the first live subuser: that the parent key with on-behalf-of is accepted on the EU host.
  • The domain mail.<domain> is authenticated on the subuser (on-behalf-of), not on the parent: who signs and who sends is the same user, otherwise DKIM is not aligned and DMARC fails. Default SendGrid selectors and return path: they live under mail. and can't collide with a SendGrid the school already uses on the root.
  • verified requires SendGrid validation and DMARC. A domain that stops validating goes back to verifying at once.
  • With a verified track, the test email and every inline academy email (reset, code, welcome, invitations…) leave from notification@mail.<domain>, through MailSenderResolver and the subuser; SendGrid templates stay on aladia.io with the academy name (Email sender and reply-to §7).

5. Session, sign-in and websockets

Branch release/custom-domain-session (slimmed-down L4, plan §4 and §5). The session is the httpOnly cookie __Host-accessToken (Secure, Path=/, no Domain, SameSite=None), set by whoever answers the sign-in.

WhereHTTP callsSession cookieWebsockets (socket.io, Hocuspocus)
app.aladia.io, beta.aladia.iodirect to api.aladia.io/v2api.aladia.io's, same sitedirect, with the cookie
<slug>.aladia.iodirect to api.aladia.io/v2the same as app.aladia.io, same sitedirect, with the cookie
app.school.com (verified domain)same-origin proxy app.school.com/_api/v2/*first-party on app.school.com, separate from the aladia.io onedirect to api.aladia.io with a single-use ticket

/_api/v2 proxy. web-next/proxy.ts (proxyApi) runs NextResponse.rewrite to NEXT_PUBLIC_API_BASE_URL only when the host is a custom domain (isCustomDomainHost in lib/tenant.ts) and resolves to a live workspace; anywhere else /_api/* answers 404. No Vercel caching (x-vercel-enable-rewrite-caching: 0). The matcher has its own entry (/_api/:path*) because API paths can contain dots. In the browser apiBaseUrl() (lib/config.ts) is /_api/v2 on those domains and the direct URL elsewhere: apiFetch and the assistant chat (assistantChatUrl()) use it. Server side stays direct.

  • Vercel forwards method, body, cookies and Set-Cookie; the Host towards the VPS is api.aladia.io, the Origin stays https://app.school.com.
  • The gateway accepts that Origin because active domains already are trusted origins (trusted-custom-domains.ts, reloaded every minute): CORS with credentials (never *), BearerOnlyMiddleware (also the CSRF check), websockets. Same-origin GETs arrive without an Origin and with Host api.aladia.io, which is allowed.
  • Signed proxy→gateway header, optional (since 06/10): with ALADIA_EDGE_SECRET set, proxyApi adds x-aladia-edge-secret and x-aladia-tenant-host (ALADIA_EDGE_SECRET). Without the secret the gateway uses the Origin of the active domain. The gateway uses the host only for the sender and links of account emails (Email sender and reply-to §7); request context still comes from x-aladia-tenant, which grants nothing by itself (tenant-context.ts: member → academy, otherwise personal context).
  • Client IP: the gateway already reads the first x-forwarded-for value, which Vercel sets to the visitor's IP.

Websocket ticket. Vercel doesn't forward websockets, and on api.aladia.io the browser of app.school.com has no cookie. POST /v2/auth/realtime-ticket (through the proxy, with the cookie) returns { ticket, expiresIn: 60 }:

  • rt_ + 32 random bytes; Redis only holds realtime-ticket:<sha256> → session token, EX 60;
  • redeemed with GETDEL in SocketGateway.authenticate and HocuspocusSocketGateway.authenticate (RealtimeTicketService.resolve): it works once, then the usual checks run (signature, expiry, token in user.tokens), so a sign-out invalidates it;
  • the JWT never reaches JavaScript; with an API key (no web session) the route answers 401;
  • client: lib/realtime/socket.ts passes auth as a function (socket.io calls it on every reconnection); the editor gets ticketed: true in INIT and asks the parent for REALTIME_TICKET on every connection (HocuspocusProvider's token as a function).

Nothing changes on the hub and on <slug>.aladia.io: no ticket, cookie as before.

Sign-out and exits (lib/session-exit.ts):

EventHubWorkspace site (<slug>.aladia.io or domain)
Sign out (site-header.tsx)https://aladia.iosame host: / (storefront) or /login with Members-only access
Session expired (401 on /profiles/me, use-me.ts)/login?redirect=<page>same, on the same host, sign-in with the academy's brand
Switch account on an invitation (email-invite-client.tsx)/login?redirect=<invitation>same, on the same host

authApi.logout() sends { devices: 'current' }: it revokes only the current token. It used to send {}, which the gateway validation rejected (400): the local flag went away but the token stayed valid and the cookie wasn't cleared. On <slug>.aladia.io the cookie is the hub's one, so signing out there also signs you out of app.aladia.io in that browser. On a custom domain the sessions are separate: two devices of the same account (plan §5.2 point 5). Assistant links to app.aladia.io or beta.aladia.io stay on the workspace site (keepOnSite).

Google. GIS only accepts origins registered by hand in the OAuth client, so on custom domains the "Continue with Google" button (and One Tap) is hidden (useGoogleSignIn in google-auth.tsx); email and password, sign-up, code, reset and invitation links remain. A Google-only account reads it in the error message and sets a password from "Forgot password?". On <slug>.aladia.io the button stays, but GIS takes no wildcards: it works only for addresses registered one by one in the OAuth client (to check on accademia-leonardo.aladia.io). Google sign-in on domains comes with the auth.aladia.io relay and the single-use code (plan §5.2): DNS record auth CNAME to Vercel, auth.aladia.io on the app-aladia-io project, origin https://auth.aladia.io in the OAuth client's Authorized JavaScript origins, a /relay page, an auth/exchange route.

Tests: web-next/lib/tenant.test.mjs (host → proxy yes/no, base URL, hub links), lib/session-exit.test.mjs (destinations); backend tests/unit/custom-domain-session.spec.ts (single-use ticket with hash and 60 s, CORS and BearerOnlyMiddleware from the verified domain through the proxy, socket.io handshake with the ticket, logout body), websocket-origin.spec.ts.

To check with the pilot domain (Safari iOS and macOS, Firefox, Chrome): password sign-in, Set-Cookie of __Host-accessToken on app.school.com (DevTools > Application > Cookies), /profiles/me through /_api/v2, real-time chat and notifications, document editor, uploads, streaming assistant chat, sign-out (stays on the domain, token revoked), expired session, and that app.aladia.io in the same browser stays as it was.

6. Limits and rate

ActionLimit
Save (either track)5/h per workspace
Check again10/h per workspace
Send to your IT5/day per workspace
Test email5/h per workspace

Background checks never call Vercel verify (50/h per team): only GET. Additions happen only after the ownership TXT (100/h per team). Backoff: every 10 min for 2 h, hourly up to 72 h, then daily; live tracks daily.

7. Configuration, in order

  1. Vercel token on the VPS: VERCEL_API_TOKEN, a token of the aladia-projects team with scope limited to that team, used on project app-aladia-io (prj_tjo3HlReufLi7kkgg3ymFcAnsB5l): project domains read/write (POST /v10/projects/:p/domains, GET|PATCH|DELETE /v9/projects/:p/domains/:d, POST …/verify; PATCH for the "Change domain" redirects) and domain config read (GET /v6/domains/:d/config). Without it the Site stops at "ownership verified, waiting for Aladia".
  2. Deploy backend, then scripts/migrations/2026-10-custom-domain-wizard.js (PHASE=plan, then PHASE=apply): sparse indexes on customDomain.nextCheckAt, customDomain.status, emailSending.nextCheckAt; removal of custom domains in the old format. Then, right after the deploy that contains §1 bis, scripts/migrations/2026-10-site-domains.js (PHASE=plan, then PHASE=apply): between the deploy and the apply the site on the custom domain doesn't resolve.
  3. Deploy web-next.
  4. SendGrid: nothing new is required. The key is SENDGRID_ADMIN_API_KEY, else SENDGRID_API_KEY (today's Full Access key, with subusers.*, ips.read, whitelabel.*, mail.send). Optional: SENDGRID_SUBUSER_IPS to pick the IP, SENDGRID_AUTO_WARMUP=force to warm up an IP shared with the parent. First check: the region of 159.26.179.2 (GET /v3/send_ips/ips/159.26.179.2?include_region=true) must be eu.
  5. Optional: CUSTOM_DOMAIN_RESERVED_OWNERS="istitutoformativoaladia.it=<orgId>" for our own domains. The pilot test domain is not in the code: the e2e reads CUSTOM_DOMAIN_PILOT.

8. Tests

  • Backend unit: tests/unit/custom-domain-change.spec.ts (§1 bis), tests/unit/custom-domain.spec.ts (rules, DMARC, providers, resolver, SendGrid with mocks, Site flow with fake Vercel/DNS/TLS, 7/30 days, Email flow with account pending, subuser creation, authentication on the subuser, required DMARC, test email, shared ownership, limits, instructions, sweep, trusted origins, emails), bucket-cors.spec.ts, marketplace-storefront.spec.ts, workspace-address.spec.ts, workspace-entitlements.spec.ts.
  • web-next: node --test lib/custom-domain.test.mjs lib/tenant.test.mjs lib/session-exit.test.mjs.
  • E2E, read-only on production: node web-next/e2e/help/flows/run.mjs settings/custom-domain (owner of Accademia Leonardo, test domain from CUSTOM_DOMAIN_PILOT, writes blocked and counted). --shots writes desktop and 375 px, light and dark, into docs/public/help/settings/custom-domain/.

9. Phase 2 (not now)

Replies into the Aladia chat: a reply subdomain (reply.mail.<domain>) with an MX to SendGrid Inbound Parse; the Reply-To of a conversation email becomes r+<token>@reply.mail.<domain>, the parse webhook turns the reply into a chat message for the right thread. Needs the Event/Parse webhook endpoint (signed), a token per thread and spam filtering.

10. Market references

How comparable platforms handle custom domains and sending domains (help centers read on 05/10/2026):

On this page