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
authenticationservice (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
/ssoto the API consistently with the session already in use: on a custom domain a rewrite to/public/sso/callback(like the/_api/v2proxy: theSet-Cookieof__Host-accessTokenbecomes first-party of the domain); on<slug>.aladia.ioa 302 toapi.aladia.io/v2/public/sso/callback(same site: the cookie isapi.aladia.io's, as for the normal login).proxy.tsalways 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'saladia-sessionflag, clears the session cache and goes toto.
2. Data model
authentication service, libs/common/src/common/models/microservices/authentication/workspace-sso.model.ts:
| Collection | Fields | Indexes |
|---|---|---|
workspace_sso_settings (line 54) | workspaceId, mode (product/mixed/aladia), verification (secret/public_key/jwks), algorithm, secrets[] revokedAt?, publicKeyPem, jwksUrl, loginUrl, logoutUrl, allowAccountLinking, updatedBy | workspaceId 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_PASSWORDand its own salt (aladia-workspace-sso), AADworkspace-sso:<workspaceId>:<kid>: copied to another workspace it does not decrypt. No new environment variable (same scheme asapps/calendar/.../token-crypto.ts). - Rotation: the current one is
secrets[0]; "Regenerate" moves it tosecrets[1]withexpiresAt= now + 24 h (dual validity) orrevokedAt= now. At most two secrets. The headerkidpicks the secret; without akidevery 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;forgotPassworddoes not apply to it (auth.service.ts:525). The email is the product's ifemail_verifiedis notfalseand it does not exist yet; otherwise an internalu-<hash>@sso.aladia.invalidaddress (.invalid: the notification recipient guard never emails it).
3. Decisions
| Topic | Decision |
|---|---|
| Algorithm | only the configured one (HS256 with the secret; RS256/ES256 with PEM or JWKS); the header alg is only compared. No none, crit rejected |
| Signature | node:crypto, no new dependencies: HMAC compared with timingSafeEqual, RSA ≥ 2048 bits, EC P-256 (ieee-p1363) |
| Times | exp and iat required, exp - iat ≤ 300 s, iat up to 180 s in the future, 60 s leeway on exp, nbf honoured |
aud | the request host, the tenant host, <slug>.aladia.io and the workspace's active domain; also as https://host |
jti | required, 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 collision | link 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) |
| Roles | student → organization-student; teacher → organization-member + course-teacher in the JWT courses. Never Admin/Owner; the JWT promotes but never demotes |
| Courses | by id (courses have no slug), workspace courses only; replace_courses removes only those in identity.courseIds |
| Groups | by id or exact name, staff only: GROUP_MEMBERS.CREATE_MANY drops students |
| Session | a new token at every sign-in (generateLoginJWT), personal context as a normal login: on the site the tenant comes from x-aladia-tenant |
| Mode A | web-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 |
| Logout | logoutUrl if any; in A without it /login (the root would bounce to the product and sign the user in again) |
| Flag and plan | workspace-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
| File | What |
|---|---|
libs/common/src/common/workspace-sso/workspace-sso.rules.ts | pure 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.ts | updateSettings (184), generateSecret (278), revokeSecret (328), testToken (356), login (430), link (573), session (711), createFederatedUser (744), consumeJti (775) |
apps/authentication/.../workspace-sso/jwks.client.ts | JWKS: 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.ts | workspace-sso.* patterns and the three collections |
apps/gateway/src/gateway/controllers/authentication/workspace-sso/workspace-sso.controller.ts | organizations/:id/sso (54) and public/sso (150) |
apps/gateway/.../workspace-sso/workspace-sso-gateway.service.ts | callback (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.ts | fixed-window limits in Redis (18) |
apps/gateway/.../authentication/auth/auth.controller.ts | mode A on register (123), login (165), google (272), reset-password (505) |
apps/gateway/.../workspace-address/workspace-address.service.ts | withSso (151): the policy in the tenant resolve for web-next |
libs/common/src/common/dto/microservices/activity-log/workspace-sso-audit.dto.ts | the Activity log event (field names only) |
libs/common/src/common/utils/redact-secrets.util.ts | jwt among the keys redacted in logs (21) |
web-next/proxy.ts | ssoEntry (158), redirect to the product login in mode A (183) |
web-next/lib/workspace-sso.ts, lib/api/workspace-sso.ts | pure rules (where /sso goes, product login, error codes) and client |
web-next/lib/tenant.ts, lib/session-exit.ts | sso in the tenant cookie; logoutDestination (17) and loginPath (29) |
web-next/components/settings/security/workspace-sso-section.tsx | the 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
| Route | What |
|---|---|
GET organizations/:id/sso | settings (never secrets) and hosts (the accepted aud) |
PUT organizations/:id/sso | mode, 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/revoke | revoke 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/logins | last 50 sign-ins |
GET public/sso/callback?jwt&return_to&host | the 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/resolve | now 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):
/sso30/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), thejtidoes (fail closed). - Logs: never tokens or secrets.
jwtis redacted byredactQueryString; the log keepssuband email only when the error comes after the signature (before, they could be made up). The gateway error filter logs redacted bodies (token,password,secretare 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,organizationdocument, fields such assso.modeorsso.secret.<kid>.revoked, never the values) and to the gateway and service logs with the id of who did it; settings storeupdatedBy. - 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
- Backend deploy (no new variable: the secrets key derives from
ENCRYPTION_PASSWORD). scripts/migrations/2026-10-workspace-sso.jswithPHASE=plan, thenPHASE=apply: indexes of the three collections and theworkspace-ssoflag for Accademia Leonardo and QA Academy. Thecustom-domainflag is needed anyway (the workspace site).- web-next deploy.
- Acceptance:
node web-next/e2e/help/flows/run.mjs settings/workspace-sso --shots(it writes: a new secret, two@mailosaur.nettest accounts, enrollment in sci1; it restores the previous mode). marketing/lib/plan-catalog.jsonis 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 withkid, aud, exp/iat/nbf, sub/jti, roles, courses and groups, rotation with dual validity and revocation, maliciousreturn_to, encryption with AAD, jti,jwtredaction);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, reusedjti, Redis down, collision with and without linking, wrong password and 5 attempts, roles and no demotion, JIT andreplace_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
ssoitem). - 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.