Web handlers and Fastify
createAuthHandlers
@circle-rd/auth-ai/web exports createAuthHandlers(options): Promise<AuthHandlers>. Options are in Configuration. The handlers are Web-standard (Request in, Response out), so any framework can mount them.
AuthHandlers
| Member | Description |
|---|---|
handle(request) | Serves the routes below basePath. Returns null for any other path or unknown route, so your application can answer. |
getSession(request) | The signed-in Session of a request, with claims renewed when due, or null when signed out. |
requireSession(request) | Like getSession, throwing SES_001 when signed out. |
origin | The origin the SDK builds URLs on: that of redirectUri, never a request header. |
basePath | The resolved base path. |
Routes
| Route | Method | Behaviour |
|---|---|---|
/login | GET | Sealed handshake cookie, then 302 to auth-service. Query: next (same-origin path, falls back to defaultRedirect) and prompt (login, consent, select_account, create or none; anything else is ignored). |
/callback | GET | Completes the sign-in, stores the grant, creates the session, then 303 to next with the session cookie. Any failure answers 403 SES_005, or 303 to <errorRedirect>?error=SES_005. |
/me | GET | { user: SessionUser, expiresAt }, or 401 SES_001. |
/logout | POST | Refused with 403 SES_004 when cross-site. Otherwise ends the current session, revokes the grant if the user has no other session, clears the cookie, then answers { logoutUrl } (Accept: application/json) or 303 to the provider's logout URL (or to next, a same-origin path that falls back to defaultRedirect, when the provider has no end-session endpoint). Idempotent without a session. |
/logout/callback | GET | The post-logout landing route. Clears the sealed logout cookie and 303 to the next path requested at logout, falling back to defaultRedirect; an absent or invalid cookie only loses that target. Register its absolute URL as the application's postLogoutRedirectUri. |
/backchannel-logout | POST | See Server API. Ends every session bound to the logout token's sid. |
/wallet | GET | With the ai option. The wallet account plus topupUrl. |
/wallet/stats | GET | With the ai option. Wallet statistics; query days is an integer from 1 to 90, otherwise 400 REQ_001. |
/models | GET | With the ai option. { models } from the gateway. |
A route called with another method answers 405 with Allow. Every JSON response carries Cache-Control: no-store.
Failure answers
Failures use { "error": { "code", "message" } } with the registry's generic message. Statuses:
| Status | Codes |
|---|---|
400 | SES_002, OIDC_002 |
401 | SES_001, TOK_001, TOK_002, TOK_003 |
402 | GW_001 |
403 | SES_004, SES_005, TOK_004, GW_003 |
429 | GW_002 |
501 | OIDC_004 |
502 | OIDC_001, OIDC_003, API_001, API_002, GW_005 |
503 | GW_004 |
500 | every other code (CFG_001, SES_003, SRV_001) |
A failure that is not an AuthAiError is passed to onError and answered 500 SRV_001. The full table with causes and remedies is in Error codes.
Cookies
| Cookie | Name on HTTPS | Name on loopback HTTP | Lifetime | Content |
|---|---|---|---|---|
| Session | __Host-aai_session | aai_session | sessionTtlSeconds | A random 256-bit id, base64url. |
| Sign-in | __Host-aai_login | aai_login | 600 seconds | The sealed handshake. Cleared after the callback. |
Both are Path=/, HttpOnly, SameSite=Lax, plus Secure on HTTPS.
safeRedirectPath(candidate, fallback)
Exported from /web. Reduces a redirect target taken from a request to a same-origin path (pathname, search and hash), or returns fallback for an absolute URL, a protocol-relative one (//host), a backslash, a control character or anything odd. Use it for your own next parameters.
Session and SessionStore
import type { IdTokenClaims } from "@circle-rd/auth-ai";
interface Session {
readonly id: string; // SHA-256 of the cookie value, base64url
readonly userId: string; // the provider's `sub`; also the grant id
readonly sessionId: string | undefined; // the provider session (`sid`)
readonly claims: IdTokenClaims;
readonly idToken: string; // hint for the provider's logout endpoint
readonly createdAt: number; // unix seconds
readonly expiresAt: number; // absolute end of the session
readonly renewAt: number; // next claims renewal
}
SessionStore has six methods: create, get (undefined for an unknown or expired session), update, delete, deleteByProviderSession(sessionId) (removes and returns every session of a provider session) and countByUser(userId). MemorySessionStore is the in-process implementation, for demos and tests. The contracts are detailed in Implement the stores.
SessionUser (sub, name?, email?, emailVerified?, picture?, roles, permissions, features, plan?, orgId?), sessionUserSchema and toSessionUser(claims) are exported from /web too: this is what /me returns.
Fastify adapter
@circle-rd/auth-ai/fastify requires fastify >=5.12.6.
| Export | Description |
|---|---|
authPlugin | FastifyPluginAsync<{ handlers: AuthHandlers }>. Serves ${handlers.basePath}/* for every method, builds the Web Request on handlers.origin, and decorates requests with authSession. Register it once. |
requireAuth(handlers) | preHandler answering 401 SES_001 to signed-out requests and setting request.authSession otherwise. |
loadSession(handlers) | preHandler setting request.authSession when signed in and leaving it null otherwise. |
request.authSession is typed Session | null, also after requireAuth. The plugin registers a body parser for application/x-www-form-urlencoded (16 KiB) in its own scope, which the back-channel logout needs, so it does not clash with a parser of yours.
import Fastify from "fastify";
import { authPlugin, loadSession } from "@circle-rd/auth-ai/fastify";
import type { AuthHandlers } from "@circle-rd/auth-ai/web";
declare const handlers: AuthHandlers;
const app = Fastify();
await app.register(authPlugin, { handlers });
// Optional session: a page that renders for everyone but differently when signed in.
app.get("/", { preHandler: loadSession(handlers) }, async (request) => ({
signedIn: request.authSession !== null,
}));
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.
Browser, React and Vue
Reference of @circle-rd/auth-ai/client, /react and /vue: the cookie-only browser client, the observable stores and the framework bindings.