feat(auth): track sign-in sessions so a session can end before it expires

A session token was a signed JWT and nothing else. Logout only cleared
the cookie, a 30-day "remember me" token stayed valid wherever a copy of
it had ended up, and nobody could sign out one device short of changing
the password or rotating the JWT secret for everyone.

Every session token now carries an id (jti) naming a row in the new
user_sessions table (id, user_id, created_at, last_seen_at, expires_at,
revoked_at, user_agent cut to 256 characters; no address is kept). The
rows live behind UserSessionsRepository and the new sessions domain,
whose SessionsService is the one issuer: AuthService.generateToken and
the OIDC sign-in both go through it, and sliding renewal re-signs a
tracked token under the same id and moves its expiry. verifyJwtAndLoadUser
takes the repository and refuses a token whose session is revoked,
expired or gone, refreshing last_seen_at at most every five minutes.
A token without a jti was issued before this change; it passes until its
own expiry (or a password change), so the upgrade signs nobody out, and
renewal turns it into a tracked session.

Sessions end on logout (the one the request names, verified even when
expired), on a password change (all, the device gets a new one), a
password reset, an admin setting a password, reset-admin.js, an MFA
disable (all but the current one), an admin clearing a user's MFA, and
with the account. GET /api/auth/sessions lists the active sessions,
DELETE /api/auth/sessions/:id ends one and POST
/api/auth/sessions/revoke-others ends all but the current, with their
contracts in @trek/shared and two new audit actions. There is no UI for
them yet. MCP exposes no account or session tools, so there is no
parallel tool to change; an MCP call made with a session JWT as bearer
goes through the same check.

The token in the login, register, demo-login, MFA and passkey bodies
stays for API clients but is marked deprecated in the API docs and in
the client type, which never read it.

A nightly session-purge job on CronRegistrarService deletes the expired
and revoked rows. The migration is 042500. The sessions domain gets its
own coverage entry at the 80 floor until a full run measures it.
This commit is contained in:
Maurice
2026-10-08 17:09:37 +02:00
parent 094e0b28f8
commit 9aab9e7513
65 changed files with 2188 additions and 154 deletions
@@ -0,0 +1,31 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UserSessionsRepository } from '../repositories/UserSessions.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class UserSessions {
[EntityRepositoryType]?: UserSessionsRepository;
id!: string;
user!: Ref<Users>;
user_id!: number;
created_at!: string & Opt;
last_seen_at!: string & Opt;
expires_at!: string;
revoked_at?: string | null;
user_agent?: string | null;
}
export const UserSessionsSchema = defineEntity({
class: UserSessions,
repository: () => UserSessionsRepository,
properties: {
id: p.text().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_user_sessions_user'),
user_id: p.integer().persist(false).index('idx_user_sessions_user'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
last_seen_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
expires_at: p.type(DbTimestampType).index('idx_user_sessions_expires'),
revoked_at: p.type(DbTimestampType).nullable(),
user_agent: p.text().nullable(),
},
});
+3
View File
@@ -60,6 +60,7 @@ import { TripMembers } from './TripMembers.entity';
import { TripPhotos } from './TripPhotos.entity';
import { Trips } from './Trips.entity';
import { UserNoticeDismissals } from './UserNoticeDismissals.entity';
import { UserSessions } from './UserSessions.entity';
import { VacayEntries } from './VacayEntries.entity';
import { VacayPlanMembers } from './VacayPlanMembers.entity';
import { VacayPlans } from './VacayPlans.entity';
@@ -182,6 +183,7 @@ export class Users {
trip_photos_collection = new Collection<TripPhotos>(this);
trips_collection = new Collection<Trips>(this);
user_notice_dismissals_collection = new Collection<UserNoticeDismissals>(this);
user_sessions_collection = new Collection<UserSessions>(this);
vacay_entries_collection = new Collection<VacayEntries>(this);
vacay_plan_members_collection = new Collection<VacayPlanMembers>(this);
vacay_plans_collection = new Collection<VacayPlans>(this);
@@ -321,6 +323,7 @@ export const UsersSchema = defineEntity({
trip_photos_collection: () => p.oneToMany(TripPhotos).mappedBy('user').hidden(),
trips_collection: () => p.oneToMany(Trips).mappedBy('user').hidden(),
user_notice_dismissals_collection: () => p.oneToMany(UserNoticeDismissals).mappedBy('user').hidden(),
user_sessions_collection: () => p.oneToMany(UserSessions).mappedBy('user').hidden(),
vacay_entries_collection: () => p.oneToMany(VacayEntries).mappedBy('user').hidden(),
vacay_plan_members_collection: () => p.oneToMany(VacayPlanMembers).mappedBy('user').hidden(),
vacay_plans_collection: () => p.oneToMany(VacayPlans).mappedBy('owner').hidden(),
+2
View File
@@ -115,6 +115,7 @@ import { TripMembersSchema } from './TripMembers.entity';
import { TripPhotosSchema } from './TripPhotos.entity';
import { TripsSchema } from './Trips.entity';
import { UserNoticeDismissalsSchema } from './UserNoticeDismissals.entity';
import { UserSessionsSchema } from './UserSessions.entity';
import { UsersSchema } from './Users.entity';
import { VacayCompanyHolidaysSchema } from './VacayCompanyHolidays.entity';
import { VacayEntriesSchema } from './VacayEntries.entity';
@@ -248,6 +249,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TripPhotosSchema,
TripsSchema,
UserNoticeDismissalsSchema,
UserSessionsSchema,
UsersSchema,
VacayCompanyHolidaysSchema,
VacayEntriesSchema,
@@ -0,0 +1,38 @@
import { Migration } from '@mikro-orm/migrations';
/**
* One row per sign-in, so a session can end before its token expires.
*
* A session token used to be a signed JWT and nothing else: logging out only
* cleared the cookie, a 30-day "remember me" token stayed valid wherever a
* copy of it had ended up, and nobody could sign out one device without
* changing the password. Every token issued from now on carries an id (the JWT
* `jti`) naming a row here, and the auth check refuses a token whose row is
* gone, revoked or expired.
*
* `id` is that `jti`, a random uuid. `expires_at` follows the token's own
* expiry (sliding renewal moves both). `user_agent` is what the browser sent at
* sign-in, cut to 256 characters like a Web Push device's, so a list of
* sessions can tell them apart; no address is kept. Tokens issued before this
* migration have no `jti` and keep working until they expire. Rows go with
* their user, and a nightly job removes the expired and revoked ones.
*/
export class Migration20200101042600_a_session_row_per_sign_in extends Migration {
override name = 'Migration20200101042600_a_session_row_per_sign_in';
override async up(): Promise<void> {
await this.execute(`
CREATE TABLE IF NOT EXISTS user_sessions (
id TEXT PRIMARY KEY NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME NOT NULL,
revoked_at DATETIME,
user_agent TEXT
)
`);
await this.execute('CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions(user_id)');
await this.execute('CREATE INDEX IF NOT EXISTS idx_user_sessions_expires ON user_sessions(expires_at)');
}
}
@@ -0,0 +1,135 @@
import type { UserSessions } from '../entities/UserSessions.entity';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** A `user_sessions` row exactly as `SELECT *` reads it. */
export interface UserSessionRow {
id: string;
user_id: number;
created_at: string;
last_seen_at: string;
expires_at: string;
revoked_at: string | null;
user_agent: string | null;
}
const _userSessionRowKeys: AssertRowKeys<UserSessionRow, UserSessions> = true;
/** What a session list shows: the row without its owner, who is the caller. */
export type UserSessionListRow = Omit<UserSessionRow, 'user_id' | 'revoked_at'>;
/** The columns a new sign-in writes; `last_seen_at` starts at `created_at`. */
export interface NewUserSessionRow {
id: string;
user_id: number;
created_at: string;
expires_at: string;
user_agent: string | null;
}
/**
* `user_sessions`: one row per issued session token, keyed by the token's
* `jti`. Every timestamp is the `YYYY-MM-DD HH:MM:SS` text the column type
* stores, and the caller passes "now" in that same form, so "active" (not
* revoked, `expires_at` still ahead) is one comparison the database makes and
* a test can pin a clock for.
*/
export class UserSessionsRepository extends TrekRepository<UserSessions> {
/** `INSERT INTO user_sessions (id, user_id, created_at, last_seen_at, expires_at, user_agent) VALUES (?, ?, ?, ?, ?, ?)`. */
async insertSession(row: NewUserSessionRow): Promise<void> {
await this.insert({
id: row.id,
user: row.user_id,
created_at: row.created_at,
last_seen_at: row.created_at,
expires_at: row.expires_at,
user_agent: row.user_agent,
});
}
/**
* The check behind every session token that carries an id:
* `SELECT id, last_seen_at FROM user_sessions WHERE id = ? AND user_id = ?
* AND revoked_at IS NULL AND expires_at > ?`. The owner is part of the
* match, so a token can only ever name a session of the user it was signed for.
*/
async findActive(id: string, userId: number, now: string): Promise<{ id: string; last_seen_at: string } | null> {
const row = await this.findOne(
{ id, user: userId, revoked_at: null, expires_at: { $gt: now } },
{ fields: ['id', 'last_seen_at'] },
);
return row ? { id: row.id, last_seen_at: row.last_seen_at } : null;
}
/** `UPDATE user_sessions SET last_seen_at = ? WHERE id = ?`. */
async touchLastSeen(id: string, now: string): Promise<void> {
await this.nativeUpdate({ id }, { last_seen_at: now });
}
/**
* Sliding renewal: `UPDATE user_sessions SET expires_at = ?, last_seen_at = ?
* WHERE id = ? AND user_id = ? AND revoked_at IS NULL AND expires_at > ?`.
* Answers whether the session was still active, so a session revoked a
* moment ago is never brought back.
*/
async extendActive(id: string, userId: number, now: string, expiresAt: string): Promise<boolean> {
const changed = await this.nativeUpdate(
{ id, user: userId, revoked_at: null, expires_at: { $gt: now } },
{ expires_at: expiresAt, last_seen_at: now },
);
return changed > 0;
}
/**
* `SELECT id, created_at, last_seen_at, expires_at, user_agent FROM user_sessions
* WHERE user_id = ? AND revoked_at IS NULL AND expires_at > ?
* ORDER BY last_seen_at DESC, id ASC`.
*/
async listActiveForUser(userId: number, now: string): Promise<UserSessionListRow[]> {
const rows = await this.find(
{ user: userId, revoked_at: null, expires_at: { $gt: now } },
{
fields: ['id', 'created_at', 'last_seen_at', 'expires_at', 'user_agent'],
orderBy: { last_seen_at: 'desc', id: 'asc' },
},
);
return rows.map((row) => ({
id: row.id,
created_at: row.created_at,
last_seen_at: row.last_seen_at,
expires_at: row.expires_at,
user_agent: row.user_agent ?? null,
}));
}
/**
* `UPDATE user_sessions SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL`;
* answers whether a session of that user was revoked. Another user's id
* matches nothing, the same answer as an id that never existed.
*/
async revokeForUser(id: string, userId: number, now: string): Promise<boolean> {
return (await this.nativeUpdate({ id, user: userId, revoked_at: null }, { revoked_at: now })) > 0;
}
/**
* `UPDATE user_sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL`,
* with `AND id <> ?` when one session is kept. Answers how many were revoked.
*/
async revokeAllForUser(userId: number, now: string, exceptId?: string): Promise<number> {
return await this.nativeUpdate(
exceptId === undefined
? { user: userId, revoked_at: null }
: { user: userId, revoked_at: null, id: { $ne: exceptId } },
{ revoked_at: now },
);
}
/**
* The nightly purge: `DELETE FROM user_sessions WHERE expires_at <= ? OR revoked_at IS NOT NULL`.
* A row that is gone refuses its token just as a revoked one does, so
* nothing depends on keeping them.
*/
async deleteInactive(now: string): Promise<number> {
return await this.nativeDelete({ $or: [{ expires_at: { $lte: now } }, { revoked_at: { $ne: null } }] });
}
}
+2 -1
View File
@@ -45,6 +45,7 @@ import { Trips } from '../../db/entities/Trips.entity';
import { Places } from '../../db/entities/Places.entity';
import { TripFiles } from '../../db/entities/TripFiles.entity';
import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
import { SessionsModule } from '../sessions/sessions.module';
/**
* MikroOrmModule.forFeature registers the repositories `AdminService`'s
@@ -62,7 +63,7 @@ import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
@Module({
imports: [
MikroOrmModule.forFeature([Users, AuditLog, AppSettings, Addons, PhotoProviders, PhotoProviderFields, DocumentProviders, McpTokens, OauthTokens, Trips, Places, TripFiles, PushSubscriptions]),
AppConfigModule, DatabaseLifecycleModule, PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule, OauthModule, SchedulingModule, KitineraryExtractorModule,
AppConfigModule, DatabaseLifecycleModule, PluginsRuntimeModule, SessionsModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule, OauthModule, SchedulingModule, KitineraryExtractorModule,
],
controllers: [AdminController],
providers: [AdminService, VersionCheckJob, DemoResetJob],
+9 -2
View File
@@ -67,6 +67,7 @@ import {
type VersionInfo,
} from './admin.helpers';
import { MANAGED_FORBIDDEN_ERROR } from '../common/managed';
import { SessionsService } from '../sessions/sessions.service';
/** Outbound GitHub calls: hard timeout and response-size cap (server/CLAUDE.md). */
const GITHUB_TIMEOUT_MS = 10_000;
@@ -131,6 +132,7 @@ export class AdminService {
private readonly uow: UnitOfWork,
@Inject(DATABASE_BACKUP) private readonly database: DatabaseBackupStrategy,
private readonly dataPaths: DataPathsService,
private readonly sessions: SessionsService,
) {}
// ── User CRUD ──────────────────────────────────────────────────────────────
@@ -284,6 +286,7 @@ export class AdminService {
// Push devices outlive every session, so the intruder's browser would
// keep receiving this account's notifications. They go with the rest.
await this.pushSubscriptions.deleteAllForUser(userId);
await this.sessions.revokeAll(userId);
}
});
} catch (err) {
@@ -351,8 +354,12 @@ export class AdminService {
if (!target) return { error: 'User not found', status: 404 };
// Same three columns disableMfa clears, so an admin reset and a self-service
// disable leave the account in exactly one state rather than two.
await this.users.disableMfa(targetId);
// disable leave the account in exactly one state rather than two; the
// account's sessions end with the second factor, as on that path.
await this.uow.transactional(async () => {
await this.users.disableMfa(targetId);
await this.sessions.revokeAll(targetId);
});
return { success: true, email: target.email };
}
+2
View File
@@ -71,6 +71,7 @@ import { RoadtripModule } from './roadtrip/roadtrip.module';
import { RouteUsageModule } from './route-usage/route-usage.module';
import { SchedulingModule } from './scheduling/scheduling.module';
import { SchoolHolidaysModule } from './school-holidays/school-holidays.module';
import { SessionsModule } from './sessions/sessions.module';
import { SettingsModule } from './settings/settings.module';
import { ShareModule } from './share/share.module';
import { StorageModule } from './storage/storage.module';
@@ -150,6 +151,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
StorageModule,
BackupModule,
AuthModule,
SessionsModule,
OidcModule,
OauthModule,
AdminModule,
+2
View File
@@ -15,6 +15,8 @@ const ACTION_LABELS: Record<string, string> = {
'user.account_delete': 'deleted account',
'user.mfa_enable': 'enabled MFA',
'user.mfa_disable': 'disabled MFA',
'user.session_revoke': 'signed out a session',
'user.sessions_revoke_others': 'signed out other sessions',
'settings.app_update': 'updated settings',
'settings.api_keys_update': 'updated API keys',
'trip.create': 'created trip',
+22 -6
View File
@@ -10,6 +10,8 @@ import { willDropSecureCookie } from '../common/cookie';
import type { User } from '../../types';
import { Public } from './public.decorator';
import { MfaExempt } from './mfa-policy.guard';
import { extractToken, verifiedSessionClaims } from './jwt-verify';
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
const WINDOW = 15 * 60 * 1000;
const LOGIN_MIN_LATENCY_MS = 350;
@@ -23,11 +25,21 @@ const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
* Express route (server/src/routes/auth.ts): the same per-IP rate-limit buckets
* + limits, the constant-time login/forgot latency padding, the enumeration-safe
* forgot response, the audit writes and the JWT httpOnly cookie set/clear via
* the shared cookie service (no new token shape).
* the shared cookie service.
*
* The `token` in the login, register, demo-login and MFA bodies is deprecated:
* the httpOnly cookie is the session, and the web app has never read the field.
* It stays for API clients that took it as a bearer token, and the API docs
* mark it; nothing here or in the client relies on it.
*/
@Controller('api/auth')
export class AuthPublicController {
constructor(private readonly auth: AuthService, private readonly rl: RateLimitService, private readonly audit: AuditService) {}
constructor(
private readonly auth: AuthService,
private readonly rl: RateLimitService,
private readonly audit: AuditService,
private readonly sessions: SessionsService,
) {}
private async limit(bucket: string, req: Request, max: number): Promise<void> {
if (!(await this.rl.check(bucket, req.ip || 'unknown', max, WINDOW, Date.now()))) {
@@ -70,7 +82,7 @@ export class AuthPublicController {
@HttpCode(201)
async register(@Body() body: RegisterDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
await this.limit('login', req, 10);
const result = await this.auth.registerUser(body);
const result = await this.auth.registerUser(body, sessionClientFrom(req));
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -85,7 +97,7 @@ export class AuthPublicController {
async login(@Body() body: LoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
await this.limit('login', req, 10);
const started = Date.now();
const result = await this.auth.loginUser(body);
const result = await this.auth.loginUser(body, sessionClientFrom(req));
if (result.auditAction) {
await this.audit.writeAudit({ userId: result.auditUserId ?? null, action: result.auditAction, ip: getClientIp(req), details: result.auditDetails });
}
@@ -160,7 +172,7 @@ export class AuthPublicController {
@HttpCode(200)
async verifyMfaLogin(@Body() body: MfaVerifyLoginDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
await this.limit('mfa', req, 5);
const result = await this.auth.verifyMfaLogin(body);
const result = await this.auth.verifyMfaLogin(body, sessionClientFrom(req));
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -172,7 +184,11 @@ export class AuthPublicController {
@Post('logout')
@Public('clearing a cookie must work even with an expired token, or the client cannot sign out')
@HttpCode(200)
logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
// Ends the session itself, not only this browser's copy of it: a copy of
// the token anywhere else stops working too. Only a token whose signature
// checks out names the session to end; anything else just loses its cookie.
await this.sessions.endSession(verifiedSessionClaims(extractToken(req)));
this.auth.clearAuthCookie(res, req);
return { success: true };
}
+4 -3
View File
@@ -39,7 +39,8 @@ import {
import { RateLimitService } from '../common/rate-limit.service';
import { JwtAuthGuard } from './jwt-auth.guard';
import { CurrentUser } from './current-user.decorator';
import { decodeSessionClaims } from './jwt-verify';
import { currentSessionId, decodeSessionClaims } from './jwt-verify';
import { sessionClientFrom } from '../sessions/sessions.service';
import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import type { User } from '../../types';
@@ -113,7 +114,7 @@ export class AuthController {
// "remember me" login survives a password change (#1927). Bearer callers
// have no cookie → undefined → the historical default duration.
const remember = decodeSessionClaims((req.cookies as Record<string, string> | undefined)?.trek_session)?.remember;
const result = await this.auth.changePassword(user.id, user.email, body, remember);
const result = await this.auth.changePassword(user.id, user.email, body, remember, sessionClientFrom(req));
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -288,7 +289,7 @@ export class AuthController {
@HttpCode(200)
async mfaDisable(@CurrentUser() user: User, @Body() body: MfaDisableDto, @Req() req: Request) {
await this.limit('login', req, 5);
const result = await this.auth.disableMfa(user.id, user.email, body);
const result = await this.auth.disableMfa(user.id, user.email, body, currentSessionId(req));
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
+8 -3
View File
@@ -21,10 +21,13 @@ import { TripMembers } from '../../db/entities/TripMembers.entity';
import { Plugins } from '../../db/entities/Plugins.entity';
import { PluginUserErasureQueue } from '../../db/entities/PluginUserErasureQueue.entity';
import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { TokensModule } from '../tokens/tokens.module';
import { AuthPublicController } from './auth-public.controller';
import { AuthController } from './auth.controller';
import { PasskeyController } from './passkey.controller';
import { SessionsController } from './sessions.controller';
import { SessionsModule } from '../sessions/sessions.module';
import { AuthService } from './auth.service';
import { UserProfileService } from './user-profile.service';
import { RegistrationInvitesService } from './registration-invites.service';
@@ -84,7 +87,7 @@ import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
}),
StorageModule,
AllowedFileTypesModule,
EphemeralTokenModule, RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule, BudgetModule,
EphemeralTokenModule, SessionsModule, RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule, BudgetModule,
// MaintenanceRepository: UserCleanupService's UC1 plugin-table erasure.
MaintenanceModule,
// AppSettings/Users: AuthService/UserProfileService each pass their own
@@ -118,8 +121,10 @@ import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
// .enqueueUserErasure` rather than re-implementing the same filter twice.
// PushSubscriptions: AuthService drops every Web Push device of the user
// on password change/reset (Web Push, #894), owned by `nest/notifications`.
MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens, BudgetItems, BudgetSettlements, JourneyShareTokens, Journeys, JourneyEntries, JourneyContributors, ShareTokens, Trips, TripMembers, Plugins, PluginUserErasureQueue, PushSubscriptions])],
controllers: [AuthPublicController, AuthController, PasskeyController],
// UserSessions: AuthService.verifyJwtToken hands it to verifyJwtAndLoadUser,
// owned by `nest/sessions`.
MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens, BudgetItems, BudgetSettlements, JourneyShareTokens, Journeys, JourneyEntries, JourneyContributors, ShareTokens, Trips, TripMembers, Plugins, PluginUserErasureQueue, PushSubscriptions, UserSessions])],
controllers: [AuthPublicController, AuthController, PasskeyController, SessionsController],
providers: [AuthService, UserProfileService, RegistrationInvitesService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService],
})
+31 -32
View File
@@ -9,7 +9,7 @@ import { randomBytes, createHash } from 'crypto';
import type { Request, Response } from 'express';
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared';
import { readEnv } from '../../app-config';
import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS } from '../../config';
import { JWT_SECRET } from '../../config';
import { UnitOfWork } from '../database/unit-of-work';
import { PermissionsService } from '../permissions/permissions.service';
import { validatePassword } from '../common/passwordPolicy';
@@ -33,6 +33,9 @@ import { PasswordResetTokens } from '../../db/entities/PasswordResetTokens.entit
import type { PasswordResetTokensRepository } from '../../db/repositories/PasswordResetTokens.repository';
import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
import type { PushSubscriptionsRepository } from '../../db/repositories/PushSubscriptions.repository';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import { SessionsService, type SessionClient } from '../sessions/sessions.service';
// Type-and-guard only: the app-config read reports the provider choice, it does
// not construct one, so this does not pull the maps domain into auth.
import { isPlacesProviderChoice } from '../maps/providers/places-provider';
@@ -185,6 +188,8 @@ export class AuthService {
@InjectRepository(WebauthnCredentials) private readonly webauthnCredentials: WebauthnCredentialsRepository,
@InjectRepository(PasswordResetTokens) private readonly passwordResetTokens: PasswordResetTokensRepository,
@InjectRepository(PushSubscriptions) private readonly pushSubscriptions: PushSubscriptionsRepository,
@InjectRepository(UserSessions) private readonly userSessions: UserSessionsRepository,
private readonly sessions: SessionsService,
) {}
// Cookie
@@ -255,22 +260,11 @@ export class AuthService {
return !(await this.resolveAuthToggles()).password_login;
}
async generateToken(user: { id: number | bigint; password_version?: number }, remember?: boolean) {
async generateToken(user: { id: number | bigint; password_version?: number }, remember?: boolean, client?: SessionClient) {
const pv = typeof user.password_version === 'number'
? user.password_version
: ((await this.usersRepo.getPasswordVersion(Number(user.id))) ?? 0);
// "Remember me" extends the JWT lifetime to match the persistent cookie maxAge;
// the cookie service decides session-vs-persistent off the same flag.
const expiresIn = remember === true ? SESSION_DURATION_REMEMBER_SECONDS : SESSION_DURATION_SECONDS;
// The flag is embedded as a claim so sliding renewal can re-issue with the
// same duration AND cookie semantics (false → browser-session cookie is not
// recoverable from exp − iat). Omitted when the caller didn't choose, so
// register/demo/passkey tokens keep their historical payload.
return jwt.sign(
{ id: user.id, pv, ...(typeof remember === 'boolean' ? { remember } : {}) },
JWT_SECRET,
{ expiresIn, algorithm: 'HS256' }
);
return this.sessions.issue({ id: Number(user.id), pv }, remember, client);
}
getPendingMfaSecret(userId: number): string | null {
@@ -442,7 +436,7 @@ export class AuthService {
return { valid: true, max_uses: invite.max_uses, used_count: invite.used_count, expires_at: invite.expires_at };
}
async registerUser(rawBody: unknown): Promise<{ error?: string; status?: number; token?: string; user?: Record<string, unknown>; auditUserId?: number; auditDetails?: Record<string, unknown> }> {
async registerUser(rawBody: unknown, client?: SessionClient): Promise<{ error?: string; status?: number; token?: string; user?: Record<string, unknown>; auditUserId?: number; auditDetails?: Record<string, unknown> }> {
const body = rawBody as { username?: string; email?: string; password?: string; invite_token?: string };
const username = typeof body.username === 'string' ? body.username.trim() : '';
const email = typeof body.email === 'string' ? body.email.trim() : '';
@@ -496,7 +490,7 @@ export class AuthService {
});
const user = { id: inserted.id, username, email, role, avatar: null, mfa_enabled: false };
const token = await this.generateToken(user);
const token = await this.generateToken(user, undefined, client);
if (validInvite) {
const updated = await this.inviteTokens.incrementUsedCount(validInvite.token);
@@ -527,7 +521,7 @@ export class AuthService {
}
}
async loginUser(rawBody: unknown): Promise<{
async loginUser(rawBody: unknown, client?: SessionClient): Promise<{
error?: string;
status?: number;
token?: string;
@@ -589,7 +583,7 @@ export class AuthService {
}
await this.usersRepo.touchLastLogin(user.id);
const token = await this.generateToken(user, remember);
const token = await this.generateToken(user, remember, client);
const userSafe = stripUserForClient(toClientUser(user)) as Record<string, unknown>;
return {
@@ -632,6 +626,7 @@ export class AuthService {
userEmail: string,
rawBody: unknown,
remember?: boolean,
client?: SessionClient,
): Promise<{ error?: string; status?: number; success?: boolean; token?: string }> {
const body = rawBody as { current_password?: string; new_password?: string };
if (await this.isOidcOnlyMode()) {
@@ -658,10 +653,9 @@ export class AuthService {
await this.uow.transactional(async () => {
await this.usersRepo.setPassword(userId, hash, newPv);
// A password change rotates the user's sessions: bumping password_version
// invalidates existing JWT cookie sessions, and the separate MCP static
// token and OAuth bearer-token stores are pruned to match (same set the
// password-reset path already revokes).
// A password change ends every session (the pv bump covers the tokens from
// before sessions were tracked) and prunes the MCP static token and OAuth
// bearer-token stores to match, the same set the password reset revokes.
await this.mcpTokens.deleteAllForUser(userId);
try {
await this.oauthTokens.revokeAllForUser(userId);
@@ -671,15 +665,14 @@ export class AuthService {
// the client reloads the user after the change, and that re-syncs its
// subscription. Other devices do so after their next sign-in.
await this.pushSubscriptions.deleteAllForUser(userId);
await this.sessions.revokeAll(userId);
});
try { revokeUserSessions?.(userId); } catch { /* best-effort */ }
// Re-issue a session bound to the new password_version so the current device
// stays logged in while other existing sessions are rotated out by the pv
// gate — preserving the login's remember choice instead of downgrading a
// remembered session to the default duration (#1927).
const token = await this.generateToken({ id: userId, password_version: newPv }, remember);
// Re-issue a session for the current device only, keeping the login's remember
// choice instead of downgrading it to the default duration (#1927).
const token = await this.generateToken({ id: userId, password_version: newPv }, remember, client);
return { success: true, token };
}
@@ -868,7 +861,8 @@ export class AuthService {
async disableMfa(
userId: number,
userEmail: string,
rawBody: unknown
rawBody: unknown,
currentSessionId?: string,
): Promise<{ error?: string; status?: number; success?: boolean; mfa_enabled?: boolean }> {
const body = rawBody as { password?: string; code?: string };
if (readEnv().demo.enabled && isDemoEmail(userEmail)) {
@@ -895,12 +889,16 @@ export class AuthService {
if (!ok) {
return { error: 'Invalid verification code', status: 401 };
}
await this.usersRepo.disableMfa(userId);
// Every other session ends with the second factor; this one just proved both.
await this.uow.transactional(async () => {
await this.usersRepo.disableMfa(userId);
await this.sessions.revokeAll(userId, currentSessionId);
});
mfaSetupPending.delete(userId);
return { success: true, mfa_enabled: false };
}
async verifyMfaLogin(rawBody: unknown): Promise<{
async verifyMfaLogin(rawBody: unknown, client?: SessionClient): Promise<{
error?: string;
status?: number;
token?: string;
@@ -944,7 +942,7 @@ export class AuthService {
} else {
await this.usersRepo.touchLastLogin(user.id);
}
const sessionToken = await this.generateToken(user, remember);
const sessionToken = await this.generateToken(user, remember, client);
const userSafe = stripUserForClient(toClientUser(user)) as Record<string, unknown>;
return {
token: sessionToken,
@@ -1103,6 +1101,7 @@ export class AuthService {
// Push devices are a delivery channel that outlives every session, so an
// intruder's browser would keep reading this account's notifications.
await this.pushSubscriptions.deleteAllForUser(user.id);
await this.sessions.revokeAll(user.id);
});
// Kick off any MCP/WS session cleanup — same hook the account-delete path uses.
@@ -1135,6 +1134,6 @@ export class AuthService {
* route) should go through.
*/
async verifyJwtToken(token: string): Promise<User | null> {
return verifyJwtAndLoadUser(token, this.usersRepo);
return verifyJwtAndLoadUser(token, this.usersRepo, this.userSessions);
}
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestj
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { verifyJwtAndLoadUser } from './jwt-verify';
/**
@@ -25,7 +26,7 @@ export class CookieAuthGuard implements CanActivate {
if (!cookieToken) {
throw new HttpException({ error: 'Cookie session required for this endpoint', code: 'COOKIE_AUTH_REQUIRED' }, 401);
}
const user = await verifyJwtAndLoadUser(cookieToken, this.em.getRepository(Users));
const user = await verifyJwtAndLoadUser(cookieToken, this.em.getRepository(Users), this.em.getRepository(UserSessions));
if (!user) {
throw new HttpException({ error: 'Invalid or expired session', code: 'AUTH_REQUIRED' }, 401);
}
+4 -3
View File
@@ -4,6 +4,7 @@ import { Reflector } from '@nestjs/core';
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
import { IS_PUBLIC, OPTIONAL_AUTH } from './public.decorator';
@@ -49,7 +50,7 @@ export class GlobalAuthGuard implements CanActivate {
if (this.reflector.getAllAndOverride(OPTIONAL_AUTH, [handler, controller])) {
const token = extractToken(req);
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users)) : null) || null;
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions)) : null) || null;
return true;
}
@@ -66,7 +67,7 @@ export class GlobalAuthGuard implements CanActivate {
];
if (declared.length > 0) {
const declaredToken = extractToken(req);
(req as { user: unknown }).user = (declaredToken ? await verifyJwtAndLoadUser(declaredToken, this.em.getRepository(Users)) : null) || null;
(req as { user: unknown }).user = (declaredToken ? await verifyJwtAndLoadUser(declaredToken, this.em.getRepository(Users), this.em.getRepository(UserSessions)) : null) || null;
return true;
}
@@ -74,7 +75,7 @@ export class GlobalAuthGuard implements CanActivate {
if (!token) {
throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401);
}
const user = await verifyJwtAndLoadUser(token, this.em.getRepository(Users));
const user = await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions));
if (!user) {
throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401);
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestj
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
/**
@@ -53,7 +54,7 @@ export class JwtAuthGuard implements CanActivate {
if (!token) {
throw new HttpException({ error: 'Access token required', code: 'AUTH_REQUIRED' }, 401);
}
const user = await verifyJwtAndLoadUser(token, this.em.getRepository(Users));
const user = await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions));
if (!user) {
throw new HttpException({ error: 'Invalid or expired token', code: 'AUTH_REQUIRED' }, 401);
}
+76 -3
View File
@@ -3,6 +3,8 @@ import jwt from 'jsonwebtoken';
import { JWT_SECRET } from '../../config';
import type { User } from '../../types';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import { dbNow } from '../../db/types';
/**
* The canonical JWT session check. Every auth surface goes through here — the
@@ -24,7 +26,8 @@ import type { UsersRepository } from '../../db/repositories/Users.repository';
* pre-init caller, `platform.routes.ts::servePhoto` — `orm.em.getRepository(Users)`
* resolved INSIDE `applyPlatformUploads`'s `withRequestContext` wrapper,
* `orm` threaded in from `bootstrap.ts`) and passes it in. The legacy `db`
* proxy import is gone.
* proxy import is gone. The `UserSessionsRepository` beside it is resolved
* the same way, from the same entity manager, and carries the session check.
*/
export function extractToken(req: Request): string | null {
// Prefer httpOnly cookie; fall back to Authorization: Bearer (MCP, API clients)
@@ -49,8 +52,17 @@ export interface SessionClaims {
purpose?: string;
iat?: number;
exp?: number;
/** The session id (`user_sessions.id`); absent on tokens issued before sessions were tracked. */
jti?: string;
}
/**
* How old a session's `last_seen_at` may get before a request refreshes it.
* Coarse on purpose: the list only has to tell "today" from "last month", and
* a write on every request would be a write on every GET.
*/
export const SESSION_TOUCH_INTERVAL_MS = 5 * 60 * 1000;
/**
* Decode (NOT verify) a session token's claims. Only for callers that have
* already authenticated the request through a guard and need the token's
@@ -64,9 +76,69 @@ export function decodeSessionClaims(token: string | undefined): SessionClaims |
return decoded as SessionClaims;
}
export async function verifyJwtAndLoadUser(token: string, users: UsersRepository): Promise<User | null> {
/**
* The session id of the token this request authenticated with, or undefined
* for a token from before sessions were tracked. Decoded, not verified: only
* for handlers behind the auth guard, which verified this same token.
*/
export function currentSessionId(req: Request): string | undefined {
const jti = decodeSessionClaims(extractToken(req) ?? undefined)?.jti;
return typeof jti === 'string' ? jti : undefined;
}
/**
* The claims of a session token whose signature checks out, expired or not;
* null for anything else (a forged or purpose-scoped token). Logout reads the
* session to end through this, since it must work with an expired token too.
*/
export function verifiedSessionClaims(token: string | null | undefined): (SessionClaims & { id: number }) | null {
if (!token) return null;
try {
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'], ignoreExpiration: true }) as SessionClaims;
if (decoded.purpose || typeof decoded.id !== 'number') return null;
return decoded as SessionClaims & { id: number };
} catch {
return null;
}
}
/**
* The session half of the check. A token with a `jti` must name an active
* session of its own user: one revoked (logout, a password change, "sign out
* other sessions"), expired or purged refuses the token. A token without one
* was issued before sessions were tracked and passes until its own expiry, so
* the upgrade signs nobody out; a password change still ends it through `pv`.
*/
async function sessionIsActive(decoded: { id: number; jti?: unknown }, sessions: UserSessionsRepository): Promise<boolean> {
if (decoded.jti === undefined) return true;
if (typeof decoded.jti !== 'string') return false;
const now = new Date();
const session = await sessions.findActive(decoded.jti, decoded.id, dbNow(now));
if (!session) return false;
const lastSeen = Date.parse(`${session.last_seen_at.replace(' ', 'T')}Z`);
if (!(now.getTime() - lastSeen < SESSION_TOUCH_INTERVAL_MS)) {
try {
await sessions.touchLastSeen(session.id, dbNow(now));
} catch {
// Bookkeeping for the session list only: a busy database must not turn
// a valid session into a 401.
}
}
return true;
}
export async function verifyJwtAndLoadUser(
token: string,
users: UsersRepository,
sessions: UserSessionsRepository,
): Promise<User | null> {
try {
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as {
id: number;
pv?: number;
purpose?: string;
jti?: unknown;
};
// Purpose-scoped tokens (e.g. the short-lived mfa_login token) share this
// secret but are not full session tokens — only their dedicated endpoint
// may accept them, so reject any token carrying a purpose claim here.
@@ -80,6 +152,7 @@ export async function verifyJwtAndLoadUser(token: string, users: UsersRepository
const tokenPv = typeof decoded.pv === 'number' ? decoded.pv : 0;
const currentPv = typeof row.password_version === 'number' ? row.password_version : 0;
if (tokenPv !== currentPv) return null;
if (!(await sessionIsActive(decoded, sessions))) return null;
// Don't leak password_version beyond the verify.
const { password_version: _pv, ...user } = row;
return user as User;
+2 -1
View File
@@ -2,6 +2,7 @@ import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
/**
@@ -20,7 +21,7 @@ export class OptionalJwtGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<Request>();
const token = extractToken(req);
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users)) : null) || null;
(req as { user: unknown }).user = (token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions)) : null) || null;
return true;
}
}
+2 -1
View File
@@ -11,6 +11,7 @@ import { PasskeyService } from './passkey.service';
import { PasskeyRegisterOptionsDto, PasskeyRegisterVerifyDto, PasskeyLoginVerifyDto, PasskeyRenameDto, PasskeyDeleteDto } from './auth.dto';
import type { User } from '../../types';
import { MfaExempt } from './mfa-policy.guard';
import { sessionClientFrom } from '../sessions/sessions.service';
const WINDOW = 15 * 60 * 1000;
const LOGIN_MIN_LATENCY_MS = 350;
@@ -86,7 +87,7 @@ export class PasskeyController {
async loginVerify(@Body() body: PasskeyLoginVerifyDto, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
await this.limit('login', req, 10);
const started = Date.now();
const result = await this.passkeys.passkeyLoginVerify(body);
const result = await this.passkeys.passkeyLoginVerify(body, sessionClientFrom(req));
if (result.auditAction) {
await this.audit.writeAudit({ userId: result.auditUserId ?? null, action: result.auditAction, ip: getClientIp(req) });
}
+3 -2
View File
@@ -21,6 +21,7 @@ import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository, UserRow } from '../../db/repositories/Users.repository';
import type { User } from '../../types';
import { toRowId } from '../common/row-id';
import type { SessionClient } from '../sessions/sessions.service';
// ---------------------------------------------------------------------------
// Constants
@@ -364,7 +365,7 @@ export class PasskeyService {
return { options };
}
async passkeyLoginVerify(body: { assertionResponse?: unknown }): Promise<{
async passkeyLoginVerify(body: { assertionResponse?: unknown }, client?: SessionClient): Promise<{
error?: string;
status?: number;
token?: string;
@@ -437,7 +438,7 @@ export class PasskeyService {
// A user-verified passkey is phishing-resistant and inherently two-factor
// (device possession + biometric/PIN), so it mints the real session directly
// — the SAME path as password and OIDC login (no new token shape).
const token = await this.auth.generateToken(user);
const token = await this.auth.generateToken(user, undefined, client);
const userSafe = stripUserForClient(toClientUser(user)) as Record<string, unknown>;
return { token, user: { ...userSafe, avatar_url: avatarUrl(user) }, auditUserId: Number(user.id) };
}
@@ -1,7 +1,7 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import type { Request, Response } from 'express';
import type { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { SessionsService, sessionClientFrom } from '../sessions/sessions.service';
import { decodeSessionClaims } from './jwt-verify';
import { setAuthCookie } from '../common/cookie';
@@ -13,10 +13,14 @@ import { setAuthCookie } from '../common/cookie';
* (true → long persistent cookie, false → browser-session cookie, absent → the
* historical default duration).
*
* Cheap by construction — no DB access:
* Cheap by construction, one write per half-life at most:
* - `req.user` is only set after a guard ran verifyJwtAndLoadUser on this exact
* request, which already proved the token's `pv` matches the DB, so both the
* user id and pv can be copied from the decoded (not re-verified) token.
* request, which already proved the token's `pv` matches the DB and its
* session is active, so the user id, pv and session id can be copied from
* the decoded (not re-verified) token.
* - A tracked token is re-signed under the same session id and the session's
* expiry moves with it; a token from before sessions were tracked comes back
* as a tracked session. If the session ended in between, nothing is renewed.
* - The cookie is only renewed when it is the verified credential: extractToken
* prefers the cookie over the Authorization header, so cookie-present +
* req.user set means the guard verified the cookie. Bearer-only callers
@@ -31,7 +35,7 @@ import { setAuthCookie } from '../common/cookie';
*/
@Injectable()
export class SessionRenewalInterceptor implements NestInterceptor {
constructor(private readonly auth: AuthService) {}
constructor(private readonly sessions: SessionsService) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
if (context.getType() === 'http') {
@@ -53,10 +57,10 @@ export class SessionRenewalInterceptor implements NestInterceptor {
const halfLife = claims.iat + (claims.exp - claims.iat) / 2;
if (Date.now() / 1000 < halfLife) return;
const token = await this.auth.generateToken(
{ id: req.user.id, password_version: claims.pv ?? 0 },
claims.remember,
const token = await this.sessions.renew(
{ id: req.user.id, pv: claims.pv, remember: claims.remember, jti: claims.jti },
sessionClientFrom(req),
);
setAuthCookie(res, token, req, claims.remember);
if (token) setAuthCookie(res, token, req, claims.remember);
}
}
@@ -0,0 +1,71 @@
import { Controller, Delete, Get, HttpCode, HttpException, Param, Post, Req, Res, UseGuards } from '@nestjs/common';
import type { Request, Response } from 'express';
import {
userSessionRevokeParamsSchema,
type UserSessionListResponse,
type UserSessionRevokeOthersResponse,
type UserSessionRevokeParams,
type UserSessionRevokeResponse,
} from '@trek/shared';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { clearAuthCookie } from '../common/cookie';
import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import { SessionsService } from '../sessions/sessions.service';
import type { User } from '../../types';
import { CurrentUser } from './current-user.decorator';
import { currentSessionId } from './jwt-verify';
import { JwtAuthGuard } from './jwt-auth.guard';
/**
* The signed-in user's own sessions: where they are signed in, and signing
* one or all the others out. Behind JwtAuthGuard like the other account
* routes, and scoped to the caller: another user's session id answers 404,
* exactly like one that does not exist.
*
* A request made with a token from before sessions were tracked sees no
* current session (`current_tracked: false`). Signing out the others then
* ends every tracked session, while that token itself runs on to its expiry.
*
* No MCP tool mirrors these routes: MCP exposes no account or session tools,
* and a session is a browser credential an assistant has no business ending.
*/
@Controller('api/auth/sessions')
@UseGuards(JwtAuthGuard)
export class SessionsController {
constructor(
private readonly sessions: SessionsService,
private readonly audit: AuditService,
) {}
@Get()
async list(@CurrentUser() user: User, @Req() req: Request): Promise<UserSessionListResponse> {
const current = currentSessionId(req);
return { sessions: await this.sessions.list(user.id, current), current_tracked: current !== undefined };
}
// Static sub-route before the `:id` one.
@Post('revoke-others')
@HttpCode(200)
async revokeOthers(@CurrentUser() user: User, @Req() req: Request): Promise<UserSessionRevokeOthersResponse> {
const revoked = await this.sessions.revokeAll(user.id, currentSessionId(req));
await this.audit.writeAudit({ userId: user.id, action: 'user.sessions_revoke_others', ip: getClientIp(req), details: { revoked } });
return { success: true, revoked };
}
@Delete(':id')
async revoke(
@CurrentUser() user: User,
@Param(new ZodValidationPipe(userSessionRevokeParamsSchema)) params: UserSessionRevokeParams,
@Req() req: Request,
@Res({ passthrough: true }) res: Response,
): Promise<UserSessionRevokeResponse> {
if (!(await this.sessions.revoke(user.id, params.id))) {
throw new HttpException({ error: 'Session not found' }, 404);
}
// Ending the session this request came with is a logout: the cookie goes too.
if (params.id === currentSessionId(req)) clearAuthCookie(res, req);
await this.audit.writeAudit({ userId: user.id, action: 'user.session_revoke', ip: getClientIp(req), resource: params.id });
return { success: true };
}
}
+2 -1
View File
@@ -12,6 +12,7 @@ import { EphemeralTokenService } from '../auth/ephemeral-token.service';
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
import { EntityManager } from '@mikro-orm/core';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { User } from '../../types';
import type { TripAccess } from '../../db/repositories/Trips.repository';
import { Trips } from '../../db/entities/Trips.entity';
@@ -168,7 +169,7 @@ export class FilesService {
// Use the shared helper so the password_version gate applies here too;
// previously this bypassed the check and stolen download tokens stayed
// valid across a password reset.
const user = await verifyJwtAndLoadUser(jwtToken, this.em.getRepository(Users));
const user = await verifyJwtAndLoadUser(jwtToken, this.em.getRepository(Users), this.em.getRepository(UserSessions));
if (!user) return { error: 'Invalid or expired token', status: 401 };
return { userId: user.id };
}
+2 -1
View File
@@ -13,6 +13,7 @@ import { getClientIp } from '../audit/client-ip';
import { AdminOidcUpdateDto } from '../admin/admin.dto';
import { Public } from '../auth/public.decorator';
import { ManagedForbidden } from '../common/managed';
import { sessionClientFrom } from '../sessions/sessions.service';
const OIDC_STATE_COOKIE = 'trek_oidc_state';
const OIDC_EXCHANGE_COOKIE = 'trek_oidc_exchange';
@@ -202,7 +203,7 @@ export class OidcController {
// Pass the flag through untouched: `undefined` must reach the token as
// "absent", not `false`, or the sliding renewal would later downgrade the
// default persistent cookie to a browser-session one (remember-me, #1927).
const jwtToken = await this.oidc.generateToken(result.user, pending.remember);
const jwtToken = await this.oidc.generateToken(result.user, pending.remember, sessionClientFrom(req));
const { code: authCode, binding } = await this.oidc.createAuthCode(jwtToken, pending.remember);
// Bind the code to THIS browser, the way the state cookie binds the callback.
// The code rides home in a URL, so it is readable from history, from a
+9 -15
View File
@@ -7,12 +7,12 @@ import bcrypt from 'bcryptjs';
import type { Request, Response } from 'express';
import { InjectRepository } from '@mikro-orm/nestjs';
import { readEnv, getAppUrl } from '../../app-config';
import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS } from '../../config';
import { User } from '../../types';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import { setAuthCookie, RememberOption } from '../common/cookie';
import { AuthService } from '../auth/auth.service';
import type { SessionClient } from '../sessions/sessions.service';
import { UnitOfWork } from '../database/unit-of-work';
import { logError } from '../audit/audit-log.logger';
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
@@ -460,20 +460,14 @@ export class OidcService implements OnModuleDestroy {
return base + path;
}
async generateToken(user: { id: number }, remember?: boolean): Promise<string> {
// Embed the current password_version so an OIDC-issued session is invalidated
// by a password change/reset exactly like a password-login session (the auth
// middleware compares this `pv` against users.password_version).
const pv = (await this.usersRepo.getPasswordVersion(user.id)) ?? 0;
// "Remember me" mirrors the password flow: the JWT lifetime matches the
// persistent cookie maxAge picked by the cookie service off the same flag,
// and the claim lets sliding renewal preserve those semantics.
const expiresIn = remember === true ? SESSION_DURATION_REMEMBER_SECONDS : SESSION_DURATION_SECONDS;
return jwt.sign(
{ id: user.id, pv, ...(typeof remember === 'boolean' ? { remember } : {}) },
JWT_SECRET,
{ expiresIn, algorithm: 'HS256' },
);
/**
* The same session token a password login gets, through the one issuer: it
* embeds the current password_version (so a password change or reset ends an
* SSO session too), takes the "remember me" lifetime and claim, and records
* the session so it can be listed and revoked.
*/
async generateToken(user: { id: number }, remember?: boolean, client?: SessionClient): Promise<string> {
return this.auth.generateToken({ id: user.id }, remember, client);
}
// -------------------------------------------------------------------------
+7 -1
View File
@@ -22,7 +22,13 @@ export function setupApiDocs(app: INestApplication): void {
.setTitle('TREK API')
.setDescription(
'The REST API the TREK web app itself runs on. Authenticate with a session JWT — '
+ 'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.',
+ 'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.\n\n'
+ 'Every session can be ended before it expires: `POST /api/auth/logout` ends the one it is called with, '
+ '`GET /api/auth/sessions` lists the signed-in sessions, `DELETE /api/auth/sessions/{id}` ends one and '
+ '`POST /api/auth/sessions/revoke-others` ends all but the current one.\n\n'
+ '**Deprecated:** the `token` field in the bodies of `POST /api/auth/login`, `/register`, `/demo-login`, '
+ '`/mfa/verify-login` and `/passkey/login/verify`. It is still sent, for clients that read it, but will be '
+ 'removed in a future major version. Use the `trek_session` cookie the same response sets.',
)
.setVersion(version)
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'session')
+23 -3
View File
@@ -8,7 +8,9 @@ import { withRequestContext } from '../database/request-context';
import { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import { ShareTokens } from '../../db/entities/ShareTokens.entity';
import type { ShareTokensRepository } from '../../db/repositories/ShareTokens.repository';
import { Photos } from '../../db/entities/Photos.entity';
@@ -114,7 +116,15 @@ export function storageStaticHandler(storage: StorageService, category: StorageC
};
}
async function servePhoto(storage: StorageService, req: Request, res: Response, users: UsersRepository, shareTokens: ShareTokensRepository, photos: PhotosRepository): Promise<void> {
async function servePhoto(
storage: StorageService,
req: Request,
res: Response,
users: UsersRepository,
shareTokens: ShareTokensRepository,
photos: PhotosRepository,
sessions: UserSessionsRepository,
): Promise<void> {
const safeName = path.basename(req.params.filename);
// Parity: after basename(), the old resolve()+startsWith guard could only
// fire when the remaining segment was '..' — keep that exact 403.
@@ -146,7 +156,7 @@ async function servePhoto(storage: StorageService, req: Request, res: Response,
}
// JWT session path (with pv check).
const user = await verifyJwtAndLoadUser(rawToken, users);
const user = await verifyJwtAndLoadUser(rawToken, users, sessions);
if (user) return sendPhoto();
// Share-token path: require the token to cover the exact trip the
@@ -240,7 +250,17 @@ export function applyPlatformUploads(app: express.Application, storage: StorageS
next(new Error('applyPlatformUploads: no MikroORM available to build a request context for /uploads/photos/*'));
return;
}
return withRequestContext(orm, () => servePhoto(storage, req, res, orm.em.getRepository(Users), orm.em.getRepository(ShareTokens), orm.em.getRepository(Photos))).catch(next);
return withRequestContext(orm, () =>
servePhoto(
storage,
req,
res,
orm.em.getRepository(Users),
orm.em.getRepository(ShareTokens),
orm.em.getRepository(Photos),
orm.em.getRepository(UserSessions),
),
).catch(next);
});
// Block direct access to /uploads/files
@@ -6,6 +6,7 @@ import { pluginsEnabled } from './kill-switch';
import { PluginRuntimeService } from './plugin-runtime.service';
import { Public } from '../auth/public.decorator';
import { Users } from '../../db/entities/Users.entity';
import { UserSessions } from '../../db/entities/UserSessions.entity';
/**
* Proxies a plugin's own HTTP routes at /api/plugins/:id/* (#plugins, M2).
@@ -102,7 +103,7 @@ export class PluginsProxyController {
let user: { id: number; username: string; role?: 'admin' | 'user' } | null = null;
if (route.auth) {
const token = extractToken(req);
const loaded = token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users)) : null;
const loaded = token ? await verifyJwtAndLoadUser(token, this.em.getRepository(Users), this.em.getRepository(UserSessions)) : null;
if (!loaded) {
res.status(401).json({ error: 'Access token required', code: 'AUTH_REQUIRED' });
return;
@@ -0,0 +1,33 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { logError, logInfo } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { SessionsService } from './sessions.service';
/**
* Nightly removal of the `user_sessions` rows that no longer let anyone in:
* expired ones, and revoked ones. Every sign-in writes a row, so without this
* the table would grow by one row per login for as long as the install runs.
* Deleting a revoked row changes nothing for its token, which a missing row
* refuses just the same.
*/
@Injectable()
export class SessionPurgeJob implements OnApplicationBootstrap {
constructor(
private readonly sessions: SessionsService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('session-purge', '45 3 * * *', () => this.tick());
}
async tick(now: Date = new Date()): Promise<void> {
try {
const removed = await this.sessions.purgeInactive(now);
if (removed > 0) logInfo(`Session purge: removed ${removed} expired or revoked session(s)`);
} catch (err: unknown) {
logError(`Session purge: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
@@ -0,0 +1,19 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { SessionPurgeJob } from './session-purge.job';
import { SessionsService } from './sessions.service';
/**
* Session tokens and the rows that let them be revoked. A leaf: it imports no
* other domain module, so auth (sign-in, logout, the session list), oidc
* (sign-in) and admin (resets) can all import it without a cycle. The routes
* over it live in auth, beside the other /api/auth account routes.
*/
@Module({
imports: [SchedulingModule, MikroOrmModule.forFeature([UserSessions])],
providers: [SessionsService, SessionPurgeJob],
exports: [SessionsService],
})
export class SessionsModule {}
@@ -0,0 +1,149 @@
import { randomUUID } from 'crypto';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { Request } from 'express';
import jwt from 'jsonwebtoken';
import type { UserSession } from '@trek/shared';
import { JWT_SECRET, SESSION_DURATION_SECONDS, SESSION_DURATION_REMEMBER_SECONDS } from '../../config';
import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { UserSessionsRepository } from '../../db/repositories/UserSessions.repository';
import { dbNow } from '../../db/types';
/** The longest User-Agent kept, the same cap a Web Push device's gets. */
export const USER_AGENT_MAX_LENGTH = 256;
/** What the issuing request tells about the device a session belongs to. */
export interface SessionClient {
userAgent?: string | null;
}
/** The claims a session token is renewed from (decoded by the caller after a guard verified it). */
export interface RenewableSessionClaims {
id: number;
pv?: number;
remember?: boolean;
jti?: string;
}
/** The device description of a request: its User-Agent header, when it sent one. */
export function sessionClientFrom(req: Pick<Request, 'headers'>): SessionClient {
const agent = req.headers['user-agent'];
return { userAgent: typeof agent === 'string' && agent.length > 0 ? agent : null };
}
/**
* Session tokens and the `user_sessions` rows behind them.
*
* Every token issued here carries a random `jti` naming its row, and
* `verifyJwtAndLoadUser` (auth/jwt-verify.ts) refuses a token whose row is
* revoked, expired or gone. That is what lets a logout end the token instead
* of only clearing the cookie, and lets a user sign out a device. A token
* without a `jti` was issued before sessions were tracked: it is never looked
* up here and stays valid until it expires or the password changes, so the
* upgrade signs nobody out.
*
* Its own domain, with no import of auth, because auth, oidc and admin all end
* or start sessions; a home inside auth would have made oidc's and admin's
* reach for it a reach into auth's internals.
*/
@Injectable()
export class SessionsService {
constructor(@InjectRepository(UserSessions) private readonly sessions: UserSessionsRepository) {}
/**
* Mint a session token for the user and record its session.
*
* `remember` picks the lifetime (true: the long "remember me" one) and is
* kept as a claim so sliding renewal keeps the same cookie semantics; it is
* left out when the caller made no choice, as before.
*
* @txStandalone the row only makes the token it returns usable: if the
* caller fails after it, nobody holds that token and the row expires with it.
*/
async issue(user: { id: number; pv: number }, remember?: boolean, client: SessionClient = {}): Promise<string> {
const jti = randomUUID();
const token = this.sign(user, remember, jti);
const { iat, exp } = this.lifetimeOf(token);
await this.sessions.insertSession({
id: jti,
user_id: user.id,
created_at: dbNow(new Date(iat * 1000)),
expires_at: dbNow(new Date(exp * 1000)),
user_agent: clipUserAgent(client.userAgent),
});
return token;
}
/**
* Sliding renewal of a verified token past half its life. A tracked token
* is re-signed under the same id and its row's expiry moves with it; a
* token from before sessions were tracked becomes a tracked session here.
* Null when the session ended in the meantime, so nothing is renewed.
*
* @txStandalone one statement either way, and a renewal stands on its own:
* the old token keeps working until its own expiry whatever happens next.
*/
async renew(claims: RenewableSessionClaims, client: SessionClient = {}): Promise<string | null> {
const user = { id: claims.id, pv: claims.pv ?? 0 };
if (claims.jti === undefined) return this.issue(user, claims.remember, client);
const token = this.sign(user, claims.remember, claims.jti);
const { exp } = this.lifetimeOf(token);
const extended = await this.sessions.extendActive(claims.jti, claims.id, dbNow(), dbNow(new Date(exp * 1000)));
return extended ? token : null;
}
/** The user's active sessions, most recently used first, the one in `currentId` flagged. */
async list(userId: number, currentId?: string): Promise<UserSession[]> {
const rows = await this.sessions.listActiveForUser(userId, dbNow());
return rows.map((row) => ({ ...row, current: row.id === currentId }));
}
/** End one of the user's sessions. False when the user has no active session by that id. */
async revoke(userId: number, sessionId: string): Promise<boolean> {
return this.sessions.revokeForUser(sessionId, userId, dbNow());
}
/**
* Logout: end the session a verified token names. False for no token, or
* for one from before sessions were tracked, which has no session to end.
*/
async endSession(claims: { id: number; jti?: string } | null): Promise<boolean> {
if (!claims || typeof claims.jti !== 'string') return false;
return this.revoke(claims.id, claims.jti);
}
/**
* End every session of the user, or every one but `exceptId`. Answers how
* many ended. Runs inside the caller's transaction where there is one (a
* password change revokes the sessions with the password write).
*/
async revokeAll(userId: number, exceptId?: string): Promise<number> {
return this.sessions.revokeAllForUser(userId, dbNow(), exceptId);
}
/** Remove the rows that refuse their token anyway: expired or revoked. */
async purgeInactive(now: Date): Promise<number> {
return this.sessions.deleteInactive(dbNow(now));
}
private sign(user: { id: number; pv: number }, remember: boolean | undefined, jti: string): string {
// "Remember me" extends the JWT lifetime to match the persistent cookie
// maxAge; the cookie service decides session-vs-persistent off the same flag.
const expiresIn = remember === true ? SESSION_DURATION_REMEMBER_SECONDS : SESSION_DURATION_SECONDS;
return jwt.sign(
{ id: user.id, pv: user.pv, ...(typeof remember === 'boolean' ? { remember } : {}) },
JWT_SECRET,
{ expiresIn, algorithm: 'HS256', jwtid: jti },
);
}
/** `iat` and `exp` of a token this service just signed. */
private lifetimeOf(token: string): { iat: number; exp: number } {
const { iat, exp } = jwt.decode(token) as { iat: number; exp: number };
return { iat, exp };
}
}
function clipUserAgent(agent: string | null | undefined): string | null {
return agent ? agent.slice(0, USER_AGENT_MAX_LENGTH) : null;
}