Skip to content

Refresh & Rotation ​

RefreshConfig opts the orchestrator into refresh tokens and controls the rotation strategy. This page covers all three modes, the grace window, reuse detection, and the per-user revocation cascade.

The shape ​

ts
interface RefreshConfig {
  ttl: number; // ms
  rotation?: "none" | "always" | "sliding"; // default 'sliding'
  rotationGraceMs?: number; // default 30_000; 0 = strict single-use
  reuseResponse?: "session" | "user"; // default 'session'
  onRotationReuse?: (state: CredentialState) => void;
  onRotationGraceHit?: (state: CredentialState) => void;
}
OptionDefaultPurpose
ttl(required)Lifetime of refresh tokens, ms.
rotation'sliding'Rotation strategy — see the three modes.
rotationGraceMs30_000sliding and always — window after rotation during which re-presenting the old refresh re-delivers the same successor pair. 0 = strict single-use.
reuseResponse'session'Blast radius on detected reuse: the compromised token family ('session') or every session for the user ('user').
onRotationReuseundefinedHook called when reuse is detected. Fires before the revoke.
onRotationGraceHitundefinedAudit hook called on a within-grace re-presentation, just before the successor pair is re-delivered. See the grace window.

The minimum opt-in:

ts
const auth = new AuthCredential({
  store: new CredentialStoreMemory(),
  accessTtl: 15 * 60 * 1000,
  refresh: { ttl: 30 * 24 * 3600 * 1000 }, // sliding by default
});

The three modes ​

ModeRefresh expiryOld refresh after success (stateful)Reuse handlingTypical use
'none'unchangedStays usable until TTLNo reuse detectionLong-lived API keys, no rotation policy
'always'fixed ceilingValid for rotationGraceMs, then deadReuse after grace → REFRESH_REUSE_DETECTED + family revokeRotation with an absolute session cap
'sliding' (default)slides (now + ttl)Valid for rotationGraceMs, then deadReuse after grace → REFRESH_REUSE_DETECTED + family revokeBrowsers with parallel tabs / retries

'always' and 'sliding' differ only in expiry: 'sliding' is a rolling session (each refresh pushes the expiry to now + ttl); 'always' keeps the family's original expiry as a fixed ceiling, so the session has an absolute maximum lifetime regardless of activity. Both rotate the token on every refresh and both are grace-tolerant on stateful stores (a benign re-presentation of the just-rotated token within rotationGraceMs idempotently re-delivers the same successor pair instead of being mistaken for theft — see the grace window). On stateless stores neither can keep the old token valid, so both fall back to single-use semantics with a process-local reuse signal.

'none' — no rotation ​

refresh() issues a new access token. The refresh token stays in place until its TTL.

Timeline:

  t=0     issue()  →  access_a, refresh_r   (both fresh)
  t=10m   refresh(refresh_r)  →  access_b  (refresh_r still valid)
  t=20m   refresh(refresh_r)  →  access_c  (refresh_r still valid)
  t=30d   refresh(refresh_r)  →  AuthError('INVALID_TOKEN')  (refresh expired)

Choose when — the refresh token is intended as a long-lived secret (API key), or rotation overhead is unacceptable. No reuse detection — a leaked refresh token is exploitable until it expires.

'always' — rotate every time, fixed session ceiling ​

Every successful refresh() rotates the refresh token, but each rotated token inherits the family's original expiresAt — the session has an absolute maximum lifetime no matter how often it refreshes. On a stateful store it shares the same grace window as 'sliding', so a benign concurrent refresh within rotationGraceMs is not mistaken for theft.

Timeline (happy path) — note the fixed expiry:

  t=0     issue()  →  access_a, refresh_r1   (refresh expires at t=30d)
  t=10m   refresh(refresh_r1)  →  access_b, refresh_r2   (still expires at t=30d)
  t=20m   refresh(refresh_r2)  →  access_c, refresh_r3   (still expires at t=30d)
  t=30d   refresh(refresh_rN)  →  AuthError('INVALID_TOKEN')  (ceiling reached)

Timeline (reuse after grace):

  t=0      issue()  →  access_a, refresh_r1
  t=10m    refresh(refresh_r1)  →  access_b, refresh_r2   (r1.rotatedAt + successor set)
  t=10m+5s refresh(refresh_r1)  →  access_b, refresh_r2   (grace hit — SAME pair, nothing minted)
  t=10m+35s refresh(refresh_r1) →  AuthError('REFRESH_REUSE_DETECTED')
                                 → onRotationReuse(state) called
                                 → revokeSession(userId, sessionId)   (family only, by default)

Choose when — you want token rotation but a hard cap on how long a session can live (high-security, compliance-driven absolute timeouts). For a rolling "stay logged in while active" session, use 'sliding'.

'sliding' — rotate with grace window ​

The default. The first refresh() marks the old token's rotatedAt and pins the successor pair on it; the old token remains presentable for rotationGraceMs, and presenting it re-delivers that same pair. After the window, presenting it is treated as reuse.

Timeline (happy path):

  t=0      issue()  →  access_a, refresh_r1
  t=10m    refresh(refresh_r1)  →  access_b, refresh_r2
                                 → r1.rotatedAt = clock.now(), r1.successor = (access_b, refresh_r2)
  t=10m+5s refresh(refresh_r1)  →  access_b, refresh_r2   (grace hit — SAME pair, nothing minted)
  t=10m+35s refresh(refresh_r1) →  AuthError('REFRESH_REUSE_DETECTED')
                                 → revokeSession(userId, sessionId)   (family only, by default)

The grace window and concurrency ​

Why the grace window — real browsers race, and real deploys drop responses. A user double-taps "refresh", two tabs both notice the access token is stale and call refresh() simultaneously, or a rolling deploy drains the task after the store rotated but before the response (carrying the successor) reached the client — the client's next perfectly legitimate attempt presents the just-consumed token. Both 'sliding' and 'always' keep that token presentable for rotationGraceMs. The window is tracked in the store (rotatedAt + the pinned successor), so it holds across multiple app instances — a refresh on instance A and a concurrent replay on instance B both land inside the window. Without it, any concurrency on a multi-instance deployment would trip the theft response and log the user out of every device on a benign race. Size it to your redeploy/retry window (30–60 s); it stays meaningless for offline token theft.

A grace hit is an idempotent re-delivery, not a second rotation. Within the window the orchestrator returns the same successor pair the original rotation produced — N grace hits return N identical responses, and nothing is minted. This is the security-critical property: an attacker who captures the old token inside the window learns only what capturing the original rotation response would have taught them — zero new minting capability — and the multi-tab race converges on a single live refresh token instead of forking the family. A grace hit also has no liveness side effects: the sliding expiry does not extend and lastSeenAt is not stamped, so a captured stale token cannot be used as a keep-alive.

Supersession ends the window early. The moment the successor itself rotates (or is revoked — e.g. logout), the old token is dead regardless of the window: presenting it then is the strict theft path, never a resurrection.

Mobile and home-screen web apps: use a longer window. An installed PWA (iOS Home Screen especially) or a mobile browser can be suspended or killed while a refresh response is in flight. The store has rotated, the client never stored the successor, and its next refresh — often when the app is reopened minutes later — presents the rotated-out token. Once that's past rotationGraceMs it is reuse: REFRESH_REUSE_DETECTED, the session is revoked, and the user has to sign in again. For these clients size the window to how long the app is typically backgrounded, e.g. rotationGraceMs: 5 * 60_000. Pair it with onRotationGraceHit / onRotationReuse logging to see how often it happens. The trade-off: a rotated-out token stays usable for longer, but a grace hit only re-delivers the pair that already exists — nothing new is minted (see above).

Revocation wins over an in-flight refresh. On a stateful store, after persisting the new pair a refresh re-reads the refresh row it started from; if a logout, session revocation or password change deleted it meanwhile, the new pair is revoked and the refresh fails with INVALID_TOKEN (see Sessions — revoking sessions).

Strict mode — an explicit rotationGraceMs: 0 disables the window entirely: every re-presentation of a rotated token is treated as theft.

At rest — the pinned successor pair is a working access + refresh token sitting on the old row. With tokens.hashAtRest it is stored encrypted with a key derived from the old refresh token, so only a client that still holds that token can read it back; a database read alone yields nothing usable.

Observability — wire onRotationGraceHit to the same sink as onRotationReuse (e.g. a refresh-grace-hit audit event). A trickle of grace hits correlated with deploys is expected; a spike means someone is replaying tokens:

ts
refresh: {
  ttl: 30 * 24 * 3600 * 1000,
  rotationGraceMs: 60_000, // sized to the redeploy window
  onRotationGraceHit: (s) =>
    audit.record({ kind: "refresh-grace-hit", userId: s.userId, sessionId: s.sessionId }),
  onRotationReuse: (s) =>
    audit.record({ kind: "refresh-reuse", userId: s.userId, sessionId: s.sessionId }),
},

Choose when — browsers are involved. Default for a reason.

Stateless stores can't offer the grace window

On stateless stores (JWT, Encapsulated), the rotatedAt marker cannot resurface — the orchestrator writes the rotated state via store.update, which on stateless stores denylists the old jti and re-encodes into a brand-new token. The next presentation of the original refresh therefore looks like "unknown token" to the store (it's denylisted), so the cross-instance grace window cannot apply. Both 'sliding' and 'always' fall back to single-use semantics there, with a process-local reuse signal: a same-process replay still fires REFRESH_REUSE_DETECTED, but a replay that lands on a different instance just returns INVALID_TOKEN.

If you're running stateless use rotation: 'always' explicitly — the single-use intent matches the actual behavior and the rotation timeline becomes predictable.

ts
const auth = new AuthCredential({
  store: new CredentialStoreJwt({ /* ... */, denylist }),
  accessTtl: 5 * 60 * 1000,
  refresh: {
    ttl: 7 * 24 * 3600 * 1000,
    rotation: 'always',   // not 'sliding' on stateless
  },
});

What rotation carries forward ​

Each rotated pair inherits the previous credential's claims, metadata, and sessionId — so a login stays one session across N refreshes (the session-family invariant the Sessions APIs rely on). parentCredentialId chains each rotation to its predecessor for reuse detection (below); sessionId is the durable id that survives the whole chain.

With trackLastSeen: 'refresh', each refresh() also stamps lastSeenAt on the newly-minted credentials — cheap activity tracking that piggybacks the rotation write. Grace hits are excluded: a re-delivery is not user activity, so it never stamps lastSeenAt. See Sessions.

Reuse detection ​

When the orchestrator detects a refresh-token reuse (a presentation after the grace window, or — on stateless stores — a replay of a single-use token), three things happen, in order:

  1. onRotationReuse(state) is called (if configured) — state is the offending CredentialState (the original, not the rotation).
  2. The compromised credentials are revoked per reuseResponse:
    • 'session' (default) — auth.revokeSession(userId, sessionId) kills only the reused token family (the compromised session). The legitimate user and the attacker share that family, so both are ended; the user's other devices keep working.
    • 'user' — auth.revokeAllForUser(userId) revokes every session for the user.
    • When the session can't be targeted (no sessionId — including one a store reads back as null, e.g. a SQL row written before session ids existed, since 0.2.7 — or a store that can't enumerate sessions, e.g. stateless), 'session' falls back to the user-wide cascade so theft is never left un-revoked.
  3. AuthError('REFRESH_REUSE_DETECTED') is thrown with details: { userId, sessionId?, rotatedAt? }.

The reasoning: a reused refresh token is taken to mean either (a) a token leak — the attacker and the legitimate user are both calling refresh() — or (b) a client bug. The default response ends the compromised session (the OAuth-best-practice token-family revocation) while leaving the user's other devices alone; escalate to 'user' when any reuse should be treated as a full-account compromise.

Hook example — alerting:

ts
const auth = new AuthCredential({
  store,
  accessTtl: 15 * 60 * 1000,
  refresh: {
    ttl: 30 * 24 * 3600 * 1000,
    rotation: "sliding",
    reuseResponse: "session", // default — or "user" to revoke everything
    onRotationReuse: (state) => {
      log.warn({ userId: state.userId, sessionId: state.sessionId }, "refresh reuse detected");
      audit.record({ kind: "refresh-reuse", userId: state.userId, sessionId: state.sessionId });
    },
  },
});

The hook fires synchronously before the revoke. It's a notification, not a veto — you cannot prevent the revoke from this hook.

Log the reuse, surface a clear UX

After REFRESH_REUSE_DETECTED, the affected session (or, with reuseResponse: 'user', every session) is ended. Show a clean message at login that explains why ("for your security, this session was ended"). Avoid blaming the user.

The per-user revocation epoch ​

revokeAllForUser works differently across store types:

Store kindMechanism
StatefuldeleteMany({ userId }) — actual rows removed.
Statelessepochs[userId] = clock.now() — gate every future retrieve against this timestamp.

The stateless gate is: validate rejects any token whose iatMs is less than the epoch.

   token.iatMs < epoch[token.sub]   →  null  (rejected)
   token.iatMs >= epoch[token.sub]  →  pass through

Note the >= — not >. This is load-bearing.

Why >= matters ​

The same-millisecond >= gate lets a workflow revokeAllForUser(userId) and then immediately issue(userId, ...) in the same millisecond, and have the newly-issued credential survive the gate. Without this, the recovery workflow would have to sleep 1ms between the revoke and the issue.

Concretely — password reset auto-login:

ts
async function resetPassword(userId, newPassword) {
  await users.password.changeFor(userId, newPassword);
  await auth.revokeAllForUser(userId); // bumps epoch to now
  const { accessToken } = await auth.issue(userId, {/* ... */});
  // newly-issued token has iatMs >= epoch → survives the gate
  return accessToken;
}

Don't widen the gate

The >= is the minimum width needed for same-ms re-issue. Do not change this to > in custom store implementations — recovery, password reset, and "kick other devices then log in here" all depend on the equality.

Per-mint refresh control (IssueOptions.refresh) ​

The instance-level refresh config decides the default; individual mints can override it:

ts
// Suppress the pair for this mint only (no orphaned refresh row) —
// e.g. a one-shot token on an instance that refreshes browser sessions.
await auth.issue("alice", { refresh: false });

// Mint a refresh token with a per-mint lifetime — works even on an instance
// with NO refresh config (then `ttl` is required). Per-mint families ALWAYS
// redeem with fixed-ceiling ('always') rotation — even when the instance
// rotates its sessions 'sliding' — so the family's lifetime is capped at the
// minted expiry and rotation never extends it.
await auth.issue("alice", { ttl: 60 * 60_000, refresh: { ttl: 30 * 24 * 3600 * 1000 } });

// A per-mint grace window (ms) fixes the family's rotation grace the same
// mint-time-authority way, honored over the instance `rotationGraceMs`;
// 0 = strict single-use for this family only.
await auth.issue("alice", { refresh: { ttl: 30 * 24 * 3600 * 1000, graceMs: 60_000 } });

Four related seams, all used by the authorization server's refresh_token grant:

  • When a refresh token is minted alongside a per-mint access ttl, the ttl is stamped on the family (metadata.accessTtl) so every refreshed access token keeps the mint-time lifetime instead of reverting to the instance accessTtl.
  • A per-mint family's rotation semantics are stamped the same way (metadata.refreshRotation: "always") and honored over the instance config on every redemption — mint-time authority, like accessTtl.
  • A per-mint graceMs stamps the family's grace window (metadata.rotationGraceMs) the same way — the seam behind TokenPolicy.refresh.graceMs, so an OAuth grant's lost-response tolerance is the policy's decision, not the session posture's.
  • auth.refresh(token, { guard }) accepts a pre-rotation guard: it sees the stored refresh credential before anything rotates, and throwing aborts the refresh with the family untouched — the seam for caller-level binding checks.

These stamps live in credential metadata

On CredentialStoreAtscriptDb the stamps above need the model's @aooth.auth.metadata column. Since 0.2 a store without one refuses such a mint with AuthError('INVALID_CONFIG') instead of silently dropping the restriction — see Stores — metadata column. Memory and Redis stores keep the whole state and need nothing.

maxConcurrent and refresh tokens ​

maxConcurrent enforces a cap on access credentials only. Refresh tokens never count toward the limit.

ts
const auth = new AuthCredential({
  store: new CredentialStoreMemory(),
  accessTtl: 15 * 60 * 1000,
  refresh: { ttl: 30 * 24 * 3600 * 1000, rotation: "always" },
  maxConcurrent: 3,
  onLimit: "reject",
});

// Three logins on three devices — fine.
await auth.issue("alice", {/* ... */});
await auth.issue("alice", {/* ... */});
await auth.issue("alice", {/* ... */});

// Fourth login on a fourth device — rejected.
await auth.issue("alice", {/* ... */});
// AuthError('MAX_CONCURRENT_REACHED', { userId: 'alice', limit: 3, active: 3 })

onLimit strategies ​

StrategyBehaviorUse case
'reject' (default)Throws MAX_CONCURRENT_REACHED. Caller must handle.Strict cap — third device on a Pro plan, fourth rejected.
'evict-oldest'Revokes oldest access credentials (by smallest issuedAt) until under the cap, then proceeds with the new issue(). No throw.Free plan — silently kick the oldest session.

'reject' throws AuthError('MAX_CONCURRENT_REACHED') with details: { userId, limit, active }; 'evict-oldest' returns the new IssueResult after the cascade. To render a "pick a device to kick" UI, use 'reject' plus listForUser + revoke in the framework layer.

Counting and stateless stores ​

The current count uses store.listForUser(userId). Stateless stores can't enumerate, so:

StoremaxConcurrent enforced?
Memory, Redis, AtscriptDbYes
Jwt, EncapsulatedNo — silently a no-op

If you need maxConcurrent on JWT, run the JWT store alongside a stateful index keyed by credentialId, and call listForUser against the index — or simply pick a stateful store.

Patterns ​

Stateful + 'sliding' (most apps) ​

ts
const auth = new AuthCredential({
  store: new CredentialStoreAtscriptDb({ table }),
  accessTtl: 15 * 60 * 1000,
  refresh: {
    ttl: 30 * 24 * 3600 * 1000,
    rotation: "sliding",
    rotationGraceMs: 30_000,
    onRotationReuse: (s) => log.warn("reuse", s.userId),
  },
  maxConcurrent: 10,
  tokens: { hashAtRest: true }, // the successor pair kept for the grace window is encrypted at rest
});

Stateless + 'always' (high-fan-out API) ​

ts
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", // explicit — not 'sliding'
    onRotationReuse: (s) => audit.record({ kind: "reuse", userId: s.userId }),
  },
});

No rotation (long-lived API tokens) ​

ts
const auth = new AuthCredential({
  store: new CredentialStoreAtscriptDb({ table }),
  accessTtl: 24 * 3600 * 1000,
  refresh: {
    ttl: 365 * 24 * 3600 * 1000,
    rotation: "none",
  },
});

Reuse detection is disabled in 'none' mode — a leaked refresh stays exploitable until TTL. Use only when you have other mitigations (IP allowlist, mTLS, etc).

Error mapping at the HTTP edge ​

ErrorSuggested HTTP status
INVALID_TOKEN401 Unauthorized
REFRESH_REUSE_DETECTED401 Unauthorized, clear cookies, redirect to login (the compromised session is ended; with reuseResponse: 'user', every session is)
STATELESS_OPERATION_UNSUPPORTED500 Internal Server Error — server misconfiguration
MAX_CONCURRENT_REACHED429 Too Many Requests or 409 Conflict, plus a body shape the client recognises

See Errors for the full table.

See also ​

Released under the MIT License.