Stores
@aooth/auth is store-agnostic — every persistence concern is behind CredentialStore<TPayload> and DenylistStore. This page covers every shipped implementation: the interfaces, the in-memory defaults, the Redis adapter, the atscript-db adapter (with the shipped .as model), and the matrix you'd use to pick between them.
The store matrix
| Store | Subpath | State location | Token shape | listForUser | consume | Notes |
|---|---|---|---|---|---|---|
CredentialStoreMemory | @aooth/auth | In-process Map | Opaque UUID | yes | yes | Dev, tests. Lost on restart. |
CredentialStoreJwt | @aooth/auth | The token itself | Signed JWT | no | requires denylist | Stateless. See Tokens. |
CredentialStoreEncapsulated | @aooth/auth | The token itself | AES-256-GCM blob | no | requires denylist | Stateless + confidential. |
CredentialStoreRedis | @aooth/auth/redis | Redis | Opaque UUID | yes | yes | Multi-instance, fast. |
CredentialStoreAtscriptDb | @aooth/auth/atscript-db | DB row via @atscript/db | Opaque UUID | yes | yes | Durable, queryable, integrates with the rest of your data model. |
And the denylist matrix:
| Denylist | Subpath | Persistence |
|---|---|---|
DenylistStoreMemory | @aooth/auth | In-process Map |
DenylistStoreRedis | @aooth/auth/redis | Redis with TTL |
CredentialStore<TPayload> — the interface
Every store implements this exact shape:
interface CredentialStore<TPayload = object> {
persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
persistAs?(id: string, state: CredentialState & TPayload, ttl?: number): Promise<void>; // since 0.2
retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
consume(token: string): Promise<(CredentialState & TPayload) | null>;
update(token: string, state: CredentialState & TPayload): Promise<string>;
revoke(token: string): Promise<void>;
revokeAllForUser(userId: string): Promise<number>;
listForUser?(userId: string): Promise<Array<CredentialState & TPayload & { token: string }>>;
// Optional session capabilities — see Sessions:
touch?(token: string, at: number, state?: CredentialState & TPayload): Promise<void>;
listSessions?(userId: string): Promise<Array<CredentialState & TPayload & { token: string }>>;
}Method semantics
| Method | Returns | On stateful store | On stateless store |
|---|---|---|---|
persist | the new token | inserts row, returns generated UUID | encodes state into token, returns it |
persistAs | void | inserts row under a caller-chosen key (memory, Redis and atscript-db implement it); required by tokens.hashAtRest / tokens.generate | absent — the token is the state |
retrieve | state or null | DB lookup; null on miss / expired / epoch-shadowed | crypto verify; null on bad sig / expired / denylisted / epoch-shadowed |
consume | state or null | atomic retrieve+delete | retrieve + denylist.add(jti, expiresAt); throws without denylist |
update | possibly-different token | updates row in place, returns same token | re-encodes state, returns new token; throws without denylist |
revoke | void | deletes row | adds to denylist; throws without denylist |
revokeAllForUser | count | deleteMany({ userId }), real count | bumps epoch, returns sentinel 1 |
listForUser | array | enumerated | optional and absent on stateless |
touch | void | sets lastSeenAt on the row (used by trackLastSeen: 'validate'); state = the state validate just read, so a store may skip re-reading it | optional and absent — token is immutable once issued |
listSessions | array | optional native session grouping (forward-compat; unused today) | optional and absent on stateless |
update and touch must never re-create a deleted row
On a stateful store, update and touch rewrite a row that exists — a missing token is a no-op. That must also hold when the row is deleted between the store's read and its write (a logout or session revocation racing a refresh or a lastSeenAt stamp): write conditionally — a matched-only UPDATE … WHERE, Redis SET … XX — never an upsert. The shipped stores do (Redis since 0.2.1). A custom store that upserts here can bring revoked credentials back.
Revocation also relies on read-your-writes: listForUser must see every row whose persist completed, and retrieve must see a completed delete (see Sessions — revoking sessions). Don't serve either from an eventually consistent replica.
update may return a new token
On stateless stores, update re-encodes the state into a fresh token — the returned string is different from the input. Callers must use the returned value, not the original. The orchestrator handles this internally; if you call update directly, do the same.
CredentialState & TPayload
The shape stored under each token — the fixed envelope CredentialState intersected with the consumer's typed payload TPayload (their flat root fields; there is no claims container):
// envelope — no generic, no `claims`
interface CredentialState {
userId: string;
issuedAt: number;
expiresAt: number;
metadata?: CredentialMetadata;
kind?: "access" | "refresh" | string;
parentCredentialId?: string;
rotatedAt?: number;
sessionId?: string; // token-family id, stable across rotation — see Sessions
lastSeenAt?: number; // activity time; only written under trackLastSeen
}
// stores deal in `CredentialState & TPayload`; the payload fields ride flat.kind is free-form when you persist directly (e.g. 'magic.recovery'). The orchestrator only emits 'access' and 'refresh'. sessionId and lastSeenAt back the Sessions APIs; both round-trip automatically in Memory/Redis (whole state is serialized) and have dedicated columns in the atscript-db .as model. The consumer's TPayload fields round-trip the same way (Memory/Redis serialize the whole state; the atscript-db adapter persists them as the typed columns the consumer added to their model).
DenylistStore — the interface
interface DenylistStore {
add(jti: string, expiresAt: number): Promise<void>;
has(jti: string): Promise<boolean>;
cleanup(): Promise<number>;
}| Method | Returns | Notes |
|---|---|---|
add | void | Adds with absolute ms expiry. After expiresAt, the entry can be evicted — it's irrelevant once the JWT itself expired. |
has | boolean | Lazy expiry: returning false for an entry past its expiresAt is allowed. |
cleanup | count of removed entries | Bulk eviction sweep. May be a no-op on backends with native TTL. |
CredentialStoreMemory
The default. A Map<token, state> keyed by token, plus a secondary Map<userId, Set<token>> for O(1) revokeAllForUser and listForUser.
import { CredentialStoreMemory, AuthCredential } from "@aooth/auth";
const auth = new AuthCredential({
store: new CredentialStoreMemory(),
accessTtl: 60 * 60 * 1000,
});| Property | Value |
|---|---|
| Token shape | randomUUID() |
| TTL enforcement | Lazy on retrieve — expired rows are skipped and (eventually) GC'd |
| Persistence across restart | None |
| Multi-instance | None |
listForUser | O(1) lookup, O(n) materialisation |
Use it for tests and dev. For everything else, pick Redis or atscript-db.
DenylistStoreMemory
import { DenylistStoreMemory } from "@aooth/auth";
const denylist = new DenylistStoreMemory();Map<jti, expiresAt> with lazy expiry on has, an amortized sweep of expired entries on add as the map grows, and an explicit cleanup sweep. Use only with CredentialStoreMemory / single-instance JWT in dev. Multi-instance JWT needs DenylistStoreRedis.
Redis adapter
pnpm add @aooth/auth ioredisimport { Redis } from "ioredis";
import { CredentialStoreRedis, DenylistStoreRedis } from "@aooth/auth/redis";
import { AuthCredential } from "@aooth/auth";
const redis = new Redis(process.env.REDIS_URL!);
const auth = new AuthCredential({
store: new CredentialStoreRedis({ redis }),
accessTtl: 15 * 60 * 1000,
refresh: { ttl: 30 * 24 * 3600 * 1000, rotation: "sliding" },
maxConcurrent: 10,
tokens: { hashAtRest: true }, // Redis holds hashes, not usable tokens
});RedisLike — structural typing
The adapters don't depend on any specific Redis client. They accept anything that implements the nine methods they use (shared by CredentialStoreRedis, DenylistStoreRedis, and RateLimitStoreRedis):
interface RedisLike {
/** `SET key value PX ms` */
set(key: string, value: string, mode: "PX", ttlMs: number): Promise<string | null>;
/** `SET key value PX ms XX` — write only if the key exists, else resolve `null`. */
set(
key: string,
value: string,
mode: "PX",
ttlMs: number,
condition: "XX",
): Promise<string | null>;
get(key: string): Promise<string | null>;
del(...keys: string[]): Promise<number>;
exists(key: string): Promise<number>;
/** `PEXPIRE key ttlMs` — ms TTL on an existing key. */
pexpire(key: string, ttlMs: number): Promise<number>;
/** `INCR key` — atomic increment-and-get; creates the key at 1. */
incr(key: string): Promise<number>;
sadd(key: string, ...members: string[]): Promise<number>;
srem(key: string, ...members: string[]): Promise<number>;
smembers(key: string): Promise<string[]>;
}The XX form is required (since 0.2.1). CredentialStoreRedis rewrites an existing credential (the rotation stamp, lastSeenAt) with SET … XX, so a write that races a logout or session revocation can never re-create the deleted key. Your adapter must pass XX through and resolve null when the key is missing — returning "OK" without honouring XX silently brings revoked credentials back.
All TTLs are milliseconds — that's why the interface exposes pexpire rather than expire: redis's EXPIRE takes seconds, and a raw client passed by shape would satisfy an expire signature while silently setting a 1000× TTL. With pexpire, a seconds-based double fails to typecheck instead of misbehaving.
ioredis and keydb clients satisfy this shape as-is. node-redis (redis@4+) uses camelCase method names — wrap it:
const redisLike: RedisLike = {
set: (k, v, _px, ttlMs, xx?: "XX") => client.set(k, v, { PX: ttlMs, ...(xx && { XX: true }) }),
get: (k) => client.get(k),
del: (...k) => client.del(k),
exists: (k) => client.exists(k),
pexpire: (k, ms) => client.pExpire(k, ms).then((ok) => (ok ? 1 : 0)),
incr: (k) => client.incr(k),
sadd: (k, ...m) => client.sAdd(k, m),
srem: (k, ...m) => client.sRem(k, m),
smembers: (k) => client.sMembers(k),
};Key namespaces
| Namespace | Shape | TTL |
|---|---|---|
aooth:cred:t:<token> | JSON-serialised CredentialState | PX (ms) from expiresAt - now |
aooth:cred:u:<userId> | Redis SET of tokens for the user | None — entries are removed on revoke / revokeAllForUser |
aooth:dl:<jti> | "1" | PX from expiresAt - now |
The prefix is configurable:
new CredentialStoreRedis({ redis, prefix: "app:" });
// keys become app:cred:t:<token>, app:cred:u:<userId>Operation costs
| Operation | Redis ops |
|---|---|
persist | set (token) + sadd (user index) |
retrieve | get |
consume | get + del (single-shot — small race window; sweeps with revoke are idempotent) |
update | set (token) |
revoke | del + srem |
revokeAllForUser | smembers + del(many) + del(set) |
listForUser | smembers + N × get |
persist fails loud on dead credentials
If you call persist with state.expiresAt <= now, the Redis adapter throws a plain Error (not an AuthError) with the message "CredentialStoreRedis.persist: refusing to persist an already-expired credential". It does not silently insert a row that's already expired. This catches clock skew and config bugs early — handle it as a non-AuthError exception.
await store.persist({ userId: "alice", issuedAt: now, expiresAt: now - 1000 /* ... */ });
// throws Error (NOT AuthError)DenylistStoreRedis
const denylist = new DenylistStoreRedis({ redis, prefix: "app:" });add writes app:dl:<jti> with PX TTL. has checks exists. cleanup is a no-op — Redis self-evicts. The method exists only for interface conformance.
Wiring stateless JWT against Redis
import { Redis } from "ioredis";
import { CredentialStoreJwt, AuthCredential } from "@aooth/auth";
import { DenylistStoreRedis } from "@aooth/auth/redis";
const redis = new Redis(process.env.REDIS_URL!);
const auth = new AuthCredential({
store: new CredentialStoreJwt({
algorithm: "EdDSA",
privateKey,
publicKey,
denylist: new DenylistStoreRedis({ redis }),
}),
accessTtl: 5 * 60 * 1000,
refresh: { ttl: 7 * 24 * 3600 * 1000, rotation: "always" },
});The denylist is durable across pods. The per-user revocation epoch map, however, is still in-memory by default — see the warning in Tokens.
atscript-db adapter
pnpm add @aooth/auth @atscript/dbimport { DbSpace } from "@atscript/db";
import { CredentialStoreAtscriptDb } from "@aooth/auth/atscript-db";
import { AuthCredential } from "@aooth/auth";
import { AoothAuthCredential } from "@aooth/auth/atscript-db/model.as";
// Importing the raw `.as` file requires the atscript build pipeline
// (`unplugin-atscript` for Vite/Rollup, or run `asc` ahead of time). Without
// it, your bundler cannot resolve the `.as` extension.
const db = new DbSpace({/* adapter, models: [AoothAuthCredential] */});
await db.sync();
const auth = new AuthCredential({
store: new CredentialStoreAtscriptDb({
table: db.getTable(AoothAuthCredential), // `{ table }` is all the store needs
}),
accessTtl: 60 * 60 * 1000,
refresh: { ttl: 30 * 24 * 3600 * 1000, rotation: "sliding" },
tokens: { hashAtRest: true }, // rows hold token hashes — see Credentials
});The shipped .as model
@aooth/auth/atscript-db/model.as exports AoothAuthCredential — a one-table model that maps directly onto CredentialState:
@db.table 'aooth_credentials'
@db.depth.limit 0
export interface AoothAuthCredential {
@meta.id
token: string
@db.index.plain
userId: string
issuedAt: number.timestamp
expiresAt: number.timestamp
kind?: string
// no metadata column — consumer-declared, see below
parentCredentialId?: string
rotatedAt?: number.timestamp
@db.index.plain
sessionId?: string
lastSeenAt?: number.timestamp
}The base model is the envelope only — there is no free-form claims column. To carry per-token payload you extends AoothAuthCredential and add your own typed columns (scalars, or @db.json for structured ones); the CredentialStoreAtscriptDb adapter round-trips them automatically. @aooth/arbac-moost consumers annotate those columns with @arbac.attenuate.role / @arbac.attenuate.attr "userAttr" for restrict-only credential attenuation.
| Field | Purpose |
|---|---|
@meta.id token | Row PK. findOne({ token }) and deleteOne(token) are O(1). |
@db.index.plain userId | Index for revokeAllForUser / listForUser scans. |
issuedAt, expiresAt | Both number.timestamp — ms since epoch. |
kind | Free string. Workflows use 'access', 'refresh', or magic-link discriminators like 'magic.recovery'. |
parentCredentialId, rotatedAt | Set by refresh-token rotation. |
The @db.depth.limit 0 annotation prevents joins / projections from cascading through this model — credentials are an opaque storage detail, not a relational entity.
Credential metadata is consumer-declared
The base model ships no metadata column. Declare a fully-typed @db.json field on your extending model — the runtime/validation twin of your CredentialMetadata declaration merge (see Credentials) — and mark it @aooth.auth.metadata. Build the shape by intersecting the exported AoothCredentialMetadataBase (the framework-written envelope keys: ip, userAgent, fingerprint, label, credentialKind) with your own extension keys, so the framework keys stay single-sourced — a future aooth envelope key flows into your schema on upgrade instead of being rejected by a hand-mirrored closed shape:
import { AoothAuthCredential, AoothCredentialMetadataBase } from '@aooth/auth/atscript-db/model'
@aooth.auth.metadata
@db.json
metadata?: AoothCredentialMetadataBase & { geoLat?: number, geoLon?: number }Pass the table of your extending model — new CredentialStoreAtscriptDb({ table: db.getTable(YourCredential) }) — and the store finds the annotated column on table.type by itself. At most one annotated field per type (throws); a field without @db.json is warn-and-disabled.
Metadata column options and the fail-closed rule
metadataField | Behaviour |
|---|---|
| omitted (default) | Resolved from table.type via getAoothCredentialMetadataSpec (exported from @aooth/auth/atscript-db); resolution warnings go to onWarning. |
'columnName' | Use this column; no lookup. |
false | Explicit opt-out: no metadata column, and no "metadata dropped" warning. |
onWarning (default console.warn) receives configuration warnings.
Since 0.2: no metadata column = fail closed for restricted credentials
Some credentials carry their restrictions in metadata — a per-mint access TTL or rotation mode (issue(userId, { ttl, refresh })), credentialKind (PATs), and the OAuth client binding of authorization-server families. The keys are exported as AUTHORITY_METADATA_KEYS (accessTtl, refreshRotation, rotationGraceMs, credentialKind, authzClientId). Dropping them would silently widen what the token can do (e.g. a fixed-lifetime family would slide forever), so a store without a metadata column now throws AuthError('INVALID_CONFIG') when asked to persist such a credential. Other metadata (ip, userAgent, label, …) is dropped with a one-time warning, so ordinary sign-in sessions still persist. Fix: declare the @aooth.auth.metadata @db.json column on your credential model.
AuthCredentialTable<TPayload> — structural interface
The adapter doesn't directly require the @atscript/db table class — it requires a structurally-typed interface that the table happens to satisfy:
interface AuthCredentialTable<TPayload = object> {
insertOne(row: AuthCredentialRow<TPayload>): Promise<{ insertedId: unknown }>;
findOne(query: { filter: Record<string, unknown> }): Promise<AuthCredentialRow<TPayload> | null>;
findMany(query: {
filter?: Record<string, unknown>;
controls?: Record<string, unknown>;
}): Promise<AuthCredentialRow<TPayload>[]>;
/** Replaces by PK on the row itself — no `{ filter, row }` wrapper. */
replaceOne(
row: AuthCredentialRow<TPayload>,
): Promise<{ matchedCount: number; modifiedCount: number }>;
/** Deletes by PK value (the token string), not by filter. */
deleteOne(idOrPk: unknown): Promise<{ deletedCount: number }>;
deleteMany(filter: Record<string, unknown>): Promise<{ deletedCount: number }>;
}Any class with those six methods is acceptable. The atscript-db generated table type satisfies the structure naturally. The table's optional type (atscript-db's table.type, the annotated model) is read once to find the metadata column; a hand-rolled table without it should pass metadataField explicitly.
Operation costs
| Operation | DB ops |
|---|---|
persist | insertOne |
retrieve | findOne (+ opportunistic deleteOne on expired row) |
consume | findOne + deleteOne |
update | replaceOne (or deleteOne if expiresAt <= now) |
revoke | deleteOne |
revokeAllForUser | deleteMany({ userId }) — one round trip |
listForUser | findMany + background deleteMany for expired rows |
Opportunistic GC
The adapter doesn't run a background sweeper. Instead:
retrievedeletes the row inline when it finds it pastexpiresAt. The call still returnsnull.listForUserissues a backgrounddeleteManyfor any expired rows it filtered out of the result.
This keeps the table from growing unboundedly without a cron job. For high-volume deployments, also schedule an external GC sweep — see your database's TTL feature (e.g. MongoDB TTL index, Postgres partitioning).
update fail-loud parity with Redis
await store.update(token, { ...state, expiresAt: now - 1000 });
// calls deleteOne, returns the original tokenUpdating a credential to be already-expired causes the row to be removed rather than rewritten. Same shape as the Redis adapter's persist rejection — config bugs surface as deletes, not zombie rows.
Writing your own store
Implement CredentialStore<TPayload>. Match these invariants:
persistis atomic — either the row exists or it doesn't, never half-written.consumeis atomic — exactly one of two concurrent calls succeeds; the other returnsnull. This is the single-use guarantee for magic links.revokeremoves the row (or denylists thejtifor stateless) such thatretrieveimmediately returnsnull.revokeAllForUsermust remove every credential — both'access'and'refresh'kinds. Stateless implementations can use the epoch-gate pattern.- TTL is real. Expired entries return
nullfromretrieveeven if the row hasn't been GC'd yet. listForUseris optional. If you support it, return every live credential, including refresh.updatereturns the (possibly-new) token. Document whether you mutate in place or re-issue.persistAs(optional) stores a row under the given key instead of minting one. Implement it if your store should supporttokens.hashAtRest.
Tests against your store should cover: same-millisecond revokeAllForUser + issue (the >= epoch gate); concurrent consume (only one wins); persist of a dead row (fail loud, in line with Redis / atscript adapters); listForUser returns both access and refresh kinds.
Picking a store
| Scenario | Recommended store |
|---|---|
| Tests, dev | CredentialStoreMemory |
| Single-process Node server with a DB | CredentialStoreAtscriptDb |
| Multi-instance Node, low latency | CredentialStoreRedis |
| Stateless API, public verification, partner audience | CredentialStoreJwt (RS* / ES* / EdDSA) + Redis denylist |
| Stateless with confidential claims | CredentialStoreEncapsulated + Redis denylist |
| Hybrid — short-lived stateless access, durable refresh | JWT for access + atscript-db for refresh (run two AuthCredential instances) |
See also
- Credentials & Sessions — the orchestrator that wraps all stores.
- Tokens (JWT) — the stateless options.
- Refresh — how rotation interacts with denylists.
- Source: packages/auth/src/stores.
.asmodel: packages/auth/src/atscript-db/auth-credential.as.