Skip to content

Authentication ​

The control plane supports two authentication mechanisms: JWT-based session auth for the dashboard and API token auth for client APIs. On the Enterprise tier, a tenant's dashboard login can additionally be backed by an external directory (LDAP) or an OIDC identity provider (SSO) instead of the local password — see External Identity Providers below. Authentication says who is calling; what the caller may do is decided by the policy engine, described in IAM.

Authentication Modes ​

ModeUsed ForMechanism
JWT SessionDashboard UIHTTP-only cookie
API TokenClient APIs (/api/client/v1/*)Authorization: Bearer <token>
LDAP (Enterprise)Dashboard UI, directory-backedLocal password path replaced per-tenant; same JWT session issued on success
SSO / OIDC (Enterprise)Dashboard UI, identity-provider-backedAuthorization-code + PKCE redirect flow; same JWT session issued on success
API Token + user tokenClient APIs, acting for your application's own signed-in usersAuthorization: Bearer <token> plus a signed X-Cognipeer-User-Token statement — see Acting for a user

JWT Session Authentication ​

Login Flow ​

  1. User submits slug + email + password to POST /api/auth/login
  2. Server finds tenant by slug, switches to tenant database
  3. Validates email/password against stored bcrypt hash
  4. Generates JWT with user info, license features, and tenant data
  5. Sets HTTP-only cookie (token)
  6. Returns user profile

Forgotten passwords, password changes and recovering the owner account of a self-hosted installation are described in Passwords and account recovery.

Registration Flow ​

  1. User submits company name, slug, name, email, password to POST /api/auth/register
  2. Server creates tenant with the given slug
  3. Creates a new tenant_{slug} database
  4. Creates user as owner with hashed password
  5. Assigns default license (FREE)
  6. Generates JWT and sets cookie
  7. Sends welcome email

JWT Payload ​

typescript
{
  userId: string;
  email: string;
  role: 'owner' | 'admin' | 'project_admin' | 'user';
  tenantId: string;
  tenantSlug: string;
  tenantDbName: string;
  licenseType: string;
  features: string[];
}

The JWT is signed using the jose library (Edge Runtime compatible) with JWT_SECRET.

Middleware Processing ​

The global middleware (src/middleware.ts) processes every request:

Request → Is public path? → Pass through
        → Is client API? → Skip cookie auth (Bearer handled in route)
        → Extract cookie → Verify JWT → Check license endpoint access
        → Inject headers → Forward to route handler

Headers injected for authenticated requests:

HeaderContent
x-user-idUser ObjectId
x-user-emailUser email
x-user-roleowner, admin, project_admin, user
x-tenant-idTenant ObjectId
x-tenant-slugTenant slug
x-tenant-db-nametenant_{slug}
x-license-typeLicense tier
x-featuresJSON array of feature flags
x-request-idRequest UUID

Sign-in hardening ​

  • Field limits. The login, register, forgot-password and reset-password bodies take strings only, within fixed lengths: email 320, password 4096, workspace slug 128, name 200, reset token 8192 characters. A field of another type, or a longer one, is answered with 400.
  • Failed sign-ins per account. Besides the general sign-in rate limit, failed sign-ins to an account are limited: AUTH_LOGIN_ACCOUNT_MAX_ATTEMPTS (default 20) per 15 minutes, then 429. Successful sign-ins do not count, 0 turns the limit off, and the count is shared between replicas when the rate limit provider is Redis. Behind a reverse proxy, set TRUSTED_PROXIES.
  • Sessions end on a password change. A password change or reset ends the sessions issued before it: their next request is answered 401 with code session_expired and the session cookies are cleared. Setting AUTH_PASSWORD_CHANGE_ENDS_SESSIONS (default true) to false turns this off.
  • Sign-in without a workspace. When a sign-in names no workspace and the user directory does not know the address, the server scans tenant databases only while AUTH_LOGIN_TENANT_SCAN is true (the default). Set it to false to turn the scan off; the server logs a warning at start-up while it is on.

The variables are listed in Configuration.

Public Paths ​

These paths skip authentication:

  • /login, /register
  • /api/auth/* (includes the SSO login flow, /api/auth/sso/* — see below)
  • /api/health/*

API Token Authentication ​

For programmatic access, tenants create API tokens through the dashboard. These tokens authenticate requests to /api/client/v1/* endpoints.

Every token is owned by a user record, and that user's canLogin flag shapes where the token gets managed:

  • A regular member (canLogin: true, the default) mints and manages their own tokens under Settings → API Tokens. That page lists your own tokens only, whatever your role: an administrator does not see anybody else's there.
  • A Programmatic User (canLogin: false) — a login-disabled identity with no password and an optional email, meant to exist only to own API tokens (a service account, a CI job, an integration) — can never sign in, so it can't reach that self-service page. An owner/admin instead manages its tokens from Settings → IAM center → Principals → API tokens, or from the service account's drawer.

For anything that isn't a human logging into the dashboard, prefer creating a Programmatic User and minting its tokens from the IAM center (or the equivalent Client API calls below) rather than handing out a real teammate's personal token. See User Types (canLogin) for how the flag interacts with roles.

Tokens are managed under Settings → API Tokens, which lists your own tokens only. Owners and admins manage other people's tokens, and the tokens of service accounts (Programmatic Users), under Settings → IAM center → Principals → API tokens (or from a person's drawer). They do so "never upward": an admin reaches every token but the owner's, and a project admin only those of service accounts in the projects they belong to. A token authorizes as its owner, so what it may do is capped by its owner's permissions and its own scope. Each row shows the label, creation date, and last-used timestamp; the full secret is shown only once at creation time:

API Tokens

Usage ​

bash
curl -X POST https://gateway.example.com/api/client/v1/chat/completions \
  -H "Authorization: Bearer cpeer_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}'

Provisioning a non-login identity from the API ​

The per-user token page has a Client API equivalent — two endpoints, both requiring an owner/admin-owned token:

  1. POST /client/v1/users — creates a Programmatic User. canLogin is always forced to false server-side, so this endpoint can never create a login-capable account no matter what the request body sends.
  2. POST /client/v1/users/:id/tokens — mints an API token for that user (or any user in the tenant) and returns the plaintext secret once.
bash
# Create a login-disabled service account
curl -X POST https://gateway.example.com/api/client/v1/users \
  -H "Authorization: Bearer cpeer_admin_token..." \
  -H "Content-Type: application/json" \
  -d '{"name": "billing-sync-bot", "role": "user"}'

# Mint an API token for it (id from the response above)
curl -X POST https://gateway.example.com/api/client/v1/users/<user_id>/tokens \
  -H "Authorization: Bearer cpeer_admin_token..." \
  -H "Content-Type: application/json" \
  -d '{"label": "billing-sync nightly job"}'

See Users API for full request/response fields and error cases.

requireApiToken Helper ​

All client API routes use the requireApiToken helper:

typescript
import { requireApiToken, ApiTokenAuthError } from '@/lib/services/apiTokenAuth';

export async function POST(request: NextRequest) {
  try {
    const ctx = await requireApiToken(request);
    // ctx.token, ctx.tokenRecord, ctx.tenant
    // ctx.tenantId, ctx.tenantSlug, ctx.tenantDbName
    // ctx.projectId, ctx.user
  } catch (error) {
    if (error instanceof ApiTokenAuthError) {
      return NextResponse.json({ error: error.message }, { status: error.status });
    }
    throw error;
  }
}

Token Validation Flow ​

  1. Extract Bearer token from Authorization header
  2. Check cache (SHA-256 hash key, 60s TTL). It holds the token record and tenant only
  3. On cache miss: query database, resolve tenant
  4. Reject an expired token (401)
  5. Reject a call from outside the token's IP allowlist (403, ip_not_allowed)
  6. Switch to tenant database
  7. Resolve the token owner fresh on every request and reject a missing or disabled owner (401)
  8. Ensure default project exists and resolve the token's project (the default project when the token has none)
  9. Check that the owner can access that project (every request, never cached); otherwise 403
  10. Fire-and-forget: update lastUsed timestamp
  11. Return ApiTokenContext
  12. The route's authorization gate decides what the token's owner, scope and project allow (see IAM)

Project Access ​

A token is bound to a project and authorises as its owner inside it, so the owner has to be able to work in that project. The rule is the one the dashboard uses:

Token ownerAccess to the token's project
owner, adminEvery project
project_admin, userProjects they are a member of: a project membership, an entry in the user's legacy project list, or a group assigned to the project
Login-disabled (programmatic) userThe token is the grant: it was minted for that project by an administrator, so no membership is consulted

A token without a project works in the default project and is checked against it.

The check reads live data on every request and is not part of the auth cache, so adding or removing a member, or changing a group's project assignment, applies to that user's tokens on the next call. Add the member back and the same token works again.

Minting a token for another user (POST /api/tokens with userId, POST /api/client/v1/users/{id}/tokens) is refused with 400 when that user can log in but cannot access the project. Because no membership is consulted for a login-disabled user, removing such a user from a project it is a member of deletes the tokens it holds for that project instead; a token minted for an account that is not a member is revoked by deleting the token.

Token Properties ​

FieldDescription
tokenThe raw token string
userIdOwning user
tenantIdOwning tenant
projectIdScoped project (optional); the owner must have access to it, see Project Access
servicePermissionsLeast-privilege scope that caps the owner's permissions, group grants included (optional)
allowedIpRangesCIDR ranges the token may be used from (optional, see IP allowlists)
allowedMcpServerIdsThe MCP servers the token may reach (optional, see Limiting a token to some MCP servers)
requireUserTokentrue = the token is only served on behalf of a verified person (optional, see Requiring a user token)
expiresAtExpiration date (optional)
lastUsedLast usage timestamp

Expiry and the tenant token policy ​

A token may carry an expiry (expiresAt). An organization can make that mandatory and cap how long a token may live under Settings → IAM center → Settings → API tokens (the GET/PUT /api/iam/settings API):

SettingMeaning
maxLifetimeDaysNo token may be set to expire later than this many days after it was created. null = no maximum.
requireExpiryEvery new token must have an expiry. A maximum lifetime implies it.

The policy is checked when a token is created and when its expiry is extended (the lifetime is counted from the token's creation, so a token cannot be renewed forever; it has to be replaced). Shortening an expiry is always accepted. Tokens that already exist keep working; the ones outside the policy are flagged (exceedsTenantPolicy) in the token list so they can be rotated. The checks run on every route that creates a token: POST /api/tokens, POST /api/projects/{projectId}/tokens and POST /api/client/v1/users/{id}/tokens.

bash
# create a token that expires in 30 days and only works from two networks
curl -X POST https://gateway.example.com/api/tokens \
  -H "Content-Type: application/json" --cookie "token=..." \
  -d '{"label": "ci", "expiresInDays": 30, "allowedIpRanges": ["203.0.113.0/24", "2001:db8::/32"]}'

expiresAt (ISO 8601, or null for "never") and expiresInDays (counted on the server clock) are two ways to say the same thing; send one of them. A refusal is a 400 with a stable code: token_expiry_required, token_expiry_too_long (details.latestExpiresAt says how far it may go), token_expiry_invalid, or policy_unavailable (503, the policy could not be read; nothing is created). GET /api/tokens/policy returns the rules for a form; PUT /api/tokens/{id} edits a token's label, expiresAt / expiresInDays, allowedIpRanges and requireUserToken. A change to the expiry or the allowlist is written to the audit log with the old and the new value (service tokens, event token.restrictions.updated), next to the regular request row, and takes effect on the very next call.

IP allowlists ​

allowedIpRanges is a list of IPv4 / IPv6 ranges in CIDR notation (a bare address means a single host; at most 100 entries). A token with a list only authenticates from an address inside one of the ranges. Any other call is refused with:

json
{ "error": "API token is not allowed from this IP address", "code": "ip_not_allowed" }

with status 403 (OpenAI- and Anthropic-compatible routes use their own error envelope with the same status and code). A token without a list, which includes every token created before the feature, is unrestricted. Refusals are written to the audit log (service tokens, action security, outcome denied, at most one row per token and address per minute).

The address that is matched is one the server can vouch for. With TRUSTED_PROXIES set it is the address Fastify resolves through those proxies: the connection address, or the forwarded one only when the connection comes from a listed proxy, taking the entry the proxy itself appended (anything a client wrote to the left of it is ignored). With TRUSTED_PROXIES unset (the default) forwarded headers are not used for IP rules at all: the connection address is matched, so a caller cannot claim an allowed address. The X-Forwarded-For, X-Real-IP and Forwarded headers are never read directly. Behind a reverse proxy or load balancer set TRUSTED_PROXIES to its address, otherwise every caller looks like the proxy and an allowlist never matches; the console says so next to the allowlist. The same address is used for the ip condition of access policies.

A token that mints another token (POST /api/client/v1/users/{id}/tokens) cannot widen its own network scope: the new token inherits the minting token's ranges unless it asks for a subset of them.

Limiting a token to some MCP servers ​

The token form has an MCP servers field (placeholder All MCP servers): "Limit the token to specific MCP servers. Leave it empty to allow all of them." Over the API the same limit is allowedMcpServerIds, a list of MCP server ids on POST /api/tokens (a value that is not a list is refused with 400). A limited token reaches only those servers on every MCP route (calls, update, delete, tool refresh) and cannot create servers. A token without the list, which includes every token created before the feature, can reach all of them.

Acting for a user (verified end-user identity) ​

Requires a Cognipeer release with the IAM engine

The X-Cognipeer-User-Token header and its per-token setup exist only in releases that include the IAM engine.

A token acts as its owner by default. An application that signs its own users in can instead let each call act as the person it is for: it keeps sending its API token and adds a signed statement about the person in the X-Cognipeer-User-Token header. Cognipeer verifies the statement (issuer, audience, pinned algorithm, signature, expiry), finds or creates the person's account, and runs the call with that person's access and limits, still capped by the token's scope and project. Without the header nothing changes; with it, a statement that is not accepted is refused and the owner is never the fallback.

Owners and admins set it up per token under Settings → IAM center → Principals → API tokens. The same two values can travel in a single Authorization header for SDKs that can only set an API key (Bearer <api token>~<user token>), and a token can be made to refuse any call that carries no user token (requireUserToken). See Acting for a user for the setup, the claims, the combined credential, the refusal codes and example code, and External users for the accounts it can create.

External Identity Providers (Enterprise) ​

Both integrations let a tenant's members sign in through a corporate identity system instead of a local password, and both just-in-time (JIT) provision a local user record on first successful login. They are configured per tenant from Settings → LDAP Directory and Settings → Single Sign-On, and require an active ENTERPRISE license on that tenant — a FREE/STARTER/PROFESSIONAL tenant sees an upgrade prompt instead of the configuration form, and the admin config/test endpoints (/api/ldap/config, /api/ldap/test, /api/sso/config, /api/sso/test) return 402 Payment Required. The login paths themselves are never license-gated — once configured, authentication keeps working even if the license check runs before every other request.

LDAP is available on self-hosted deployments only. On the hosted (SaaS) Cognipeer the LDAP Directory entry is hidden and /api/ldap/* answers 404 with requiresOnPrem.

LDAP ​

Verifies the login against a directory (OpenLDAP, Active Directory, …): binds as a service account, searches for the user entry, then re-binds as that entry to verify the password — the directory always holds the real credential, console never sees or stores it.

FieldDescription
urlldap://ldap.corp:389 or ldaps://ldap.corp:636
bindDN / bindCredentialsService account used to search for the user entry (password encrypted at rest)
searchBaseSubtree to search for user entries
userFiltere.g. (|(uid={{username}})(mail={{username}})) — {{username}}/{{uid}} are replaced with the escaped login identifier
emailAttribute / nameAttributeDirectory attributes read into the local user record
defaultRole / adminGroupDNsTenant role for provisioned users; members of any admin group DN become tenant admin
groupSearchBase / groupMemberAttributeOptional — enables group→role resolution via a subtree search in addition to the user entry's own memberOf
syncGroups / ldapGroupMappingsOptional — reconciles console user groups (Members → Groups) from directory group membership on every login. Cognipeer groups are auto-created on first match; what a synced group grants (role, service permissions, project access) is still configured in the Groups admin UI — LDAP only owns membership, and never touches a group's local (hand-added) members
tlsRejectUnauthorizedSet to false to accept a self-signed certificate (ldaps://, dev only)

Login is slug-scoped — a directory user signs in with their organization's slug the same way a local user does; there is no cross-tenant directory lookup for LDAP identities on their first login. Password login for an existing account is refused (not silently allowed) once LDAP rejects a directory user, so a directory outage fails closed rather than falling back to a stale local password.

SSO (OIDC) ​

Authorization-code + PKCE (S256) against any OIDC-conformant provider — Keycloak, Okta, Entra ID, Auth0, Google Workspace — configured generically, with no per-provider code.

/login → "Sign in with SSO"
  → GET /api/auth/sso/discover
      exactly one tenant-wide connection enabled? → skip the email step, redirect straight to the IdP
      otherwise → show the email field
  → GET /api/auth/sso/start?email=…
      resolve the tenant by matching the email's domain against each connection's allowed domains
      → redirect to the identity provider with a signed, httpOnly state cookie (PKCE + nonce)
  IdP → GET /api/auth/sso/callback
      → exchange the code, verify the id_token against the provider's JWKS, resolve/provision the user
      → mint a short-lived, single-use ticket (the session token itself never appears in a URL)
      → redirect to /login/sso-callback?ticket=…
  browser → POST /api/auth/sso/session { ticket }
      → claims the ticket exactly once and issues the same JWT/cookie session as password login
FieldDescription
issuer / discoveryUrlProvider issuer; discovery defaults to {issuer}/.well-known/openid-configuration and is resolved once, at save time
clientId / clientSecret / clientAuthMethodConfidential client credentials (secret encrypted at rest)
scopes / usePkce / fetchUserInfo["openid","email","profile"] by default; PKCE on by default; optionally merge in /userinfo claims
subjectClaimThe stable identity anchor (default sub) — matched before email on every login, so a changed or synthesized email can never orphan the account
requireVerifiedEmailReject the login when the provider's email_verified claim is false
allowedEmailDomainsRoutes a login attempt to this tenant's connection; public mailbox domains (gmail.com, outlook.com, …) are rejected outright
defaultRole / adminClaimName / adminClaimValuesTenant role for provisioned users; a matching claim value maps to tenant admin

Email is not required. Two independent mechanisms cover directories that never send a usable email claim, or deployments with only one identity provider:

  • Synthetic email — configure a username claim (default preferred_username) and a synthetic domain; console builds {localpart}@{syntheticdomain} as a placeholder email. The account stays stable across a resynthesized email because it's matched by the subject claim, not the email.
  • Single-connection shortcut — when exactly one tenant-wide SSO connection is enabled (a single-tenant/on-prem deployment), the login page skips the email step entirely and redirects straight to the identity provider.

License-Based Feature Control ​

Features are controlled through a license system defined in src/config/policies.json:

typescript
import { LicenseManager } from '@/lib/license/license-manager';

const hasAccess = LicenseManager.hasFeature(licenseType, 'LLM_CHAT');
const canAccessEndpoint = LicenseManager.hasEndpointAccess(licenseType, '/api/models');

License Tiers ​

TierFeaturesRequest Limit
FREE16 features1,000/month
STARTER10 features10,000/month
PROFESSIONAL14 features100,000/month
ENTERPRISEAll featuresUnlimited
ON_PREMISEAll featuresUnlimited

The enterprise modules (portals, flows, sandbox, SSO and the others) are not decided by the tier: a licence is a package of modules, see Licence packages.

Feature Endpoint Mapping ​

Each feature in policies.json maps to API endpoint patterns:

json
{
  "LLM_CHAT": {
    "name": "LLM Chat",
    "endpoints": ["/api/chat/*", "/api/client/v1/chat/*"]
  }
}

The middleware checks these mappings automatically.

User Roles ​

RoleScope
ownerFull tenant control
adminManage users and settings
project_adminManage assigned projects
userAccess assigned projects only

A role sets the default level of each service. What a person can actually do is the result of their role, their own service permissions, the grants of their groups, their project permissions and, for API tokens, the token's scope, all decided by one policy engine, with custom policies for exceptions. See Authorization (IAM) for how the levels combine, and Troubleshooting and FAQ for reading a refusal (403 with a decision id).

User Types (canLogin) ​

role and canLogin are independent axes on the same user record — role governs what a user can do once authenticated, canLogin governs whether it can authenticate as a dashboard session at all. A user of any role can be either type:

canLoginTypeMeaning
true (default — missing/undefined is treated as true for back-compat)Regular memberHas a password, can log into the dashboard and hold a JWT session, in addition to owning API tokens.
falseProgrammatic UserNo password, no dashboard session, email optional. Exists only to own API tokens — a service account, integration, or CI identity. Shown with a "No login" status badge and a "Programmatic" badge next to its role in the IAM center's Principals tab.

POST /client/v1/users (the Client API) can only ever create canLogin: false users — it forces the flag server-side regardless of the request body, so an API token can never provision a login-capable account. A human teammate must still be added from the dashboard, with a password, with Invite person on the IAM center's Principals tab (with the Send invite switch left on).

Configuration ​

VariableDefaultDescription
JWT_SECRET—Required. Secret for JWT signing
JWT_EXPIRES_IN7dJWT expiration duration
PROVIDER_ENCRYPTION_SECRET—Required. Key that encrypts stored provider credentials at rest. Min 32 chars, must differ from JWT_SECRET
TRUSTED_PROXIES— (unset: forwarded headers are not used for authorization)Comma-separated IPs / CIDRs of the reverse proxies or load balancers allowed to set X-Forwarded-For. Set it whenever the console runs behind one: the client address that token IP allowlists, the IP condition of policies, rate limits and audit logs use depends on it.

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub · Contact Support