Architecture
How to read these diagrams
Nine diagrams, each tied to the repository: system overview, request lifecycle, tenant isolation, tokens and keys, sign-in and MFA, OAuth and OIDC, federation, mail and events, and monorepo topology. Click a node for its responsibility. They are drawn from the architecture docs, ADRs and module tree rather than from a deployment, so ports and TTLs are the defaults in code and env validation.
Components and connections (12 / 11)
- Admin portal (Client): Next.js 16 console: platform dashboard, tenant workspaces at /t/{slug}, hosted login pages at /u/*. Port 3000.
- Apps using @scrolloop/sdk (Client): Browser, React and Next.js client. Cookie-based; sends credentials on every request and refreshes silently on a 401.
- OIDC / SAML relying parties (External): Third-party apps that sign users in through /oauth/* or /saml/sso/{tenant}.
- Social providers (External): Google, GitHub and Microsoft sign-in via Passport strategies.
- SCIM / LDAP sources (External): Enterprise directories and provisioning clients that push or are pulled into tenant user lists.
- auth-service (Service): NestJS 11 API on port 4000. Every authentication, tenancy, RBAC and protocol endpoint. One process owns config, cache, queues and tenant middleware.
- Docs site (Client): Fumadocs developer documentation on port 3001, independent of the API at runtime.
- PostgreSQL 16 (Database): public schema for platform data (tenants, key_pairs, migrations) and one fk_{slug} schema per tenant.
- Redis 7 (Database): Sessions cache, sliding-window rate limits, WebAuthn challenges, email OTPs, link tokens and BullMQ queues.
- BullMQ queues (Queue): mail.send and webhook delivery. Retries with exponential backoff, run off the request path.
- SES / SMTP (External): Mail providers tried in order SES, SMTP, Console. Console is refused in production.
- Webhook receivers (External): Tenant endpoints that receive HMAC-SHA256 signed events.
- Admin portal to auth-service: HTTPS + cookies
- Apps using @scrolloop/sdk to auth-service: HTTPS + cookies
- OIDC / SAML relying parties to auth-service: OAuth 2.0 / OIDC / SAML
- Social providers to auth-service: OAuth callback
- SCIM / LDAP sources to auth-service: SCIM v2 / LDAP sync
- auth-service to PostgreSQL 16: TypeORM, tenant search_path
- auth-service to Redis 7: sessions, limits, challenges
- auth-service to BullMQ queues: enqueue
- BullMQ queues to Redis 7: backed by
- BullMQ queues to SES / SMTP: MailProcessor
- BullMQ queues to Webhook receivers: signed POST
Who talks to auth-service, and what it depends on.
System overview
The platform is one NestJS API in front of PostgreSQL and Redis. Two ideas shape everything else: a tenant is resolved before any business logic runs, and anything slow or external (mail, webhooks) leaves the request through a queue.
Components and connections (14 / 14)
- Browser or SDK (Client): Sends cookies; may also send X-Tenant-Slug on a shared hostname.
- ValidationPipe + controller (Service): Whitelist and transform on class DTOs, then the controller calls the service.
- helmet, cookies, CORS (Service): Security headers, cookie parser and a per-request CORS delegate that checks the origin against the request tenant (ADR-0006).
- PermissionsGuard / RolesGuard (Service): Evaluates role permissions and IAM policies with explicit-deny-wins.
- ResponseInterceptor (Service): Wraps JSON as { status, data } unless the route is marked @RawResponse.
- public.tenants (Database): Lookup table for slug, custom domain and status.
- TenantResolverMiddleware (Service): Resolves req.tenant: custom domain, then subdomain of SENTRY_PLATFORM_DOMAIN, then X-Tenant-Slug, then X-Tenant-ID when permitted.
- SessionGuard (Service): Confirms the server-side session still exists (Redis first, Postgres fallback), so logout takes effect immediately.
- Cleanup (Process): On finish or close: roll back if needed, reset search_path, release the QueryRunner to the pool.
- TenantSchemaMiddleware (Service): Takes a QueryRunner, runs SET search_path TO fk_{slug}, public and stores it in AsyncLocalStorage.
- TenantBindingGuard (Service): Rejects a token whose tenant differs from the tenant the request resolved to.
- RateLimitGuard (Service): Global guard. Redis sliding window configured per route with @RateLimit.
- JwtAuthGuard (Service): Verifies the RS256 access token from the cookie, resolving the key by kid.
- Redis (Database): Rate-limit counters and session cache.
- Browser or SDK to helmet, cookies, CORS
- helmet, cookies, CORS to TenantResolverMiddleware
- TenantResolverMiddleware to TenantSchemaMiddleware
- TenantSchemaMiddleware to RateLimitGuard
- RateLimitGuard to JwtAuthGuard: if @Protected()
- JwtAuthGuard to TenantBindingGuard
- TenantBindingGuard to SessionGuard
- SessionGuard to PermissionsGuard / RolesGuard
- PermissionsGuard / RolesGuard to ValidationPipe + controller
- ValidationPipe + controller to ResponseInterceptor
- ResponseInterceptor to Cleanup
- TenantResolverMiddleware to public.tenants: lookup
- RateLimitGuard to Redis: sliding window
- SessionGuard to Redis: cache read
Middleware and guard order for a tenant route.
Request lifecycle
Order matters. The tenant is resolved first, then the schema is pinned, then rate limiting runs before any token is parsed. Guards run only on routes marked @Protected().
Components and connections (12 / 13)
- Layer 1: schema (Process): search_path points at fk_{slug}, so an unfiltered query can only touch one tenant.
- fk_other (Database): Another tenant. Dropped explicitly with DROP SCHEMA ... CASCADE when the tenant is deleted (ADR-0005).
- Tenant request (Client): Any route except /health*, /.well-known/*, /superadmin/*, POST /tenants/register, GET /tenants/slug-check and /saml/metadata/*.
- Resolve tenant (Process): custom domain, subdomain, X-Tenant-Slug, then X-Tenant-ID (development or ALLOW_TENANT_ID_HEADER).
- QueryRunner in AsyncLocalStorage (Service): search_path is pinned for the request. The DataSource proxy makes every repository use this runner without per-query changes.
- fk_acme (Database): Users, sessions, roles, policies, OAuth clients, MFA, audit and security events for one tenant.
- Layer 2: tenant_id (Process): Tenant tables keep tenant_id and every query keeps WHERE tenant_id = ... as defence in depth.
- TenantSchemaService (Service): createSchema under a Postgres advisory lock so concurrent pods cannot race; dropSchema on deletion. No foreign keys to public.tenants.
- public schema (Database): tenants, key_pairs, migrations and admin users. Platform-level, never tenant-scoped.
- TenantBindingGuard (Service): A token minted for tenant A is rejected on tenant B even with a valid signature.
- template schema (Database): Maintained by migrations. New tenants are cloned from it with CREATE TABLE ... (LIKE template.table INCLUDING ALL).
- TenantJobRunner (Service): Cron and queue work outside a request sets tenant context explicitly and runs under a cluster-wide advisory lock.
- Tenant request to Resolve tenant
- Resolve tenant to QueryRunner in AsyncLocalStorage: req.tenant
- QueryRunner in AsyncLocalStorage to Layer 1: schema
- QueryRunner in AsyncLocalStorage to Layer 2: tenant_id
- Resolve tenant to public schema: lookup
- TenantBindingGuard to QueryRunner in AsyncLocalStorage: token tenant must match
- Layer 1: schema to fk_other
- Layer 1: schema to fk_acme
- template schema to fk_acme: cloned from
- template schema to fk_other: cloned from
- TenantSchemaService to template schema: LIKE ... INCLUDING ALL
- TenantSchemaService to fk_acme: create / drop
- TenantJobRunner to QueryRunner in AsyncLocalStorage: sets context
Schema per tenant with a row-level second layer.
Tenant isolation
Isolation does not depend on foreign keys. It comes from search_path and from tenant_id filters, which is why ADR-0005 could drop the cross-schema constraints that stopped tenant deletion from scaling.
Components and connections (12 / 12)
- Logout / password reset (Process): Revokes the session in Postgres and Redis and revokes the user refresh tokens.
- Successful login (Process): Any completed method (password, magic link, social, passkey) plus any required second factor.
- MFA enrollment token (Service): HS256 JWT signed with JWT_SECRET, 5 minutes, cookie scoped to /auth/mfa/enroll.
- Session (Database): Row in fk_*.sessions plus a Redis cache entry. TTL is SESSION_TTL (7 days). Records the methods used as amr.
- Access token (Service): RS256 JWT with kid, 15 minutes, httpOnly cookie. Never returned in the response body (ADR-0003). Carries amr and authTime.
- Refresh token (Service): 256-bit opaque value, SHA-256 hashed at rest, 30 days, rotated on every use, httpOnly cookie.
- JwksService (Service): Single instance. Chooses the tenant key when one exists, resolves verification keys by kid, re-validates its cache against the DB every 5 minutes.
- Refresh family (Process): Presenting an already-used token revokes the entire family (stolen-token detection).
- public.key_pairs (Database): RSA-2048 pairs. Private keys are AES-256-GCM encrypted with a key derived from KEYRING_MASTER_KEY.
- KeyRotationService (Process): Daily cron under a cluster-wide lock. Retires keys older than 90 days, provisions missing tenant keys and revokes retired keys after a 7 day grace.
- SecurityNotifier (Service): Emails the user a session-reuse alert after reuse is detected. Failures never fail the request.
- /.well-known/jwks.json (External): Published verification keys (active and retired) for relying parties.
- Successful login to Session: creates
- Successful login to Access token: issues
- Successful login to Refresh token: issues
- Refresh token to Refresh family: grouped in
- Refresh family to SecurityNotifier: on reuse
- Access token to JwksService: signed with
- JwksService to public.key_pairs: loads / creates
- KeyRotationService to public.key_pairs: rotates
- JwksService to /.well-known/jwks.json: publishes
- Logout / password reset to Session: revokes
- Logout / password reset to Refresh token: revokes
- MFA enrollment token to Successful login: pre-session enrolment
What a login produces and how keys rotate.
Tokens, sessions and signing keys
Access tokens are short and cookie-only, refresh tokens rotate in families, and each tenant signs with its own key. A daily job rotates keys that are past their active lifetime and retires old ones after a grace window.
Components and connections (13 / 16)
- Password (Client): Argon2id verification, strength rules, reuse check against the last 5, lockout after 5 attempts in 15 minutes.
- Magic link (Client): Link-first sign-in with 256-bit one-time tokens. Cross-device polling needs a 6-digit number match (ADR-0007).
- Social login (Client): Google, GitHub or Microsoft. Finds or creates the user in the tenant schema and claims a session.
- Passkey (Client): WebAuthn Level 2 through SimpleWebAuthn, with an atomic signature counter for clone detection.
- BruteForceService + RateLimitGuard (Service): Per-account lockout plus Redis rate limits on every auth endpoint.
- TenantMfaPolicy (Service): Decides whether a second factor is required for this tenant and user. Enforced on all login paths.
- Pre-session enrollment (Process): If policy requires MFA and none is enrolled, a short-lived enrollment token lets the user enrol before getting a session.
- TOTP + backup codes (Service): Authenticator app codes, with Argon2id-hashed single-use backup codes.
- WebAuthn credential (Service): Hardware key or passkey as a second factor.
- Email OTP (Service): Stored hashed in Redis with a TTL, 5 attempts and single use. Only allowed when nothing stronger is enrolled.
- Security events (Database): Auth, MFA and admin actions recorded with requestId and outcome; metadata redacted recursively.
- Session + cookies (Service): Server-side session, httpOnly access and refresh cookies, amr recorded.
- Step-up (POST /auth/reauth) (Process): Must be as strong as sign-in: with an enrolled second factor the password alone is refused. Its amr is exactly the factors proven in that request.
- Password to BruteForceService + RateLimitGuard
- BruteForceService + RateLimitGuard to TenantMfaPolicy: credentials ok
- Magic link to TenantMfaPolicy: link verified
- Social login to TenantMfaPolicy: profile claimed
- Passkey to TenantMfaPolicy: assertion ok
- TenantMfaPolicy to TOTP + backup codes: required
- TenantMfaPolicy to WebAuthn credential: required
- TenantMfaPolicy to Email OTP: required
- TenantMfaPolicy to Pre-session enrollment: required, none enrolled
- Pre-session enrollment to Session + cookies
- TenantMfaPolicy to Session + cookies: not required
- TOTP + backup codes to Session + cookies
- WebAuthn credential to Session + cookies
- Email OTP to Session + cookies
- Session + cookies to Step-up (POST /auth/reauth): sensitive action
- Session + cookies to Security events: records
Four ways in, one MFA policy gate, one session.
Sign-in and MFA flows
Every method converges on TenantMfaPolicy. Email codes are allowed as a second factor only when nothing stronger is enrolled, so a mailbox takeover cannot bypass TOTP or a passkey.
Components and connections (9 / 11)
- Discovery + JWKS (External): /.well-known/openid-configuration (issuer matches the token iss) and /.well-known/jwks.json.
- Relying party app (External): Registered OAuth client. Public clients must use PKCE.
- GET /oauth/authorize (Service): Validates client_id, redirect_uri, scope and PKCE. Invalid requests get a 400 and are never redirected.
- Hosted login /u/login (Client): Portal page used when there is no valid session cookie. Returns to the authorize URL through continue.
- Consent /u/consent (Client): Shown when the client requires consent. Decisions are stored in oauth_consents.
- Authorization code (Database): Bound to client, redirect URI, S256 challenge, amr and authTime; spent once.
- POST /oauth/token (Service): authorization_code with verifier, client_credentials and refresh_token grants. PKCE verification is constant-time.
- Access, ID and refresh tokens (Service): RS256 JWTs signed with the tenant key. Refresh tokens rotate within a family.
- userinfo, introspect, revoke, end_session (Service): Resource and logout endpoints alongside the token endpoint.
- Relying party app to Discovery + JWKS: fetch metadata
- Relying party app to GET /oauth/authorize: browser redirect, code_challenge S256
- GET /oauth/authorize to Hosted login /u/login: no session
- Hosted login /u/login to GET /oauth/authorize: continue
- GET /oauth/authorize to Consent /u/consent: consent needed
- GET /oauth/authorize to Authorization code: issue
- Consent /u/consent to Authorization code: approved
- Authorization code to Relying party app: 302 redirect_uri?code
- Relying party app to POST /oauth/token: code + code_verifier
- POST /oauth/token to Access, ID and refresh tokens: issue
- Access, ID and refresh tokens to userinfo, introspect, revoke, end_session
Authorization code with PKCE, end to end.
OAuth 2.0 and OIDC
Sentry is an OIDC provider as well as a login system. Only S256 PKCE is accepted and public clients must use it. Discovery issuer matches the token iss.
Components and connections (11 / 11)
- SAML service provider (External): Starts SP-initiated SSO at /saml/sso/{tenantSlug}. Metadata at /saml/metadata/{tenantSlug}.
- SCIM client / IdP (External): Provisions users and groups with a per-tenant bearer token.
- LDAP directory (External): Customer directory pulled on demand with POST /ldap/connections/{id}/sync.
- SamlService (samlify) (Service): Peeks the issuer, re-validates it against the tenant active SamlServiceProvider, and signs the response with XML-DSig using the tenant key.
- ScimGuard + ScimController (Service): Validates the SCIM token (ScimTokenService) and serves SCIM v2 users, groups and patch operations.
- LdapService (Service): Resolves the host once, checks every address, dials the checked IP with certificate verification on. Private ranges need LDAP_ALLOWED_PRIVATE_CIDRS.
- SSO continuation nonce (Database): Stored for 10 minutes and bound to the initiating browser by the saml_sso_nonce cookie, closing a login-CSRF path.
- Tenant signing key (Database): Per-tenant key from key_pairs (ADR-0004) shared by JWTs, OAuth tokens and SAML assertions for that tenant only.
- Deactivation safety valve (Process): Users missing from the directory are deactivated, never deleted. A sync that would deactivate more than 20 percent aborts and is audited.
- Hosted login (Client): User authenticates normally; the flow resumes at GET /saml/sso/continue/{nonce}.
- Tenant users and groups (Database): fk_{slug}.users and groups, tagged with the connection that provisioned them.
- SAML service provider to SamlService (samlify): AuthnRequest
- SamlService (samlify) to SSO continuation nonce: store
- SSO continuation nonce to Hosted login: redirect to login
- Hosted login to SamlService (samlify): continue after login
- SamlService (samlify) to Tenant signing key: sign assertion
- SamlService (samlify) to SAML service provider: signed response
- SCIM client / IdP to ScimGuard + ScimController: SCIM v2
- ScimGuard + ScimController to Tenant users and groups: create / update
- LDAP directory to LdapService: bind + search
- LdapService to Deactivation safety valve: diff
- Deactivation safety valve to Tenant users and groups: create / deactivate
Enterprise federation paths and their guard rails.
SAML, SCIM and LDAP
SAML signs with the tenant key and binds the continuation to the browser; LDAP is SSRF-checked and cannot mass-deactivate users; SCIM is token-guarded per tenant.
Components and connections (11 / 10)
- Domain services (Service): Auth, MFA, session, RBAC and tenant services publish in-process DomainEvents after the DB transaction commits.
- x-request-id (Process): Accepted from the client only if it matches the allowed pattern, otherwise a UUID. Echoed in headers, error bodies and audit rows.
- SecurityNotifier (Service): Subscribes and emails the affected user: refresh reuse, cloned passkey, MFA enabled or disabled, password changed, account locked, ownership transferred.
- SecurityEventService (Service): Writes security_events with requestId and outcome. Metadata is redacted at every nesting depth. CSV export is formula-injection safe.
- MailService.enqueue (Service): Mail is never sent inline with a request.
- Webhook module (Service): Tenant-scoped endpoints with event filters. Events are sent about 500 ms after they occur so the request has committed.
- BullMQ mail.send (Queue): 3 attempts with exponential backoff; completed jobs purged after 1 hour, failed kept 24 hours.
- BullMQ webhook delivery (Queue): Retries and manual redelivery keep the same delivery id, which receivers use as the idempotency key.
- MailProcessor + @repo/emails (Service): Renders HTML and text with React Email after sanitising display text and rejecting non-http(s) URLs.
- Webhook receiver (External): Verifies X-Sentry-Signature (HMAC-SHA256 of the raw body). Private, loopback and metadata addresses are rejected; DNS fails closed and redirects are not followed.
- SES, SMTP or Console (External): Provider order SES then SMTP then Console. Console is refused in production.
- Domain services to SecurityNotifier: DomainEvents
- Domain services to SecurityEventService: security events
- Domain services to Webhook module: events
- SecurityNotifier to MailService.enqueue
- MailService.enqueue to BullMQ mail.send: enqueue
- BullMQ mail.send to MailProcessor + @repo/emails
- MailProcessor + @repo/emails to SES, SMTP or Console: send
- Webhook module to BullMQ webhook delivery: enqueue
- BullMQ webhook delivery to Webhook receiver: signed POST
- x-request-id to SecurityEventService: stored on rows
Everything that leaves the request path.
Mail, events and webhooks
Events are published after commit so listeners never see rolled-back state. Notification failures never fail the originating request.
Components and connections (12 / 12)
- PostgreSQL 16 (Database): public schema plus fk_* tenant schemas.
- packages/ui, shared (Storage): Shared UI kit and utilities.
- packages/database (Storage): TypeORM entities, migrations and the single buildDataSourceOptions() used by runtime, migrations, seeders and scripts.
- packages/security (Storage): Argon2id password hashing, AES-256-GCM, rate limiter.
- packages/emails (Storage): React Email templates and renderEmail().
- apps/admin-portal (Client): Next.js 16 App Router console and hosted login pages, port 3000. TanStack Query v5, Tailwind CSS v4, shadcn/ui.
- apps/auth-service (Service): NestJS 11 API, port 4000.
- apps/docs (Client): Fumadocs site, port 3001.
- packages/sdk-typescript (Storage): @scrolloop/sdk: typed sign-in, account, MFA, session, invite and consent modules for browser, React and Next.js.
- packages/admin-client (Storage): Typed client for the admin API.
- sentry-config + sentry-types (Storage): SDK configuration and shared types.
- Turborepo + CI (Process): Yarn 4 workspaces; typecheck, unit tests and a boot-and-smoke e2e job; Playwright journeys in e2e/.
- apps/auth-service to packages/database: imports
- apps/auth-service to packages/security: imports
- apps/auth-service to packages/emails: imports
- packages/database to PostgreSQL 16: connects
- apps/admin-portal to packages/sdk-typescript: imports
- apps/admin-portal to packages/admin-client: imports
- apps/admin-portal to packages/ui, shared: imports
- packages/sdk-typescript to sentry-config + sentry-types: imports
- packages/admin-client to sentry-config + sentry-types: imports
- apps/admin-portal to apps/auth-service: HTTP API
- Turborepo + CI to apps/auth-service: verifies
- Turborepo + CI to apps/admin-portal: verifies
Apps, shared packages and how they depend on each other.
Monorepo topology
Three apps and a set of focused packages in a Turborepo with Yarn 4. The database package owns the one connection builder used everywhere.
Components and connections (10 / 11)
- Any explicit Deny? (Process): A matching Deny in any policy ends evaluation with DENY. Deny always wins.
- DENY (Component): Implicit deny when nothing grants the action.
- Permission check (Process): A guard or service asks: may this principal perform resource:action, optionally on a specific resource.
- Collect grants (Process): Permissions from every role of the user, plus policy documents attached to the user, its roles and its groups.
- Match policies (Service): PolicyEvaluationService matches action and resource patterns with * wildcards and evaluates conditions (StringEquals, StringLike, Bool, IpAddress).
- Any explicit Allow? (Process): A matching Allow policy grants access.
- Role permissions (Process): No policy matched: fall back to the union of role permissions (resource:action, wildcards allowed).
- ALLOW (Component): Access granted. The UI only hides or disables controls; the backend always enforces.
- RbacCacheService (Database): The single cache for effective permissions and policies. ADR-0002 removed the second cache that disagreed after role changes.
- Permission boundary (Service): A boundary caps what a role can ever grant, even through its own Allow policies.
- Permission check to Collect grants
- Collect grants to RbacCacheService: read / fill
- Collect grants to Match policies
- Match policies to Any explicit Deny?
- Any explicit Deny? to DENY: yes
- Any explicit Deny? to Any explicit Allow?: no
- Permission boundary to Any explicit Allow?: caps
- Any explicit Allow? to ALLOW: yes
- Any explicit Allow? to Role permissions: no
- Role permissions to ALLOW: permission found
- Role permissions to DENY: none
How a permission check resolves.
Authorization evaluation
Roles give additive permissions; policy documents add Allow and Deny with conditions. Explicit deny wins, a permission boundary caps grants, and the absence of any match is a deny.
Components and connections (9 / 8)
- public schema (Database): tenants (slug, custom domain, status, allowed origins), key_pairs (RSA keys, encrypted private halves, status active / retired / revoked), admin users and migrations.
- Identity (Database): users, sessions (with amr), user_invites, social connections and link requests, webauthn_credentials, mfa_settings, password history and backup codes.
- Authorization (Database): roles, permissions, role_permissions, user_roles, policies with role, user and group attachments, groups and user_groups.
- OAuth / OIDC (Database): oauth_clients, authorization codes, access tokens (encrypted at rest), refresh tokens (hashed, family id) and oauth_consents.
- Federation (Database): saml_service_providers, scim_tokens and ldap_connections (bind password stored encrypted and never returned by the API).
- Tenant policy (Database): tenant_password_policy, tenant_mfa_policy, tenant_branding and tenant_social_providers. Defaults apply until a tenant sets its own.
- Operations (Database): security_events (requestId, outcome, redacted metadata), webhook_endpoints and webhook_deliveries.
- template schema (Database): The migration-maintained source of every tenant table. 35 entities and 39 migrations in packages/database.
- No cross-schema foreign keys (Process): Tenant tables keep a plain tenant_id column. Only foreign keys inside a tenant schema (for example sessions.user_id to users.id) are recreated (ADR-0005).
- template schema to Identity: cloned into fk_{slug}
- template schema to Authorization
- template schema to OAuth / OIDC
- template schema to Federation
- template schema to Tenant policy
- template schema to Operations
- public schema to template schema: migrations update
- No cross-schema foreign keys to public schema: no FK to
Entity groups and where they live.
Data model
Thirty-five entities fall into six groups. Everything tenant-owned is cloned from the template schema; only platform data lives in public.
Components and connections (7 / 8)
- Requesting device (Client): Calls send with poll enabled. It alone receives the polling nonce and a 6-digit match code, both hashed server side, tenant-bound, 10 minute lifetime.
- Email with link (External): The link is a 256-bit token; only its SHA-256 is stored.
- GET magic-link/preview (Service): Non-consuming. Shows the requester coarse user agent and IP so the recipient can recognise a request they did not make.
- Plain click (Process): Signs the clicking device in and voids the polling request, so an attacker poll can never collect that session.
- Verify with match code (Service): The confirming device types the code shown on the requesting device. Compared in constant time; five wrong codes void the request and the link is not spent.
- Poll completes (Service): Only a correct match code lets the poll succeed. The requesting device gets the session; the confirming device gets none.
- Residual risk (Process): A user who is socially engineered into typing an attacker code. This is the standard limit of number matching.
- Requesting device to Email with link: send
- Email with link to GET magic-link/preview: inspect
- Email with link to Plain click: same device
- Email with link to Verify with match code: other device
- Requesting device to Verify with match code: user reads code
- Verify with match code to Poll completes: correct code
- Poll completes to Requesting device: session
- Verify with match code to Residual risk
Why a polling nonce alone is unsafe, and what replaces it.
Cross-device magic link
The design closes a device-code-phishing hole: the requesting device must prove it is the one the user is looking at by showing a code the other device types in.
Components and connections (9 / 9)
- First-run setup (Process): On a fresh install the API prints a one-time setup token. The portal /setup page takes it and creates the first platform admin through /superadmin/create-first-admin.
- POST /tenants/register (Client): Self-service workspace creation. Rate limited to 3 per hour per IP; slugs are 4 to 63 characters of lowercase letters, digits and hyphens, with reserved words refused. An idempotency key is supported.
- GET /tenants/slug-check (Client): Live availability check used by the onboarding wizard.
- Create tenant row (Database): public.tenants.
- createSchema (Service): Clones the template schema under an advisory lock.
- ensureTenantKeyExists (Service): Provisions the tenant RSA signing key; idempotent (ADR-0004).
- cleanupFailedRegistration (Process): If any step fails: drop the schema, delete the tenant row and delete the provisioned key, so no encrypted private key is orphaned.
- Bootstrap roles (Process): owner, admin, member and guest system roles. The registering user becomes owner.
- First admin + session (Service): Creates the admin user and sets httpOnly session cookies. No token is in the body.
- POST /tenants/register to Create tenant row
- GET /tenants/slug-check to POST /tenants/register: before submit
- Create tenant row to createSchema
- createSchema to ensureTenantKeyExists
- ensureTenantKeyExists to Bootstrap roles
- Bootstrap roles to First admin + session
- createSchema to cleanupFailedRegistration: on error
- ensureTenantKeyExists to cleanupFailedRegistration: on error
- First-run setup to First admin + session: platform admin
First-run setup and self-service registration.
Tenant onboarding
Provisioning is a sequence with a compensating cleanup, because the key, schema and row are written to different places and no transaction spans them.
Components and connections (10 / 9)
- Next.js middleware (Service): Checks the initialised flag (redirects to /setup), routes subdomains (acme.sentry.scrolloop.com to /t/acme) and applies JWT claim checks for platform and tenant routes.
- app/ routes (Client): Routes only: each page imports one view and passes route params. Groups: /u/* hosted identity, /t/[slug] workspace, platform /dashboard, /tenants, /users, /audit-logs, /settings, /setup, /invite, /mfa.
- constants/feature-flags (Process): Capabilities without a backend contract are false and render ProposedCapabilityView: a Planned badge, a handoff list, no sample data.
- features/*/views (Client): Compose components, api hooks and model functions into a screen or a Planned shell.
- i18n catalogue (Storage): Typed copy: en/{auth,account,tenant,platform,common,errors,states}.
- components + model (Client): Presentational pieces and pure view-models. Copy comes from typed i18n through useCopy(); ESLint forbids string literals in JSX.
- features/*/api (Service): TanStack Query hooks over the SDK, wrapped by withErrorHandler. Query keys are scoped by tenant and principal.
- packages/ui patterns (Storage): Copy-free generic patterns; props carry all text. Tokens only, including success, warning and info.
- @scrolloop/sdk client (Service): One client per tenant: session runtime, typed modules, silent refresh on 401, discriminated AuthOutcome results.
- auth-service API (Service): Enforces everything. usePermission in the UI only hides or disables.
- Next.js middleware to app/ routes: routes request
- app/ routes to features/*/views: imports one view
- features/*/views to components + model
- features/*/views to features/*/api
- features/*/api to @scrolloop/sdk client
- @scrolloop/sdk client to auth-service API: HTTPS + cookies
- components + model to packages/ui patterns: uses
- features/*/views to constants/feature-flags: gated by
- components + model to i18n catalogue: copy
Layering rules for apps/admin-portal.
Admin portal architecture
Dependencies point one way: views to components to model, and views to api to the SDK. Raw fetch is banned outside lib/ and middleware.
Components and connections (7 / 8)
- *.e2e.test hostnames (Network): Chromium host-resolver rules and a Node DNS map give every journey its own tenant subdomain with real shared-parent-domain cookies.
- Playwright journeys (Process): 11 journeys: sign-up and verify, password + TOTP + recovery codes, reset links, magic link variants, invites, step-up, console roles and webhooks, tenant isolation, axe WCAG 2.2 AA, forced MFA, workspace registration.
- Portal (next start) (Client): Built into .next-e2e and served on port 3110.
- auth-service (Service): Booted on port 4110 with test environment overrides, RECENT_AUTH_WINDOW_SECONDS at the service minimum so step-up screens are reachable.
- SMTP sink (External): Port 4125 with an HTTP view on 4126. Journeys read emailed links the way a person would follow them. Nothing is mocked.
- scrolloop_sentry_test (Database): Migrated by the backend own e2e setup. The harness refuses any database name without _test and prunes orphaned e2e tenants.
- Redis DB 15 (Database): Key prefix sentry_e2e. Only rate-limit keys are cleared, never FLUSHALL.
- Playwright journeys to Portal (next start): drives browser
- Playwright journeys to auth-service: direct calls
- Portal (next start) to auth-service: HTTP
- auth-service to SMTP sink: SMTP
- Playwright journeys to SMTP sink: reads emails
- auth-service to scrolloop_sentry_test
- auth-service to Redis DB 15
- *.e2e.test hostnames to Portal (next start): tenant subdomains
How the Playwright tests run against the real stack.
Browser journey harness
No mocks. The real portal talks to the real service, mail goes through a real SMTP sink, and each journey owns a tenant subdomain.