AuthAPI internals
Internals of the Authentication API domain. For the public API, see Authentication API. For the whole auth system (tellyid, CoreAPI RBAC, consoles, runbook, prioritised issues), read the Auth, identity and RBAC handover guide; this page covers AuthAPI itself and doesn't repeat it. Social sign-in has its own page: Social sign-in internals.
AuthAPI fronts Zitadel, which holds credentials, Zitadel organizations, users and the password policy, and adds what Zitadel doesn't do: multi-device sessions, magic-link invite activation and password reset, organization self-signup with approval, company-code hosting discovery and on-prem licensing. It issues RS256 access tokens and HS256 refresh tokens for web (cookie) and mobile (token in body) clients.
How it works¶
graph LR
Client["Client (web / mobile)"]
AuthAPI["AuthAPI (Go / Fiber)"]
Zitadel["Zitadel<br/>(orgs, users, credentials)"]
DB["PostgreSQL (GORM)<br/>orgs, users, refresh_tokens,<br/>magic_link_tokens, password_reset_tokens,<br/>org_invitations, auth_codes, local_license"]
CoreAPI["CoreAPI<br/>(mirrors orgs and users, owns roles)"]
Cloud["PlayTelly Cloud<br/>(license issuance for on-prem)"]
Client -->|login, refresh, sessions| AuthAPI
AuthAPI -->|authenticate, create org and user| Zitadel
AuthAPI --> DB
AuthAPI -->|roles, user/org upsert, reset e-mail - internal token| CoreAPI
CoreAPI -->|/api/v1/internal/* - internal token| AuthAPI
AuthAPI -->|on-prem: fetch license| Cloud
Zitadel is the system of record for credentials, organization membership and password policy: login calls
zitadel.Authenticate, never a local password check. AuthAPI's database is a local mirror plus PlayTelly-only
state: account_state, refresh-token sessions with device info, magic-link and reset tokens, company codes and the
cached on-prem license. POST /api/v1/internal/platform/reconcile repairs drift between the two
(Zitadel reconciliation).
Schema is managed by GORM AutoMigrate at boot (internal/migration): eight models, no standalone .sql files.
The boot order (Zitadel, then AuthAPI bootstrap, then CoreAPI seed) is in the handover guide,
§3.
Account and organization states¶
Two independent status fields gate authentication. Both are checked on login; refresh checks a subset (see Refresh rules).
User account_state (users.account_state)¶
| State | Meaning | Login outcome |
|---|---|---|
active |
Normal account | Allowed |
pending |
Accepted by the schema and by PUT …/users/:userId/status, but no flow sets it: every creation path writes active or invited |
403 ACCOUNT_PENDING |
disabled |
Deactivated by an admin | 403 ACCOUNT_DISABLED; refresh also fails |
invited |
Created by POST …/users/invite; has a random internal password in Zitadel that is never exposed. Activates only via the magic link (or a provider sign-in with the invited e-mail, see Social sign-in internals) |
403 ACCOUNT_INVITED |
Organization status (orgs.status)¶
| Status | Meaning | Login outcome |
|---|---|---|
active |
Normal | Allowed |
pending |
Self-signup application awaiting platform approval. No Zitadel org or user exists yet | 403 ORG_PENDING for every member |
disabled |
Disabled by a platform admin | 403 ORG_DISABLED |
hosting_type (cloud or on_prem) is a third, independent field; see Company code and licensing.
Self-signup approval¶
sequenceDiagram
participant Applicant
participant CoreAPI
participant AuthAPI
participant PlatformAdmin
participant Zitadel
Applicant->>CoreAPI: POST /api/v1/tenancy/organizations/self-signup
CoreAPI->>AuthAPI: POST /internal/platform/orgs/self-signup<br/>{name, admin{username,email,given_name,family_name}, company_code[, idp_proof]}
AuthAPI->>AuthAPI: store org row, status="pending"<br/>(applicant_* columns only, no Zitadel calls)
AuthAPI-->>CoreAPI: 201 {org, idp_verified}
PlatformAdmin->>CoreAPI: approve
CoreAPI->>AuthAPI: PUT /internal/platform/orgs/:orgId/status {"status":"active"}
AuthAPI->>Zitadel: create org + admin user<br/>(random temporary password, or IdP-linked without password)
AuthAPI->>AuthAPI: org.status="active", admin active,<br/>password_change_required=true (password path)
AuthAPI-->>CoreAPI: 200 {org, admin_user, temporary_password}
CoreAPI e-mails the temporary password; it exists only in that response. Abandoned applications never create Zitadel objects.
Token design¶
| Token | Algorithm | Default lifetime | Storage |
|---|---|---|---|
| Access | RS256 (AUTHAPI_JWT_RSA_PRIVATE_KEY) |
900 s (AUTHAPI_JWT_ACCESS_EXPIRY, integer seconds) |
Not stored; verified by public key / JWKS |
| Refresh | HS256 (AUTHAPI_JWT_REFRESH_SECRET) |
168h (AUTHAPI_JWT_REFRESH_EXPIRY, Go duration) |
SHA-256 hash in refresh_tokens, rotated on every use |
Access-token claims:
{
"iss": "authapi",
"sub": "<user-uuid>",
"uid": "<user-uuid>",
"zid": "<zitadel-user-id>",
"sid": "<session-uuid>",
"iat": 1794816000,
"exp": 1794816900,
"jti": "<uuid>",
"org": { "org_id": "<uuid>", "org_slug": "acme", "role": "ORG_ADMIN" },
"app_roles": [ { "scope": "organization", "scope_id": "<org-uuid>", "role": "ORG_ADMIN" } ]
}
- Each user belongs to exactly one organization: the claim is a single
orgobject. org.roleandapp_rolescome from CoreAPI (GET /api/v1/internal/users/:id/roles) at every issue and refresh. If that call fails, the failure is logged and the token is issued withrole: "member"and emptyapp_roles, so a CoreAPI outage silently drops permissions instead of blocking sign-in. Per the handover guide, CoreAPI doesn't populateapp_rolestoday (§4.2); the partner page tells partners not to rely on it.issand the discovery document'sissuerboth come fromJWT_ISSUER(defaultauthapi). The discovery URLs (jwks_uri,token_endpoint,introspection_endpoint) areissuer + path, so with the default they aren't absolute URLs. NoJWT_ISSUERis set in the playtelly-iac overlays outside the secret files (not checked).- JWKS publishes one key;
kidis derived from the public key. There is no key rotation support.
Web cookies¶
access_token (path /) and refresh_token (path /api/v1), HttpOnly, SameSite=Lax,
Domain=AUTHAPI_COOKIE_DOMAIN, Secure unless AUTHAPI_COOKIE_SECURE=false. When the cookie domain is
localhost or 127.0.0.1, Domain and Secure are dropped. RequireAuth reads Authorization: Bearer first and
falls back to the access_token cookie.
Login flow¶
sequenceDiagram
participant Client
participant AuthAPI
participant Zitadel
participant PostgreSQL
participant CoreAPI
Client->>AuthAPI: POST /login {username, password, company_code}
AuthAPI->>AuthAPI: 503 LICENSE_EXPIRED if the license guard is blocked
AuthAPI->>Zitadel: Authenticate(username, password)
Zitadel-->>AuthAPI: user info + zitadel_session_id + zitadel_org_id
AuthAPI->>PostgreSQL: company_code → local org (web)
AuthAPI->>Zitadel: SearchOrg(name), SearchUserInOrg (membership)
AuthAPI->>PostgreSQL: local org by zitadel_org_id, check status
AuthAPI->>PostgreSQL: upsert local user (keeps existing account_state)
AuthAPI->>AuthAPI: check account_state
AuthAPI->>CoreAPI: GET /internal/users/:id/roles
AuthAPI->>PostgreSQL: store refresh token (session_id, device, zitadel_session_id)
AuthAPI-->>Client: tokens (body or cookies) + org claim
- A user who isn't a member of the company code's organization gets
INVALID_CREDENTIALS, deliberately the same as a wrong password. - Mobile clients may omit
company_code; the organization then comes from the Zitadel session. - Step-by-step detail with line references is in the handover guide, §4.1.
Refresh rules¶
- The stored refresh token is looked up by hash, deleted, and a new pair issued with the same
session_id, device info andcreated_at. A second refresh with the same token gets401; there is no reuse detection. - Refresh fails with a generic
401when the account isdisabledor the session's organization ispendingordisabled.pendingandinvitedaccounts are not blocked on refresh. - Error bodies differ by branch: web without cookie
{"error":"no_refresh_token","message"}, mobile without token{"code":"no_refresh_token","message"}, badclient_type{"code":"invalid_client_type","message"}, others{"error":"<text>"}.
Sessions and the event stream¶
Every login, redeem or provider sign-in creates a refresh_tokens row with a stable session_id plus device
metadata. Web devices are parsed from User-Agent; mobile clients send PlayTelly-SessionDetail (base64 JSON with
osName, osVersion, modelName, appVersion) and optionally PlayTelly-AppVersion (see deviceFromRequest).
Revocation deletes the refresh token(s), deletes the Zitadel session(s) (failures only logged) and publishes on the
SSE hub (internal/sse):
| Trigger | Event | reason |
Stream closed |
|---|---|---|---|
POST /protected/logout with a refresh token |
session_revoked to that session |
logout |
Yes |
POST /protected/logout without a refresh token, POST /protected/logout/all |
session_revoked to every session of the user |
logout_all |
No (client should close) |
POST /sessions/:id/revoke, DELETE /protected/users/me/sessions/:id |
to that session | revoked_by_user |
Yes |
POST /sessions/revoke-others |
to each other session | revoked_other_devices |
Yes |
DELETE /internal/orgs/:orgId/users/:userId |
to every session of the user | account_deleted |
No |
There is no per-request access-token revocation check in AuthAPI, so a revoked session's access token works until it
expires. The hub is in-process only: with several AuthAPI replicas, an event published on one replica never reaches a
stream held by another. AUTHAPI_WRITE_TIMEOUT must stay 0 (unlimited) or the stream is cut. What the consoles
actually do with the events is in the handover guide, §4.3.
Invite flow¶
An org admin invites a user through CoreAPI; activation is a magic link, a one-time opaque 32-byte URL-safe token
redeemed through its own endpoint, never through /login. (Before 2026-08-13 this was a 6-character invite code typed
into /login; that mechanism is gone.)
sequenceDiagram
participant OrgAdmin
participant CoreAPI
participant AuthAPI
participant Zitadel
participant Invitee
OrgAdmin->>CoreAPI: POST /tenancy/organizations/:orgId/invitations
CoreAPI->>AuthAPI: POST /internal/orgs/:orgId/users/invite<br/>{username, email, given_name, family_name}
AuthAPI->>AuthAPI: generate a random internal password (never returned)
AuthAPI->>Zitadel: CreateUser(..., internalPassword)
AuthAPI->>AuthAPI: account_state="invited", password_change_required=true<br/>magic link (hashed at rest, 10 min default)
AuthAPI-->>CoreAPI: 201 {user, magic_link_token, magic_link_expires_at, company_code}
CoreAPI->>CoreAPI: build the link, send it with the org's "user_invite" e-mail profile
CoreAPI-->>OrgAdmin: 201 {user, email_sent, email_error}
Invitee->>AuthAPI: POST /auth/magic-link/redeem {token}
AuthAPI->>AuthAPI: consume token (single use), invited → active
AuthAPI-->>Invitee: session (same shape as /login)
- AuthAPI returns the raw
magic_link_tokenonly to CoreAPI. CoreAPI's response to the org admin doesn't include it. Without auser_invite(orfallback) e-mail profile, CoreAPI fails with400before calling AuthAPI. POST /internal/orgs/:orgId/users/:userId/reinvitereplaces the token (one row per user, upsert);409if the user is no longerinvited.GET /auth/magic-link/statuspeeks without consuming.POST /auth/magic-link/redeemconsumes the token before checking expiry, so an expired token is also used up.- Redeem doesn't re-check the organization's status or a
disabledaccount; it only flipsinvitedtoactive. - Lifetime:
PLAYTELLY_MAGIC_LINK_TOKEN_DURATION, default 10 minutes.PLAYTELLY_INVITE_CODE_LENGTHandPLAYTELLY_INVITE_CODE_DURATIONare dead: nothing reads them. - After redeem, tellyid forces a password change;
PUT /protected/users/me/passwordaccepts an emptycurrent_passwordwhilepassword_change_requiredis set (it then uses Zitadel's admin reset instead of verify-then-change).
Password reset flow¶
Self-service "forgot my password", separate from the invite flow and from the signed-in password change.
sequenceDiagram
participant User
participant AuthAPI
participant CoreAPI
participant Zitadel
User->>AuthAPI: POST /auth/password-reset/request {email, company_code}
AuthAPI->>AuthAPI: org by company_code, user by e-mail, same org<br/>(silent on mismatch)
AuthAPI->>AuthAPI: reset token (hashed, 1h default), one row per user
AuthAPI->>CoreAPI: POST /internal/email/password-reset<br/>{org_id, email, reset_link, expiry_minutes}
CoreAPI->>CoreAPI: send with the org's "password_reset" (or "fallback") e-mail profile
AuthAPI-->>User: 200 {success: true}
User->>AuthAPI: POST /auth/password-reset/confirm {token, new_password}
AuthAPI->>Zitadel: check complexity, reset password
AuthAPI->>AuthAPI: token consumed, password_change_required cleared
AuthAPI-->>User: 200 {success: true}
- The request answers
200whenever no account matches. A failure to send the e-mail is only logged. Database errors still return500 SERVER_ERROR. - The link is
<AUTHAPI_FRONTEND_URL>/reset-password?token=…. Lifetime:PLAYTELLY_PASSWORD_RESET_TOKEN_DURATION, default 1 hour. Existing sessions are not revoked. - The platform has three separate password mechanisms: this one, the signed-in change
(
PUT /api/v1/protected/users/me/password), and ticketing's legacy customer/admin reset in CoreAPI (see the Identity API). Don't conflate them.
Company code and licensing¶
company_code is a short, unique, lowercase alphanumeric code per organization that lets a client find which
backend to talk to before it knows anything else, because PlayTelly runs both multi-tenant (cloud) and
self-hosted (on_prem).
GET /api/v1/company-code/:code(public, on the partner page) returnshosting_type, plusapi_urlandauth_urlfor on-prem organizations that have phoned home.POST /api/v1/company-code/:code/phone-homeandGET /api/v1/company-code/:code/statusare called by on-prem instances withX-License-Key. They are in the internal reference, not on the partner page.POST /api/v1/internal/platform/orgscreates either kind:cloudcreates the Zitadel org and admin and returns tokens;on_premmints a license key (needsAUTHAPI_LICENSE_PRIVATE_KEY, so only on the cloud instance) and creates only the local row.
On-prem licenses are Ed25519-signed tokens (internal/license) that bind a company code and an expiry.
license.Guard starts blocked, verifies the license at boot (the company code must equal
AUTHAPI_DEFAULT_ORG_COMPANY_CODE) and re-checks every 24 hours. Within a month either side of expiry it warns;
past the grace window it blocks, and login, refresh, magic-link, password-reset and social sign-in routes return
503 LICENSE_EXPIRED (an in-memory check per request). An on-prem instance without a cached license fetches one
from AUTHAPI_LICENSE_CLOUD_URL at first boot and caches it in the single-row local_license table.
Zitadel reconciliation¶
POST /api/v1/internal/platform/reconcile?dry_run=true|false walks every organization AuthAPI knows, lists its
users in Zitadel, and:
- Upserts any Zitadel user missing from AuthAPI's
userstable asactive(this can bring back a user that Zitadel still has but AuthAPI lost). - Pushes each synced user into CoreAPI (
UpsertUserInCoreDB). - Finds Zitadel organizations with no
orgsrow, creates them (cloud,active) and reconciles their users.
dry_run=true reports what would change without writing. It is a one-way pull: it never deletes and never pushes
local state to Zitadel. The only caller is CoreAPI's cmd/migrate-zitadel CLI.
Service-to-service routes¶
/api/v1/internal/* is protected only by RequireInternalToken: the X-Internal-Token header must equal
COREAPI_AUTHAPI_PSK. The value is in the AuthAPI and CoreAPI deployment secrets; never copy it into docs. There is
no per-caller authorization in AuthAPI: the per-org middleware that older docs mentioned has been removed, so any
holder of the token can act on any organization. Authorization happens in CoreAPI before it calls in. Which CoreAPI
code calls which route, and the AuthAPI → CoreAPI calls, are in the handover guide,
§5.
Not implemented¶
These routes are wired in the router but the handlers return 501 {"error": "not implemented"}. The
org_invitations table and its repository methods exist, but nothing calls them; this "invite a sysadmin into
another org" concept is unrelated to the user invite flow.
| Route | Intended use |
|---|---|
PUT /api/v1/protected/users/me, DELETE /api/v1/protected/users/me |
Self-service profile edit and account deletion |
POST /api/v1/protected/invitations/:invitationId/accept |
Sysadmin accepts an org invitation |
GET, PUT /api/v1/internal/orgs/:orgId |
Get and update an organization |
GET /api/v1/internal/orgs/:orgId/members, DELETE …/members/:userId |
Org members |
POST, GET /api/v1/internal/orgs/:orgId/invitations, DELETE …/invitations/:invitationId |
Sysadmin invitations |
GET /api/v1/internal/platform/orgs/:orgId |
Get one organization (platform) |
GET /api/v1/internal/platform/users, GET, DELETE …/users/:userId |
Platform-wide user management |
Known gaps¶
- Three error body shapes.
apiError()in the auth and IdP handlers returns{"error":{"code","message"}}; the org, user, token and company-code handlers return{"error":"<text>"}; the global FiberErrorHandlerreturns{"error":"<slug>","message"}; refresh mixes all three plus{"code","message"}. The partner page documents each shape. account_state: "pending"has a login error but no flow sets it.- Dead SSO code.
AuthService.WebLogin/ExchangeAuthCodeand theauth_codestable support an authorization-code flow that no route calls. - No per-caller authorization on
/internal(see Service-to-service routes). PUT /internal/orgs/:orgId/users/:userId/statusignoresorgIdand only changes the local state: it neither disables the user in Zitadel nor revokes sessions.- Logout needs a live access token (it sits under
/protected), so after 15 idle minutes logout401s and the refresh cookie survives. Tracked in the handover guide, §11. - SSE is single-replica (see Sessions and the event stream).
- Discovery document URLs aren't absolute with the default issuer (see Token design).
Configuration reference¶
Names and defaults only. Secret values (keys, PAT, internal token, database password) live in the deployment secrets; see Deployment.
| Variable | Default | Purpose |
|---|---|---|
AUTHAPI_SERVER_PORT |
8080 |
Listen port |
AUTHAPI_WRITE_TIMEOUT |
0 (unlimited) |
Must stay unlimited for the SSE stream |
AUTHAPI_CORS_ORIGIN |
http://localhost:8080 |
Comma-separated allowed origins |
AUTHAPI_COOKIE_SECURE |
true |
false only for local HTTP |
AUTHAPI_COOKIE_DOMAIN |
required | localhost/127.0.0.1 drop Secure and Domain |
AUTHAPI_DB_HOST, _USER, _PASSWORD, _NAME |
required | Postgres connection |
AUTHAPI_DB_PORT, _SSLMODE, _MAX_CONNS |
5432, disable, 10 |
Postgres connection |
AUTHAPI_JWT_RSA_PRIVATE_KEY |
required | Base64 PEM, PKCS#8 or PKCS#1 |
AUTHAPI_JWT_REFRESH_SECRET |
required | HS256 secret; also the root of the social sign-in signing key |
AUTHAPI_JWT_ACCESS_EXPIRY |
900 (seconds) |
Keep short: it is the exposure window after a revoke |
AUTHAPI_JWT_REFRESH_EXPIRY |
168h |
Go duration |
JWT_ISSUER |
authapi |
iss claim and discovery issuer |
ZITADEL_DOMAIN |
required | Zitadel base URL |
ZITADEL_PAT / ZITADEL_PAT_PATH |
one required | Service-user PAT; the file path wins |
AUTHAPI_ZITADEL_DEFAULT_ORG |
required | Platform org name, seeded locally as 00000000-0000-0000-0000-000000000001 |
AUTHAPI_DEFAULT_ORG_COMPANY_CODE |
required | Company code of the platform org; must match the license |
AUTHAPI_ZITADEL_SYSADMIN_USER |
required | Login name bootstrapped as the first sysadmin |
COREAPI_BASE_URL |
http://localhost:8081 |
For AuthAPI → CoreAPI calls |
COREAPI_AUTHAPI_PSK |
empty | Shared internal token; empty disables /internal and the role lookup |
PLAYTELLY_MAGIC_LINK_TOKEN_DURATION |
10m |
Invite / reinvite link lifetime |
PLAYTELLY_PASSWORD_RESET_TOKEN_DURATION |
1h |
Reset link lifetime |
AUTHAPI_FRONTEND_URL |
http://localhost:5173 |
tellyid base URL: reset links, social sign-in screens, default redirect |
AUTHAPI_PUBLIC_URL |
http://localhost:3002 |
How browsers reach AuthAPI (social sign-in callback) |
AUTHAPI_IDP_PROVIDERS |
empty (feature off) | key:<zitadel idp id> pairs; see Social sign-in internals |
AUTHAPI_REDIRECT_ORIGINS |
CORS origins + frontend URL | Allowed social sign-in redirect_uri origins |
AUTHAPI_HOSTING_MODE |
cloud |
cloud or on_prem |
AUTHAPI_LICENSE_KEY |
none | Required for cloud: the instance's own license |
AUTHAPI_LICENSE_CLOUD_URL |
none | Required for on_prem: where to fetch a license |
AUTHAPI_LICENSE_PUBLIC_KEY |
required | Base64 Ed25519 public key that verifies licenses |
AUTHAPI_LICENSE_PRIVATE_KEY |
none | Only on the instance that mints on-prem licenses |
PLAYTELLY_INVITE_CODE_LENGTH, PLAYTELLY_INVITE_CODE_DURATION |
none | Dead since 2026-08-13; nothing reads them |
Internal routes reference¶
Routes partners never call: /api/v1/internal/* (CoreAPI, internal token) and the on-prem licensing routes
(X-License-Key). Routes that return 501 are in Not implemented instead.
Related¶
- Authentication API: the partner reference
- Auth, identity and RBAC handover guide
- Social sign-in internals
- Tenancy API: the CoreAPI side of invites, org creation and self-signup
Change history¶
Internal and documentation changes. Partner-visible API changes are in the Authentication API changelog.
2026-11-16¶
- AuthAPI docs split: the partner reference keeps public and signed-in routes;
/internal/*, phone-home and license status moved to this page andauthapi-internal.yaml. Social sign-in internals moved from the sign-in guide to Social sign-in internals.
2026-08-31¶
- Password reset flow added (tokens in
password_reset_tokens, e-mail sent by CoreAPI).
2026-08-13¶
- Invite codes replaced by magic links (
magic_link_tokens);PLAYTELLY_INVITE_CODE_*became dead.
2026-08-07¶
- Documentation rewritten after a full audit against the code. The previous version (2026-06-29) described a service without Zitadel, sessions, invites or licensing.
- Login resolves
company_codeto a local org, then a Zitadel org, then checks membership. The platform org is seeded at startup fromAUTHAPI_ZITADEL_DEFAULT_ORG. - Self-signup no longer creates anything in Zitadel until approval; approval generates a random temporary password and forces a change at first login. The old public "join an existing org" sign-up endpoint was removed.
- Company code, on-prem phone-home and status, Ed25519 licenses with a grace window. Schema moved from SQL migrations to GORM auto-migration.
- Refresh tokens carry a stable session ID and device metadata; session endpoints and the SSE stream added.
Reconciliation endpoint added. JWKS and discovery endpoints added. The JWT
orgsarray became a singleorg.
2026-06-29¶
POST /api/v1/login/mobileremoved;PlayTelly-Platformheader added toPOST /api/v1/login.
2026-06-23¶
- First AuthAPI documentation.