Skip to content
rw3iss Auth

AuthClient

AuthClient

Defined in: auth-client/src/core/auth-client.ts:187

The SDK core — owns authentication context (tokens, session snapshot, refresh scheduling, cross-tab sync) and exposes the API surface two ways:

Namespaced modules (recommended): client.auth, client.account, client.sessions, client.users, client.organizations, client.apps, client.services, client.pools, client.audit.

The endpoint implementations live in the modules (src/core/modules/*); this class is the session engine: config, ports, reactive snapshot, token storage/refresh, cross-tab sync, and the session-mutating operations the modules delegate back to (see module-context.ts for the architecture diagram).

Constructors

Constructor

new AuthClient(config): AuthClient

Defined in: auth-client/src/core/auth-client.ts:263

Parameters

config

AuthClientConfig

Returns

AuthClient

Properties

account

readonly account: AccountModule

Defined in: auth-client/src/core/auth-client.ts:254


apps

readonly apps: AppsModule

Defined in: auth-client/src/core/auth-client.ts:258


audit

readonly audit: AuditModule

Defined in: auth-client/src/core/auth-client.ts:261


auth

readonly auth: AuthModule

Defined in: auth-client/src/core/auth-client.ts:253


organizations

readonly organizations: OrganizationsModule

Defined in: auth-client/src/core/auth-client.ts:257


pools

readonly pools: PoolsModule

Defined in: auth-client/src/core/auth-client.ts:260


services

readonly services: ServicesModule

Defined in: auth-client/src/core/auth-client.ts:259


sessions

readonly sessions: SessionsModule

Defined in: auth-client/src/core/auth-client.ts:255


users

readonly users: UsersModule

Defined in: auth-client/src/core/auth-client.ts:256

Methods

AuthClient is the session engine — endpoint methods live on the module classes (AuthModule, UsersModule, …; see their own pages). The methods below are the core lifecycle surface plus the session-mutating operations the modules delegate to.

Client lifecycle & state · 10 methods

Boot, readiness, snapshot subscription, raw authenticated requests and teardown — infrastructure on the client core itself (no module).

getSnapshot()

getSnapshot(): AuthSnapshot

Defined in: auth-client/src/core/auth-client.ts:524

Snapshot of the current reactive state. Reference-stable: the same object is returned until something changes. Adapters use this with useSyncExternalStore / createMemo / computed.

Returns

AuthSnapshot


subscribe()

subscribe(listener): () => void

Defined in: auth-client/src/core/auth-client.ts:531

Subscribe to snapshot changes. Returns the unsubscribe function. Adapters typically register one subscriber per component instance via their framework’s effect primitive.

Parameters

listener

(snapshot) => void

Returns

() => void


ready()

ready(): Promise<AuthSnapshot>

Defined in: auth-client/src/core/auth-client.ts:541

Resolves with the current snapshot once bootstrap completes. UIs gate their first authenticated render on this — a splash screen shows while ready() is pending.

Returns

Promise<AuthSnapshot>


isReady()

isReady(): boolean

Defined in: auth-client/src/core/auth-client.ts:546

True once bootstrap (auto / lazy / offline) has finished.

Returns

boolean


getStatus()

getStatus(): AuthStatus

Defined in: auth-client/src/core/auth-client.ts:551

Current lifecycle status. Equivalent to getSnapshot().status.

Returns

AuthStatus


isOfflineMode()

isOfflineMode(): boolean

Defined in: auth-client/src/core/auth-client.ts:557

True when the client is configured offline. All flow methods throw OfflineModeError; read-state methods return null/false.

Returns

boolean


authenticatedRequest()

authenticatedRequest<T>(req): Promise<TransportResponse<T>>

Defined in: auth-client/src/core/auth-client.ts:850

Issue an authenticated HTTP request against an arbitrary URL. On 401, the SDK refreshes (under the mutex) and retries once. On refresh failure, it emits session_expired and clears local state before re-throwing the original 401.

Use this for downstream service calls that share the same JWT — e.g., a marketplace API endpoint that validates the auth-server’s token locally. The retry semantics handle the racy “token expired between our last refresh and this call” case without the consumer writing it themselves.

Disable the retry via config.autoRetryOn401 = false. Calls that are themselves to /auth/refresh skip the retry to avoid a loop.

Type Parameters

T

T = unknown

Parameters

req

TransportRequest

Returns

Promise<TransportResponse<T>>


destroy()

destroy(): void

Defined in: auth-client/src/core/auth-client.ts:1162

Tear down — unsubscribes from cross-tab, clears event listeners. Called by the host app on unmount; subsequent calls are no-ops.

Returns

void


on()

on<T>(type, handler): () => void

Defined in: auth-client/src/core/auth-client.ts:566

Subscribe to an event. Returns the unsubscribe function.

Type Parameters

T

T extends "authenticated" | "logged_out" | "token_refreshed" | "requires_two_factor" | "session_expired" | "status_changed" | "org_switched" | "error"

Parameters

type

T

handler

AuthEventHandler<T>

Returns

() => void


off()

off<T>(type, handler): void

Defined in: auth-client/src/core/auth-client.ts:571

Manual unsubscribe — usually use the return of on() instead.

Type Parameters

T

T extends "authenticated" | "logged_out" | "token_refreshed" | "requires_two_factor" | "session_expired" | "status_changed" | "org_switched" | "error"

Parameters

type

T

handler

AuthEventHandler<T>

Returns

void


Authentication & identityclient.auth.* · 16 methods

Credentials in/out (password, SSO, magic link), refresh, org switching and the current-identity getters.

loginWithPassword()

loginWithPassword(params): Promise<AuthResponse>

Defined in: auth-client/src/core/auth-client.ts:626

Password login. On success, persists tokens + emits “authenticated”. On 2FA challenge, returns {requires_2fa: true} without throwing. On hard failure (bad password, locked account, etc.), throws.

Parameters

params

LoginParams

Returns

Promise<AuthResponse>


register()

register(params): Promise<AuthResponse>

Defined in: auth-client/src/core/auth-client.ts:661

Register a new user. The mode field on the server lets registration also act as login when the email is already known (see auth-server RegistrationMode); the SDK exposes this via the explicit register_or_login parameter.

Parameters

params

RegisterParams

Returns

Promise<AuthResponse>


completeSso()

completeSso(params): Promise<AuthResponse>

Defined in: auth-client/src/core/auth-client.ts:650

Complete an SSO sign-in. Pass the code + state the provider redirected back with. The SDK exchanges with the auth-server, handles the PKCE auth_code redemption automatically, and emits “authenticated” on success.

Parameters

params
code

string

provider?

string

state

string

Returns

Promise<AuthResponse>


requestMagicLink(email, appCode?): Promise<void>

Defined in: auth-client/src/core/auth-client.ts:1089

Request a magic-link email. Anonymous flow; server is silent on whether the email is registered.

appCode defaults to the AuthClient’s configured app code so the resulting token-pair scopes correctly. Pass an explicit code to override.

Parameters

email

string

appCode?

string

Returns

Promise<void>


verifyMagicLink(token): Promise<AuthResponse>

Defined in: auth-client/src/core/auth-client.ts:1107

Verify a magic-link token. On success, persists the returned tokens AND emits the authenticated event — the AuthClient’s snapshot transitions exactly as if the user had logged in via password. Caller’s UI can subsequently navigate away.

Throws on any error shape; the typical failure is TokenInvalid (unknown / expired / consumed token — all collapsed for anti-enumeration).

Parameters

token

string

Returns

Promise<AuthResponse>


getRegistrationPolicy()

getRegistrationPolicy(appCode?): Promise<RegistrationPolicy>

Defined in: auth-client/src/core/auth-client.ts:1022

Fetch the public registration policy for an app. Anonymous — no token required. Useful for rendering the login / register UI BEFORE the user submits: pre-filter SSO buttons against allowed_auth_methods, show a domain hint from allowed_email_domains. Server still enforces on the actual register/login call. Migration 013.

If appCode is omitted, defaults to the AuthClient’s configured appCode (set on construction). Throws if neither is set.

Parameters

appCode?

string

Returns

Promise<RegistrationPolicy>


logoutCurrent()

logoutCurrent(): Promise<void>

Defined in: auth-client/src/core/auth-client.ts:684

Logout the current session — revokes the refresh token server-side, clears local state, emits “logged_out”.

Returns

Promise<void>


logoutAll()

logoutAll(): Promise<void>

Defined in: auth-client/src/core/auth-client.ts:703

Revoke every refresh token for the current user AND bump the server’s per-user token-version so any outstanding access token is immediately invalid cross-replica. AUDIT 1.10.

Returns

Promise<void>


refreshAccessToken()

refreshAccessToken(context?): Promise<TokenPair>

Defined in: auth-client/src/core/auth-client.ts:728

Refresh the access token using the stored refresh token. Coalesced — concurrent calls share one in-flight request.

Optional context switches the issued token’s org and/or app scope. The server honors either or both:

  • organizationId — re-scope to a different org the user belongs to. Membership is re-verified each refresh.
  • appCode — re-scope to a different consuming app.

For the common “switch org” case prefer switchOrg(orgId) — it’s a thinner shorthand that also emits the org_switched event so subscribers can react.

Parameters

context?
appCode?

string

organizationId?

string

Returns

Promise<TokenPair>


switchOrg()

switchOrg(organizationId): Promise<TokenPair>

Defined in: auth-client/src/core/auth-client.ts:768

Switch the active organization context. Refreshes the token with the new organization_id, persists the new token-pair, and emits org_switched (in addition to the usual token_refreshed).

Requires the user to be a member of the target org; the server 403s otherwise and the call throws. Membership is verified server-side on every switch, so a stale MyOrgRecord from getMyOrgs() won’t sneak the caller into an org they were removed from.

Pair with <OrgSwitcher> for a drop-in UI affordance, or call directly from your own selector.

Parameters

organizationId

string

Returns

Promise<TokenPair>


whoami()

whoami(): Promise<User>

Defined in: auth-client/src/core/auth-client.ts:784

Hit /auth/me — the source of truth for the current user. Use this after a permission grant on the server side to refresh local state.

The server returns the identity fields flat at the top level (user_id, email, first_name, roles, permissions, …), not wrapped under a user key. Earlier versions of this method did resp.body.user and got undefined — every consumer crashed on .display_name or similar. We now reshape into a User-compatible object so callers can rely on the typed return value.

Returns

Promise<User>

getAccessToken()

getAccessToken(): Promise<string | null>

Defined in: auth-client/src/core/auth-client.ts:585

Current access token, if any. Returns null when logged out. The Transport already attaches this automatically; consumers calling other HTTP clients (axios, etc.) can use this to attach manually.

Returns

Promise<string | null>


isAuthenticated()

isAuthenticated(): boolean

Defined in: auth-client/src/core/auth-client.ts:577

Are we currently authenticated? Synchronous; reflects cached state. In offline mode this is always false.

Returns

boolean


getDecodedClaims()

getDecodedClaims(): DecodedAccessToken | null

Defined in: auth-client/src/core/auth-client.ts:604

Decoded claims of the current access token. Null when logged out or token is malformed. Synchronous — reads the cached value.

Returns

DecodedAccessToken | null


getCurrentUser()

getCurrentUser(): { email: string; id: string; } | null

Defined in: auth-client/src/core/auth-client.ts:611

Convenience: current user as a User object, reconstructed from the decoded token. For a server-authoritative snapshot, call whoami() — it hits /auth/me.

Returns

{ email: string; id: string; } | null


isImpersonating()

isImpersonating(): boolean

Defined in: auth-client/src/core/auth-client.ts:619

True if the current session is an impersonation (AUDIT C7). UIs can use this to render an “Acting as X” banner.

Returns

boolean


Own accountclient.account.* · 3 methods

Password lifecycle, email verification, two-factor, own memberships + invitations, self-deletion.

disableTwoFactor()

disableTwoFactor(params): Promise<void>

Defined in: auth-client/src/core/auth-client.ts:882

Turn 2FA off — requires the current password + a fresh code.

Parameters

params
code

string

password

string

Returns

Promise<void>


getMyOrgs()

getMyOrgs(): Promise<MyOrgRecord[]>

Defined in: auth-client/src/core/auth-client.ts:823

GET /me/orgs — the authenticated user’s organization memberships. Self-service mirror of getMyApps() / /me/apps. Lets UIs render an org-switcher without admin scope (AUTH-PHP-LARAVEL-DESIGN §5).

Returns the raw organizations array; consumers map it to their own UI shape. The response shape matches the admin variant so a shared renderer can take either source.

Returns

Promise<MyOrgRecord[]>


deleteMyAccount()

deleteMyAccount(currentPassword): Promise<void>

Defined in: auth-client/src/core/auth-client.ts:1140

Delete the caller’s own account. Calls DELETE /me/account with the user’s current password + a typed “DELETE” confirmation (the server enforces both — we don’t try to be clever here). On success, the AuthClient’s snapshot transitions to anonymous (the access token’s tv claim is bumped server-side, refresh row was cascade-deleted with the user row).

Parameters

currentPassword

string

Returns

Promise<void>


User administrationclient.users.* · 1 method

Back-office user ops: listing, lookup, base roles, password override, session control, impersonation, hard delete.

impersonate()

impersonate(params): Promise<AuthResponse>

Defined in: auth-client/src/core/auth-client.ts:903

Impersonate another user (AUDIT C7). The caller’s token must carry a role authorized for impersonation (system_admin / super_admin anywhere, org_admin within their org). On success, the SDK swaps in the new token pair so subsequent requests act as the target.

Parameters

params

ImpersonateParams

Returns

Promise<AuthResponse>