Skip to content

Class: AuthClient

Class: AuthClient

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

@vendidit/auth-client — public API barrel.

Everything a consumer needs to integrate the SDK lives here. The /core/* tree contains the implementation; framework adapters live under /framework-adapters/.

Typical consumer usage:

import { createAuthClient } from ‘@vendidit/auth-client’; const auth = createAuthClient({ apiBaseUrl: ‘https://auth.vendidit.com/api/v1’, appCode: ‘marketplace-buyer’, });

const result = await auth.loginWithPassword({ email, password }); if (result.requires_2fa) { const code = await promptUserForTotp(); await auth.loginWithPassword({ email, password, twoFactorCode: code }); }

const off = auth.on(‘logged_out’, () => router.push(‘/login’));

Advanced customization — swap ports:

import { createAuthClient, MemoryTokenStore } from ‘@vendidit/auth-client’; const auth = createAuthClient({ apiBaseUrl: ’…’, ports: { tokenStore: new MemoryTokenStore() }, // SSR-safe });

Constructors

Constructor

new AuthClient(config): AuthClient

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

Parameters

config

AuthClientConfig

Returns

AuthClient

Methods

acceptInvitation()

acceptInvitation(invitationId): Promise<Organization | null>

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

POST /me/invitations/{id}/accept — join the org. After success call switchOrg(organizationId) to scope the active token.

Parameters

invitationId

string

Returns

Promise<Organization | null>


adminListUserSessions()

adminListUserSessions(userId): Promise<SessionRecord[]>

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

GET /admin/users/{userId}/sessions — list a target user’s active sessions. Admin only. See getSessions() for the self-service equivalent.

Parameters

userId

string

Returns

Promise<SessionRecord[]>


adminRevokeUserSessions()

adminRevokeUserSessions(userId): Promise<void>

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

POST /admin/users/{userId}/revoke-sessions — terminate every session for a target user. Admin only. Equivalent of logoutAll() applied to someone else.

Parameters

userId

string

Returns

Promise<void>


adminTerminateUserSession()

adminTerminateUserSession(userId, sessionId): Promise<void>

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

DELETE /admin/users/{userId}/sessions/{sessionId} — terminate one specific session belonging to a target user. Admin only. Granular counterpart to adminRevokeUserSessions().

Parameters

userId

string

sessionId

string

Returns

Promise<void>


authenticatedRequest()

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

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

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>>


changePassword()

changePassword(currentPassword, newPassword): Promise<void>

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

Change the password for the currently-signed-in user. Server verifies the current password before applying the change. Authenticated flow — caller must be signed in.

Parameters

currentPassword

string

newPassword

string

Returns

Promise<void>


completeSso()

completeSso(params): Promise<AuthResponse>

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

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>


createInvitation()

createInvitation(orgId, body): Promise<InvitationRecord>

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

POST /orgs/{orgId}/invitations — invite by email.

Parameters

orgId

string

body

CreateInvitationRequest

Returns

Promise<InvitationRecord>


createOrg()

createOrg(body): Promise<Organization>

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

POST /admin/organizations — create. Admin only.

Parameters

body

CreateOrgRequest

Returns

Promise<Organization>


createOrgRole()

createOrgRole(orgId, body): Promise<OrgRoleRecord>

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

POST /orgs/{orgId}/roles — create a custom role.

Parameters

orgId

string

body

CreateOrgRoleRequest

Returns

Promise<OrgRoleRecord>


declineInvitation()

declineInvitation(invitationId): Promise<void>

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

POST /me/invitations/{id}/decline.

Parameters

invitationId

string

Returns

Promise<void>


deleteMyAccount()

deleteMyAccount(currentPassword): Promise<void>

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

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>


deleteOrg()

deleteOrg(orgId): Promise<void>

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

DELETE /admin/organizations/{orgId}. Admin only.

Parameters

orgId

string

Returns

Promise<void>


deleteOrgRole()

deleteOrgRole(orgId, roleId): Promise<void>

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

DELETE /orgs/{orgId}/roles/{roleId}.

Parameters

orgId

string

roleId

string

Returns

Promise<void>


destroy()

destroy(): void

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

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

Returns

void


disableTwoFactor()

disableTwoFactor(params): Promise<void>

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

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

Parameters

params
code

string

password

string

Returns

Promise<void>


enableTwoFactor()

enableTwoFactor(code): Promise<void>

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

Submit the first TOTP code to complete enrollment.

Parameters

code

string

Returns

Promise<void>


getAccessToken()

getAccessToken(): Promise<string | null>

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

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>


getCurrentUser()

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

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

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


getDecodedClaims()

getDecodedClaims(): DecodedAccessToken | null

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

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

Returns

DecodedAccessToken | null


getMyOrgs()

getMyOrgs(): Promise<MyOrgRecord[]>

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

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[]>


getOrg()

getOrg(orgId): Promise<Organization>

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

GET /orgs/{orgId} — read settings. Requires org:read.

Parameters

orgId

string

Returns

Promise<Organization>


getOrgRole()

getOrgRole(orgId, roleId): Promise<OrgRoleRecord>

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

GET /orgs/{orgId}/roles/{roleId}.

Parameters

orgId

string

roleId

string

Returns

Promise<OrgRoleRecord>


getRegistrationPolicy()

getRegistrationPolicy(appCode?): Promise<RegistrationPolicy>

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

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>


getSessions()

getSessions(): Promise<SessionRecord[]>

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

List the current user’s active sessions across devices.

Returns

Promise<SessionRecord[]>


getSnapshot()

getSnapshot(): AuthSnapshot

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

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


getStatus()

getStatus(): AuthStatus

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

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

Returns

AuthStatus


getUsersBulk()

getUsersBulk(req): Promise<LookupUserRecord[]>

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

Bulk-resolve users by email and/or id in a single call. Admin only (system_admin or super_admin); 403 otherwise. Either input array may be omitted; both empty returns an empty array.

Use this when a back-office tool needs to render N users from a mix of identifiers — e.g. “look up these 30 emails” — instead of issuing N separate /admin/users requests.

Parameters

req
emails?

string[]

ids?

string[]

Returns

Promise<LookupUserRecord[]>


hardDeleteUser()

hardDeleteUser(params): Promise<void>

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

Hard-delete a user (AUDIT C8). system_admin only — server-side gate.

Parameters

params
reason

string

userId

string

Returns

Promise<void>


impersonate()

impersonate(params): Promise<AuthResponse>

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

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>


isAuthenticated()

isAuthenticated(): boolean

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

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

Returns

boolean


isImpersonating()

isImpersonating(): boolean

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

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

Returns

boolean


isOfflineMode()

isOfflineMode(): boolean

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

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

Returns

boolean


isReady()

isReady(): boolean

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

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

Returns

boolean


listAssignablePermissions()

listAssignablePermissions(orgId): Promise<AssignablePermissionRecord[]>

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

GET /orgs/{orgId}/permissions/assignable — for the role-editor picker.

Parameters

orgId

string

Returns

Promise<AssignablePermissionRecord[]>


listAuditLog()

listAuditLog(q?): Promise<AuditLogResult>

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

GET /admin/audit-log — paginated, admin-only.

Parameters

q?

AuditLogQuery

Returns

Promise<AuditLogResult>


listMyInvitations()

listMyInvitations(): Promise<InvitationRecord[]>

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

GET /me/invitations — invitations addressed to me.

Returns

Promise<InvitationRecord[]>


listOrgInvitations()

listOrgInvitations(orgId): Promise<InvitationRecord[]>

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

GET /orgs/{orgId}/invitations — list pending org-side.

Parameters

orgId

string

Returns

Promise<InvitationRecord[]>


listOrgMembers()

listOrgMembers(orgId): Promise<OrgMemberRecord[]>

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

GET /orgs/{orgId}/members. Requires org:members:read.

Parameters

orgId

string

Returns

Promise<OrgMemberRecord[]>


listOrgRoles()

listOrgRoles(orgId): Promise<OrgRoleRecord[]>

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

GET /orgs/{orgId}/roles. Requires org:roles:read.

Parameters

orgId

string

Returns

Promise<OrgRoleRecord[]>


listUsers()

listUsers(req?): Promise<ListUsersResult>

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

GET /admin/users — paginated list. Admin only.

Parameters

req?

ListUsersRequest

Returns

Promise<ListUsersResult>


loginWithPassword()

loginWithPassword(params): Promise<AuthResponse>

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

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>


logoutAll()

logoutAll(): Promise<void>

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

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>


logoutCurrent()

logoutCurrent(): Promise<void>

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

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

Returns

Promise<void>


off()

off<T>(type, handler): void

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

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


on()

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

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

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


ready()

ready(): Promise<AuthSnapshot>

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

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>


refreshAccessToken()

refreshAccessToken(context?): Promise<TokenPair>

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

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>


register()

register(params): Promise<AuthResponse>

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

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>


removeOrgMember()

removeOrgMember(orgId, userId): Promise<void>

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

DELETE /orgs/{orgId}/members/{userId}. Requires org:members:remove.

Parameters

orgId

string

userId

string

Returns

Promise<void>


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

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

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>


requestPasswordReset()

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

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

Request a password-reset email. Server returns 200 regardless of whether the email exists (anti-enumeration). Anonymous flow.

Parameters

email

string

appCode?

string

Returns

Promise<void>


resendVerificationEmail()

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

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

Re-issue a verification email. Always succeeds (anti-enumeration).

Parameters

email

string

appCode?

string

Returns

Promise<void>


resetPassword()

resetPassword(token, newPassword): Promise<void>

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

Reset a password using a single-use token from the reset email. After success, the user must log in normally with the new password. Anonymous flow — no existing session required.

Parameters

token

string

newPassword

string

Returns

Promise<void>


revokeInvitation()

revokeInvitation(orgId, invitationId): Promise<void>

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

DELETE /orgs/{orgId}/invitations/{id} — revoke.

Parameters

orgId

string

invitationId

string

Returns

Promise<void>


setupTwoFactor()

setupTwoFactor(): Promise<{ provisioningUri: string; secret: string; }>

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

Begin TOTP enrollment. Returns the provisioning URI + base32 secret for the consumer to render as a QR code.

Returns

Promise<{ provisioningUri: string; secret: string; }>


setUserPassword()

setUserPassword(userId, newPassword): Promise<void>

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

POST /auth/admin/set-password — reset a user’s password. Admin only.

Parameters

userId

string

newPassword

string

Returns

Promise<void>


setUserRoles()

setUserRoles(userId, roleCodes): Promise<void>

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

PUT /admin/users/{id}/roles — replace base roles. Admin only.

Parameters

userId

string

roleCodes

string[]

Returns

Promise<void>


startSso()

startSso(params): Promise<SsoStartResult>

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

Begin an SSO sign-in. The SDK auto-generates a PKCE pair, persists the verifier (so a subsequent /sso/callback POST can redeem it), and returns the provider’s auth URL for the caller to navigate to.

Parameters

params

SsoStartParams

Returns

Promise<SsoStartResult>


subscribe()

subscribe(listener): () => void

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

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


switchOrg()

switchOrg(organizationId): Promise<TokenPair>

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

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>


terminateSession()

terminateSession(sessionId): Promise<void>

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

Terminate a specific session. Passing the caller’s own session id logs them out as a side-effect.

Parameters

sessionId

string

Returns

Promise<void>


updateOrg()

updateOrg(orgId, body): Promise<Organization>

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

PUT /orgs/{orgId} — update settings. Requires org:update.

Parameters

orgId

string

body

UpdateOrgRequest

Returns

Promise<Organization>


updateOrgMemberStatus()

updateOrgMemberStatus(orgId, userId, status): Promise<void>

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

PUT /orgs/{orgId}/members/{userId}/status. Requires org:members:update.

Parameters

orgId

string

userId

string

status

string

Returns

Promise<void>


updateOrgRole()

updateOrgRole(orgId, roleId, body): Promise<OrgRoleRecord>

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

PUT /orgs/{orgId}/roles/{roleId} — edit a custom role.

Parameters

orgId

string

roleId

string

body

UpdateOrgRoleRequest

Returns

Promise<OrgRoleRecord>


verifyEmail()

verifyEmail(token): Promise<void>

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

Consume a single-use email-verification token from the verify email.

Parameters

token

string

Returns

Promise<void>


verifyMagicLink(token): Promise<AuthResponse>

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

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>


whoami()

whoami(): Promise<User>

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

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.

Returns

Promise<User>