Writing a store adapter
The core never talks to a database. It is handed four stores, and any implementation that passes the conformance suite in @noctcore/auth/testing is a valid one. @noctcore/auth-redis and @noctcore/auth-prisma are adapters like any other: both run the same suite against a real Redis and PostgreSQL in CI.
What each store must guarantee
Section titled “What each store must guarantee”The interfaces are in packages/auth/src/ports/stores.ts, with the guarantee each method gives in its comment. The ones the flows depend on, and that the suite tests under concurrency:
UserStore (users and password hashes)
createreturnsnullwhen the email is taken, even under 20 concurrent creates of one address. It never throws on a unique violation.setPasswordHashis guarded: it writes nothing and returnsfalsefor a missing or soft-deleted user. Withexpected, it is a compare-and-set in one statement, so a rehash on login can never overwrite a password changed meanwhile.markEmailVerifiedwrites only while the stored email still equals the one given, so a stale code cannot verify a changed address.changeEmail(optional; the email change flows need it) moves the user fromfromtoto, marks the address verified and, withclearPassword, removes the hash, in one statement guarded on the stored email still equallingfrom. It answersstalewhen that guard fails or the user is missing or soft-deleted, andtakenwhen another user (soft-deleted ones included) holdsto, never throwing on the unique violation: of 10 users racing for one address, exactly one getschanged.- The
find*methods return live users only: a soft-deleted user is not found.
TokenStore (one-time codes and links, as hashes)
putkeeps one token per user and purpose, replacing the old one; concurrent puts never throw.consumeremoves and returns the token atomically: of 50 concurrent callers, exactly one gets it.consumeremoves only the token with that hash. A refused code is removed this way, by the hash that was read, so a code resent meanwhile (another hash for the same user and purpose) survives.extendExpiry(optional, but the suite expects it) moves a token’s expiry only while it still exists and has not expired (its expiry is after thenowit is given), in one step, and reports whether it did; it never creates a token. Put both conditions in the update itself (awhereon the hash and onexpiresAt). The email change revert lockout extends the owner’s revert link with it, so a link spent by a concurrent click stays spent and one that expired meanwhile stays expired. A store without it still works: the link is then extended by aconsumeand aput. That never brings a spent or expired link back, but it hides the link for one round trip (a click landing in that gap is refused), theputreplaces a link of the same user and purpose issued between the two calls, and aputthat fails after theconsumeloses the link.incrementAttemptsnever passes the cap: of N concurrent callers, at mostmaxget a number.incrementAttemptsByHash(optional, but the suite expects it) is the same capped increment on the token with that hash only, and answers null when that token is gone. A code check counts its attempt on the code it read, so a code resent between the read and the count is never charged for a guess at the old one. A store without it still works: the attempt is then counted by user and purpose, which lands on the resent code.
SessionStore (sessions and revocation epochs)
touchreplaces a session only if it still exists, keeping its TTL, and never brings back a deleted one, even when racing the delete on another connection.deletereturns the ids it removed (the ones that still existed), so that of two deletes racing on one session exactly one reports it. Evictions, sign-outs and revocations report toonSessionsRevokedfrom this list. A store that returns nothing still works, but a session two of them race on may then be reported twice. Run the conformance suite withdeleteReportsRemoved: falsefor such a store: the delete cases are then listed as skipped instead of failing.bumpEpochis an atomic increment, and the epoch must outlive every session it guards. A store that can only guard sessions up to some age says so inmaxSessionTtlMs, andcreateAuthrefuses longer sessions. A store that forgets an epoch some time after its last write (and then reads it as 0) says how long inepochTtlMs: device cookies and trusted devices are fenced by the epoch alone, socreateAuthrefuses athrottle.lockout.deviceMaxAgeor a two-factortrustedDevices.ttlthat is not at least a minute (the clock skew a device cookie is allowed) shorter. Leave it out when the epoch never lapses; a value that is not a positive number is refused.- Every record expires with its session: the session at its TTL, its index entry with it.
CounterStore (rate limits and lockout)
- The first
incrementarms the window; later hits never extend it. Concurrent increments each see a distinct count. - Every key has a TTL, always, so no counter outlives its window.
decrementlowers the count by one, never below 0, keeps the TTL and never creates a missing key.
A worked example
Section titled “A worked example”A CounterStore on node:sqlite, for a single-process app. Each method is one SQL statement and SQLite runs one statement at a time, which is what makes the increment atomic. On a database shared by several processes the same logic needs a conditional upsert your database runs atomically, as the Redis store does with a script.
import type { DatabaseSync } from 'node:sqlite';import { systemClock, type Clock, type CounterStore, type CounterWindow } from '@noctcore/auth';
interface Row { readonly count: number; readonly reset_at: number;}
/** * A CounterStore on node:sqlite, for a single-process app. Each method is one * statement, and SQLite runs one statement at a time, so concurrent calls * cannot interleave. An expired row counts as missing and is replaced on the * next hit. */export class SqliteCounterStore implements CounterStore { readonly #db: DatabaseSync; readonly #clock: Clock;
constructor(db: DatabaseSync, clock: Clock = systemClock) { this.#db = db; this.#clock = clock;
db.exec(`CREATE TABLE IF NOT EXISTS auth_counters ( key TEXT PRIMARY KEY, count INTEGER NOT NULL, reset_at INTEGER NOT NULL )`); }
async increment(key: string, windowMs: number): Promise<CounterWindow> { const now = this.#clock.now();
// The first hit, or the first after the window ended, starts a new window. // Later hits only add one: the window end never moves. const row = this.#db .prepare( `INSERT INTO auth_counters (key, count, reset_at) VALUES (?, 1, ?) ON CONFLICT (key) DO UPDATE SET count = CASE WHEN reset_at <= ? THEN 1 ELSE count + 1 END, reset_at = CASE WHEN reset_at <= ? THEN excluded.reset_at ELSE reset_at END RETURNING count, reset_at`, ) .get(key, now + windowMs, now, now) as unknown as Row;
return { count: row.count, resetAt: row.reset_at }; }
async get(key: string): Promise<CounterWindow | null> { const row = this.#db .prepare('SELECT count, reset_at FROM auth_counters WHERE key = ? AND reset_at > ?') .get(key, this.#clock.now()) as unknown as Row | undefined;
return row ? { count: row.count, resetAt: row.reset_at } : null; }
async set(key: string, count: number, windowMs: number): Promise<void> { this.#db .prepare('INSERT OR REPLACE INTO auth_counters (key, count, reset_at) VALUES (?, ?, ?)') .run(key, count, this.#clock.now() + windowMs); }
async decrement(key: string): Promise<void> { // Only a live row is touched, so a missing key stays missing and the TTL stays. this.#db .prepare('UPDATE auth_counters SET count = MAX(count - 1, 0) WHERE key = ? AND reset_at > ?') .run(key, this.#clock.now()); }
async reset(key: string): Promise<void> { this.#db.prepare('DELETE FROM auth_counters WHERE key = ?').run(key); }}Running the conformance suite
Section titled “Running the conformance suite”Each suite is a function that takes your store and returns a list of named cases that assert with node:assert, so they run under any test runner. runConformance(title, cases, { describe, it }) registers them with yours. This test runs the counter suite with node --test:
import { DatabaseSync } from 'node:sqlite';import { describe, it } from 'node:test';import { counterStoreConformance, manualClock, runConformance } from '@noctcore/auth/testing';import { SqliteCounterStore } from './sqlite-counter-store.ts';
// A manual clock makes the expiry cases instant instead of sleeping. It starts// at the real time because some cases compare against Date.now().const clock = manualClock(Date.now());const store = new SqliteCounterStore(new DatabaseSync(':memory:'), clock);
runConformance( 'sqlite counter store', counterStoreConformance(store, { advanceTime: async (ms) => clock.advance(ms) }), { describe, // node:test takes its options before the test body; Vitest and Jest can // pass their own `it` unchanged. it: (name, body, timeout) => it(name, { timeout }, body), },);Under Vitest or Jest, pass the runner’s own functions: runConformance('my store', cases, { describe, it }). That is how both shipped adapters do it, in packages/auth-redis/tests/redis.int.test.ts and packages/auth-prisma/tests/prisma.int.test.ts.
| Suite | Options |
|---|---|
userStoreConformance(store, options) |
softDelete(id): soft-deletes a user, if your store supports soft deletion. Without it that case is left out. |
tokenStoreConformance(store) |
none |
sessionStoreConformance(store, options) |
secondary: a second instance of your store on its own connection, so the touch-versus-delete race really crosses connections. epochTtlMs(userId): the remaining TTL of a user’s epoch, for stores that expire epochs; enables the check that the epoch outlives the longest session. deleteReportsRemoved: false: for a store whose delete cannot return the ids it removed; the three delete cases are listed as skipped. advanceTime, as below. |
counterStoreConformance(store, context) |
advanceTime, as below. |
membershipStoreConformance(store) |
none. For the membership plugin: a role change and a removal apply only to the role the caller decided on, and never leave a scope without an admin, checked with concurrent demotions and removals (Membership guards). |
invitationStoreConformance(store) |
none. For the invitations plugin: consume gives an invitation to exactly one of many concurrent callers, and create keeps one live invitation per scope and address, also under concurrent creates (Invitations). |
The expiry cases move time forward. By default they sleep, which suits a real backend with its own clock. A store built on an injectable Clock can pass advanceTime: (ms) => clock.advance(ms) with a manualClock(), and those cases then run instantly. Start the manual clock at Date.now(), because the sample records carry real timestamps.
On a shared backend, every case writes under ids from uniqueId, so parallel runs never collide. Give the store a prefix of its own (the Redis tests use uniqueId('test')) and remove its keys after the run.
Switching from your own sessions
Section titled “Switching from your own sessions”An app that already has signed-in users keeps its sessions in its own format, so pointing stores.sessions at the package’s store signs everyone out. adoptLegacySessions(store, options) wraps the package’s store instead: a session it does not hold is looked up once in your old store, converted, written to the package’s store in its format, and removed from the old one. Every later request is served from the package’s store alone.
It works when your old cookie carries a token the package accepts (64 lowercase hex characters, the shape of generateToken) under the cookie name the package reads (session.cookie.name), and your old store can find a session by the SHA-256 hex of that token, the package’s store key. An old store keyed by the raw token can be rekeyed once with a script before the switch. Otherwise, the package cannot recognise the old cookies, and the switch signs those users out.
import type { DatabaseSync } from 'node:sqlite';import { adoptLegacySessions, type LegacySession, type SessionStore } from '@noctcore/auth';
/** A row of the app's own session table from before the switch. */interface OldSessionRow { readonly user_id: string; readonly created_at: number; readonly last_seen_at: number; readonly expires_at: number; readonly remember: number;}
/** * Wraps the package's session store so the sessions in the old `sessions` * table keep working. The old table already keyed each row by the SHA-256 hex * of the cookie token, the package's own store key, and the cookie keeps its * name. Remove the wrapper 30 days after the switch: by then every old row has * been adopted or has expired. */export function withOldSessions(store: SessionStore, db: DatabaseSync): SessionStore { // One statement reads and removes the row, so two requests on one cookie // cannot both get it. const takeRow = db.prepare( 'DELETE FROM sessions WHERE token_hash = ? RETURNING user_id, created_at, last_seen_at, expires_at, remember', );
return adoptLegacySessions(store, { maxTtl: '30d', // the app's session.rememberMeTtl take: async (id): Promise<LegacySession | null> => { const row = takeRow.get(id) as OldSessionRow | undefined;
if (!row) return null;
return { userId: row.user_id, createdAt: row.created_at, // Grants fresh-auth standing: the old table has no later sign-in time. authenticatedAt: row.created_at, lastActiveAt: row.last_seen_at, expiresAt: row.expires_at, idleTimeoutMs: row.remember ? 7 * 86_400_000 : 30 * 60_000, rememberMe: row.remember === 1, }; }, });}take(id) returns the old session as a LegacySession (userId, createdAt, authenticatedAt, lastActiveAt, expiresAt, idleTimeoutMs, rememberMe, and optionally persistentCookie, ip, userAgent and attributes), or null. It must remove the record as it reads it, in one atomic step, like TokenStore.consume. Report createdAt as authenticatedAt unless your old store recorded a later sign-in or re-authentication: authenticatedAt grants fresh-auth standing, so a later value lets the session change the password or revoke other devices without asking for the password again. What the wrapper does with it:
- Adopted once. The old record is gone before the new session is written, so signing out of an adopted session cannot be undone by adopting it again, and of two requests racing on one cookie only one adopts it. The other looks for the session the first is writing, once more after 50 ms, and is refused if that write is still not visible, with the reason
session_adopting(adoptingfrom the session manager) instead ofsession_unknown. That request is answered as signed out, but its cookie is kept:clearsSessionCookie(result)is false for it, and both@noctcore/auth-nestjs(its CSRF middleware) and@noctcore/auth-trpc(its context) clear the session cookie only when that check says so. The browser keeps sending the cookie, and the next request finds the adopted session. An adapter of your own should clear the cookie through the same check. A request on one process cannot see that another process took the record, so every token neither store knows (one revoked or expired since the switch, or made up) is refused this way while the wrapper is installed: refused, never accepted, but its cookie stays until the user signs in again or the wrapper is removed. A malformed token, and an old record the wrapper drops (below), are refused for good and their cookie is cleared. Every cookie neither store knows pays the 50 ms wait on each request while the wrapper is in place. - Revocations reach it. The adopted session carries revocation epoch 0, the epoch of a user whose sessions were never revoked. After a password change or a sign-out everywhere, any old session the user had not used since the switch is refused when it is presented. For the same reason, a user whose epoch was already bumped in the store you switch to loses their old sessions.
- Never longer. The session expires at its old expiry, but never later than
maxTtlafter itscreatedAt(or the store’smaxSessionTtlMs, when shorter). SetmaxTtlto yoursession.rememberMeTtl. A futureauthenticatedAtorlastActiveAtis brought back to now. - Dropped, not adopted. An expired record, one created in the future, or one with a missing user id, a time that is not a number, a zero idle timeout or a non-boolean
rememberMeis removed and refused. So is one whose idle timeout is no longer thansession.touchInterval, the rule a sign-in applies: such a session is never touched before it goes idle, so it would be refused while in use; its user signs in once more instead. The wrapper never raises the idle timeout to fit, since that would let an old session live longer than its own record allows. A malformed one, and one dropped for its idle timeout, are reported tologgerwith the user id only. The idle timeout is checked on the session manager’s lookups (validateRequestand the flows); callinggeton the wrapper yourself adopts without it. Attributes go throughsession.attributeslike any session’s.
Old sessions are not listed in auth.sessions.list until they are first used, and the per-user cap counts them from then on.
Pass the result directly to createAuth. The adopting signal lives on the store adoptLegacySessions returns, and the session manager reads it from there. A store of your own that wraps that result (to log or count calls) hides it, so a request that loses the race is refused as session_unknown and its cookie is cleared: the user is signed out again. To log or count, wrap the package’s store first and pass the wrapped store to adoptLegacySessions.
Remove the wrapper once maxTtl has passed since the switch. By then every old session has been adopted or has expired, so the wrapper has nothing left to adopt, but while it is installed every cookie the package’s store does not know still costs a read of your old store, a second read of the package’s store and the 50 ms wait, and keeps its cookie. Pass the package’s store to createAuth directly again, then drop the old table.
In-memory stores
Section titled “In-memory stores”memoryStores() from @noctcore/auth/testing returns all four stores in memory. They pass the same suite and are meant for unit tests and prototypes: nothing survives a restart and nothing is shared between processes. The fakes beside them (manualClock, plainHasher, recordingMailer, recordingAudit) let a unit test drive createAuth without Redis, a database or Argon2.