Skip to content

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 ​

StoreSubpathState locationToken shapelistForUserconsumeNotes
CredentialStoreMemory@aooth/authIn-process MapOpaque UUIDyesyesDev, tests. Lost on restart.
CredentialStoreJwt@aooth/authThe token itselfSigned JWTnorequires denylistStateless. See Tokens.
CredentialStoreEncapsulated@aooth/authThe token itselfAES-256-GCM blobnorequires denylistStateless + confidential.
CredentialStoreRedis@aooth/auth/redisRedisOpaque UUIDyesyesMulti-instance, fast.
CredentialStoreAtscriptDb@aooth/auth/atscript-dbDB row via @atscript/dbOpaque UUIDyesyesDurable, queryable, integrates with the rest of your data model.

And the denylist matrix:

DenylistSubpathPersistence
DenylistStoreMemory@aooth/authIn-process Map
DenylistStoreRedis@aooth/auth/redisRedis with TTL

CredentialStore<TPayload> — the interface ​

Every store implements this exact shape:

ts
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 ​

MethodReturnsOn stateful storeOn stateless store
persistthe new tokeninserts row, returns generated UUIDencodes state into token, returns it
persistAsvoidinserts row under a caller-chosen key (memory, Redis and atscript-db implement it); required by tokens.hashAtRest / tokens.generateabsent — the token is the state
retrievestate or nullDB lookup; null on miss / expired / epoch-shadowedcrypto verify; null on bad sig / expired / denylisted / epoch-shadowed
consumestate or nullatomic retrieve+deleteretrieve + denylist.add(jti, expiresAt); throws without denylist
updatepossibly-different tokenupdates row in place, returns same tokenre-encodes state, returns new token; throws without denylist
revokevoiddeletes rowadds to denylist; throws without denylist
revokeAllForUsercountdeleteMany({ userId }), real countbumps epoch, returns sentinel 1
listForUserarrayenumeratedoptional and absent on stateless
touchvoidsets lastSeenAt on the row (used by trackLastSeen: 'validate'); state = the state validate just read, so a store may skip re-reading itoptional and absent — token is immutable once issued
listSessionsarrayoptional 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):

ts
// 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 ​

ts
interface DenylistStore {
  add(jti: string, expiresAt: number): Promise<void>;
  has(jti: string): Promise<boolean>;
  cleanup(): Promise<number>;
}
MethodReturnsNotes
addvoidAdds with absolute ms expiry. After expiresAt, the entry can be evicted — it's irrelevant once the JWT itself expired.
hasbooleanLazy expiry: returning false for an entry past its expiresAt is allowed.
cleanupcount of removed entriesBulk 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.

ts
import { CredentialStoreMemory, AuthCredential } from "@aooth/auth";

const auth = new AuthCredential({
  store: new CredentialStoreMemory(),
  accessTtl: 60 * 60 * 1000,
});
PropertyValue
Token shaperandomUUID()
TTL enforcementLazy on retrieve — expired rows are skipped and (eventually) GC'd
Persistence across restartNone
Multi-instanceNone
listForUserO(1) lookup, O(n) materialisation

Use it for tests and dev. For everything else, pick Redis or atscript-db.

DenylistStoreMemory ​

ts
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 ​

bash
pnpm add @aooth/auth ioredis
ts
import { 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):

ts
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:

ts
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 ​

NamespaceShapeTTL
aooth:cred:t:<token>JSON-serialised CredentialStatePX (ms) from expiresAt - now
aooth:cred:u:<userId>Redis SET of tokens for the userNone — entries are removed on revoke / revokeAllForUser
aooth:dl:<jti>"1"PX from expiresAt - now

The prefix is configurable:

ts
new CredentialStoreRedis({ redis, prefix: "app:" });
// keys become app:cred:t:<token>, app:cred:u:<userId>

Operation costs ​

OperationRedis ops
persistset (token) + sadd (user index)
retrieveget
consumeget + del (single-shot — small race window; sweeps with revoke are idempotent)
updateset (token)
revokedel + srem
revokeAllForUsersmembers + del(many) + del(set)
listForUsersmembers + 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.

ts
await store.persist({ userId: "alice", issuedAt: now, expiresAt: now - 1000 /* ... */ });
// throws Error (NOT AuthError)

DenylistStoreRedis ​

ts
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 ​

ts
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 ​

bash
pnpm add @aooth/auth @atscript/db
ts
import { 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:

as
@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.

FieldPurpose
@meta.id tokenRow PK. findOne({ token }) and deleteOne(token) are O(1).
@db.index.plain userIdIndex for revokeAllForUser / listForUser scans.
issuedAt, expiresAtBoth number.timestamp — ms since epoch.
kindFree string. Workflows use 'access', 'refresh', or magic-link discriminators like 'magic.recovery'.
parentCredentialId, rotatedAtSet 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:

as
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 ​

metadataFieldBehaviour
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.
falseExplicit 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:

ts
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 ​

OperationDB ops
persistinsertOne
retrievefindOne (+ opportunistic deleteOne on expired row)
consumefindOne + deleteOne
updatereplaceOne (or deleteOne if expiresAt <= now)
revokedeleteOne
revokeAllForUserdeleteMany({ userId }) — one round trip
listForUserfindMany + background deleteMany for expired rows

Opportunistic GC ​

The adapter doesn't run a background sweeper. Instead:

  • retrieve deletes the row inline when it finds it past expiresAt. The call still returns null.
  • listForUser issues a background deleteMany for 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 ​

ts
await store.update(token, { ...state, expiresAt: now - 1000 });
// calls deleteOne, returns the original token

Updating 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:

  1. persist is atomic — either the row exists or it doesn't, never half-written.
  2. consume is atomic — exactly one of two concurrent calls succeeds; the other returns null. This is the single-use guarantee for magic links.
  3. revoke removes the row (or denylists the jti for stateless) such that retrieve immediately returns null.
  4. revokeAllForUser must remove every credential — both 'access' and 'refresh' kinds. Stateless implementations can use the epoch-gate pattern.
  5. TTL is real. Expired entries return null from retrieve even if the row hasn't been GC'd yet.
  6. listForUser is optional. If you support it, return every live credential, including refresh.
  7. update returns the (possibly-new) token. Document whether you mutate in place or re-issue.
  8. persistAs (optional) stores a row under the given key instead of minting one. Implement it if your store should support tokens.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 ​

ScenarioRecommended store
Tests, devCredentialStoreMemory
Single-process Node server with a DBCredentialStoreAtscriptDb
Multi-instance Node, low latencyCredentialStoreRedis
Stateless API, public verification, partner audienceCredentialStoreJwt (RS* / ES* / EdDSA) + Redis denylist
Stateless with confidential claimsCredentialStoreEncapsulated + Redis denylist
Hybrid — short-lived stateless access, durable refreshJWT for access + atscript-db for refresh (run two AuthCredential instances)

See also ​

Released under the MIT License.