Tokens and sessions
The four token kinds, their generators and validators, the token payload, and the `Session` table and model.
Overview
The interface issues four kinds of token, and it records a login as a row in the sessions table. Three of the four token kinds have an exported validator. The authentication decorators validate the access token.
| Token | Generated by | Validated by | Carries |
|---|---|---|---|
| Access | generateAccessToken | The authentication decorators in Authentication | id, tenantId, sessionId, a purpose marker |
| Refresh | generateRefreshToken | validateRefreshToken | id, tenantId, sessionId, a purpose marker |
| Two-factor | generateTwoFactorToken | validateTwoFactorToken | id, tenantId, a purpose marker |
| Tenant assignment | generateTenantAssignmentToken | validateTenantAssignmentToken | id, a purpose marker |
Every generator takes the User it signs for, and every validator loads that user before it returns. All seven functions are interface functions, so every call returns a promise. The purpose marker keeps one kind of token from being accepted as another. A refresh token sent as a bearer token fails authentication, for example.
A client holds the access and refresh pair. The access token goes in the Authorization header of ordinary requests, and the refresh token gets a new access token when the old one expires. Two-factor and tenant-assignment tokens are short-lived steps between a password check and a real session.
Issue an access and refresh token pair
generateAccessToken(
tenantId: string,
user: User,
sessionId?: string,
): Promise<{ expiresIn: number; token: string }>
generateRefreshToken(
tenantId: string,
user: User,
sessionId?: string,
): Promise<{ expiresIn: number; token: string }>
| Parameter | Description |
|---|---|
tenantId | The tenant the token is scoped to. It goes in the tenantId claim of the token, and the request's tenant resolution reads it back. |
user | The User the token is issued for. The user's authKey is part of the signing secret, so rotating authKey invalidates every token issued to that user before. |
sessionId | The _id of the Session row that records this login. The type marks it optional, but both functions throw when it is missing or empty. An access token is refused as soon as that row is deleted, and a token that carries no sessionId claim is always refused. |
Both functions return the signed token, and its lifetime as expiresIn in milliseconds. The lifetimes come from the accessTokenLifetime and refreshTokenLifetime settings of the deployment.
import {
createSession,
generateAccessToken,
generateRefreshToken,
} from "@antelopejs/interface-dms/auth";
import type {
SessionModel,
User,
} from "@antelopejs/interface-dms/auth/db";
export async function startSession(
sessionModel: SessionModel,
user: User,
tenantId: string,
userAgent: string,
ip: string,
) {
const sessionId = await createSession(sessionModel, user._id, userAgent, ip);
const access = await generateAccessToken(tenantId, user, sessionId);
const refresh = await generateRefreshToken(tenantId, user, sessionId);
// store the token's hash on the session so it can be matched and revoked
await sessionModel.replaceRefreshToken(sessionId, refresh.token);
return {
token_type: "Bearer",
access_token: access.token,
expires_in: access.expiresIn,
refresh_token: refresh.token,
};
}
Validate a refresh token
validateRefreshToken(
token: string,
): Promise<{ id: string; tenantId: string; sessionId?: string }>
The function decodes the token, loads the user it names, and verifies the signature against that user. It also checks that the token was issued as a refresh token and carries non-empty id, tenantId and sessionId claims. It throws HTTPResult(401) with the same message, $dms.refusals.auth.invalid_session_token, when the token is malformed, names no existing user, is badly signed, expired or issued for another purpose, so a forged token cannot tell whether its id names a user. A token naming no user is still verified, against a key no token is signed with, so the refusal takes as long either way. It returns the claims only. The caller must still confirm three things: that the session exists, that the token is its current one (isCurrentRefreshToken), and that the user still has access to tenantId.
import { HTTPResult } from "@antelopejs/interface-api";
import {
generateAccessToken,
validateRefreshToken,
} from "@antelopejs/interface-dms/auth";
import {
isCurrentRefreshToken,
type SessionModel,
type UserModel,
} from "@antelopejs/interface-dms/auth/db";
const UNAUTHORIZED = 401;
export async function refresh(
userModel: UserModel,
sessionModel: SessionModel,
token: string,
) {
const payload = await validateRefreshToken(token);
const user = await userModel.get(payload.id);
if (!user) throw new HTTPResult(UNAUTHORIZED, "error.invalid_token");
if (!payload.sessionId) {
throw new HTTPResult(UNAUTHORIZED, "error.invalid_token");
}
const session = await sessionModel.get(payload.sessionId);
if (!session || !isCurrentRefreshToken(session, token)) {
throw new HTTPResult(UNAUTHORIZED, "error.session_expired");
}
await sessionModel.update(payload.sessionId, { lastActiveAt: new Date() });
const access = await generateAccessToken(
payload.tenantId,
user,
payload.sessionId,
);
return { access_token: access.token, expires_in: access.expiresIn };
}
The returned payload names a tenantId, so the same call also backs a tenant switch. Validate the refresh token, check the user's membership of the target tenant, then issue a new pair for that tenant.
Hand off to a second factor
When the credentials of a user check out but the account has second factors enabled, issue a two-factor token instead of a session. The client then comes back with the code.
generateTwoFactorToken(
tenantId: string,
user: User,
): Promise<{ token: string; expiresIn: number }>
validateTwoFactorToken(token: string): Promise<{
id: string;
tenantId: string;
purpose?: string;
user: User;
}>
A two-factor token lives five minutes, and expiresIn gives that lifetime in milliseconds. validateTwoFactorToken rejects a token that was not issued for the two-factor purpose. It resolves the User for you, so the verification route can read twoFactorMethods, twoFactorSecret and the other fields without a second lookup. Whatever is wrong with the token, it throws the same HTTPResult(401, "error.invalid_2fa_token"): not a JWT, unknown user, bad signature, expired, or another purpose. A caller therefore cannot tell which user ids exist.
import { createHash } from "node:crypto";
import {
generateTwoFactorToken,
send2FAEmail,
validateTwoFactorToken,
} from "@antelopejs/interface-dms/auth";
import type {
User,
UserModel,
} from "@antelopejs/interface-dms/auth/db";
export async function beginTwoFactor(tenantId: string, user: User) {
const { token, expiresIn } = await generateTwoFactorToken(tenantId, user);
return {
requires_2fa: true,
two_factor_token: token,
expires_in: expiresIn,
methods: user.twoFactorMethods,
};
}
export async function requestEmailCode(
userModel: UserModel,
twoFactorToken: string,
code: string,
) {
const { user } = await validateTwoFactorToken(twoFactorToken);
// Stored hashed, the way the DMS's own verification route reads it back.
user.twoFactorEmailCode = createHash("sha256")
.update(JSON.stringify([user._id, code]))
.digest("hex");
user.twoFactorEmailCodeRequestedAt = new Date();
await userModel.update(user);
await send2FAEmail(user, code);
}
Once the code checks out, the route issues a real access and refresh pair for the tenantId the two-factor token carried. Users covers send2FAEmail and the other mail functions.
Hand off tenant assignment
A user whose credentials are valid but who belongs to no tenant yet cannot receive an access token, because an access token is always scoped to a tenant. generateTenantAssignmentToken fills that gap. It signs the user without a tenant claim, so an onboarding flow can pick or create a tenant.
generateTenantAssignmentToken(
user: User,
): Promise<{ token: string; expiresIn: number }>
validateTenantAssignmentToken(token: string): Promise<{ id: string; user: User }>
A tenant-assignment token lives fifteen minutes. validateTenantAssignmentToken rejects a token that was not issued for the tenant-assignment purpose, and returns the user id together with the loaded User. Like the two-factor check, every refusal is the same HTTPResult(401, "$dms.refusals.auth.invalid_tenant_assignment_token").
import {
createSession,
generateAccessToken,
generateTenantAssignmentToken,
validateTenantAssignmentToken,
} from "@antelopejs/interface-dms/auth";
import type { SessionModel, User } from "@antelopejs/interface-dms/auth/db";
export async function offerTenantAssignment(user: User) {
const { token } = await generateTenantAssignmentToken(user);
return { requires_tenant_assignment: true, tenant_assignment_token: token };
}
export async function completeTenantAssignment(
sessionModel: SessionModel,
assignmentToken: string,
tenantId: string,
) {
const { user } = await validateTenantAssignmentToken(assignmentToken);
// the caller attaches the user to `tenantId` before issuing real tokens
const sessionId = await createSession(sessionModel, user._id, "", "");
return generateAccessToken(tenantId, user, sessionId);
}
The token payload
JwtUserPayload describes the claims an access or refresh token carries about its subject. Use it as the target type when you decode a token yourself.
export interface JwtUserPayload {
id: string;
tenantId: string;
sessionId?: string;
}
| Field | Type | Description |
|---|---|---|
id | string | The _id of the user the token was issued for. |
tenantId | string | The tenant the token is scoped to. |
sessionId | string | undefined | The Session row behind the token. Every access and refresh token carries it. |
TenantTokenInput, from Authentication, describes the same subject from the other side. It is what a validator receives: id and tenantId, plus the undecoded rawToken. JwtUserPayload is what the token itself says. The two types share id and tenantId, and neither is a subset of the other.
Record a login session
createSession inserts a Session row for a login and returns its _id. Pass that id as the sessionId of the token pair.
createSession(
sessionModel: SessionModel,
userId: string,
userAgent: string,
ip: string,
): Promise<string>
| Parameter | Description |
|---|---|
sessionModel | The SessionModel instance to insert through. |
userId | The _id of the user logging in. |
userAgent | The User-Agent header of the request. The DMS parses it into the browser, os and deviceType fields and keeps the raw string in userAgent. |
ip | The IP address of the caller, stored as given. |
The row starts with no refresh token hash, an empty location, and createdAt and lastActiveAt set to the current time. Record the refresh token with sessionModel.replaceRefreshToken once you have generated it, as in the first example on this page.
The session table
Session is registered as the sessions table in the DMS core schema. Its rows are shared across tenants, and you obtain its model without a tenant instance. The class, its table-name constant and its model all live in @antelopejs/interface-dms/auth/db.
import {
SESSIONS_TABLE_NAME,
Session,
SessionModel,
} from "@antelopejs/interface-dms/auth/db";
| Field | Type | Description |
|---|---|---|
_id | string | Primary key. This value travels in the sessionId claim of the token. |
userId | string | The _id of the owning user. Indexed, and declared as a relation to the User table. |
refreshTokenHash | string | null, optional | SHA-256 of the refresh token currently valid for this session. A refresh matches against it, which makes the session revocable. The token itself is never stored. |
sealedRefreshToken | string | null, optional | The current refresh token, encrypted under a key derived from its predecessor. A client that still holds the predecessor during the rotation grace window can get the current token back. Without the predecessor, the value is unreadable. |
previousRefreshTokenHash | string | null, optional | SHA-256 of the refresh token the last rotation replaced. |
refreshTokenRotatedAt | Date | null, optional | When the last rotation happened. It starts the grace window. |
userAgent | string | The raw User-Agent string captured at login. |
ip | string | The IP address captured at login. |
browser | string | Browser name and version parsed from userAgent, or "Unknown". |
os | string | OS name and version parsed from userAgent, or "Unknown". |
deviceType | string | Device class parsed from userAgent: "mobile", "tablet", or "desktop" when neither applies. |
location | string | Free-form location label. createSession leaves it empty. |
createdAt | Date | Set on insert by the creation-time decorator. Indexed. |
lastActiveAt | Date | The last time the session was used. Refresh handlers update it. Indexed. Every day at 03:30, a DMS job deletes the sessions last active longer ago than refreshTokenLifetime. |
SESSIONS_TABLE_NAME holds the table name, "sessions".
isCurrentRefreshToken(session, token) tells whether a presented token is the current one of the session. It compares hashes in constant time, and returns false when the session has no refreshTokenHash.
Query sessions with SessionModel
SessionModel extends BasicDataModel(Session, SESSIONS_TABLE_NAME). It has the standard get, getBy, getAll, insert, update and delete operations, plus the refresh-token operations and two lookups by user.
| Method | Signature | Description |
|---|---|---|
replaceRefreshToken | (sessionId: string, refreshToken: string) => Promise<void> | Makes a token the current one of the session, storing only its hash. Clears the sealed token and the predecessor, so no grace window applies. |
rotateRefreshToken | (sessionId: string, presentedToken: string, refreshToken: string, rotatedAt?: Date) => Promise<string | null> | Replaces the presented token with a new one in one atomic update, and sets lastActiveAt. A client that presents the immediate predecessor within the 15-second grace window gets the current token back. Any other token, the predecessor after that window or an older token, is a replay: the session is deleted and the call returns null. Pass only a token whose signature you verified and whose claims name sessionId. |
deleteInactiveSince | (threshold: Date) => Promise<void> | Deletes the sessions last active before a date. |
getByUserId | (userId: string) => Promise<Session[]> | Every session of a user, read through the userId index. |
deleteByUserId | (userId: string) => Promise<void> | Deletes every session of a user. |
import { Controller, Delete, Get } from "@antelopejs/interface-api";
import { Model } from "@antelopejs/interface-database-decorators";
import { AuthUser } from "@antelopejs/interface-dms/auth";
import {
SessionModel,
type User,
} from "@antelopejs/interface-dms/auth/db";
export class SessionsController extends Controller("/api/sessions") {
@AuthUser()
declare user: User;
@Model(SessionModel)
declare sessionModel: SessionModel;
@Get("")
list() {
return this.sessionModel.getByUserId(this.user._id);
}
@Delete("")
revokeAll() {
// drops every session; their access tokens stop working with them
return this.sessionModel.deleteByUserId(this.user._id);
}
}
Deleting a session stops its refreshes, and cuts off the access tokens issued for it at once. The authentication decorators refuse an access token whose sessionId no longer names a session of its user. A token issued without a sessionId stays valid until it expires. To cut those tokens off too, rotate the user's authKey, as described in Users.
Next steps
Continue with Users for the User table, UserModel, sanitizeUser, and the account mail functions.