Introducing a new way to review your PRs.

Read the announcement

ever-co / ever-gauzy

Ever® Gauzy™ - Open Business Management Platform (ERP/CRM/HRM/ATS/PM) - https://gauzy.co

View on GitHub

27 documents · Updated Nov 23, 2026

docs / identity-and-access-control

Identity and access control

Identity and access control lets a person or service prove who it is, select a tenant workspace, and use only the data and actions allowed for that identity. The API is the final authority: it validates tokens, account status, role state, tenant scope, and approved third-party app scope on each protected request. Shared auth services also turn user-managed credentials into bounded sessions without weakening that authority. See Backend platform for the wider platform view.

Identity boundary

The identity boundary starts at a public sign-in or registration request and ends with an authenticated request context. The API returns credentials only after it accepts the identity and its account state. The client keeps the session data and sends the access token on later requests.

Account identity

An account is represented by a user identity. The identity can use an email and password, a one-time email code, or a linked social account. The account also carries its tenant, role, organization choice, and optional employee identity. These values give later authorization checks the context they need without treating an email alone as a complete identity. An account must remain active and not archived while it uses a session. A user whose employee records are all inactive or archived is also refused; an active employee record in another organization still permits sign-in.

Placeholder accounts represent members without an account. They have no sign-in identity, and the token-minting boundary refuses to create a session for them even when another employee record or organization is active.

Social provider links are tenant-owned records that connect one provider account identifier to a local user. The API links them only after it verifies the provider identity, its trusted email, and the local account's email state.

References: packages/…/user.entity.ts• L50-191 packages/…/auth.service.ts• L470-579 packages/…/auth.service.ts• L990-1035 packages/…/placeholder-account.ts• L3-13 packages/…/auth.service.ts• L2320-2340 packages/…/deactivated-employee.ts• L1-16 packages/…/social-account.entity.ts• L11-47

Authentication methods

The API supports password sign-in, email magic-code sign-in, social sign-in, registration, email confirmation, and password recovery. Social sign-in first checks the provider token and its verified email. By default it then matches only local accounts that confirmed that email. When several confirmed workspaces match, the person selects one instead of the provider flow choosing one silently. Password recovery uses a separate short-lived purpose-bound token rather than an access token. Password and magic-code checks also use account-scoped failure control so a distributed guessing attack cannot rely only on address-based throttling.

Provider adapters preserve only the email evidence that the provider can support. The API remains responsible for deciding whether that evidence identifies a local account and which workspace may be used.

References: packages/…/auth.controller.ts• L149-298 packages/…/auth.service.ts• L470-579 packages/…/auth.service.ts• L782-969 packages/…/social-auth-emails.ts• L1-54 packages/…/email-confirmation.service.ts• L45-110 packages/…/login-attempt.service.ts• L323-352

Purpose-bound tokens

Purpose-bound tokens carry a claim that names the flow that may consume them. The shared verifier checks the signature algorithm, expiry, purpose, and required identity claims before a flow uses the payload. This prevents a valid token from one flow, such as an invite or password reset, from becoming proof for another flow, such as workspace sign-in.

References: packages/…/purpose-token.ts• L7-35 packages/…/purpose-token.ts• L55-67 packages/…/purpose-token.ts• L80-137

Registration binds a new account to the legal documents that the API currently requires. The client loads the published documents for the selected language and sends those same documents with the registration request. The API validates the document claims before it creates the account and records the accepted document version after the account exists.

Self-registration is inactive until email confirmation by default. Invited accounts and accounts created inside a tenant follow their trusted creation path instead. Registration policy can close public sign-up or new tenant creation without closing invitations, administrator-created users, or sign-in.

References: packages/…/register.component.ts• L25-189 packages/…/signup-email-verification.ts• L1-25 packages/…/auth.service.ts• L1493-1752 packages/…/registration-policy.service.ts• L7-113

Token pair

An access token proves the current session to protected API routes. A refresh token is a separate credential that the API checks against its token service and the user identity before it issues a new pair. Both validations reject an account that is missing, inactive, archived, or no longer has a usable employee state. Logout revokes the supplied refresh token and the current access token when possible.

New access tokens omit the role's permission list by default. The API loads current role permissions during token validation, so a role change does not wait for an old token to expire. Third-party OAuth app tokens carry a separate approved-scope claim and are narrowed after normal identity and role checks. When the API refreshes a token pair, it keeps the organization carried by that refresh token while the user remains an active member. A missing or stale organization falls back to the stored organization and its normal membership checks.

References: packages/…/auth.controller.ts• L300-355 packages/…/jwt.strategy.ts• L75-145 packages/…/jwt.strategy.ts• L274-418 packages/…/jwt-refresh-token.strategy.ts• L42-123 packages/…/auth.service.ts• L907-987 packages/…/auth.service.ts• L2133-2257 packages/…/auth.service.ts• L2340-2420 packages/…/oauth-app-scope.ts• L1-27

Embedded sessions

An embedded session is a short-lived access token for a client application that acts for one tenant member. The API can create it from an embedded credential or from a person's approved site grant. The token carries the tenant, organization, employee, origin, and optional client boundary needed to keep the embedded experience inside its approved context. It has no refresh token and ends at its assigned expiry.

Embedded access is narrower than the member's normal role. JWT validation records the embedded credential and intersects the current role permissions with the small set of timer and team permissions allowed to embedded clients. Route and request-scope checks then keep reads and writes within the token's member, organization, tenant, and permitted client. A normal first-party token for the same person keeps its normal permissions.

This diagram shows how an embedded credential or site grant becomes a bounded API session.

sequenceDiagram
    participant W as Widget or embedded client
    participant A as Auth API
    participant T as Token service
    participant P as Protected API
    W->>A: Present credential or approved site grant
    A->>A: Check member, tenant, organization, origin, and client scope
    A->>T: Issue short-lived embedded access token
    T-->>W: Access token without refresh token
    W->>P: Use bearer access token
    P->>P: Validate identity and narrow role permissions
    P-->>W: Only approved embedded data or timer action

References: packages/…/auth.service.ts• L752-784 packages/…/embed-session.ts• L11-29 packages/…/embed-session.ts• L78-121 packages/…/jwt.strategy.ts• L269-300 packages/…/jwt.strategy.embed-token.spec.ts• L159-297

Two-factor authentication

Two-factor authentication adds a second proof after a password, email code, or social/workspace identity has been accepted. A sign-in with two-factor enabled receives a short-lived challenge instead of a session; the API issues the access and refresh tokens only after it accepts an authenticator code or a single-use recovery code.

Users enroll with a time-based code from an authenticator app. The API keeps the authenticator secret encrypted and gives recovery codes only when setup is confirmed. Each time step and each recovery code can be used once. An organization can require setup for its members, while an operator switch controls whether new enrollment is open. A first-party session can manage its own factor; an authorized administrator can reset a member's factor.

This diagram shows how a first-factor sign-in becomes a session only after the second-factor proof succeeds.

sequenceDiagram
    participant C as Client
    participant A as Auth API
    participant F as Two-factor service
    participant T as Token services
    C->>A: Submit password, email code, or workspace proof
    A->>F: Check whether a second factor is required
    F-->>A: Short-lived challenge
    A-->>C: Challenge without session tokens
    C->>A: Submit challenge and authenticator or recovery code
    A->>F: Verify and consume the second factor
    F-->>A: Accepted proof
    A->>T: Issue access and refresh tokens
    T-->>C: Tenant-scoped session

References: packages/…/two-factor-challenge.ts• L11-25 packages/…/totp.ts• L4-19 packages/…/recovery-codes.ts• L5-13 packages/…/user-two-factor.service.ts• L62-73 packages/…/user-two-factor.service.ts• L220-317 packages/…/two-factor.controller.ts• L46-53 packages/…/auth.service.ts• L678-732 packages/…/auth.service.ts• L2898-2978

User sessions

A user session groups the access and refresh tokens created by one sign-in on one device or app. Session claims let the user see active first-party sessions and sign out another session as a whole. Personal API-token and third-party application credentials are not user sessions.

The API records a bounded description of the client that opened a session, such as its app, web host, browser, and operating system. Sign-out writes a session marker before it revokes the stored tokens. Access-token validation, refresh validation, and later token minting all honor that marker, including tokens created during a sign-out race.

References: packages/…/user-session-claims.ts• L5-20 packages/…/user-session-claims.ts• L87-125 packages/…/user-session-client.ts• L40-63 packages/…/user-session-list.ts• L27-75 packages/…/user-session.service.ts• L72-85 packages/…/user-session.service.ts• L98-176 packages/…/user-session-revocation.ts• L1-21 packages/…/jwt.strategy.ts• L127-175 packages/…/jwt-refresh-token.strategy.ts• L99-123

Personal API token sessions

Personal API tokens give a user a long-lived credential for an agent or script without creating a second user identity. The user creates, lists, and revokes only their own tokens from a first-party session. The API stores only a digest and returns the secret once. An expiry and a limit on active tokens bind the credential.

The public exchange endpoint turns a valid personal token into an ordinary short-lived access token. The exchange uses the token's tenant and checks the current account, employee state, and organization membership before minting the session. The resulting token carries the user's current role and permissions through the normal JWT path. It has no refresh token and cannot outlive the personal token. Revocation stops later exchanges; an already exchanged session ends at its short session limit.

The API marks the resulting session so it can block actions that would create access that survives the personal token. This includes creating another personal token, minting first-party tokens through workspace or organization changes, approving or changing OAuth clients, creating another persistent credential, and changing account credentials. The session can still use ordinary tenant and permission checks for permitted work.

This diagram shows how a user-managed credential becomes a normal tenant-aware session while keeping credential creation behind a first-party boundary.

sequenceDiagram
    participant S as Script or agent
    participant E as API-token exchange
    participant A as Auth service
    participant P as Protected API
    S->>E: Submit personal API token
    E->>E: Check shape, digest, expiry, and revocation
    E->>A: Check owner, tenant, employee, and organization
    A-->>E: Short-lived access token with API-token marker
    E-->>S: Access token
    S->>P: Use bearer access token
    P->>P: Apply normal JWT, tenant, role, and permission checks

References: packages/…/user-api-token.controller.ts• L30-116 packages/…/user-api-token.service.ts• L39-50 packages/…/user-api-token.service.ts• L130-231 packages/…/user-api-token.entity.ts• L12-71 packages/…/user-api-token.utils.ts• L4-52 packages/…/user-api-token-session.ts• L5-45 packages/…/auth.service.ts• L752-842

Validated context reuse

Access-token validation normally rechecks the user, current authorization state, employee claim, and organization membership against the database. An optional per-process cache can reuse a recently validated context for the same identity and scope claims. The default window is zero and the maximum is five minutes.

The cache keeps only successful validation results. Each request gets its own user copy. OAuth app and embedded scope narrowing happens after cache reuse, so a scoped request cannot leave narrowed permissions or grant markers in the cache for a later first-party request.

References: packages/…/authenticated-user-cache.ts• L14-31 packages/…/authenticated-user-cache.ts• L96-112 packages/…/authenticated-user-cache.ts• L142-224 packages/…/jwt.strategy.ts• L133-146

Tenant identity

A tenant is the workspace boundary for data and access rules. A user can belong to more than one tenant and can select one as the active workspace. The selected tenant is placed in the authenticated identity and must agree with the tenant information sent by the client.

Workspace selection

Workspace discovery returns the tenants available to the authenticated user. Access to other accounts that share the user's email requires that the caller has confirmed the current address. Workspace switching checks membership before it returns tokens scoped to the target tenant. Organization switching applies the same idea inside the current tenant.

The stored organization is a preference, not proof of membership. If it is stale, sign-in and token refresh replace it with the first active membership or clear it when none exists. A third-party OAuth app or personal API-token session cannot use switching to mint a first-party token. A refresh token keeps its own active organization, so switching one client does not move another client when that client renews its session.

References: packages/…/auth.controller.ts• L357-437 packages/…/auth.service.ts• L553-637 packages/…/auth.service.ts• L907-987 packages/…/auth.service.ts• L3022-3268 packages/…/oauth-app-first-party.ts• L5-32

Request scope

The request context is the shared server view of the current user, tenant, organization, role, permissions, and token grant. It is created for each request and is available to guards and tenant-aware services. JWT validation checks employee and organization membership before it puts those values into this context.

References: packages/…/request-context.middleware.ts• L8-61 packages/…/request-context.ts• L159-207 packages/…/jwt.strategy.ts• L274-418 packages/…/role-authorization.service.ts• L24-149

Tenant checks

Tenant checks prevent a valid identity from using the same request to reach another workspace. The tenant guard compares the active tenant with the tenant header or with tenant data in the request. API-key and similar service credentials use the tenant that owns the valid credential.

References: packages/…/tenant-base.guard.ts• L8-18 packages/…/tenant-base.guard.ts• L20-100 packages/…/api-key-auth.guard.ts• L17-45

Authorization model

Authorization answers whether an already identified actor may perform an action. The model combines tenant scope, role membership, named permissions, organization policy, and any narrower third-party app or embedded grant. The API resolves current role and permission state during token validation and fails closed when it cannot establish the needed state.

Authentication guard

The authentication guard protects routes by validating a bearer access token. A route marked public can skip this check, which is required for sign-in and token exchange entry points. The JWT strategy rejects tokens without a user identity and checks account status, employee claims, and organization claims before it accepts the request. A database outage is reported as a temporary service failure rather than as a bad token.

References: packages/…/auth.guard.ts• L8-56 packages/…/jwt.strategy.ts• L75-125 packages/…/auth.controller.ts• L66-79

Role and permission checks

Role checks answer whether the identity has one of the roles required by a route. Permission checks answer whether the active role has the named action permission in the active tenant. Client checks control the view only; protected API routes still perform the server check. OAuth app and embedded grants narrow the user's current permissions and the permissions declared by a route before the guard decides.

Role assignment and role administration are separate decisions. They resolve roles inside the caller's active tenant and keep platform roles reserved. Role management remains behind tenant and permission checks.

References: packages/…/role.guard.ts• L9-33 packages/…/permission.guard.ts• L29-91 packages/…/tenant-permission.guard.ts• L63-109 packages/…/role-authorization.service.ts• L24-149 packages/…/role.service.ts• L185-324 packages/…/jwt.strategy.ts• L228-300

Invitation access

Invitation access combines tenant scope, invitation permissions, team management, and the role being granted. A caller without an organization-wide grant can reach only invitations for teams they manage or invitations with no team. Creating, resending, or deleting an invitation requires control of every team that the invitation affects.

Invitation roles cannot exceed the inviter's stored role. Invitation creation stays with a first-party session rather than a delegated OAuth app token or a personal API-token session.

References: packages/…/invite.service.ts• L93-163 packages/…/invite.service.ts• L329-408 packages/…/invite.service.ts• L988-1119 packages/…/oauth-app-first-party.ts• L14-22

OAuth app scope boundary

Third-party OAuth app access is a narrower authorization grant than the user's own session. The code exchange records the approved client and scopes in the access token. During request authentication, the API intersects those scopes with the user's current role permissions. Identity scopes grant no permission, while read and write scopes grant only their mapped actions.

The boundary also blocks actions that create or extend first-party control. This includes creating accounts, sending invitations, deleting users, approving apps, minting first-party tokens, and creating personal API tokens. OAuth clients must be registered, redirect addresses must match exactly, and authorization codes are short-lived and single-use.

References: packages/…/oauth-app-scope.ts• L1-27 packages/…/oauth-app-scope.ts• L99-154 packages/…/jwt.strategy.ts• L226-264 packages/…/oauth-app-first-party.ts• L5-32 packages/…/auth.service.ts• L383-582

Embedded access boundary

Embedded access is a separate narrow grant for timer and team features inside another application. It does not give the embedded client the member's full role or the exemptions of an administrator. The API keeps the grant tied to the signed token's employee, organization, tenant, origin, and optional organization contact.

The embedded route boundary accepts only the routes and request fields needed by the widget. The permission boundary allows only the timer and team permissions that the member's role already has. This prevents a powerful member's embedded token from becoming a general workspace token and prevents a forged narrowing claim from expanding access.

References: packages/…/embed-session.ts• L78-121 packages/…/embed-session.ts• L324-386 packages/…/embed-session.ts• L389-418 packages/…/jwt.strategy.ts• L269-300 packages/…/jwt.strategy.embed-token.spec.ts• L159-297

OAuth client registry

The OAuth client registry gives each third-party app its own identity and secret. Tenant-scoped clients serve only their owner tenant; global clients are available across tenants to super administrators. The API generates client identifiers and secrets. It stores the client-secret verifier and keeps the code-signing secret server-side. Secret rotation returns the new plaintext secret once and prevents new exchanges with the old secret.

Client lookup for public OAuth flows is by client identifier and active state. Administrative reads and changes still apply tenant visibility. Current registration accepts confidential clients; public PKCE clients are not yet usable through this path.

References: packages/…/oauth-client.service.ts• L1-20 packages/…/oauth-client.service.ts• L75-155 packages/…/oauth-client.service.ts• L177-239 packages/…/oauth-client.service.ts• L279-347

Tracked-data access

Tracked-data access adds an organization setting to the normal role and tenant checks for employee callers. Administrators with the employee-change permission can view the data. Other employees can view it only when each affected organization allows it or when they manage an active team or project there.

References: packages/…/employee-tracked-data.guard.ts• L7-31 packages/…/employee-tracked-data.guard.ts• L34-184

Organization policies

Organization policies add a second boundary to actions such as manual time entry, time changes, and time deletion. The organization guard checks every organization touched by a request and resolves target records inside the caller's tenant. It applies to every role.

References: packages/…/organization-permission.guard.ts• L26-38 packages/…/organization-permission.guard.ts• L64-180 packages/…/organization-permission.guard.ts• L570-645

Shared auth package

The @gauzy/auth package is the shared auth boundary for social provider strategies, OpenID Connect provider flows, OAuth application flows, and the MCP OAuth authorization server. The API registers it with application-specific services, so common provider behavior uses the API's user, tenant, membership, and token rules. The API auth module also connects the shared boundary to local two-factor, session, login-attempt, and token services.

Social provider boundary

Social provider strategies verify credentials issued by an external provider before the API maps them to a local account. The shared package exposes provider controllers and strategies, while the API auth service owns the local user, trusted email, social-account link, and workspace decision. A provider-verified email is not by itself proof of a local account.

References: packages/…/social-auth.module.ts• L1-41 packages/…/social-auth.service.ts• L68-205 packages/…/social-auth-emails.ts• L1-54 packages/…/auth.module.ts• L69-95 packages/…/auth.service.ts• L1151-1220

OpenID Connect provider boundary

The shared OpenID Connect client gives provider plugins one boundary for browser sign-in, token exchange, and token checks. A plugin supplies the issuer and client settings. The library protects the authorization transaction with state, nonce, and PKCE and validates issuer metadata, signing keys, claims, and audiences. It returns verified identity data but leaves local account linking, email trust, tenant choice, and authorization decisions to the caller.

References: packages/…/README.md• L31-40 packages/…/index.ts• L1-36 packages/…/oidc-client.service.ts• L66-257 packages/…/oidc-transaction.service.ts• L9-22

First-party token sign-in

The first-party token sign-in boundary lets an approved client hand a user identity to the API through an OpenID Connect token. The API selects a configured issuer, verifies the token, and checks its audience before it uses the subject. It then applies the normal workspace and tenant flow.

References: packages/…/zitadel-token-signin.service.ts• L82-175 packages/…/zitadel-token.e2e.spec.ts• L27-129 packages/…/oidc-client.service.ts• L181-231

Login attempt control

Login attempt control limits credential guessing by account and credential family. Password, magic-code, team-join-code, and two-factor-code attempts have separate counters. Redis shares the count across API replicas when available. A bounded in-process store keeps the check available when Redis is absent or slow.

Password checks use a distributed-guessing rule that needs failures from more than one client source before an account block. Two-factor checks use a stricter rule because the first factor has already been proven. Infrastructure failures release the reservation instead of counting a bad credential.

References: packages/…/login-attempt.service.ts• L11-20 packages/…/login-attempt.service.ts• L344-373 packages/…/login-attempt.service.ts• L460-504 packages/…/user-two-factor.service.ts• L35-46 packages/…/oauth-authorization-server.ts• L84-92

MCP OAuth boundary

The shared package provides an OAuth 2.0 authorization server for MCP clients. It supports authorization code with PKCE, refresh-token, and client-credentials grants. A host supplies the user authenticator and user information provider. The server handles consent, redirect checks, token exchange, token introspection, sessions, CSRF protection, and rate limits.

The server accepts the collaboration scopes chat, docs, and inbox with read and write forms alongside the general MCP scopes. It keeps account state live after sign-in: code exchange, refresh, and introspection recheck the account, while a configured periodic sweep revokes tokens for accounts that can no longer sign in. A failed account lookup is retryable and does not revoke or consume usable credentials.

Production use requires durable session storage so authentication state can survive more than one process. Only an operator-registered resource server may use introspection. Dynamic registration cannot grant client credentials, and client-credentials tokens are limited to confidential clients that were configured for that grant.

References: packages/…/authorization-config.ts• L8-27 packages/…/oauth-authorization-server.ts• L22-66 packages/…/oauth-authorization-server.ts• L186-249 packages/…/oauth-authorization-server.ts• L661-715 packages/…/oauth-authorization-server.ts• L1382-1705 packages/…/oauth-authorization-server.ts• L1717-1805 packages/…/oauth-token-manager.ts• L227-389

MCP client registry

The MCP client registry gives each MCP application a client identity, redirect list, grant list, and approved scope list. It supports public clients without secrets and confidential clients with hashed secrets. Dynamic registrations are bounded, and the registry removes unused registrations before it removes least-recently-used registrations that have already obtained tokens.

The registry accepts general MCP scopes and the collaboration read and write scopes. Unknown scopes are dropped; a request with no known scope is rejected. Resource servers are registered through a separate operator-controlled path, so an arbitrary dynamically registered client cannot call token introspection.

References: packages/…/oauth-client-manager.ts• L13-30 packages/…/oauth-client-manager.ts• L48-85 packages/…/oauth-client-manager.ts• L166-212 packages/…/oauth-client-manager.ts• L222-357 packages/…/oauth-client-manager.ts• L536-576 packages/…/oauth-client-manager.collaboration-scopes.spec.ts• L1-34

Client session

The client auth layer turns API identity results into a usable application session. It keeps the user, access token, refresh token, tenant, organization, and role permissions available to route guards and request interceptors.

Session state

The shared client Store keeps short-lived application state and persisted session state apart. It tracks the active user and workspace for the current UI and persists the token pair plus selected tenant and organization so the application can restore a session.

References: packages/…/store.service.ts• L25-57 packages/…/store.service.ts• L71-112 packages/…/store.service.ts• L277-329 packages/…/store.service.ts• L483-520

Request headers

The tenant interceptor adds the active tenant and selected organization to outgoing requests when a user is present. The access token is sent as a bearer header by the request path that calls the API.

References: packages/…/tenant.interceptor.ts• L19-57 packages/…/auth-refresh.interceptor.ts• L114-126

Token renewal

When a protected request returns unauthorized, the client makes one refresh request and makes other failed requests wait for the same new access token. Auth endpoints do not trigger renewal. The API keeps the organization of the refresh token when it issues the new pair, so another client changing the account's stored organization does not silently move this session. If renewal fails, the client clears the token pair and sends the user to sign-in.

References: packages/…/auth-refresh.interceptor.ts• L21-97 packages/…/auth-refresh.interceptor.ts• L100-169 packages/…/auth.service.ts• L907-987 packages/…/auth.service.ts• L2340-2420

Route protection

The client route guard checks the token shape and asks the API whether the session is authenticated before it allows navigation. It clears the session and preserves the intended return URL when the check fails. This is a navigation aid, not a replacement for API authorization.

References: packages/…/auth.guard.ts• L17-50 packages/…/auth.service.ts• L20-32

Authentication flows

The main identity flows connect public entry points, server validation, tenant selection, and protected use. The API remains authoritative at every boundary.

Email verification

Email verification confirms control of an account's email before the account uses the verified state. The API can send a signed link or a tenant-bound code, stores the link token in protected form, and accepts each code only once. A requested redirect is used only when its origin belongs to the deployment's approved origins.

References: packages/…/email-confirmation.service.ts• L45-110 packages/…/email-confirmation.service.ts• L146-175 packages/…/email-link-origin.ts• L14-21 packages/…/email-link-origin.ts• L105-215

Password sign-in

Password sign-in first reserves an account-scoped attempt. It resolves active local accounts, validates the password and employee state, selects an organization scope when one is available, and returns the token pair. A wrong credential counts as a failure. An infrastructure error releases the reservation without counting a failed password. If the account has two-factor authentication enabled, the API returns a challenge instead of the token pair.

This diagram shows the normal password path from the client to a tenant-scoped session.

sequenceDiagram
    participant C as Client
    participant A as Auth API
    participant L as Login control
    participant U as User and membership data
    participant F as Two-factor service
    participant T as Token services
    C->>A: Submit email and password
    A->>L: Reserve account-scoped attempt
    A->>U: Find active account and membership
    U-->>A: User, tenant, role, organization context
    A->>F: Check second-factor state
    F-->>A: No challenge or short-lived challenge
    A->>T: Issue tokens when no challenge is needed
    T-->>A: Token pair
    A-->>C: User and session or second-factor challenge

References: packages/…/auth.service.ts• L31-45 packages/…/auth.service.ts• L591-749 packages/…/login-attempt.service.ts• L421-504 packages/…/two-factor-challenge.ts• L41-66

Magic-code sign-in

Magic-code sign-in checks the email and code under account-scoped attempt control. It then presents the user's available workspaces. A valid code is claimed once before the API returns workspace tokens. A confirmed workspace token completes sign-in for the selected tenant. If the selected account has two-factor authentication enabled, workspace completion returns a second-factor challenge before it issues a session.

References: packages/…/auth.controller.ts• L163-264 packages/…/auth.service.ts• L825-929 packages/…/auth.service.ts• L2260-2389 packages/…/auth.service.ts• L2898-2978 packages/…/workspace-selection.component.ts• L13-75

Password recovery

Password recovery returns a generic result for an unknown email, then sends a short-lived password-reset token for each matching active account. The reset flow checks token purpose and tenant identity before it changes the password. The stored reset record is claimed before the password change so only one concurrent request can use it. Caller-supplied reset pages are restricted to approved deployment origins.

References: packages/…/auth.service.ts• L983-1074 packages/…/auth.service.ts• L1127-1249 packages/…/purpose-token.ts• L93-135 packages/…/email-link-origin.ts• L105-215

Workspace switch

Workspace switching does not edit the identity's memberships. It asks the API to verify access and then replaces the token pair with tokens scoped to the new tenant. Organization switching uses the same membership rule inside the current tenant. The selected organization remains the account's preference for later sign-in, while each existing refresh token keeps its own active organization. Personal API-token and third-party OAuth sessions cannot use these flows because the result would be an unrestricted first-party session.

References: packages/…/auth.controller.ts• L357-412 packages/…/auth.service.ts• L3116-3257 packages/…/auth.service.ts• L3259-3294 packages/…/auth.service.ts• L907-987 packages/…/oauth-app-first-party.ts• L10-17

Identity and access control is a shared boundary for API request handling and client behavior. Read Backend platform for the platform view, Embedded client access for the bounded widget session, Domain services and contracts for service boundaries, MCP authentication and client for MCP OAuth, Angular web application for the main client, and Frontend shared libraries for shared client auth state and request behavior. Read API application lifecycle for request processing. Read Account deletion for identity removal, Plugin architecture for feature extension points, Background jobs and scheduling for work that runs outside a user request, and Subscription billing for subscription gates that can affect account creation.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep access-token claims, RequestContext fields, tenant headers, and client store values aligned. A change in one can silently change the scope used by guards or tenant-aware services.
  • When changing token purposes or claims, review every issuer and consumer. A signed token is not safe if a consumer accepts the wrong purpose or a missing required claim.
  • When changing JWT validation or off-boarding behavior, review the authenticated-context cache key, reuse window, and invalidation path.
  • When changing refresh-token claims or rotation, preserve the organization bound to the refresh token and define the fallback when that membership is no longer active.
  • When changing OAuth app scopes or token claims, keep code exchange, JWT validation, permission guards, write checks, and first-party-only actions aligned.
  • When changing embedded sessions, keep credential and grant claims, employee and organization scope, origin and client limits, embedded route fields, permission narrowing, expiry, and the no-refresh boundary aligned.
  • When changing OAuth client registration, keep tenant ownership, active lookup, redirect matching, client-secret handling, code lifetime, and single-use behavior aligned.
  • When changing personal API tokens, keep the one-time secret response, digest lookup, owner and tenant scope, expiry, revocation, session lifetime, and first-party restrictions aligned.
  • When changing a session claim or session revocation rule, keep access validation, refresh validation, token minting, session grouping, and sign-out race handling aligned.
  • When changing two-factor enrollment or sign-in, keep the operator switch, encryption-key check, challenge purpose, code replay rule, recovery-code consumption, login-attempt scope, and first-party boundary aligned.
  • When changing an auth route, classify it as public or protected in both the server guard path and the client refresh-interceptor exclusion list. Give public token and code endpoints an explicit request limit.
  • When changing workspace or organization switching, preserve the membership check before issuing new tokens and block delegated sessions from minting first-party credentials.
  • When changing account or employee status rules, keep login, access-token validation, refresh-token validation, social sign-in, magic-code validation, and personal API-token exchange aligned.
  • When changing email links, keep the allowed-origin check and canonical URL used in every email flow aligned. Never let a caller-supplied page carry a token to an unserved origin.
  • When changing the shared auth package public API, preserve existing exports and keep provider plugins responsible for selecting issuers and routes. The OpenID Connect client must remain inactive until a plugin configures it.
  • When changing the MCP OAuth server, keep client type and grant checks, collaboration scope lists, dynamic-client bounds, resource-server introspection access, durable sessions, account re-checks, token revocation, and retryable store failures aligned.

Important failure modes

TriggerConsequenceGuard
User is inactive, archived, or has no active employee recordSign-in, protected use, and personal API-token exchange are rejectedSign-in and token minting check current account and employee state
A placeholder employee record exists for the userThe user cannot receive an access or refresh tokenToken minting checks all employee records before issuing a session
A role or membership changes after token issueAn old token must not preserve the former role or organizationJWT validation attaches current role and membership state; cache reuse is off by default and bounded
Database cannot be reached while judging a bearer or refresh tokenA valid session is not mistaken for an invalid credentialRecognized lookup failures return a retryable service error; ordinary refusals return 401
Personal API token is malformed, expired, revoked, or has no tenant ownerNo access token is mintedShape, digest, expiry, revocation, owner, and tenant checks run before minting
Personal API-token session tries to create a credential or switch workspaceThe session cannot outlive the personal token through a new first-party credentialThe API-token marker is rejected by first-party boundaries
Cached request user is mutated by one requestAnother request could receive changed identity or scope stateEach cache hit receives its own user copy; OAuth and embedded scope narrowing happens after cache reuse
An embedded token names another tenant, organization, employee, origin, or clientThe widget can cross its approved boundary or act for another memberSigned claims, embedded route scope checks, and client-specific start checks must agree
An embedded token is used on a route outside the widget contractThe token could expose general workspace data or unsupported writesThe embedded route list and permission boundary allow only timer and team access
OAuth app scope is missing, malformed, or too narrowThe app cannot use the routeScopes fail closed and intersect with current role permissions
OAuth app tries to create an account, invite a user, delete a user, or mint a first-party tokenDelegated access could become control of a first-party sessionFirst-party-only actions reject OAuth app tokens directly
OAuth client is inactive, belongs to another tenant, or uses a bad redirectNo authorization code or token is issuedClient registry and authorization flow enforce active state, tenant visibility, and exact redirect matching
Public provider email is unverified or the local account has not confirmed itSocial sign-in cannot safely prove local account ownershipProvider and local account verification are both required by default
Stored organization is staleA newly issued token could fail its organization checkSign-in and exchange replace it with an active organization or clear it
A refresh token names an organization that the user no longer belongs toRenewal falls back to the stored active organization rather than preserving invalid scopeRefresh checks the token's organization membership and then uses the stored-organization resolver
One client changes the stored organization while another client renewsThe second client must not silently move to the first client's organizationRefresh renewal prefers the organization carried by its own refresh token
Verification code or OAuth authorization code is replayedA one-time proof could be reusedConditional claims and single-use code state prevent replay
Two-factor challenge is expired, used for another flow, or has a wrong codeNo session is issuedPurpose verification, short expiry, second-factor checks, and per-user failure control run before minting
Two-factor time step or recovery code is replayedA copied second factor could be used againThe last accepted time step and recovery-code list are consumed with conditional updates
Authenticator secret cannot be decrypted after restartCode verification cannot completeEnrollment requires a durable ENCRYPTION_KEY; the API reports a service failure rather than accepting the proof
A session is signed out while it refreshesThe session could otherwise mint a successor tokenA sign-out marker is checked before minting and by access and refresh validation
MCP account becomes inactive after authorizationPreviously issued MCP tokens are rejected when the server rechecks the accountCode exchange, refresh, introspection, and the configured account sweep recheck account state
OpenID Connect callback has changed, expired, or reused stateThe authorization code is not acceptedA signed, short-lived, one-use transaction binds state, nonce, and PKCE data
A dynamically registered MCP client requests only unknown scopesThe registration is refused rather than creating an unbounded permission grantThe registry drops unknown scopes and rejects an empty approved set
A public or dynamically registered MCP client requests client credentials or introspectionThe client could receive a service token or inspect other tokens without operator approvalClient-credentials requires an eligible confidential client; introspection requires an operator-registered resource server
Dynamic MCP registrations fill the in-memory registryNew registrations could displace clients that are in useThe registry removes unused clients first and then removes the least recently used client

Key files

FileWhy to read it
packages/…/auth.module.tsAPI auth boundary and registration of shared provider, token, login-attempt, two-factor, and session services
packages/…/auth.controller.tsMain API entry points for sign-in, registration, token renewal, workspace access, and registration availability
packages/…/auth.service.tsCentral identity service that connects users, memberships, tokens, recovery, registration, OAuth apps, personal API-token sessions, embedded sessions, two-factor completion, and organization-aware token refresh
packages/…/jwt.strategy.tsAPI-side validation of account state, current authorization, employee claims, organization membership, session revocation, OAuth app scope, and embedded scope
packages/…/embed-session.tsEmbedded token claims, permitted widget routes, request scope, client limits, and the embedded permission set
packages/…/jwt-refresh-token.strategy.tsRefresh-token ownership, account state, session state, and organization carried by renewal
packages/…/purpose-token.tsShared rules for token purpose, signature algorithm, required claims, and access-token classification
packages/…/login-attempt.service.tsAccount-scoped failure control across password, magic-code, team-join, and two-factor proofs
packages/…/user-two-factor.service.tsTwo-factor enrollment, code and recovery-code checks, replay control, reset, and organization policy
packages/…/two-factor-challenge.tsShort-lived proof that connects a first-factor sign-in to second-factor completion
packages/…/two-factor.controller.tsFirst-party enrollment and management routes plus the public sign-in completion route
packages/…/user-two-factor.entity.tsTenant-owned factor state and the protected credential fields
packages/…/user-session-claims.tsSession identity shared by access and refresh tokens
packages/…/user-session.service.tsUser-owned session listing and sign-out behavior
packages/…/user-session-list.tsGrouping of stored tokens into sessions and client descriptions
packages/…/user-session-revocation.tsRule that makes session sign-out effective during later token validation
packages/…/oauth-app-scope.tsScope-to-permission rules for delegated OAuth app access
packages/…/oauth-app-first-party.tsActions that remain available only to the user's own session
packages/…/oauth-client.service.tsTenant-scoped OAuth client registry, secret lifecycle, and visibility rules
packages/…/user-api-token.controller.tsUser-token management routes and the public exchange route
packages/…/user-api-token.service.tsPersonal API-token ownership, exchange checks, revocation, expiry, and session minting boundary
packages/…/user-api-token.entity.tsTenant-owned token record and credential protection rules
packages/…/user-api-token-session.tsMarker that distinguishes personal API-token sessions at first-party boundaries
packages/…/README.mdShared package boundary, OpenID Connect client role, and provider plugin model
packages/…/oidc-client.service.tsOpenID Connect discovery, token exchange, claim checks, and UserInfo subject binding
packages/…/oauth-authorization-server.tsMCP OAuth authorization, consent, token, introspection, session, rate-limit, and account-status boundary
packages/…/oauth-client-manager.tsMCP client types, scope approval, dynamic registration limits, client authentication, and resource-server identity
packages/…/auth.service.tsShared client calls for authentication, workspace discovery, switching, and token renewal
packages/…/store.service.tsClient state for the current identity, tenant, organization, permissions, and token pair
packages/…/auth-refresh.interceptor.tsClient recovery path for expired access tokens
packages/…/tenant.interceptor.tsClient propagation of tenant and organization scope
packages/…/register.component.tsRegistration boundary that loads required legal documents and blocks submission when acceptance data is unavailable