AladiaDocs

Customer SSO

Phase 1 of workspace SSO: the customer's product signs a JWT and its users enter the academy (/sso). Architecture, data model, files and lines, routes, decisions, security, limits, configuration and next phases.

Status: built on the release/workspace-sso branch (06/10/2026), not released. Feature approved by the Owner (phase 1, "Customer SSO", Featurebase/Thinkific/Zendesk model). Guides: Customer SSO for academy admins, developer guide for whoever integrates the product. Paths are relative to backend/ and web-next/.

1. Shape

A SaaS product has its own users and embeds the Aladia academy on its domain (academy.product.com, Domain and email). The product server signs a JWT for the user and sends it to https://<academy>/sso?jwt=…&return_to=…; Aladia verifies it, creates or updates the user, enrolls them and opens the first-party session of the host.

flowchart LR
  P[Product server] -- JWT --> B[Browser]
  B -- GET /sso --> W[web-next proxy.ts]
  W -- rewrite (domain) or 302 (slug) --> G[gateway /public/sso/callback]
  G -- SSO_LOGIN --> A[authentication: verify, jti, identity, account, token]
  G -- profile, workspace, courses, groups --> S[profile, course, storage]
  G -- Set-Cookie + 302 --> B
  B -- /sso/complete --> W
  • Where verification runs: in the authentication service (encrypted secrets, Mongo, Redis for the jti, session token issuance). The plain secret never leaves the service, except in the create or rotate response.
  • The gateway does HTTP (cookie, redirects, limits), resolves host → workspace and orchestrates profile, membership, courses and groups by calling the other services, like the sign-up does.
  • web-next routes /sso to the API consistently with the session already in use: on a custom domain a rewrite to /public/sso/callback (like the /_api/v2 proxy: the Set-Cookie of __Host-accessToken becomes first-party of the domain); on <slug>.aladia.io a 302 to api.aladia.io/v2/public/sso/callback (same site: the cookie is api.aladia.io's, as for the normal login). proxy.ts always sets the host, never the request parameter.
  • End: the gateway answers 302 to https://<host>/sso/complete?to=<return_to> (the JWT leaves the URL; Referrer-Policy: no-referrer, Cache-Control: no-store); the page sets the host's aladia-session flag, clears the session cache and goes to to.

2. Data model

authentication service, libs/common/src/common/models/microservices/authentication/workspace-sso.model.ts:

CollectionFieldsIndexes
workspace_sso_settings (line 54)workspaceId, mode (product/mixed/aladia), verification (secret/public_key/jwks), algorithm, secrets[] revokedAt?, publicKeyPem, jwksUrl, loginUrl, logoutUrl, allowAccountLinking, updatedByworkspaceId unique
workspace_sso_identities (line 104)workspaceId, externalId (= sub), userId, email, origin (created/linked), courseIds (enrolled by SSO), lastLoginAt(workspaceId, externalId) unique; userId
workspace_sso_logins (line 145)workspaceId, at, outcome, code, detail, externalId, email, userId, host, warnings[](workspaceId, at); 90-day TTL on at
  • Secrets: 32 random bytes as base64url (43 characters), shown once. At rest AES-256-GCM with a key derived with scrypt from ENCRYPTION_PASSWORD and its own salt (aladia-workspace-sso), AAD workspace-sso:<workspaceId>:<kid>: copied to another workspace it does not decrypt. No new environment variable (same scheme as apps/calendar/.../token-crypto.ts).
  • Rotation: the current one is secrets[0]; "Regenerate" moves it to secrets[1] with expiresAt = now + 24 h (dual validity) or revokedAt = now. At most two secrets. The header kid picks the secret; without a kid every valid one is tried (all of them, so timing does not reveal which one matched).
  • Users: an account created by SSO has source: 'workspace-sso', is verified and has no password; forgotPassword does not apply to it (auth.service.ts:525). The email is the product's if email_verified is not false and it does not exist yet; otherwise an internal u-<hash>@sso.aladia.invalid address (.invalid: the notification recipient guard never emails it).

3. Decisions

TopicDecision
Algorithmonly the configured one (HS256 with the secret; RS256/ES256 with PEM or JWKS); the header alg is only compared. No none, crit rejected
Signaturenode:crypto, no new dependencies: HMAC compared with timingSafeEqual, RSA ≥ 2048 bits, EC P-256 (ieee-p1363)
Timesexp and iat required, exp - iat ≤ 300 s, iat up to 180 s in the future, 60 s leeway on exp, nbf honoured
audthe request host, the tenant host, <slug>.aladia.io and the workspace's active domain; also as https://host
jtirequired, SET NX in Redis sso:jti:<workspace>:<sha256> until exp + 60 s. Fail closed: without Redis the sign-in is refused
Identity(workspace, sub) → user; the email never links on its own
Email collisionlink only if enabled and confirmed with the Aladia account password (pending in Redis for 10 minutes, 5 attempts, single use with GETDEL); disabled: federated account with an internal address. The email OTP is postponed (it needs a new template)
Rolesstudent → organization-student; teacher → organization-member + course-teacher in the JWT courses. Never Admin/Owner; the JWT promotes but never demotes
Coursesby id (courses have no slug), workspace courses only; replace_courses removes only those in identity.courseIds
Groupsby id or exact name, staff only: GROUP_MEMBERS.CREATE_MANY drops students
Sessiona new token at every sign-in (generateLoginJWT), personal context as a normal login: on the site the tenant comes from x-aladia-tenant
Mode Aweb-next: without a session → product login (also / and /register), /login stays for staff. Gateway: sign-up refused from the site Origin (or x-aladia-tenant); after a password, Google or reset login, non-staff get 403 workspace-sso-required and the token just issued is revoked
LogoutlogoutUrl if any; in A without it /login (the root would bounce to the product and sign the user in again)
Flag and planworkspace-sso flag (per organization) + customer_sso plan feature on Organization and Enterprise (assertFeature, 402 only in the workspace-plans pilot). sso stays the Enterprise staff-SSO item

4. Code

FileWhat
libs/common/src/common/workspace-sso/workspace-sso.rules.tspure rules: verifySsoToken (672), signature verifyTokenSignature (372), parseSsoClaims (543), times checkTimes (637), isSecretUsable (329), safeReturnTo (749), encryption ssoEncryptionKey (837), internalSsoEmail (896), SsoErrorCode codes
apps/authentication/src/authentication/workspace-sso/workspace-sso.service.tsupdateSettings (184), generateSecret (278), revokeSecret (328), testToken (356), login (430), link (573), session (711), createFederatedUser (744), consumeJti (775)
apps/authentication/.../workspace-sso/jwks.client.tsJWKS: public https, 3 s, 64 KB, no redirects, 10-minute cache, refetch on a new kid at most once a minute
apps/authentication/.../workspace-sso/workspace-sso.controller.ts, .repository.tsworkspace-sso.* patterns and the three collections
apps/gateway/src/gateway/controllers/authentication/workspace-sso/workspace-sso.controller.tsorganizations/:id/sso (54) and public/sso (150)
apps/gateway/.../workspace-sso/workspace-sso-gateway.service.tscallback (236), finish (356), provision (426), ensureMembership (545), enrollCourses (574), joinGroups (671), assertRegistrationAllowed (759), assertPasswordLoginAllowed (773), workspaceHosts (820), audit (891)
apps/gateway/.../workspace-sso/sso-rate-limiter.tsfixed-window limits in Redis (18)
apps/gateway/.../authentication/auth/auth.controller.tsmode A on register (123), login (165), google (272), reset-password (505)
apps/gateway/.../workspace-address/workspace-address.service.tswithSso (151): the policy in the tenant resolve for web-next
libs/common/src/common/dto/microservices/activity-log/workspace-sso-audit.dto.tsthe Activity log event (field names only)
libs/common/src/common/utils/redact-secrets.util.tsjwt among the keys redacted in logs (21)
web-next/proxy.tsssoEntry (158), redirect to the product login in mode A (183)
web-next/lib/workspace-sso.ts, lib/api/workspace-sso.tspure rules (where /sso goes, product login, error codes) and client
web-next/lib/tenant.ts, lib/session-exit.tssso in the tenant cookie; logoutDestination (17) and loginPath (29)
web-next/components/settings/security/workspace-sso-section.tsxthe section (88): mode, signature, product, Test a token, log
web-next/components/auth/workspace-sso.tsx/sso/complete, /sso/error, /sso/link, "Continue with …" in the login

5. Routes

RouteWhat
GET organizations/:id/ssosettings (never secrets) and hosts (the accepted aud)
PUT organizations/:id/ssomode, signature, key, URLs, linking (customer_sso)
POST organizations/:id/sso/secret {revokePrevious?}create or rotate; the only response with the plain secret (Cache-Control: no-store)
POST organizations/:id/sso/secret/:kid/revokerevoke the previous one (always allowed)
POST organizations/:id/sso/test {token}Test a token: full check, does not consume the jti, no session
GET organizations/:id/sso/loginslast 50 sign-ins
GET public/sso/callback?jwt&return_to&hostthe sign-in: always a 302 on the same host (/sso/complete, /sso/link, /sso/error?code=), a plain 404 only for a host of nobody
GET public/sso/link?token, POST public/sso/link {token,password}link confirmation
GET public/tenants/resolvenow with sso: {mode, loginUrl, logoutUrl} when the flag is on and the mode is not "Aladia only"

Settings: workspace-sso flag (404 outside the pilot), ResourceAbilityGuard(UPDATE) (Owners and Admins, like Domain and email).

6. Security

  • Limits (Redis, shared across instances): /sso 30/min per IP (hashed) and 600/min per workspace; Test a token 30/h per workspace; Regenerate 10/h; link confirmation 10 every 10 minutes per IP, plus 5 passwords per pending link. Without Redis the limits do not apply (fail open), the jti does (fail closed).
  • Logs: never tokens or secrets. jwt is redacted by redactQueryString; the log keeps sub and email only when the error comes after the signature (before, they could be made up). The gateway error filter logs redacted bodies (token, password, secret are already sensitive).
  • return_to: only paths or URLs of the same host, no //, /\, control characters or spaces; the final redirect is built on the host resolved by the gateway.
  • Audit: every settings change, generation, rotation and revocation goes to the workspace Activity log (workspace-sso.workspace-sso-updated, organization document, fields such as sso.mode or sso.secret.<kid>.revoked, never the values) and to the gateway and service logs with the id of who did it; settings store updatedBy.
  • Still open: the JWT travels in the URL (nginx access logs on the VPS and Vercel's), mitigated by short life and single use; login CSRF (another user's valid token) as in any GET-based SSO; the JWKS is downloaded without DNS-rebinding protection.

7. Configuration, in order

  1. Backend deploy (no new variable: the secrets key derives from ENCRYPTION_PASSWORD).
  2. scripts/migrations/2026-10-workspace-sso.js with PHASE=plan, then PHASE=apply: indexes of the three collections and the workspace-sso flag for Accademia Leonardo and QA Academy. The custom-domain flag is needed anyway (the workspace site).
  3. web-next deploy.
  4. Acceptance: node web-next/e2e/help/flows/run.mjs settings/workspace-sso --shots (it writes: a new secret, two @mailosaur.net test accounts, enrollment in sci1; it restores the previous mode).
  5. marketing/lib/plan-catalog.json is regenerated (a new "Sign-in from your product (JWT SSO)" row on Organization): it ships with the next site deploy.

8. Tests

  • Backend: tests/unit/workspace-sso.rules.spec.ts (valid and wrong signature, alg confusion, none, crit, RS256/ES256, private or short PEM, JWKS with kid, aud, exp/iat/nbf, sub/jti, roles, courses and groups, rotation with dual validity and revocation, malicious return_to, encryption with AAD, jti, jwt redaction); tests/unit/workspace-sso.flow.spec.ts (secret shown once and encrypted, rotation and revocation, settings validation, Test a token not consuming, first and second sign-in, reused jti, Redis down, collision with and without linking, wrong password and 5 attempts, roles and no demotion, JIT and replace_courses, groups for staff only, error pages, 404 for unknown hosts, remote login, rate limit, mode A on login and sign-up, logs without tokens).
  • web-next: node --test lib/workspace-sso.test.mjs lib/tenant.test.mjs lib/session-exit.test.mjs.
  • E2E: web-next/e2e/help/flows/settings/workspace-sso.spec.mjs (run by hand after the release).

9. Next phases

  • 2FA: Aladia has no two-step verification today (no TOTP and no OTP at login: the email code exists only at sign-up, "new device" is only a notice). Phase 2: TOTP for Owners and Admins (and a per-workspace requirement), which also strengthens the emergency access.
  • Email OTP to confirm the link, as an alternative to the password.
  • OIDC as a second integration path (authorization code + PKCE towards the customer's IdP).
  • Enterprise: staff SSO (SAML/OIDC) and SCIM provisioning via WorkOS or BoxyHQ (the plan's sso item).
  • Out for now: IP allowlist; the legacy "identity verification" (HMAC hash of the user in the widget, Intercom style).
  • Mobile app with Customer SSO; course slugs for courses.

10. Market references

How similar platforms do it (public documentation read on 06/10/2026): Featurebase (HS256 JWT signed with the organization secret, redirect with return_to), Thinkific (JWT SSO, return_to and error_url, regenerable secret), Zendesk (JWT with jti, iat, short life, remote login URL and logout URL, secret rotation). Our phase 1 follows the same model, plus a required aud, a single-use jti on the Aladia side, dual validity on rotation and Test a token.

On this page