Core API
Everything on this page is exported from @circle-rd/auth-ai. The core uses Web-standard APIs only (fetch, Request, Web Crypto), with no node: import.
AuthClient
createAuthClient(config, options?) (or new AuthClient(...)) returns the OIDC relying party. It keeps no session: callers persist the handshake, the tokens and the claims. Discovery and signing keys are cached for one hour and reloaded on the next call after that; a failed discovery is not cached.
| Member | Signature | Description |
|---|---|---|
config | ResolvedAuthClientConfig | The validated configuration. |
fetch | typeof fetch | The fetch used for every request. |
startLogin | (options?: { prompt?, loginHint? }) => Promise<LoginRequest> | Builds the authorization URL (PKCE S256, state, nonce, one resource per entry of resources). prompt is one of login, consent, select_account, create, none. |
handleCallback | (callbackUrl: URL | string, handshake: LoginHandshake) => Promise<LoginResult> | Exchanges the code and verifies the ID token and its nonce. No resource is sent on the exchange. |
verifyIdToken | (idToken: string) => Promise<IdTokenClaims> | Verifies an ID token issued for clientId. |
refresh | (refreshToken: string, options?: { resource?: string }) => Promise<TokenSet> | Refresh grant, optionally narrowed to one audience. Never sends scope. Prefer GrantManager. |
logoutUrl | (options?: { idTokenHint?, state? }) => Promise<string> | RP-initiated logout URL. Throws OIDC_004 when the provider advertises no end_session_endpoint. |
revoke | (token: string, hint?: "access_token" | "refresh_token") => Promise<void> | Throws OIDC_004 without a revocation_endpoint. |
introspect | (token: string, hint?) => Promise<IntrospectionResult> | Throws OIDC_004 without an introspection_endpoint. |
verifyJwt | (token: string, options: { audience: string; typ?: string }) => Promise<JWTPayload> | Low-level: verifies signature, issuer, audience and expiry. Prefer the bearer and logout verifiers. |
clientCredentials | (options?: { scope?, resource? }) => Promise<TokenSet> | Machine token for the application itself. Throws CFG_001 without a clientSecret. |
import { createAuthClient } from "@circle-rd/auth-ai";
import type { LoginHandshake } from "@circle-rd/auth-ai";
const auth = createAuthClient({
issuer: "https://auth.example.com",
clientId: "my-app",
clientSecret: "<client-secret>",
redirectUri: "https://app.example.com/auth/callback",
});
// Start: persist `handshake` (sealed) between the redirect and the callback.
const { url, handshake } = await auth.startLogin({ prompt: "login" });
// Callback: `callbackUrl` is the URL the provider redirected to.
async function complete(callbackUrl: string, saved: LoginHandshake) {
const { tokens, claims, sessionId } = await auth.handleCallback(callbackUrl, saved);
return { sub: claims.sub, sessionId, hasRefreshToken: tokens.refreshToken !== undefined };
}
You rarely call these directly: createAuthHandlers does the whole flow. Use them to build your own.
Types
| Type | Fields |
|---|---|
TokenSet | accessToken, tokenType, expiresAt (unix seconds), optional scope, refreshToken, idToken. |
LoginHandshake | state, nonce, codeVerifier. |
LoginRequest | url, handshake. |
LoginResult | tokens (a TokenSet with a guaranteed idToken), claims (IdTokenClaims), sessionId (the sid, or undefined). |
IntrospectionResult | active, and optionally scope, client_id, sub, username, iss, aud, exp, iat; other fields are kept. |
GrantManager
Described in Sessions and grants. new GrantManager({ auth, store, lock?, expirySkewSeconds? }) or createGrantManager(options).
| Method | Description |
|---|---|
save(grantId, refreshToken) | Stores the refresh token from sign-in, replacing any older chain, and forgets cached access tokens. |
has(grantId) | Whether a grant exists. |
getAccessToken(grantId, { resource? }) | Returns { accessToken, expiresAt } for one audience, from cache or by refreshing. Throws TOK_002 when there is no usable grant. |
refreshTokens(grantId) | Refreshes without narrowing and returns the whole TokenSet, ID token included. |
invalidate(grantId, resource?) | Drops a cached access token the API refused. |
revoke(grantId) | Revokes the refresh token at the provider, then forgets the grant. |
Interfaces to implement, and their in-memory implementations MemoryGrantStore and InProcessGrantLock, are covered in Implement the stores.
AiClient and UserAi
import { createAiClient } from "@circle-rd/auth-ai";
import type { AuthClient, GrantManager } from "@circle-rd/auth-ai";
declare const auth: AuthClient;
declare const grants: GrantManager;
const ai = createAiClient({ auth, grants });
const user = ai.forUser("user-sub"); // the grant id, typically the user's `sub`
const account = await user.wallet.getAccount();
const models = await user.gateway.listModels(); // needs `gatewayUrl`
ai.forUser(grantId) returns a UserAi with wallet: WalletClient and a gateway: GatewayClient getter that throws CFG_001 when gatewayUrl is not configured.
WalletClient
Reads the signed-in user's own wallet with a token for the auth-service audience and the wallet:self:read scope. An application only reads: the gateway makes the debits.
| Method | Description |
|---|---|
getAccount() | WalletAccount: balance (bigint, negative when in debt), isUnlimited, canSpend, currency ("eur"). |
getStats({ days? }) | WalletStats over 1 to 90 days (30 by default): total, notBilled, calls, and series by day, application, kind and model. |
getSessionUsage(sessionId, { days? }) | WalletSessionUsage for one session_id, for the calling application only: total, notBilled, calls, byModel. |
listTransactions({ limit?, cursor?, type? }) | WalletTransactionPage (items, nextCursor), newest first. Pass nextCursor back until it is null. type is one of topup, grant, refund, usage, adjust, reversal. |
getTopupOptions() | TopupOptions: enabled, currency, minCents, maxCents. |
topupUrl() | The Credit tab of the user's profile: <issuer>/profile. |
All amounts are bigint micro-euros: see Credit wallet and LiteLLM gateway. formatEuros(amount, fractionDigits = 2) and MICRO_PER_EUR are exported for display.
GatewayClient
The LiteLLM gateway on behalf of a signed-in user.
| Member | Description |
|---|---|
openAiBaseUrl | <gatewayUrl>/v1: the baseURL of an OpenAI-compatible SDK. |
fetch | A fetch that signs requests to the gateway with a fresh user token, replacing any Authorization header. It throws CFG_001 for any other origin, and drops the cached token on a 401. |
getAccessToken() | A fresh access token, for clients that cannot take a custom fetch. |
listModels() | GatewayModel[] (id, optional object, created, owned_by) from /v1/models. |
listAgents() | GatewayAgent[] (agent_id, agent_name) from /v1/agents. |
listMcpServers() | GatewayMcpServer[] (server_id, optional server_name, alias, description, transport) from /v1/mcp/server. |
mcpUrl(serverName?) | <gatewayUrl>/mcp, or <gatewayUrl>/<serverName>/mcp. The name must match ^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$, otherwise CFG_001. |
postJson(path, body) | POSTs JSON to a gateway route and returns the parsed answer as unknown; you validate it. A refusal becomes a gateway error. |
A listing whose answer is not the expected shape throws GW_005. Helpers:
| Export | Description |
|---|---|
isInsufficientCredit(err) | True for an AuthAiError with code GW_001. |
isInsufficientCreditStatus(err) | True for any error exposing status === 402, such as the error of an OpenAI-compatible SDK. |
toGatewayError(status, body, headers?) | Maps a failed gateway answer to the registry. |
Claims helpers and schemas
hasRole, hasPermission, hasFeature and getFeature are described in Entitlements. idTokenClaimsSchema and accessTokenClaimsSchema are the zod schemas that validate tokens; unknown claims are kept as they are. The types IdTokenClaims, FeatureValue and PermissionAction are exported.
Errors
AuthAiError (with code, message, details, cause, toJSON() and toPublicJSON()) and the factory registry ERR are exported, with the types AuthAiErrorCode, AuthAiErrorDetails and AuthAiErrorOptions. ERR.<CODE>(message?, { details?, cause? }) creates an error; the message defaults to the registry's. See Error codes.
Configuration
Every option of createAuthClient, createAuthHandlers and the other clients, with defaults and validation rules.
Server API
Reference of @circle-rd/auth-ai/server: Bearer verification, scopes, protected-resource metadata, back-channel logout and the machine API for billing and consumption.