Implementation notes
auth-service modules
• Global infrastructure: GlobalModule (config, cache, BullMQ, tenant middleware), DatabaseModule, SharedServicesModule, GuardsModule, HealthCheckModule and a stats module.
• Identity: auth, mfa (TOTP, WebAuthn, email OTP, policy and enforcement), social-auth, session, user, email, password-policy.
• Authorization: rbac with roles, permissions, policies, groups and policy evaluation.
• Federation: oauth (authorize, token, introspect, revoke, userinfo, end_session, discovery, JWKS), saml, scim, ldap.
• Platform: tenant (provisioning, branding, registration, allowed origins), admin and superadmin, audit, webhook, dashboard, mail, notifier.
Request pipeline in practice
Order is deliberate. helmet, cookies and the per-tenant CORS delegate run first; then the tenant resolver and schema middleware pin the request to one tenant; the global rate limiter runs before any token is parsed; route guards declared with @Protected() run JwtAuthGuard, TenantBindingGuard and SessionGuard, then permissions or roles.
A ValidationPipe with whitelist and transform validates class DTOs, a ResponseInterceptor wraps JSON as { status, data }, and errors leave as RFC 9457 problem details carrying a stable code and the request id. On finish or close the QueryRunner is rolled back if needed, search_path is reset and the connection is released.
Authentication details
• Passwords: Argon2id, a platform minimum length of 12, reuse check against the last 5, lockout after 5 attempts in 15 minutes, and per-tenant policy in tenant_password_policy.
• Magic links and reset links: 256-bit one-time tokens (only the SHA-256 stored), scanner-safe inspect, atomic claim, and distinct LINK_EXPIRED, LINK_ALREADY_USED and LINK_WRONG_ACCOUNT results. A 6-digit reset code remains as a fallback; the first success spends both.
• MFA: TOTP with Argon2id-hashed single-use backup codes, WebAuthn with an atomic counter, and email OTP held hashed in Redis. Tenant MFA policy is enforced on every login path, and a short-lived enrolment token lets a user enrol before a session exists.
• Step-up: POST /auth/reauth requires the same strength as sign-in; its amr contains exactly the factors proven in that request.
• Social: Google, GitHub and Microsoft through Passport strategies, with an HMAC-signed, browser-bound, single-use state to stop login CSRF and an origin check on the return URL.
Authorization model
Roles carry permissions written as resource:action with wildcards. Each tenant is bootstrapped with owner, admin, member and guest, and the invite flow enforces a role hierarchy so a user with users:write cannot grant a role above their own. IAM-style policy documents (Allow and Deny, resources, conditions) attach to users, roles and groups.
PolicyEvaluationService applies explicit-deny-wins and permission boundaries; results are cached once in RbacCacheService. Effective permissions are exposed to the portal so it can hide or disable controls, while the backend remains the only enforcement point.
Federation details
• OAuth and OIDC: authorization code with PKCE, client credentials and refresh token grants, consent storage, introspection (RFC 7662), revocation (RFC 7009), userinfo and end-session. The token endpoint honours each client's allowed grant types. The discovery issuer equals the token iss.
• SAML: SP-initiated SSO through samlify with XML-DSig assertions signed by the tenant key, metadata per tenant, an issuer re-check against the tenant's active service provider and a browser-bound continuation nonce.
• SCIM v2: per-tenant bearer tokens, users, groups and patch operations, with its own exception filter that returns SCIM-shaped errors.
• LDAP: connection management, on-demand sync, deactivate-never-delete, a safety valve and an SSRF-checked, TLS-verified dial.
Operations and platform features
• Webhooks: tenant-scoped endpoints with event filters, HMAC-SHA256 signed bodies (X-Sentry-Signature), a delivery id used as the idempotency key, retries and manual redelivery, and SSRF protection that fails closed on DNS and never follows redirects.
• Audit: security_events with request id and outcome, recursive metadata redaction, CSV export protected against formula injection, and a GDPR export and erasure path.
• Mail: 24 React Email templates (verification, magic link, OTP, reset, invitation, MFA and passkey changes, account lock and suspension, session-reuse alert, ownership transfer, tenant deletion and restore), rendered after sanitising all display text and rejecting non-http(s) URLs.
• Health: GET /health for liveness and GET /health/ready for Postgres and Redis. Swagger is available outside production only.
Admin portal and hosted login
The portal separates routes, views, components, pure models and data access, enforced by ESLint rules and a typed copy catalogue. Platform operators use /dashboard, /tenants, /users and /audit-logs; tenant admins use /t/{slug}; end users get hosted /u/login, /u/signup, /u/consent, /u/magic-link, /u/mfa, reset and verify pages, plus invite acceptance. A first-run /setup page takes the one-time token printed by the API.
Tests render components to markup to assert roles and aria wiring; journeys cover axe WCAG 2.2 AA at 375 and 1280 pixels in light and dark.
@scrolloop/sdk
One client per tenant, built with createWebClient and a tenant taken from the subdomain. Modules cover signIn, account, mfa, passkeys, sessions, invites, consent, social, tenant, audit and saml; client.request() is the escape hatch for admin APIs and adds the tenant header, cookies and a silent refresh on 401.
Flows that can end without a session return a discriminated union (AuthOutcome) so MFA challenge and enrolment branches are never flattened. After ADR-0003 the SDK tracks only whether a session is live and its non-secret claims.
Build, test and run
Yarn 4 workspaces under Turborepo. docker compose provides Postgres 16, Redis 7 and Mailpit; migrations and a seed run from auth-service, and a first-run setup token appears in the API log. CI runs typecheck, unit tests and a boot-and-smoke job (scripts/smoke-test.sh). Playwright journeys run on separate ports against a _test database and a Redis DB reserved for them. Environment is validated at boot and the service refuses to start on a missing or malformed value; production additionally requires TOKEN_ENCRYPTION_KEY, a trusted-proxy setting and TLS-verified database settings.