Implement the stores
The in-memory stores (MemorySessionStore, MemoryGrantStore, InProcessGrantLock, MemoryReplayStore) are for demos, tests and a single instance: a restart signs everyone out, and replicas cannot share them. In production, implement the interfaces on your application's database.
| Interface | Holds | Shared across replicas? |
|---|---|---|
SessionStore | Browser sessions: claims and ID token. | Yes, required. |
GrantStore | One refresh token per user. | Yes, required. |
GrantLock | Mutual exclusion of refreshes per grant. | Yes, with several replicas. |
ReplayStore | The jti of accepted logout tokens. | Yes, with several replicas. |
SessionStore
From @circle-rd/auth-ai/web. Records are keyed by Session.id, which is already the SHA-256 of the cookie value: store it as is. Index userId and sessionId.
| Method | Contract |
|---|---|
create(session) | Inserts the session. |
get(id) | Returns the session, or undefined for an unknown or expired one (expiresAt in unix seconds is in the past). |
update(session) | Replaces an existing session (the claims renewal). Do nothing if it no longer exists, so a renewal never resurrects a session that was ended meanwhile. |
delete(id) | Removes the session. Idempotent. |
deleteByProviderSession(sessionId) | Removes every session whose sessionId equals the argument and returns what was removed. Back-channel logout relies on the returned list to revoke grants. |
countByUser(userId) | Number of non-expired sessions of the user. The grant is revoked when it reaches zero after a sign-out. |
Session holds claims (JSON) and idToken: treat them as sensitive. Purge expired rows periodically.
GrantStore
From @circle-rd/auth-ai. The provider rotates the refresh token on every use, so a store holds exactly one value per grant.
| Method | Contract |
|---|---|
get(grantId) | The refresh token, or undefined. |
set(grantId, refreshToken) | Inserts or overwrites. |
delete(grantId) | Removes the grant. Idempotent. |
The refresh token is a long-lived credential: encrypt it at rest (for example AES-256-GCM with a key from your secret manager).
GrantLock
run<T>(grantId, task): Promise<T> must run the tasks of one grant one at a time and return the task's result (or rethrow its error, without leaving the lock held). Tasks of different grants may run in parallel. The default, InProcessGrantLock, only covers one process.
ReplayStore
From @circle-rd/auth-ai/server. claim(jti, expiresAt): Promise<boolean> must be atomic: true the first time a jti is seen, false afterwards, until expiresAt (unix seconds). Pass your store to createAuthHandlers({ replayStore }).
import type { Redis } from "ioredis";
import type { ReplayStore } from "@circle-rd/auth-ai/server";
export class RedisReplayStore implements ReplayStore {
constructor(private readonly redis: Redis) {}
async claim(jti: string, expiresAt: number): Promise<boolean> {
const ttlMs = Math.max(1, Math.ceil(expiresAt * 1000 - Date.now()));
// SET ... NX only succeeds for the first caller.
const result = await this.redis.set(`logout-jti:${jti}`, "1", "PX", ttlMs, "NX");
return result === "OK";
}
}
Postgres and Drizzle sketch
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
import { and, count, eq, gt, sql } from "drizzle-orm";
import { bigint, jsonb, pgTable, text } from "drizzle-orm/pg-core";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import type { GrantLock, GrantStore, IdTokenClaims } from "@circle-rd/auth-ai";
import type { Session, SessionStore } from "@circle-rd/auth-ai/web";
const unixSeconds = (name: string) => bigint(name, { mode: "number" }).notNull();
export const sessions = pgTable("auth_sessions", {
id: text("id").primaryKey(), // SHA-256 of the cookie, from the SDK
userId: text("user_id").notNull(), // index it
providerSessionId: text("provider_session_id"), // index it
claims: jsonb("claims").$type<IdTokenClaims>().notNull(),
idToken: text("id_token").notNull(),
createdAt: unixSeconds("created_at"),
expiresAt: unixSeconds("expires_at"),
renewAt: unixSeconds("renew_at"),
});
export const grants = pgTable("auth_grants", {
grantId: text("grant_id").primaryKey(),
refreshToken: text("refresh_token").notNull(), // encrypted
});
type Db = NodePgDatabase;
type Row = typeof sessions.$inferSelect;
const toSession = (row: Row): Session => ({
id: row.id,
userId: row.userId,
sessionId: row.providerSessionId ?? undefined,
claims: row.claims,
idToken: row.idToken,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
renewAt: row.renewAt,
});
const toRow = (session: Session): Row => ({
id: session.id,
userId: session.userId,
providerSessionId: session.sessionId ?? null,
claims: session.claims,
idToken: session.idToken,
createdAt: session.createdAt,
expiresAt: session.expiresAt,
renewAt: session.renewAt,
});
const now = () => Math.floor(Date.now() / 1000);
export class DbSessionStore implements SessionStore {
constructor(private readonly db: Db) {}
async create(session: Session): Promise<void> {
await this.db.insert(sessions).values(toRow(session));
}
async get(id: string): Promise<Session | undefined> {
const [row] = await this.db
.select()
.from(sessions)
.where(and(eq(sessions.id, id), gt(sessions.expiresAt, now())));
return row ? toSession(row) : undefined;
}
async update(session: Session): Promise<void> {
// Updates an existing row only: never resurrects an ended session.
await this.db.update(sessions).set(toRow(session)).where(eq(sessions.id, session.id));
}
async delete(id: string): Promise<void> {
await this.db.delete(sessions).where(eq(sessions.id, id));
}
async deleteByProviderSession(sessionId: string): Promise<readonly Session[]> {
const rows = await this.db
.delete(sessions)
.where(eq(sessions.providerSessionId, sessionId))
.returning();
return rows.map(toSession);
}
async countByUser(userId: string): Promise<number> {
const [row] = await this.db
.select({ value: count() })
.from(sessions)
.where(and(eq(sessions.userId, userId), gt(sessions.expiresAt, now())));
return row?.value ?? 0;
}
}
// AES-256-GCM; `key` is 32 bytes from your secret manager.
function encrypt(key: Buffer, plaintext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", key, iv);
const body = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
return [iv, cipher.getAuthTag(), body].map((part) => part.toString("base64url")).join(".");
}
function decrypt(key: Buffer, value: string): string {
const [iv, tag, body] = value.split(".").map((part) => Buffer.from(part, "base64url"));
const decipher = createDecipheriv("aes-256-gcm", key, iv!);
decipher.setAuthTag(tag!);
return Buffer.concat([decipher.update(body!), decipher.final()]).toString("utf8");
}
export class DbGrantStore implements GrantStore {
constructor(
private readonly db: Db,
private readonly key: Buffer,
) {}
async get(grantId: string): Promise<string | undefined> {
const [row] = await this.db.select().from(grants).where(eq(grants.grantId, grantId));
return row ? decrypt(this.key, row.refreshToken) : undefined;
}
async set(grantId: string, refreshToken: string): Promise<void> {
const encrypted = encrypt(this.key, refreshToken);
await this.db
.insert(grants)
.values({ grantId, refreshToken: encrypted })
.onConflictDoUpdate({ target: grants.grantId, set: { refreshToken: encrypted } });
}
async delete(grantId: string): Promise<void> {
await this.db.delete(grants).where(eq(grants.grantId, grantId));
}
}
// One refresh at a time per grant, across replicas, with a Postgres advisory lock.
export class PgGrantLock implements GrantLock {
constructor(private readonly db: Db) {}
run<T>(grantId: string, task: () => Promise<T>): Promise<T> {
return this.db.transaction(async (tx) => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${grantId}))`);
return task();
});
}
}
Wire them together:
const grantManager = new GrantManager({
auth,
store: new DbGrantStore(db, encryptionKey),
lock: new PgGrantLock(db),
});
const handlers = await createAuthHandlers({
auth,
grants: grantManager,
sessions: new DbSessionStore(db),
replayStore: new RedisReplayStore(redis),
secret: cookieSecret,
});
GrantManager stays in each process: that is by design, since access tokens are never persisted. Each replica mints its own, serialised by the shared lock.