Server API
Everything on this page is exported from @circle-rd/auth-ai/server.
Bearer verification
createBearerVerifier(auth, { audience }) verifies JWT access tokens minted for your API. audience must be a URL (your RFC 8707 resource identifier), otherwise CFG_001. Opaque tokens are refused (TOK_001): they carry no audience your API could trust.
| Member | Description |
|---|---|
verify(token) | Verifies a raw JWT: signature, issuer, aud containing your audience, expiry, and a client binding (azp). Returns a VerifiedAccessToken. |
verifyHeader(authorization) | Same for an Authorization header value. Throws TOK_003 when it is missing or not Bearer <token>. |
VerifiedAccessToken:
| Field | Description |
|---|---|
userId | The end user's sub, or null for a client_credentials token (a machine call), where sub equals the client id. |
clientId | The OAuth client (azp) the token was issued to. |
scopes | The scope claim split on spaces. |
audiences | The aud claim as an array. |
claims | The validated claims, including roles, permissions, features, plan and org_id when present. |
extractBearerToken(authorization) returns the token of an Authorization: Bearer <token> header or throws TOK_003.
requireScopes(token, ...scopes) throws TOK_004 ("Missing required scope: …") unless the token carries every scope. The missing ones are in details.missing.
Protected-resource metadata
RFC 9728 metadata lets MCP and OAuth clients discover which authorization server protects your API.
| Function | Description |
|---|---|
protectedResourceMetadata(auth, { resource, scopesSupported? }) | Returns { resource, authorization_servers: [issuer], bearer_methods_supported: ["header"], scopes_supported? }. |
protectedResourceMetadataPath(resource) | The path to serve it on: /.well-known/oauth-protected-resource followed by the resource's path (nothing for a bare origin). |
bearerChallenge({ resourceMetadataUrl, error?, scope? }) | The WWW-Authenticate value of a 401 or 403: Bearer resource_metadata="…", plus error (invalid_token or insufficient_scope) and scope when given. Throws CFG_001 if a value contains ", \, CR or LF. |
See Protect an API for a complete route.
Back-channel logout
createBackchannelLogoutHandler({ auth, onLogout, replayStore?, onError? }) returns a Web-standard (request: Request) => Promise<Response>. When you use createAuthHandlers, this is already mounted at <basePath>/backchannel-logout: use the function directly only for your own session layer.
| Request | Response |
|---|---|
Not POST | 405 with Allow: POST. |
Not application/x-www-form-urlencoded, body over 16 KiB, or no logout_token | 400 { "error": "invalid_request" }. |
| Token rejected | 400 { "error": "invalid_request" }, and onError receives the cause. |
onLogout throws | 500 { "error": "server_error" }, and onError receives the cause. |
| Accepted | 204. |
All responses carry Cache-Control: no-store, and none carries detail. onLogout receives { sid, sub }: end every local session whose stored sid equals the given one. The handler is called without cookies or credentials, so mount it outside any session or CSRF protection.
verifyLogoutToken(auth, token, replayStore) validates a token (spec §2.6) and returns { sid, sub, jti, iat, exp }; it throws TOK_001 for a bad typ, a missing logout event, a nonce, a missing jti, sid, sub, iat or exp, an implausible lifetime or a replay.
ReplayStore has one method, claim(jti, expiresAt): Promise<boolean>: true the first time a jti is claimed, false on a replay. MemoryReplayStore is the per-process implementation. See Implement the stores for a shared one.
MachineApi
createMachineApi(auth) returns a MachineApi: the auth-service REST API as your backend, with a client_credentials token minted from the application's own secret (one cached token per scope). It throws CFG_001 without a clientSecret. The scopes billing:read, consumption:read and consumption:write must be granted to the application; when one is not, the call throws TOK_004 with the scope in details.
An error answer from auth-service becomes API_001, with details.status and, when the body is an auth-service error, details.apiCode. An answer that is not the expected shape becomes API_002. A 401 is retried once with a fresh token.
machine.billing
Needs billing:read. It reads the data of your application only, for the user you name.
| Method | Returns |
|---|---|
getSubscription(userId) | SubscriptionView | null: plan (id, name), isActive, expiresAt, stripeStatus, currentPeriodStart, currentPeriodEnd, cancelAtPeriodEnd, canceledAt. null when the user holds no subscription. |
getUsage(userId) | UsageView: periodStart and features[] with featureKey, unit, usageLimit (-1 is unlimited), used, remaining (null when unlimited). |
listInvoices(userId, { limit?, cursor? }) | InvoicePage: items[] (InvoiceView) and nextCursor. limit is 1 to 100. Newest first. |
machine.consumption
| Method | Scope | Description |
|---|---|---|
report({ userId, key, value, idempotencyKey? }) | consumption:write | Records usage. Returns { aggregate: { key, total }, metered }. |
list(userId) | consumption:read | Every running total of the user: { key, total, updatedAt }[]. |
get(userId, key) | consumption:read | One running total. Rejects with API_001 (details.apiCode CONS_003) when the key was never reported. |
report validates its input before sending anything and throws CFG_001 otherwise: userId is non-empty, key is 1 to 64 characters from a-zA-Z0-9., value is a finite number (negative credits back), and idempotencyKey, when set, is 1 to 200 characters after trimming. total is a decimal string: a running total is not bounded by a double. metered is true when the key prices a metered feature of the user's plan and was billed through Stripe. See Billing and consumption.
Core API
Reference of the main entry point, @circle-rd/auth-ai: AuthClient, GrantManager, AiClient, WalletClient, GatewayClient, claims helpers and the error registry.
Web handlers and Fastify
Reference of @circle-rd/auth-ai/web and @circle-rd/auth-ai/fastify: the routes, the session model, the stores and the Fastify plugin.