Credentials & Sessions
AuthCredential<TPayload> is the single orchestrator over every store. It issues, validates, refreshes and revokes bearer credentials, enforces concurrency limits, and detects refresh-token reuse. The store decides where state lives; the orchestrator decides how the lifecycle works.
This page covers every constructor option and every public method.
Construction
import { AuthCredential, CredentialStoreMemory } from "@aooth/auth";
const auth = new AuthCredential<{ roles: string[] }>({
store: new CredentialStoreMemory(),
accessTtl: 15 * 60 * 1000,
tokens: { hashAtRest: true }, // recommended for new apps — see Tokens at rest
});Constructor options
interface AuthCredentialOptions<TPayload extends object> {
store: CredentialStore<TPayload>;
method?: "session" | "token";
accessTtl?: number;
refresh?: RefreshConfig;
denylist?: DenylistStore;
maxConcurrent?: number;
onLimit?: "reject" | "evict-oldest";
trackLastSeen?: "refresh" | "validate" | false;
validateCache?: { ttlMs: number; max?: number }; // since 0.1.78, opt-in
tokens?: { hashAtRest?: boolean | "migrate"; generate?: () => string }; // since 0.2, opt-in
clock?: Clock;
}| Option | Default | Purpose |
|---|---|---|
store | (required) | The CredentialStore<TPayload> instance. See Stores. |
method | 'token' | Tags every issued credential. AuthContext.method mirrors it. Use 'session' for long-lived server-side sessions, 'token' for short-lived bearer access. |
accessTtl | 60 * 60 * 1000 (1 h) | Lifetime of access credentials, ms. Validated > 0 at construction — throws INVALID_CONFIG otherwise. |
refresh | undefined | Opt in to refresh tokens. See Refresh & Rotation. |
denylist | undefined | Required when using a stateless store for revoke / consume / update. |
maxConcurrent | undefined | Cap on live access credentials per user. Refresh tokens don't count. |
onLimit | 'reject' | What happens when maxConcurrent is reached on issue() — see the limit policies. |
trackLastSeen | false | Activity stamping — see Sessions. |
validateCache | undefined (off) | Opt-in cache of validated access-token state — see Opt-in validate cache. |
tokens | undefined (off) | How tokens are minted and stored — hashAtRest keeps only a SHA-256 of each token in the store; generate supplies your own token format. See Tokens at rest. |
clock | { now: () => Date.now() } | Injectable clock for tests. Used everywhere — TTL expiry, JWT iat/exp, the rotation grace window, the per-user revocation epoch. |
accessTtl must be positive
new AuthCredential({ store, accessTtl: 0 }) throws AuthError('INVALID_CONFIG'). So does a negative value. The default applies only when the option is omitted entirely.
Tests use injected clocks
Pass a custom clock in unit tests to make rotation grace windows, refresh expiry and revocation epochs deterministic. The orchestrator never reads Date.now() directly.
Sessions vs. tokens
The package treats sessions and tokens as the same machinery — same store, same orchestrator, same validation path. The method option is a tag on the issued context, nothing more.
Use method: 'session' when | Use method: 'token' when |
|---|---|
| Browser-first app, cookie transport, server-side state | API-first app, Authorization: Bearer ..., stateless or short-lived |
| Long TTL (hours to days) | Short TTL (minutes to hours), refresh on top |
Stateful store (Memory, Redis, AtscriptDb) | Either, but JWT is common |
You can run both in one app — issue different credentials with different methods over different transports.
For the multi-device "active sessions" view — listing a user's signed-in devices and revoking one or all-but-this-one — see Sessions.
issue(userId, options?)
Creates a new access credential (and optionally a refresh token).
Signature
issue(
userId: string,
// IssueOptions<TPayload> = TPayload & { metadata?; sessionId? } — the typed
// payload fields are passed FLAT, not under a `claims` key.
options?: IssueOptions<TPayload>,
): Promise<IssueResult>;
interface IssueResult {
accessToken: string;
accessExpiresAt: number;
refreshToken?: string;
refreshExpiresAt?: number;
}Behavior
- Enforces
maxConcurrentagainst the user's current live count (onlykind: 'access'). - Calls
store.persist(state, ttl)withkind: 'access'. - If
refreshis configured, also persists akind: 'refresh'credential. - Returns both tokens plus their absolute expiry timestamps.
Example
const { accessToken, refreshToken, accessExpiresAt } = await auth.issue("alice", {
// typed root fields on your credential model, passed flat (no `claims` wrapper)
roles: ["admin"],
tenantId: "t-1",
metadata: { ip: req.ip, userAgent: req.headers["user-agent"] },
});The instance-level accessTtl can be overridden per mint: issue() accepts ttl (relative ms, > 0) or expiresAt (absolute ms instant) — mutually exclusive — so one AuthCredential can mint a 30-minute browser session and a long-lived PAT/CLI token without a second instance. Pair with kind: "pat" (stored as metadata.credentialKind, carried across rotation) so listSessions({ kind }) can keep non-browser credentials out of the default "active sessions" view. The refresh TTL has no per-call override — it keeps refresh.ttl; workflows that need "remember me" must construct a second AuthCredential with a longer-lived refresh.ttl.
maxConcurrent and onLimit
maxConcurrent is an integer cap on live access credentials per user. Refresh tokens are excluded from the count. The orchestrator counts via store.listForUser(userId) — stateful stores only. Stateless stores cannot enumerate, so maxConcurrent is silently a no-op on JWT / Encapsulated stores.
onLimit | Behavior |
|---|---|
'reject' (default) | Throws AuthError('MAX_CONCURRENT_REACHED') with details: { userId, limit, active }. |
'evict-oldest' | Revokes the access credentials with the smallest issuedAt (oldest first) until the user is under the cap, then proceeds with the new issue(). Refresh tokens are unaffected. No error is thrown. |
Refresh tokens are free
Long-lived refresh credentials don't count toward maxConcurrent. A user on three devices with maxConcurrent: 3 has three access slots; the refresh tokens behind them don't tip the count.
validate(accessToken)
The hot path. Returns an AuthContext for a valid access token, or null for anything else — expired, revoked, malformed, unknown, wrong kind.
Signature
validate(accessToken: string): Promise<AuthContext<TPayload> | null>;
// AuthContext<TPayload> = envelope & TPayload — the credential's typed root
// fields surface FLAT (read `ctx.tenantId`, not `ctx.claims.tenantId`).
type AuthContext<TPayload extends object = object> = {
userId: string;
method: 'session' | 'token';
credentialId: string; // sha256(accessToken)
sessionId?: string; // stable across rotation; "this device" — see Sessions
expiresAt: number;
} & TPayload;sessionId identifies the token family this request authenticated with — stable across refresh, the key for "this device" matching and per-device revoke. See Sessions.
Behavior
store.retrieve(token)— returnsnullif missing, expired or epoch-shadowed. When adenylistis configured it is checked at the same time (one round trip); a denied token returnsnull.- Rejects tokens with
kind: 'refresh'(returnnull). - Builds
AuthContext;credentialId = sha256(token)is computed when first read.
Example
const ctx = await auth.validate(bearer);
if (!ctx) throw new HttpError(401);
// ctx.userId, ctx.roles (typed payload, flat), ctx.credentialId are safe to logNever throws
validate collapses every failure mode to null. If you need to distinguish "expired" from "revoked" for UX, encode the reason at issue-time in metadata, not by inspecting the validation path.
Opt-in validate cache (validateCache)
Every validate() reads the store (and the denylist). For a remote store on a hot API you can reuse a validated state for a few seconds instead:
const auth = new AuthCredential({
store,
validateCache: { ttlMs: 3_000, max: 10_000 }, // off unless set
});| Field | Default | Meaning |
|---|---|---|
ttlMs | (required) | How long a validated state is reused. Must be > 0. |
max | 10000 | Most cached tokens; the oldest entry is dropped first. |
- A hit still re-checks expiry, and refresh tokens and unknown tokens are never cached.
- This instance's
revoke,revokeAllForUser,revokeSession,revokeOtherSessions, themaxConcurrenteviction and the refresh-reuse response evict their tokens at once.
Revocation lag across processes
A revocation made on another process, by another AuthCredential instance, or by writing to the store / denylist directly is seen only when the entry expires — at most ttlMs later. Keep ttlMs to seconds, and leave it off where an immediate cross-node logout is a requirement.
Tokens at rest (tokens.hashAtRest)
By default a stateful store keys each row by the token itself, so anyone who can read the credential table, a backup or a replica holds working sessions, refresh tokens and PATs. With hashAtRest the store only ever sees a SHA-256 of each token:
const auth = new AuthCredential({
store: new CredentialStoreAtscriptDb({ table }),
refresh: { ttl: 30 * 24 * 3600 * 1000 },
tokens: { hashAtRest: true }, // new app: no sessions to keep
});| Setting | Effect |
|---|---|
hashAtRest: false | Default. Rows are keyed by the token itself. |
hashAtRest: true | Rows are keyed by the token's SHA-256. The successor pair kept on a rotated refresh row (the grace window) is encrypted with a key derived from that refresh token, and parentCredentialId holds the hash. Tokens become 256-bit random base64url strings. |
hashAtRest: 'migrate' | As true, but a token of the legacy shape (the randomUUID the bundled stores minted) whose hash is not found is also looked up as-is, so sessions issued before the switch keep working; a legacy refresh token is re-issued hashed on its next rotation. A 64-hex value (the shape of a stored hash) is never looked up as-is. |
generate: () => string | Your own token generator (default: 32 random bytes, base64url), e.g. to add a recognisable prefix that secret scanners can match. It must supply at least 128 bits of randomness — a plain SHA-256 of a guessable token is guessable too. |
isLegacyToken: (t) => boolean | 'migrate' only: which presented tokens may be looked up as-is. Default: the randomUUID shape. Pass a predicate when your pre-migration tokens came from a custom generate; it must match the exact token shape (an anchored pattern such as /^pat_[A-Za-z0-9_-]{43}$/), never a prefix test. Tokens containing whitespace are never looked up as-is. |
- Store support. Both options need a store that implements the optional
persistAsmethod —CredentialStoreMemory,CredentialStoreRedisandCredentialStoreAtscriptDbdo. The stateless JWT / encapsulated stores (the token is the state) throwAuthError('INVALID_CONFIG')at construction. - New app: use
true. Existing app:truesigns every current session out (their rows are keyed by the raw token and are no longer found) — deploy'migrate'first, then switch totrueonce your longest refresh lifetime has passed. - Finishing a migration. Only refresh tokens that rotate (
'always'/'sliding') are re-issued hashed. Tokens that never rotate — PATs and other access-only credentials, and refresh tokens underrotation: 'none'— stay keyed by the raw token for their whole life. Before switching totrue, list the user's credentials (listForUser) and re-issue the ones whose row key is not a 64-hex hash, or accept that those credentials stop working at the switch. - A database read is not a session. Under
trueand'migrate', presenting a row key (the hash) tovalidate,refreshorrevokematches nothing. credentialIdand session ids stay the same SHA-256 fingerprints described below, so audit logs and session lists are unaffected.
The credentialId fingerprint
credentialId = sha256(accessToken) is the non-replayable identifier of the credential. Three properties hold:
- Stable. Two calls to
validateon the same token return the samecredentialId. Safe to use as a cache key or DB row id. - Loggable. Logging the fingerprint never leaks the bearer token. Logging
accessTokenwould. - Non-replayable. An attacker who steals the fingerprint cannot call
validate(credentialId)—sha256is one-way.
Use it as the audit-log session key, the rate-limit key, and the websocket connection tag. Never use the raw accessToken for any of those.
refresh(refreshToken)
Exchanges a refresh token for a fresh access token (and, depending on rotation mode, a fresh refresh token). See Refresh & Rotation for the full state machine.
Signature
refresh(refreshToken: string): Promise<IssueResult>;Behavior summary
refresh.rotation | What happens on success |
|---|---|
'none' | New access token issued. Old refresh stays valid until its own TTL. |
'always' | New access + new refresh issued with a fixed family ceiling; old refresh grace-tolerant on stateful stores (consumed on stateless). Reuse after grace → REFRESH_REUSE_DETECTED. |
'sliding' (default) | First call marks rotatedAt + pins the successor pair. Within rotationGraceMs (default 30s) re-presenting the old refresh re-delivers the same pair; after → REFRESH_REUSE_DETECTED. |
See Refresh & Rotation for the grace-window semantics (idempotent re-delivery, supersession, strict rotationGraceMs: 0).
Errors
INVALID_TOKEN— unknown / malformed token, or an access token presented as a refresh.REFRESH_REUSE_DETECTED— reuse outside the grace window (or a superseded token). Revokes perreuseResponse— session family by default.STATELESS_OPERATION_UNSUPPORTED—'always'/'sliding'rotation on a stateless store without adenylist.
Example
try {
const next = await auth.refresh(oldRefreshToken);
res.cookie("access", next.accessToken, { maxAge: next.accessExpiresAt - Date.now() });
if (next.refreshToken) {
res.cookie("refresh", next.refreshToken, { maxAge: next.refreshExpiresAt! - Date.now() });
}
} catch (e) {
if (e instanceof AuthError && e.type === "REFRESH_REUSE_DETECTED") {
// The whole user has been logged out — surface a "you've been signed out everywhere"
res.status(401).clearCookie("access").clearCookie("refresh").end();
}
}revoke(token)
Revokes a single credential by its token (access or refresh — the store doesn't care). Use this to log out a single device.
Signature
revoke(token: string): Promise<void>;Behavior
- Stateful:
store.revoke(token)— row deleted. - Stateless: adds the credential's
jtito thedenylistuntil its naturalexpiresAt. ThrowsSTATELESS_OPERATION_UNSUPPORTEDif nodenylistwas passed.
Example
// Single-device logout
await auth.revoke(req.cookies.access);
await auth.revoke(req.cookies.refresh);revokeAllForUser(userId)
Logs the user out everywhere. Used by password reset, "sign out all devices", and reuse detection.
Signature
revokeAllForUser(userId: string): Promise<number>;Returns the count of credentials revoked. Stateful stores return the actual row count. Stateless stores return the sentinel 1 to mean "the per-user revocation epoch was bumped" — the actual number of tokens affected isn't knowable without enumeration.
Behavior: after revokeAllForUser(userId), every previously-issued credential for that user becomes invalid. Credentials issued after the call (including in the same millisecond) remain valid — this is what enables auto-login immediately after a password reset. See Refresh — Epoch revocation gate for the full mechanics and the durable-store caveats.
Stateless epoch is in-memory by default
The default CredentialStoreJwt tracks per-user revocation in process memory. A restart loses it; multi-instance deployments lose it across nodes. For durable per-user revocation on JWT, back it with Redis or atscript — see Stores.
listForUser(userId)
Returns every live AuthContext for the user. Useful for "active sessions" UI.
Signature
listForUser(userId: string): Promise<AuthContext<TPayload>[]>;Stateful stores enumerate. Stateless stores cannot enumerate — listForUser returns []. Don't rely on this method for JWT deployments.
Example
const sessions = await auth.listForUser("alice");
for (const s of sessions) {
console.log(s.credentialId, s.method, new Date(s.expiresAt));
}AuthContext shape
The exact shape returned by validate and listForUser:
type AuthContext<TPayload extends object = object> = {
userId: string;
method: "session" | "token";
credentialId: string;
expiresAt: number;
} & TPayload; // typed payload fields surface flat| Field | Meaning |
|---|---|
userId | Subject the credential was issued to. |
method | Whatever was configured at construction. |
credentialId | sha256(accessToken). Stable, loggable, non-replayable. |
expiresAt | Absolute ms timestamp. |
claims | The TPayload object passed at issue() time, if any. |
Note: metadata (IP, UA, fingerprint, label) is not on AuthContext. It lives in CredentialState server-side. The orchestrator deliberately doesn't echo it to the validation surface — keep it on the server.
CredentialMetadata declaration merging
CredentialMetadata is the open shape used for the per-credential metadata field. The package ships these keys:
interface CredentialMetadata {
ip?: string;
userAgent?: string;
fingerprint?: string;
label?: string;
}It is explicitly designed for TypeScript declaration merging. Augment it in your app to add app-specific keys with end-to-end type safety:
// types/aooth.d.ts
declare module "@aooth/auth" {
interface CredentialMetadata {
geoCountry?: string;
deviceId?: string;
enrolledTotp?: boolean;
}
}Then:
await auth.issue("alice", {
metadata: {
ip: req.ip,
geoCountry: "PT", // typed
deviceId: req.headers["x-device-id"] as string,
},
});The metadata is persisted by the store but never returned through validate. Read it via listForUser or directly from the underlying store when you need it.
Full lifecycle example
import { AuthCredential, CredentialStoreMemory } from "@aooth/auth";
const auth = new AuthCredential<{ roles: string[] }>({
store: new CredentialStoreMemory(),
accessTtl: 15 * 60 * 1000,
refresh: { ttl: 30 * 24 * 3600 * 1000, rotation: "always" },
maxConcurrent: 5,
});
// Login
const { accessToken, refreshToken } = await auth.issue("alice", {
roles: ["admin"], // typed payload field, flat
metadata: { ip: "1.1.1.1", userAgent: "Mozilla/..." },
});
// Each request
const ctx = await auth.validate(accessToken);
// Token rotation
const next = await auth.refresh(refreshToken!);
// Logout this device
await auth.revoke(next.accessToken);
await auth.revoke(next.refreshToken!);
// Logout everywhere (e.g. password reset)
await auth.revokeAllForUser("alice");
// Active sessions UI
const live = await auth.listForUser("alice");That covers every method on the orchestrator. Pick the right store next: see Stores for the implementation matrix, Tokens for the stateless options, and Refresh & Rotation for the rotation modes.
See the orchestrator source at packages/auth/src/auth-credential.ts.