Token service
ValidatedIssue JWTs, rotate refresh tokens, and wire key providers and stores for Express, Fastify, and Hono.
The token service issues short-lived JWT access tokens and single-use refresh tokens. It verifies signatures, issuer, audience, expiry, token type, and an optional JTI denylist before returning access claims.
Your app still authenticates users, stores credentials, manages cookies and CSRF, and decides authorization. This block handles token mechanics and refresh rotation.
MemoryTokenStore is process-local and loses state on restart. Use PostgreSQL or Redis for
refresh tokens in a multi-instance deployment. Use StatelessTokenStore only for
access-token-only services that do not need refresh or server-side revocation.
Quick start
pnpm dlx blockend-cli init
pnpm dlx blockend-cli add token-serviceThis example creates a temporary RSA key, issues one access token, and verifies it:
import { generateKeyPairSync } from "node:crypto";
import {
createTokenService,
LocalKeyProvider,
StatelessTokenStore
} from "@/blocks/token-service/src";
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
modulusLength: 2048
});
const tokens = createTokenService({
deploymentMode: "development",
issuer: "http://localhost:3000",
algorithms: ["RS256"],
keyProvider: new LocalKeyProvider({
signingKid: "local-dev",
keys: [
{
kid: "local-dev",
alg: "RS256",
privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
publicKeyPem: publicKey.export({ type: "spki", format: "pem" }).toString()
}
]
}),
tokenStore: new StatelessTokenStore()
});
const pair = await tokens.issue({
sub: "user-123",
tokens: { access: true, refresh: false }
});
const result = await tokens.verify(pair.accessToken!);
console.log(result.claims.sub); // "user-123"The example generates new keys on every start, so tokens from an earlier run will not verify. It also has no refresh or revocation state. Continue to Production setup for a persistent store.
Files
token-service/
├── sql/
│ └── postgres.sql
├── src/
│ ├── adapters/
│ │ ├── express.ts
│ │ ├── fastify.ts
│ │ ├── hono.ts
│ │ └── http.ts
│ ├── core/
│ │ ├── crypto.ts
│ │ ├── errors.ts
│ │ ├── token-service.ts
│ │ ├── types.ts
│ │ └── validation.ts
│ ├── providers/
│ │ ├── kms-rsa-key-provider.ts
│ │ ├── local-key-provider.ts
│ │ └── remote-jwks-provider.ts
│ ├── stores/
│ │ ├── memory-token-store.ts
│ │ ├── postgres-token-store.ts
│ │ ├── redis-token-store.ts
│ │ └── stateless-token-store.ts
│ └── index.ts
└── tests/With paths.blocks set to src/blocks and aliases.blocks set to @/blocks, the CLI copies this block to src/blocks/token-service, so the public entry point is @/blocks/token-service/src. Importing from @/blocks/token-service fails because the block's root has no index.ts.
Installation
pnpm dlx blockend-cli add token-serviceThe CLI installs jose, zod, your selected framework package, and the block's dev dependencies, including pg, ioredis, and Vitest, when you accept the dependency prompt. It copies the block with one adapter.
Copy src/ and sql/ into blocks/token-service and install jose, zod, and your framework package.
| Package | Required for |
|---|---|
jose | JWT signing and verification |
zod | Configuration and input validation |
express | Express adapter |
fastify | Fastify adapter |
hono | Hono adapter |
pg | Only if your PgLike wrapper uses it |
ioredis | Only if you use the ioredis adapter example; the store accepts any RedisLike client |
Public entry point
export { createTokenService } from "./core/token-service.js";
export { TokenError, isTokenError } from "./core/errors.js";
export type * from "./core/types.js";
export { LocalKeyProvider } from "./providers/local-key-provider.js";
export type { LocalKey } from "./providers/local-key-provider.js";
export { RemoteJwksKeyProvider } from "./providers/remote-jwks-provider.js";
export { KmsRsaKeyProvider } from "./providers/kms-rsa-key-provider.js";
export type { KmsRsaSigner } from "./providers/kms-rsa-key-provider.js";
export { MemoryTokenStore } from "./stores/memory-token-store.js";
export { StatelessTokenStore } from "./stores/stateless-token-store.js";
export { RedisTokenStore } from "./stores/redis-token-store.js";
export type { RedisLike, RedisTokenStoreOptions } from "./stores/redis-token-store.js";
export { PostgresTokenStore } from "./stores/postgres-token-store.js";
export type { PgLike, PgTransaction, QueryResult } from "./stores/postgres-token-store.js";
Service
import {
decodeProtectedHeader,
errors as JoseErrors,
jwtVerify,
SignJWT,
type JWTPayload
} from "jose";
import { TokenError, isTokenError } from "./errors.js";
import {
clamp,
familyIdFromOpaqueToken,
hashToken,
jsonByteLength,
newId,
newOpaqueToken
} from "./crypto.js";
import {
assertAllowedAlgorithm,
parseIssue,
parseOptions,
parseRevoke,
type IssueInput
} from "./validation.js";
import type {
AccessTokenClaims,
RefreshTokenRecord,
RevokeInput,
SigningAlgorithm,
TokenEvent,
TokenPair,
TokenService,
TokenServiceOptions,
VerifyResult
} from "./types.js";
const ACCESS_DEFAULT = 900,
ACCESS_MIN = 60,
ACCESS_MAX = 3600;
const REFRESH_DEFAULT = 604_800,
REFRESH_MIN = 3600,
REFRESH_MAX = 2_592_000;
const FAMILY_MAX_DEFAULT = 7_776_000,
FAMILY_MAX_MIN = 3600,
FAMILY_MAX_MAX = 31_536_000,
FAMILY_ROTATIONS_DEFAULT = 10_000,
FAMILY_ROTATIONS_MAX = 1_000_000;
const DEFAULT_FORBIDDEN = [
"password",
"password_hash",
"secret",
"private_key",
"privatekey",
"access_token",
"refresh_token",
"token",
"__proto__",
"prototype",
"constructor"
];
const RESERVED = new Set(["iss", "sub", "aud", "exp", "nbf", "iat", "jti", "type"]);
class DefaultTokenService implements TokenService {
private readonly options: TokenServiceOptions;
private readonly allowedAlgorithms: SigningAlgorithm[];
private readonly forbidden: Set<string>;
private readonly accessTtl: number;
private readonly refreshTtl: number;
private readonly familyMaxLifetime: number;
private readonly familyMaxRotations: number;
constructor(options: TokenServiceOptions) {
this.options = parseOptions(options);
this.allowedAlgorithms = options.algorithms ?? ["RS256", "ES256"];
this.forbidden = new Set(
(options.forbiddenClaimKeys ?? DEFAULT_FORBIDDEN).map((key) => key.toLowerCase())
);
this.accessTtl = clamp(options.accessTokenTtlSeconds, ACCESS_DEFAULT, ACCESS_MIN, ACCESS_MAX);
this.refreshTtl = clamp(
options.refreshTokenTtlSeconds,
REFRESH_DEFAULT,
REFRESH_MIN,
REFRESH_MAX
);
this.familyMaxLifetime = clamp(
options.maxRefreshFamilyLifetimeSeconds,
FAMILY_MAX_DEFAULT,
FAMILY_MAX_MIN,
FAMILY_MAX_MAX
);
this.familyMaxRotations = clamp(
options.maxRefreshRotations,
FAMILY_ROTATIONS_DEFAULT,
1,
FAMILY_ROTATIONS_MAX
);
}
async issue(raw: IssueInput): Promise<TokenPair> {
try {
const input = parseIssue(raw);
this.assertClaims(input.claims ?? {});
this.assertAudience(input.audience);
const access = input.tokens?.access ?? true;
const refresh = input.tokens?.refresh ?? true;
if (!access && !refresh)
throw new TokenError("INVALID_INPUT", "At least one token must be requested");
const now = this.nowSeconds();
const pair: TokenPair = { tokenType: "Bearer", issuedAt: now };
if (access) {
const ttl = clamp(input.accessTokenTtlSeconds, this.accessTtl, ACCESS_MIN, ACCESS_MAX);
pair.accessToken = await this.signAccess(
input.sub,
input.claims ?? {},
input.audience ?? this.options.audience,
ttl,
now
);
pair.expiresIn = ttl;
}
if (refresh) {
const ttl = clamp(input.refreshTokenTtlSeconds, this.refreshTtl, REFRESH_MIN, REFRESH_MAX);
const familyId = this.options.tokenStore.createFamilyId?.(input.sub) ?? newId();
const familyExpiresAt = new Date((now + this.familyMaxLifetime) * 1000);
const token = newOpaqueToken(familyId);
const record = this.refreshRecord(
token,
input.sub,
familyId,
ttl,
now,
familyExpiresAt,
0,
this.familyMaxRotations
);
await this.store(() => this.options.tokenStore.saveRefreshToken(record));
pair.refreshToken = token;
pair.refreshExpiresIn = Math.max(
0,
Math.floor((record.expiresAt.getTime() - now * 1000) / 1000)
);
}
this.emit({
name: "token.issued",
at: this.now().toISOString(),
sub: input.sub
});
return pair;
} catch (error) {
throw this.failure(error);
}
}
async verify(accessToken: string): Promise<VerifyResult> {
try {
if (typeof accessToken !== "string" || accessToken.length < 20 || accessToken.length > 16_384)
throw new TokenError("INVALID_TOKEN", "Invalid access token");
const header = decodeProtectedHeader(accessToken);
if (!header.alg || header.alg === "none")
throw new TokenError("INVALID_TOKEN", "Missing or invalid algorithm");
assertAllowedAlgorithm(header.alg, this.allowedAlgorithms);
const verification = await this.options.keyProvider.getVerificationKey({
...(header.kid ? { kid: header.kid } : {}),
alg: header.alg
});
if (verification.alg !== header.alg)
throw new TokenError("INVALID_TOKEN", "Key algorithm mismatch");
const result = await jwtVerify(accessToken, verification.key, {
algorithms: this.allowedAlgorithms,
issuer: this.options.issuer,
...(this.options.audience ? { audience: this.options.audience } : {}),
clockTolerance: this.options.clockSkewSeconds ?? 30,
currentDate: this.now(),
requiredClaims: ["sub", "exp", "iat", "jti", "type"]
});
const claims = this.toAccessClaims(result.payload);
if (
this.options.tokenStore.isJtiRevoked &&
(await this.store(() => this.options.tokenStore.isJtiRevoked!(claims.jti)))
) {
throw new TokenError("TOKEN_REVOKED", "Access token has been revoked");
}
this.emit({
name: "token.verified",
at: this.now().toISOString(),
sub: claims.sub,
jti: claims.jti
});
return { valid: true, claims };
} catch (error) {
throw this.failure(error);
}
}
async refresh(refreshToken: string): Promise<TokenPair> {
try {
if (typeof refreshToken !== "string" || refreshToken.length < 32 || refreshToken.length > 512)
throw new TokenError("INVALID_TOKEN", "Invalid refresh token");
const tokenFamilyId = familyIdFromOpaqueToken(refreshToken);
if (!tokenFamilyId) throw new TokenError("INVALID_TOKEN", "Invalid refresh token");
const nowDate = this.now();
const now = Math.floor(nowDate.getTime() / 1000);
const currentHash = hashToken(refreshToken);
const current = await this.store(() =>
this.options.tokenStore.getRefreshToken(currentHash, tokenFamilyId)
);
if (!current) throw new TokenError("INVALID_TOKEN", "Unknown refresh token");
if (current.familyId !== tokenFamilyId)
throw new TokenError("INVALID_TOKEN", "Invalid refresh token");
if (current.status === "revoked")
throw new TokenError("TOKEN_REVOKED", "Refresh token revoked");
if (current.status === "active" && current.expiresAt.getTime() <= nowDate.getTime())
throw new TokenError("TOKEN_EXPIRED", "Refresh token expired");
if (current.status === "active" && current.familyExpiresAt.getTime() <= nowDate.getTime())
throw new TokenError("TOKEN_EXPIRED", "Refresh family expired");
if (
current.status === "active" &&
current.rotationCount >= Math.min(current.rotationLimit, this.familyMaxRotations)
)
throw new TokenError("REFRESH_LIMIT", "Refresh family reached its rotation limit");
// Complete fallible identity lookups and signing before consuming the current token.
// The store still performs the final status check and rotation atomically.
let accessToken: string | undefined;
if (current.status === "active") {
const context = (await this.options.resolveRefreshContext?.(current.sub)) ?? {};
this.assertClaims(context.claims ?? {});
const audience = context.audience ?? this.options.audience;
this.assertAudience(audience);
accessToken = await this.signAccess(
current.sub,
context.claims ?? {},
audience,
this.accessTtl,
now
);
}
// Context resolution and key signing can be slow. Recheck expiration at
// the rotation boundary instead of letting an earlier timestamp extend
// an expired credential's authority.
const rotationDate = this.now();
const rotationNow = Math.floor(rotationDate.getTime() / 1000);
if (current.status === "active" && current.expiresAt.getTime() <= rotationDate.getTime())
throw new TokenError("TOKEN_EXPIRED", "Refresh token expired");
const replacementToken = newOpaqueToken(current.familyId);
const placeholder = this.refreshRecord(
replacementToken,
current.sub,
current.familyId,
this.refreshTtl,
rotationNow,
current.familyExpiresAt,
current.rotationCount + 1,
current.rotationLimit
);
const result = await this.store(() =>
this.options.tokenStore.rotateRefreshToken({
currentHash,
replacement: placeholder,
now: rotationDate,
maxRotations: this.familyMaxRotations
})
);
if (result.status === "missing")
throw new TokenError("INVALID_TOKEN", "Unknown refresh token");
if (result.status === "expired")
throw new TokenError("TOKEN_EXPIRED", "Refresh token expired");
if (result.status === "limit")
throw new TokenError("REFRESH_LIMIT", "Refresh family reached its rotation limit");
if (result.status === "revoked")
throw new TokenError("TOKEN_REVOKED", "Refresh token revoked");
if (result.status === "reused") {
await this.store(() => this.options.tokenStore.revokeByFamily(result.record.familyId));
this.emit({
name: "token.reuse_detected",
at: nowDate.toISOString(),
sub: result.record.sub,
familyId: result.record.familyId
});
throw new TokenError(
"REFRESH_REUSED",
"Refresh token reuse detected; token family revoked"
);
}
if (!accessToken)
throw new TokenError("KEY_UNAVAILABLE", "Could not prepare the access token");
const { sub, familyId } = result.record;
this.emit({
name: "token.refreshed",
at: nowDate.toISOString(),
sub,
familyId
});
return {
accessToken,
refreshToken: replacementToken,
tokenType: "Bearer",
expiresIn: this.accessTtl,
refreshExpiresIn: Math.max(
0,
Math.floor((result.record.expiresAt.getTime() - rotationDate.getTime()) / 1000)
),
issuedAt: now
};
} catch (error) {
throw this.failure(error);
}
}
async revoke(raw: RevokeInput): Promise<void> {
try {
const input = parseRevoke(raw);
const nowDate = this.now();
if ("refreshToken" in input) {
const familyId = familyIdFromOpaqueToken(input.refreshToken);
if (!familyId) throw new TokenError("INVALID_INPUT", "Invalid refresh token");
await this.store(() =>
this.options.tokenStore.revokeByHash(hashToken(input.refreshToken), familyId)
);
} else if ("familyId" in input)
await this.store(() => this.options.tokenStore.revokeByFamily(input.familyId));
else if ("sub" in input)
await this.store(() => this.options.tokenStore.revokeBySub(input.sub));
else {
if (!this.options.tokenStore.revokeByJti)
throw new TokenError(
"UNSUPPORTED_OPERATION",
"This store does not support access-token revocation"
);
const clockTolerance = this.options.clockSkewSeconds ?? 30;
const expiresAt = new Date(nowDate.getTime() + (ACCESS_MAX + clockTolerance) * 1000);
await this.store(() => this.options.tokenStore.revokeByJti!(input.jti, expiresAt));
}
this.emit({
name: "token.revoked",
at: this.now().toISOString(),
...("jti" in input ? { jti: input.jti } : {}),
...("sub" in input ? { sub: input.sub } : {}),
...("familyId" in input ? { familyId: input.familyId } : {})
});
} catch (error) {
throw this.failure(error);
}
}
private async signAccess(
sub: string,
claims: Record<string, unknown>,
audience: string | string[] | undefined,
ttl: number,
now: number
): Promise<string> {
const customSigner = this.options.keyProvider.signJwt;
if (customSigner) {
const signing = await this.options.keyProvider.getSigningKey?.();
if (!signing)
throw new TokenError(
"KEY_UNAVAILABLE",
"Custom signer must expose its active kid and algorithm"
);
if (!this.allowedAlgorithms.includes(signing.alg))
throw new TokenError("KEY_UNAVAILABLE", "Signing key algorithm is not allowed");
return customSigner.call(this.options.keyProvider, {
protectedHeader: { alg: signing.alg, kid: signing.kid, typ: "JWT" },
payload: {
...claims,
type: "access",
iss: this.options.issuer,
sub,
...(audience ? { aud: audience } : {}),
iat: now,
exp: now + ttl,
jti: newId()
}
});
}
const signing = await this.options.keyProvider.getSigningKey?.();
if (!signing) throw new TokenError("KEY_UNAVAILABLE", "No signing capability is configured");
if (!this.allowedAlgorithms.includes(signing.alg))
throw new TokenError("KEY_UNAVAILABLE", "Signing key algorithm is not allowed");
let jwt = new SignJWT({ ...claims, type: "access" })
.setProtectedHeader({ alg: signing.alg, kid: signing.kid, typ: "JWT" })
.setIssuer(this.options.issuer)
.setSubject(sub)
.setIssuedAt(now)
.setExpirationTime(now + ttl)
.setJti(newId());
if (audience) jwt = jwt.setAudience(audience);
return jwt.sign(signing.key);
}
private assertClaims(claims: Record<string, unknown>): void {
if (jsonByteLength(claims) > (this.options.maxClaimsBytes ?? 4096))
throw new TokenError("CLAIMS_TOO_LARGE", "Custom claims exceed the configured byte limit");
const inspect = (value: unknown, root = true): void => {
if (!value || typeof value !== "object") return;
for (const [key, nested] of Object.entries(value)) {
const normalized = key.toLowerCase();
if (root && RESERVED.has(normalized))
throw new TokenError("FORBIDDEN_CLAIM", `Reserved claim: ${key}`);
if (this.forbidden.has(normalized))
throw new TokenError("FORBIDDEN_CLAIM", `Forbidden claim: ${key}`);
inspect(nested, false);
}
};
inspect(claims);
}
private assertAudience(requested: string | string[] | undefined): void {
if (!requested || !this.options.audience) return;
const allowed = new Set(
Array.isArray(this.options.audience) ? this.options.audience : [this.options.audience]
);
const values = Array.isArray(requested) ? requested : [requested];
if (values.some((audience) => !allowed.has(audience)))
throw new TokenError("INVALID_INPUT", "Requested audience is not allowed");
}
private refreshRecord(
token: string,
sub: string,
familyId: string,
ttl: number,
now: number,
familyExpiresAt: Date,
rotationCount: number,
rotationLimit: number
): RefreshTokenRecord {
const expiresAt = new Date(Math.min((now + ttl) * 1000, familyExpiresAt.getTime()));
return {
tokenHash: hashToken(token),
sub,
familyId,
status: "active",
createdAt: new Date(now * 1000),
expiresAt,
familyExpiresAt,
rotationCount,
rotationLimit
};
}
private toAccessClaims(payload: JWTPayload): AccessTokenClaims {
if (
payload.type !== "access" ||
typeof payload.sub !== "string" ||
typeof payload.iss !== "string" ||
typeof payload.exp !== "number" ||
typeof payload.iat !== "number" ||
typeof payload.jti !== "string"
)
throw new TokenError("INVALID_TOKEN", "Invalid access-token claims");
return payload as AccessTokenClaims;
}
private now(): Date {
return this.options.now?.() ?? new Date();
}
private nowSeconds(): number {
return Math.floor(this.now().getTime() / 1000);
}
private emit(event: TokenEvent): void {
try {
this.options.onEvent?.(event);
} catch {
/* telemetry must not change auth behavior */
}
}
private async store<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (cause) {
if (isTokenError(cause)) throw cause;
throw new TokenError("STORE_UNAVAILABLE", "Token store operation failed", { cause });
}
}
private failure(error: unknown): TokenError {
const mapped = isTokenError(error)
? error
: error instanceof JoseErrors.JWTExpired
? new TokenError("TOKEN_EXPIRED", "Access token expired", {
cause: error
})
: error instanceof JoseErrors.JOSEError
? new TokenError("INVALID_TOKEN", "Access token validation failed", {
cause: error
})
: new TokenError("KEY_UNAVAILABLE", "Token operation failed", {
cause: error
});
this.emit({
name: "token.failed",
at: this.now().toISOString(),
code: mapped.code
});
return mapped;
}
}
/** Creates an isolated token service. Configuration is validated immediately. */
export function createTokenService(options: TokenServiceOptions): TokenService {
return new DefaultTokenService(options);
}
Types
import type { JWK } from "jose";
import type { IssueInput } from "./validation.js";
export type SigningAlgorithm =
| "RS256"
| "RS384"
| "RS512"
| "PS256"
| "PS384"
| "PS512"
| "ES256"
| "ES384"
| "ES512"
| "EdDSA"
| "HS256"
| "HS384"
| "HS512";
export interface TokenPair {
accessToken?: string;
refreshToken?: string;
tokenType: "Bearer";
expiresIn?: number;
refreshExpiresIn?: number;
issuedAt: number;
}
export interface AccessTokenClaims {
sub: string;
iss: string;
aud?: string | string[];
exp: number;
iat: number;
jti: string;
type: "access";
[key: string]: unknown;
}
export interface VerifyResult {
valid: true;
claims: AccessTokenClaims;
}
export type RevokeInput =
| { refreshToken: string }
| { jti: string }
| { sub: string }
| { familyId: string };
export type TokenErrorCode =
| "INVALID_INPUT"
| "INVALID_TOKEN"
| "TOKEN_EXPIRED"
| "TOKEN_REVOKED"
| "REFRESH_REUSED"
| "REFRESH_LIMIT"
| "CLAIMS_TOO_LARGE"
| "FORBIDDEN_CLAIM"
| "KEY_UNAVAILABLE"
| "STORE_UNAVAILABLE"
| "UNSUPPORTED_OPERATION";
export type TokenEvent = {
name:
| "token.issued"
| "token.verified"
| "token.refreshed"
| "token.revoked"
| "token.reuse_detected"
| "token.failed";
at: string;
sub?: string;
jti?: string;
familyId?: string;
code?: TokenErrorCode;
};
export interface SigningKey {
key: CryptoKey | Uint8Array;
kid: string;
alg: SigningAlgorithm;
}
export interface VerificationKey {
key: CryptoKey | Uint8Array;
kid?: string;
alg: SigningAlgorithm;
}
/** Supplies private signing keys and public verification keys. Providers may rotate by changing the returned `kid`. */
export interface ProviderSignInput {
protectedHeader: { alg: SigningAlgorithm; kid: string; typ: "JWT" };
payload: Record<string, unknown>;
}
export interface KeyProvider {
getSigningKey?(): Promise<SigningKey>;
signJwt?(input: ProviderSignInput): Promise<string>;
getVerificationKey(input: { kid?: string; alg: SigningAlgorithm }): Promise<VerificationKey>;
getPublicJwks?(): Promise<{ keys: JWK[] }>;
}
export interface RefreshTokenRecord {
tokenHash: string;
familyId: string;
sub: string;
expiresAt: Date;
/** Fixed absolute deadline shared by every descendant in the family. */
familyExpiresAt: Date;
/** Number of successful rotations already performed in this family. */
rotationCount: number;
/** Rotation ceiling fixed when the family was issued. */
rotationLimit: number;
/** Redis-internal generation used to invalidate every family for a subject. */
subjectGeneration?: string;
status: "active" | "used" | "revoked";
createdAt: Date;
usedAt?: Date;
metadata?: Record<string, unknown>;
}
export type RotateResult =
| { status: "rotated"; record: RefreshTokenRecord }
| { status: "missing" }
| { status: "expired"; record: RefreshTokenRecord }
| { status: "limit"; record: RefreshTokenRecord }
| { status: "reused"; record: RefreshTokenRecord }
| { status: "revoked"; record: RefreshTokenRecord };
/** Persistence boundary. Rotation and reuse-triggered family revocation must each be atomic across all instances. */
export interface TokenStore {
/**
* Optional store-specific family ID. Return a UUID or `<43-char-base64url-route>.<UUID>`;
* Redis uses the latter to route a subject's state to one cluster slot.
*/
createFamilyId?(sub: string): string;
saveRefreshToken(record: RefreshTokenRecord): Promise<void>;
getRefreshToken(tokenHash: string, familyId?: string): Promise<RefreshTokenRecord | undefined>;
rotateRefreshToken(input: {
currentHash: string;
replacement: RefreshTokenRecord;
now: Date;
maxRotations: number;
}): Promise<RotateResult>;
revokeByHash(tokenHash: string, familyId?: string): Promise<void>;
revokeByFamily(familyId: string): Promise<void>;
revokeBySub(sub: string): Promise<void>;
revokeByJti?(jti: string, expiresAt?: Date): Promise<void>;
isJtiRevoked?(jti: string): Promise<boolean>;
}
export interface TokenServiceOptions {
/** Defaults to production; development permits localhost HTTP and an omitted audience. */
deploymentMode?: "development" | "production";
issuer: string;
audience?: string | string[];
accessTokenTtlSeconds?: number;
refreshTokenTtlSeconds?: number;
/** Absolute lifetime of one refresh family; defaults to 90 days. */
maxRefreshFamilyLifetimeSeconds?: number;
/** Maximum successful rotations per family; defaults to 10,000. */
maxRefreshRotations?: number;
clockSkewSeconds?: number;
algorithms?: SigningAlgorithm[];
keyProvider: KeyProvider;
tokenStore: TokenStore;
maxClaimsBytes?: number;
forbiddenClaimKeys?: string[];
onEvent?: (event: TokenEvent) => void;
/** Reload current authorization claims instead of copying stale data from refresh tokens. */
resolveRefreshContext?: (sub: string) => Promise<{
claims?: Record<string, unknown>;
audience?: string | string[];
}>;
now?: () => Date;
}
export interface TokenService {
issue(input: IssueInput): Promise<TokenPair>;
verify(accessToken: string): Promise<VerifyResult>;
refresh(refreshToken: string): Promise<TokenPair>;
revoke(input: RevokeInput): Promise<void>;
}
Local key provider
import { exportJWK, importPKCS8, importSPKI, type JWK } from "jose";
import { TokenError } from "../core/errors.js";
import type { KeyProvider, SigningAlgorithm, SigningKey, VerificationKey } from "../core/types.js";
export interface LocalKey {
kid: string;
alg: SigningAlgorithm;
privateKeyPem: string;
publicKeyPem: string;
}
/** PEM-backed provider supporting a current signing key and old verification keys during rotation. */
export class LocalKeyProvider implements KeyProvider {
private readonly keys: LocalKey[];
private readonly signingKid: string;
private readonly privateCache = new Map<string, CryptoKey>();
private readonly publicCache = new Map<string, CryptoKey>();
constructor(input: { keys: LocalKey[]; signingKid: string }) {
if (!input.keys.length || new Set(input.keys.map((key) => key.kid)).size !== input.keys.length)
throw new TokenError("INVALID_INPUT", "Local keys require unique kid values");
if (!input.keys.some((key) => key.kid === input.signingKid))
throw new TokenError("INVALID_INPUT", "signingKid was not found");
this.keys = input.keys;
this.signingKid = input.signingKid;
}
async getSigningKey(): Promise<SigningKey> {
const entry = this.keys.find((key) => key.kid === this.signingKid)!;
let key = this.privateCache.get(entry.kid);
if (!key) {
key = await importPKCS8(entry.privateKeyPem, entry.alg);
this.privateCache.set(entry.kid, key);
}
return { key, kid: entry.kid, alg: entry.alg };
}
async getVerificationKey(input: {
kid?: string;
alg: SigningAlgorithm;
}): Promise<VerificationKey> {
if (!input.kid) throw new TokenError("INVALID_TOKEN", "Token is missing kid");
const entry = this.keys.find((key) => key.kid === input.kid && key.alg === input.alg);
if (!entry) throw new TokenError("KEY_UNAVAILABLE", "No matching verification key");
let key = this.publicCache.get(entry.kid);
if (!key) {
key = await importSPKI(entry.publicKeyPem, entry.alg);
this.publicCache.set(entry.kid, key);
}
return { key, kid: entry.kid, alg: entry.alg };
}
async getPublicJwks(): Promise<{ keys: JWK[] }> {
const keys = await Promise.all(
this.keys.map(async (entry) => ({
...(await exportJWK(
(await this.getVerificationKey({ kid: entry.kid, alg: entry.alg })).key as CryptoKey
)),
kid: entry.kid,
alg: entry.alg,
use: "sig"
}))
);
return { keys };
}
}
PostgreSQL store
import type { RefreshTokenRecord, RotateResult, TokenStore } from "../core/types.js";
export interface QueryResult<Row = Record<string, unknown>> {
rows: Row[];
rowCount: number | null;
}
export interface PgTransaction {
query<Row = Record<string, unknown>>(sql: string, values?: unknown[]): Promise<QueryResult<Row>>;
}
export interface PgLike extends PgTransaction {
transaction<T>(work: (tx: PgTransaction) => Promise<T>): Promise<T>;
}
type RefreshRow = {
token_hash: string;
family_id: string;
subject: string;
expires_at: Date;
family_expires_at: Date;
rotation_count: number;
rotation_limit: number;
status: RefreshTokenRecord["status"];
created_at: Date;
used_at: Date | null;
metadata: Record<string, unknown> | null;
};
/** PostgreSQL store using row locks for one-time refresh-token consumption. */
export class PostgresTokenStore implements TokenStore {
constructor(
private readonly db: PgLike,
private readonly table = "blockend_refresh_tokens",
private readonly denyTable = "blockend_revoked_jtis"
) {
if (!/^[a-z_][a-z0-9_]*$/i.test(table) || !/^[a-z_][a-z0-9_]*$/i.test(denyTable))
throw new Error("Unsafe SQL identifier");
}
async saveRefreshToken(r: RefreshTokenRecord): Promise<void> {
await this.db.transaction(async (tx) => {
await this.setReadCommitted(tx);
await this.lockSubject(tx, r.sub);
const clock = await tx.query<{ now: Date }>("SELECT clock_timestamp() AS now");
const now = clock.rows[0]?.now;
if (!(now instanceof Date)) throw new Error("PostgreSQL did not return its current time");
const familyLifetime = r.familyExpiresAt.getTime() - r.createdAt.getTime();
const refreshLifetime = r.expiresAt.getTime() - r.createdAt.getTime();
if (familyLifetime <= 0 || refreshLifetime <= 0)
throw new Error("Refresh family lifetime must be positive");
const record = {
...r,
createdAt: now,
familyExpiresAt: new Date(now.getTime() + familyLifetime),
expiresAt: new Date(
Math.min(now.getTime() + refreshLifetime, now.getTime() + familyLifetime)
)
};
await tx.query(
`INSERT INTO ${this.table} (token_hash,family_id,subject,expires_at,family_expires_at,rotation_count,rotation_limit,status,created_at,metadata) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
[
record.tokenHash,
record.familyId,
record.sub,
record.expiresAt,
record.familyExpiresAt,
record.rotationCount,
record.rotationLimit,
record.status,
record.createdAt,
record.metadata ?? null
]
);
});
}
async getRefreshToken(
tokenHash: string,
_familyId?: string
): Promise<RefreshTokenRecord | undefined> {
const result = await this.db.query<RefreshRow>(
`SELECT * FROM ${this.table} WHERE token_hash=$1`,
[tokenHash]
);
const row = result.rows[0];
return row ? this.fromRow(row) : undefined;
}
async rotateRefreshToken(input: {
currentHash: string;
replacement: RefreshTokenRecord;
now: Date;
maxRotations: number;
}): Promise<RotateResult> {
return this.db.transaction(async (tx) => {
await this.setReadCommitted(tx);
const identity = await tx.query<{ subject: string }>(
`SELECT subject FROM ${this.table} WHERE token_hash=$1`,
[input.currentHash]
);
const subject = identity.rows[0]?.subject;
if (!subject) return { status: "missing" };
await this.lockSubject(tx, subject);
const found = await tx.query<RefreshRow>(
`SELECT * FROM ${this.table} WHERE token_hash=$1 FOR UPDATE`,
[input.currentHash]
);
const row = found.rows[0];
if (!row) return { status: "missing" };
const current = this.fromRow(row);
const clock = await tx.query<{ now: Date }>("SELECT clock_timestamp() AS now");
const databaseNow = clock.rows[0]?.now;
if (!(databaseNow instanceof Date))
throw new Error("PostgreSQL did not return its current time");
if (current.status === "used") {
await tx.query(`UPDATE ${this.table} SET status='revoked' WHERE family_id=$1`, [
current.familyId
]);
return { status: "reused", record: current };
}
if (current.status === "revoked") return { status: "revoked", record: current };
if (current.expiresAt.getTime() <= databaseNow.getTime())
return { status: "expired", record: current };
if (current.familyExpiresAt.getTime() <= databaseNow.getTime())
return { status: "expired", record: current };
if (current.rotationCount >= Math.min(current.rotationLimit, input.maxRotations))
return { status: "limit", record: current };
const refreshLifetime =
input.replacement.expiresAt.getTime() - input.replacement.createdAt.getTime();
if (refreshLifetime <= 0) return { status: "expired", record: current };
await tx.query(`UPDATE ${this.table} SET status='used',used_at=$2 WHERE token_hash=$1`, [
input.currentHash,
databaseNow
]);
const next = {
...input.replacement,
sub: current.sub,
familyId: current.familyId,
familyExpiresAt: current.familyExpiresAt,
rotationCount: current.rotationCount + 1,
rotationLimit: Math.min(current.rotationLimit, input.maxRotations),
createdAt: databaseNow,
expiresAt: new Date(
Math.min(databaseNow.getTime() + refreshLifetime, current.familyExpiresAt.getTime())
)
};
await tx.query(
`INSERT INTO ${this.table} (token_hash,family_id,subject,expires_at,family_expires_at,rotation_count,rotation_limit,status,created_at,metadata) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
[
next.tokenHash,
next.familyId,
next.sub,
next.expiresAt,
next.familyExpiresAt,
next.rotationCount,
next.rotationLimit,
next.status,
next.createdAt,
next.metadata ?? null
]
);
return { status: "rotated", record: next };
});
}
async revokeByHash(hash: string): Promise<void> {
await this.db.transaction(async (tx) => {
await this.setReadCommitted(tx);
const found = await tx.query<{ subject: string; family_id: string }>(
`SELECT subject,family_id FROM ${this.table} WHERE token_hash=$1`,
[hash]
);
const identity = found.rows[0];
if (!identity) return;
await this.lockSubject(tx, identity.subject);
await tx.query(
`UPDATE ${this.table} SET status='revoked' WHERE family_id=$1 AND status='active'`,
[identity.family_id]
);
});
}
async revokeByFamily(id: string): Promise<void> {
await this.db.transaction(async (tx) => {
await this.setReadCommitted(tx);
const subjects = await tx.query<{ subject: string }>(
`SELECT DISTINCT subject FROM ${this.table} WHERE family_id=$1 ORDER BY subject`,
[id]
);
for (const { subject } of subjects.rows) await this.lockSubject(tx, subject);
await tx.query(
`UPDATE ${this.table} SET status='revoked' WHERE family_id=$1 AND status='active'`,
[id]
);
});
}
async revokeBySub(sub: string): Promise<void> {
await this.db.transaction(async (tx) => {
await this.setReadCommitted(tx);
await this.lockSubject(tx, sub);
await tx.query(
`UPDATE ${this.table} SET status='revoked' WHERE subject=$1 AND status='active'`,
[sub]
);
});
}
async revokeByJti(jti: string, expiresAt?: Date): Promise<void> {
await this.db.query(
`INSERT INTO ${this.denyTable} (jti,expires_at) VALUES ($1,$2) ON CONFLICT (jti) DO UPDATE SET expires_at=EXCLUDED.expires_at`,
[jti, expiresAt ?? new Date(Date.now() + 3_600_000)]
);
await this.db.query(
`WITH expired AS (SELECT ctid FROM ${this.denyTable} WHERE expires_at <= NOW() LIMIT 1000) DELETE FROM ${this.denyTable} AS revoked USING expired WHERE revoked.ctid=expired.ctid`
);
}
async isJtiRevoked(jti: string): Promise<boolean> {
const r = await this.db.query(
`SELECT 1 FROM ${this.denyTable} WHERE jti=$1 AND expires_at>NOW()`,
[jti]
);
return (r.rowCount ?? 0) > 0;
}
private fromRow(r: RefreshRow): RefreshTokenRecord {
return {
tokenHash: r.token_hash,
familyId: r.family_id,
sub: r.subject,
expiresAt: r.expires_at,
familyExpiresAt: r.family_expires_at,
rotationCount: r.rotation_count,
rotationLimit: r.rotation_limit,
status: r.status,
createdAt: r.created_at,
...(r.used_at ? { usedAt: r.used_at } : {}),
...(r.metadata ? { metadata: r.metadata } : {})
};
}
private async lockSubject(tx: PgTransaction, subject: string): Promise<void> {
await tx.query(`SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))`, [
"blockend_refresh_subject",
subject
]);
}
private async setReadCommitted(tx: PgTransaction): Promise<void> {
await tx.query("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
}
}
PostgreSQL schema
CREATE TABLE IF NOT EXISTS blockend_refresh_tokens (
token_hash text PRIMARY KEY,
family_id uuid NOT NULL,
subject text NOT NULL,
expires_at timestamptz NOT NULL,
family_expires_at timestamptz NOT NULL,
rotation_count integer NOT NULL DEFAULT 0 CHECK (rotation_count >= 0),
rotation_limit integer NOT NULL DEFAULT 10000 CHECK (rotation_limit > 0),
status text NOT NULL CHECK (status IN ('active', 'used', 'revoked')),
created_at timestamptz NOT NULL DEFAULT now(),
used_at timestamptz,
metadata jsonb
);
-- Upgrade pre-v2 installations. Old families receive the default 90-day absolute cap.
ALTER TABLE blockend_refresh_tokens ADD COLUMN IF NOT EXISTS family_expires_at timestamptz;
ALTER TABLE blockend_refresh_tokens ADD COLUMN IF NOT EXISTS rotation_count integer;
ALTER TABLE blockend_refresh_tokens ADD COLUMN IF NOT EXISTS rotation_limit integer;
WITH family_limits AS (
SELECT family_id, MIN(created_at) + INTERVAL '90 days' AS family_expires_at,
GREATEST(COUNT(*) - 1, 0)::integer AS rotation_count
FROM blockend_refresh_tokens GROUP BY family_id
)
UPDATE blockend_refresh_tokens AS tokens
SET family_expires_at = COALESCE(tokens.family_expires_at, family_limits.family_expires_at),
rotation_count = COALESCE(tokens.rotation_count, family_limits.rotation_count),
rotation_limit = COALESCE(tokens.rotation_limit, 10000)
FROM family_limits
WHERE tokens.family_id = family_limits.family_id
AND (tokens.family_expires_at IS NULL OR tokens.rotation_count IS NULL OR tokens.rotation_limit IS NULL);
ALTER TABLE blockend_refresh_tokens ALTER COLUMN family_expires_at SET NOT NULL;
ALTER TABLE blockend_refresh_tokens ALTER COLUMN rotation_count SET DEFAULT 0;
ALTER TABLE blockend_refresh_tokens ALTER COLUMN rotation_count SET NOT NULL;
ALTER TABLE blockend_refresh_tokens ALTER COLUMN rotation_limit SET DEFAULT 10000;
ALTER TABLE blockend_refresh_tokens ALTER COLUMN rotation_limit SET NOT NULL;
CREATE INDEX IF NOT EXISTS blockend_refresh_family_idx ON blockend_refresh_tokens (family_id);
CREATE INDEX IF NOT EXISTS blockend_refresh_subject_idx ON blockend_refresh_tokens (subject);
CREATE INDEX IF NOT EXISTS blockend_refresh_expiry_idx ON blockend_refresh_tokens (expires_at);
CREATE INDEX IF NOT EXISTS blockend_refresh_family_expiry_idx ON blockend_refresh_tokens (family_expires_at);
CREATE TABLE IF NOT EXISTS blockend_revoked_jtis (
jti text PRIMARY KEY,
expires_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS blockend_revoked_jti_expiry_idx ON blockend_revoked_jtis (expires_at);
Express adapter
import { Router, type Request, type Response } from "express";
import type { TokenService } from "../core/types.js";
import {
errorBody,
requireStringField,
statusFor,
type HttpAdapterOptions,
type ProtectedAction
} from "./http.js";
export type ExpressTokenAdapterOptions = HttpAdapterOptions<Request>;
/** Creates opt-in JSON routes. Privileged routes require an authorization callback. */
export function createExpressTokenRouter(
service: TokenService,
options: ExpressTokenAdapterOptions = {}
): Router {
const router = Router();
const run =
(operation: (body: unknown) => Promise<unknown>) => async (req: Request, res: Response) => {
try {
res.json(await operation(req.body));
} catch (error) {
res.status(statusFor(error)).json(errorBody(error));
}
};
const protectedRun =
(action: ProtectedAction, operation: (body: never) => Promise<unknown>) =>
async (req: Request, res: Response) => {
try {
if (!options.authorize || !(await options.authorize(action, req))) {
res.status(403).json({ error: { code: "FORBIDDEN", message: "Forbidden" } });
return;
}
} catch {
res.status(500).json(errorBody(undefined));
return;
}
await run((body) => operation(body as never))(req, res);
};
if (options.exposeIssue)
router.post(
"/issue",
protectedRun("issue", (body) => service.issue(body))
);
if (options.exposeVerify)
router.post(
"/verify",
run((body) => service.verify(requireStringField(body, "accessToken")))
);
router.post(
"/refresh",
run((body) => service.refresh(requireStringField(body, "refreshToken")))
);
if (options.exposeRevoke)
router.post(
"/revoke",
protectedRun("revoke", async (body) => {
await service.revoke(body);
return { revoked: true };
})
);
return router;
}
Configuration
const tokens = createTokenService({
issuer: "https://auth.example.com",
audience: ["https://api.example.com"],
keyProvider,
tokenStore,
accessTokenTtlSeconds: 900,
refreshTokenTtlSeconds: 604_800
});| Option | Default | Description |
|---|---|---|
deploymentMode | "production" | Development allows localhost HTTP and omits the audience requirement. |
issuer | Required | Production requires an https:// URL or a urn:. |
audience | Required in production | Allowed audience values. |
accessTokenTtlSeconds | 900 | Clamped to 60 through 3600. |
refreshTokenTtlSeconds | 604800 | Clamped to 3600 through 2,592,000. |
maxRefreshFamilyLifetimeSeconds | 7776000 | Absolute family lifetime, 3600 through 31,536,000. |
maxRefreshRotations | 10000 | Successful rotations per family, 1 through 1,000,000. |
clockSkewSeconds | 30 | JWT clock tolerance, 0 through 300. |
algorithms | ["RS256", "ES256"] | Signing algorithms. Production rejects HS*. |
maxClaimsBytes | 4096 | Custom claim size limit, 256 through 16,384 bytes. |
forbiddenClaimKeys | Built-in list | Replaces the default forbidden claim list. |
keyProvider | Required | Signing and verification keys. |
tokenStore | Required | Refresh and revocation state. |
onEvent | None | Receives token lifecycle events. Throwing from it is ignored. |
resolveRefreshContext | None | Reloads current claims and audience during refresh. |
now | () => new Date() | Clock injection for tests. |
createTokenService validates the options immediately. Invalid options throw TokenError with code INVALID_INPUT.
Issue input
| Field | Default | Description |
|---|---|---|
sub | Required | Trimmed subject, 1 to 512 characters. |
claims | {} | Custom JSON claims. Reserved and forbidden names are rejected. |
tokens.access | true | Issue an access token. |
tokens.refresh | true | Issue a refresh token. At least one token must be requested. |
accessTokenTtlSeconds | Service setting | Per-token access lifetime, clamped to 60 through 3600. |
refreshTokenTtlSeconds | Service setting | Per-token refresh lifetime, clamped to 3600 through 2,592,000. |
audience | Service setting | Must be contained in the configured audience. |
Usage
Production setup
Apply token-service/sql/postgres.sql before using PostgresTokenStore. Provide a PgLike implementation whose transaction() runs every callback query on one connection:
import {
createTokenService,
LocalKeyProvider,
PostgresTokenStore
} from "@/blocks/token-service/src";
import { database } from "./database";
export const tokens = createTokenService({
issuer: "https://auth.example.com",
audience: ["https://api.example.com"],
algorithms: ["RS256"],
accessTokenTtlSeconds: 600,
keyProvider: new LocalKeyProvider({
signingKid: "rsa-2026-09",
keys: [
{
kid: "rsa-2026-09",
alg: "RS256",
privateKeyPem: process.env.JWT_PRIVATE_KEY_PEM!,
publicKeyPem: process.env.JWT_PUBLIC_KEY_PEM!
}
]
}),
tokenStore: new PostgresTokenStore(database),
resolveRefreshContext: async (sub) => {
const user = await database.users.findAuthorizationContext(sub);
if (!user || user.disabled) {
throw new Error("User is unavailable");
}
return {
claims: {
role: user.role,
permissions: user.permissions
}
};
}
});The transaction wrapper must check out one client, run BEGIN, commit on success, and roll back on error. The store does not manage a pool.
For Redis, pass a client implementing get, hget, set, and eval. ioredis needs a small adapter. Use a stable base64url-encoded subject routing key with at least 32 decoded bytes:
import { Redis } from "ioredis";
import { RedisTokenStore, type RedisLike } from "@/blocks/token-service/src";
const redis = new Redis(process.env.REDIS_URL!);
const redisAdapter: RedisLike = {
get: (key) => redis.get(key),
hget: (key, field) => redis.hget(key, field),
set: (key, value, options) => {
if (options?.PX !== undefined && options.NX) {
return redis.set(key, value, "PX", options.PX, "NX");
}
if (options?.PX !== undefined) return redis.set(key, value, "PX", options.PX);
if (options?.NX) return redis.set(key, value, "NX");
return redis.set(key, value);
},
eval: (script, input) => redis.eval(script, input.keys.length, ...input.keys, ...input.arguments)
};
const redisStore = new RedisTokenStore(redisAdapter, {
prefix: "company-auth:v2:",
subjectRoutingKey: Buffer.from(process.env.TOKEN_REDIS_SUBJECT_KEY!, "base64url")
});Keep the routing key and prefix identical on every instance. Do not rotate the routing key until every family created with it has expired or been revoked.
Run Redis token state with maxmemory-policy noeviction in a dedicated deployment. Redis must
reject writes instead of evicting family or JTI state. Redis Cluster replication is asynchronous
and can lose acknowledged writes during failover. Use PostgreSQL if revocation durability across
failover is a hard requirement.
Express
import express from "express";
import { createExpressTokenRouter } from "@/blocks/token-service/src/adapters/express";
import { tokens } from "./tokens";
const app = express();
app.use(express.json({ limit: "8kb" }));
app.use(
"/auth/tokens",
createExpressTokenRouter(tokens, {
exposeIssue: true,
exposeRevoke: true,
authorize: (_action, request) => request.auth?.service === "identity-api"
})
);Install authentication middleware before the router when you expose /issue or /revoke.
Fastify
import Fastify from "fastify";
import { createFastifyTokenPlugin } from "@/blocks/token-service/src/adapters/fastify";
import { tokens } from "./tokens";
const app = Fastify({ bodyLimit: 8 * 1024 });
await app.register(
createFastifyTokenPlugin(tokens, {
exposeIssue: true,
authorize: (_action, request) => request.user?.service === "identity-api"
}),
{ prefix: "/auth/tokens" }
);Register the plugin before listen(). The framework body limit applies before these routes run.
Hono
import { Hono } from "hono";
import { createHonoTokenRoutes } from "@/blocks/token-service/src/adapters/hono";
import { tokens } from "./tokens";
type Variables = {
service?: string;
};
const app = new Hono<{ Variables: Variables }>();
app.route(
"/auth/tokens",
createHonoTokenRoutes(tokens, {
exposeRevoke: true,
authorize: (_action, context) => context.get("service") === "identity-api"
})
);Mount the route group behind your authentication and request size middleware. The examples assume your auth layer sets request.auth on Express, decorates request.user on Fastify, and sets the service variable in Hono.
How refresh works
A refresh request:
- Parses the family hint from the opaque refresh token.
- Hashes the token and looks up the record.
- Reloads current claims with
resolveRefreshContextwhen configured. - Signs a new access token before consuming the old refresh token.
- Atomically marks the old hash used and stores the replacement.
- Revokes the whole family if an already-used token appears again.
A refresh token is an opaque credential, not a JWT. It is 32 to 512 characters and contains a family routing hint plus a random secret. The store keeps only a SHA-256 hash.
The refresh token lifetime is clamped to the family deadline. A family also has a rotation ceiling. Reaching either limit returns TOKEN_EXPIRED or REFRESH_LIMIT.
If resolveRefreshContext throws, the old refresh token is not consumed, so the client can retry. Keep that callback fast and reliable.
Key rotation
Keep old public keys in the provider while access tokens signed with them can still verify:
const provider = new LocalKeyProvider({
signingKid: "rsa-2026-10",
keys: [
{ kid: "rsa-2026-10", alg: "RS256", privateKeyPem: newPem, publicKeyPem: newPub },
{ kid: "rsa-2026-09", alg: "RS256", privateKeyPem: oldPem, publicKeyPem: oldPub }
]
});Switch signingKid to the new key, wait at least the maximum access token lifetime plus clock skew, then remove the old key. For a remote JWKS provider, publish the new public key before signing with it.
LocalKeyProvider requires a kid on every token it verifies. Keys must have unique IDs. KmsRsaKeyProvider signs RS256 through an external function but does not hold private key material.
HTTP routes
The adapters mount refresh by default. Issue, verify, and revoke are opt-in.
| Route | Default | Authorization | Success |
|---|---|---|---|
POST /refresh | Enabled | Application policy | Rotated token pair |
POST /issue | Disabled | authorize callback required | Token pair |
POST /verify | Disabled | Application policy | { valid: true, claims } |
POST /revoke | Disabled | authorize callback required | { revoked: true } |
A missing or denied authorization callback returns 403. Errors use { error: { code, message } }.
| Error type | Status |
|---|---|
| Invalid input, oversized claims, forbidden claims | 400 |
| Invalid, expired, revoked, or reused token | 401 |
| Store or key unavailable | 503 |
| Unsupported operation | 501 |
The adapters do not add authentication, CSRF, CORS, or rate limiting. Set a body size limit before mounting them. Exposing /issue without an authorization check lets callers mint tokens.
API reference
createTokenService
function createTokenService(options: TokenServiceOptions): TokenService;TokenService
interface TokenService {
issue(input: IssueInput): Promise<TokenPair>;
verify(accessToken: string): Promise<VerifyResult>;
refresh(refreshToken: string): Promise<TokenPair>;
revoke(input: RevokeInput): Promise<void>;
}verify accepts access tokens only. Refresh tokens cannot be used as access tokens.
Result types
interface TokenPair {
accessToken?: string;
refreshToken?: string;
tokenType: "Bearer";
expiresIn?: number;
refreshExpiresIn?: number;
issuedAt: number;
}
interface AccessTokenClaims {
sub: string;
iss: string;
aud?: string | string[];
exp: number;
iat: number;
jti: string;
type: "access";
[key: string]: unknown;
}
interface VerifyResult {
valid: true;
claims: AccessTokenClaims;
}
type RevokeInput =
| { refreshToken: string }
| { jti: string }
| { sub: string }
| { familyId: string };Revoke accepts exactly one target. Revoking a refresh token revokes its whole family. Revoking an access token requires a store that implements revokeByJti and isJtiRevoked; verification checks the denylist when they are present.
Store contract
A TokenStore implements:
interface TokenStore {
createFamilyId?(sub: string): string;
saveRefreshToken(record: RefreshTokenRecord): Promise<void>;
getRefreshToken(tokenHash: string, familyId?: string): Promise<RefreshTokenRecord | undefined>;
rotateRefreshToken(input: {
currentHash: string;
replacement: RefreshTokenRecord;
now: Date;
maxRotations: number;
}): Promise<RotateResult>;
revokeByHash(tokenHash: string, familyId?: string): Promise<void>;
revokeByFamily(familyId: string): Promise<void>;
revokeBySub(sub: string): Promise<void>;
revokeByJti?(jti: string, expiresAt?: Date): Promise<void>;
isJtiRevoked?(jti: string): Promise<boolean>;
}Rotation and family revocation must be atomic across every app instance. MemoryTokenStore is for tests and single-process development. StatelessTokenStore supports access tokens only and throws UNSUPPORTED_OPERATION for refresh and server-side revoke.
RedisTokenStoreOptions requires subjectRoutingKey and accepts an optional prefix. The default prefix is blockend:v2:. PostgresTokenStore requires PgLike with query() and transaction(). The transaction callback receives a PgTransaction with query().
Events and errors
Events are token.issued, token.verified, token.refreshed, token.revoked, token.reuse_detected, and token.failed. Each has an ISO timestamp and optional subject, JTI, family ID, or error code. Raw tokens are never included.
| Code | Meaning |
|---|---|
INVALID_INPUT | Configuration or operation input failed validation. |
INVALID_TOKEN | Malformed token or issuer, audience, algorithm, or type mismatch. |
TOKEN_EXPIRED | Access token, refresh token, or refresh family expired. |
TOKEN_REVOKED | Refresh token or access JTI is revoked. |
REFRESH_REUSED | A used refresh token appeared again; its family was revoked. |
REFRESH_LIMIT | The family reached its rotation ceiling. |
CLAIMS_TOO_LARGE | Custom claims exceed maxClaimsBytes. |
FORBIDDEN_CLAIM | Custom claims contain a reserved or forbidden name. |
KEY_UNAVAILABLE | A signing or verification key could not be used. |
STORE_UNAVAILABLE | A store operation failed. |
UNSUPPORTED_OPERATION | The selected store does not support the operation. |
Testing your integration
Use MemoryTokenStore and a fixed key pair in tests. Inject now when you need deterministic expiry:
import { createTokenService, LocalKeyProvider, MemoryTokenStore } from "@/blocks/token-service/src";
let now = new Date("2026-01-01T00:00:00Z");
const tokens = createTokenService({
deploymentMode: "development",
issuer: "http://localhost:3000",
audience: "test-api",
keyProvider: new LocalKeyProvider({
signingKid: "test",
keys: [{ kid: "test", alg: "RS256", privateKeyPem, publicKeyPem }]
}),
tokenStore: new MemoryTokenStore(),
now: () => now
});Test these cases:
- A valid access token verifies and returns the subject and claims.
- A token with the wrong audience or issuer is rejected.
- An expired access token returns
TOKEN_EXPIRED. - Refresh rotates the token; reusing the old token returns
REFRESH_REUSEDand revokes the family. - Rotating past
maxRefreshRotationsreturnsREFRESH_LIMIT. - Revoking a subject invalidates its refresh families.
- A custom store's rotation is atomic under concurrent requests.
Run these tests against the same database or Redis engine you use in production. In-memory behavior can hide transaction and concurrency bugs.
When not to use it
- You need a complete identity provider, login UI, OAuth/OIDC server, account recovery, or authorization policy.
- You need refresh state that survives restarts but can only use
MemoryTokenStore. - You need multi-region refresh consistency without a strongly consistent shared store.
- You need access tokens without a server, such as a static client. There is no secure place to keep a signing key.
Related blocks
- Password hash verifies credentials before your app calls
issue. - Rate limiter limits refresh and privileged issue routes.
- Environment configuration validates issuer, audience, and key settings at startup.