CIRCLE
Reference

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.

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

MemberDescription
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.
originThe origin the SDK builds URLs on: that of redirectUri, never a request header.
basePathThe resolved base path.

Routes

RouteMethodBehaviour
/loginGETSealed 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).
/callbackGETCompletes 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.
/meGET{ user: SessionUser, expiresAt }, or 401 SES_001.
/logoutPOSTRefused 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/callbackGETThe 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-logoutPOSTSee Server API. Ends every session bound to the logout token's sid.
/walletGETWith the ai option. The wallet account plus topupUrl.
/wallet/statsGETWith the ai option. Wallet statistics; query days is an integer from 1 to 90, otherwise 400 REQ_001.
/modelsGETWith 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:

StatusCodes
400SES_002, OIDC_002
401SES_001, TOK_001, TOK_002, TOK_003
402GW_001
403SES_004, SES_005, TOK_004, GW_003
429GW_002
501OIDC_004
502OIDC_001, OIDC_003, API_001, API_002, GW_005
503GW_004
500every 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

CookieName on HTTPSName on loopback HTTPLifetimeContent
Session__Host-aai_sessionaai_sessionsessionTtlSecondsA random 256-bit id, base64url.
Sign-in__Host-aai_loginaai_login600 secondsThe 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.

ExportDescription
authPluginFastifyPluginAsync<{ 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,
}));
Copyright © 2026