Move tokens out of AuthService into a domain of their own

AuthService carried identity, profile, settings and tokens at once. Tokens
are the cleanest of those to cut loose: they touch one table plus the
ephemeral-token store, and nothing in them needs to know how a password is
hashed or how a session is established.

TokenService takes the six user-facing methods plus verifyMcpToken, and the
two admin-side ones that only lived on AdminService because the admin route
did. The pairs are genuinely different queries rather than duplicates, so
both survive under names that say which is which: the user-facing ones scope
every statement by user_id and treat the session sweep as best-effort, the
admin ones do neither.

Left behind on purpose: verifyJwtToken, which is login identity and belongs
next to the cookie logic, and isDemoUser, which is a demo gate that happens
to read the users table.

TokensModule is a leaf with nothing but DatabaseService, because auth, admin
and the MCP transport all import it and anything added here lands in three
graphs at once.

Both bridges and both controller test harnesses construct these classes
positionally and had to be pulled along; the new argument goes in an
optional slot so untouched call sites stay untouched.
This commit is contained in:
Maurice
2026-08-09 21:40:46 +02:00
committed by Maurice
parent e8d4278899
commit 03fbced20b
14 changed files with 497 additions and 229 deletions
+4 -2
View File
@@ -2,6 +2,7 @@ import { Body, Controller, Delete, Get, HttpCode, HttpException, NotFoundExcepti
import type { Request } from 'express';
import { readEnv } from '../../app-config';
import { AdminService } from './admin.service';
import { TokenService } from '../tokens/token.service';
import {
AdminUserCreateDto,
AdminUserUpdateDto,
@@ -61,6 +62,7 @@ export class AdminController {
private readonly pluginRuntime: PluginRuntimeService,
private readonly audit: AuditService,
private readonly notifications: NotificationsService,
private readonly tokens: TokenService,
) {}
// ── Users ──
@@ -243,11 +245,11 @@ export class AdminController {
// ── MCP tokens / OAuth sessions ──
@Get('mcp-tokens')
listMcpTokens() { return { tokens: this.admin.listMcpTokens() }; }
listMcpTokens() { return { tokens: this.tokens.listAllMcpTokens() }; }
@Delete('mcp-tokens/:id')
deleteMcpToken(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
ok(this.admin.deleteMcpToken(id));
ok(this.tokens.adminDeleteMcpToken(id));
this.audit.writeAudit({ userId: user.id, action: 'admin.mcp_token_delete', resource: String(id), ip: getClientIp(req) });
return { success: true };
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { TokensModule } from '../tokens/tokens.module';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module';
@@ -18,7 +19,7 @@ import { PackingModule } from '../packing/packing.module';
import { PermissionsModule } from '../permissions/permissions.module';
@Module({
imports: [PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule],
imports: [PluginsRuntimeModule, SettingsModule, AuditModule, AddonsModule, AuthModule, NotificationsModule, PackingModule, PermissionsModule, TokensModule],
controllers: [AdminController],
providers: [AdminService],
})
-19
View File
@@ -667,25 +667,6 @@ export class AdminService {
};
}
// ── MCP Tokens ─────────────────────────────────────────────────────────────
listMcpTokens() {
return this.db.all(`
SELECT t.id, t.name, t.token_prefix, t.created_at, t.last_used_at, t.user_id, u.username
FROM mcp_tokens t
JOIN users u ON u.id = t.user_id
ORDER BY t.created_at DESC
`);
}
deleteMcpToken(id: string) {
const token = this.db.get<{ id: number; user_id: number }>('SELECT id, user_id FROM mcp_tokens WHERE id = ?', id);
if (!token) return { error: 'Token not found', status: 404 };
this.db.run('DELETE FROM mcp_tokens WHERE id = ?', id);
revokeUserSessions(token.user_id);
return {};
}
// ── OAuth Sessions ─────────────────────────────────────────────────────────
listOAuthSessions() {
+5 -2
View File
@@ -3,6 +3,7 @@ import { DatabaseService } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import { AuthService } from './auth.service';
import { TokenService } from '../tokens/token.service';
import { MailerService } from '../notifications/mailer/mailer.service';
import { UserCleanupService } from './user-cleanup.service';
import { WebauthnConfigService } from './webauthn-config.service';
@@ -46,6 +47,8 @@ const auth = new AuthService(
new MailerService(dbs),
);
const tokens = new TokenService(dbs);
export { stripUserForClient } from './auth.helpers';
export { avatarUrl } from '../common/avatarUrl';
@@ -54,7 +57,7 @@ export function isDemoUser(userId: number): boolean {
}
export function verifyMcpToken(rawToken: string): User | null {
return auth.verifyMcpToken(rawToken);
return tokens.verifyMcpToken(rawToken);
}
export function verifyJwtToken(token: string): User | null {
@@ -70,5 +73,5 @@ export function generateToken(user: { id: number | bigint; password_version?: nu
}
export function createWsToken(userId: number) {
return auth.createWsToken(userId);
return tokens.createWsToken(userId);
}
+7 -6
View File
@@ -23,6 +23,7 @@ import path from 'path';
import fs from 'fs';
import { v4 as uuid } from 'uuid';
import { AuthService } from './auth.service';
import { TokenService } from '../tokens/token.service';
import { avatarDir } from './auth.helpers';
import {
ChangePasswordDto,
@@ -72,7 +73,7 @@ const AVATAR_UPLOAD = {
@Controller('api/auth')
@UseGuards(JwtAuthGuard)
export class AuthController {
constructor(private readonly auth: AuthService, private readonly rl: RateLimitService, private readonly audit: AuditService, private readonly env: RuntimeEnvService) {}
constructor(private readonly auth: AuthService, private readonly tokens: TokenService, private readonly rl: RateLimitService, private readonly audit: AuditService, private readonly env: RuntimeEnvService) {}
private limit(bucket: string, req: Request, max: number): void {
if (!this.rl.check(bucket, req.ip || 'unknown', max, WINDOW, Date.now())) {
@@ -238,14 +239,14 @@ export class AuthController {
@Get('mcp-tokens')
listMcpTokens(@CurrentUser() user: User) {
return { tokens: this.auth.listMcpTokens(user.id) };
return { tokens: this.tokens.listMcpTokens(user.id) };
}
@Post('mcp-tokens')
@HttpCode(201)
createMcpToken(@CurrentUser() user: User, @Body() body: McpTokenCreateDto, @Req() req: Request) {
this.limit('login', req, 5);
const result = this.auth.createMcpToken(user.id, body.name);
const result = this.tokens.createMcpToken(user.id, body.name);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -254,7 +255,7 @@ export class AuthController {
@Delete('mcp-tokens/:id')
deleteMcpToken(@CurrentUser() user: User, @Param('id') id: string) {
const result = this.auth.deleteMcpToken(user.id, id);
const result = this.tokens.deleteMcpToken(user.id, id);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -264,7 +265,7 @@ export class AuthController {
@Post('ws-token')
@HttpCode(200)
wsToken(@CurrentUser() user: User) {
const result = this.auth.createWsToken(user.id);
const result = this.tokens.createWsToken(user.id);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
@@ -274,7 +275,7 @@ export class AuthController {
@Post('resource-token')
@HttpCode(200)
resourceToken(@CurrentUser() user: User, @Body() body: ResourceTokenDto) {
const token = this.auth.createResourceToken(user.id, body.purpose);
const token = this.tokens.createResourceToken(user.id, body.purpose);
if (!token) {
throw new HttpException({ error: 'Service unavailable' }, 503);
}
+2 -1
View File
@@ -1,5 +1,6 @@
import { RateLimitModule } from '../common/rate-limit.module';
import { Module } from '@nestjs/common';
import { TokensModule } from '../tokens/tokens.module';
import { AuthPublicController } from './auth-public.controller';
import { AuthController } from './auth.controller';
import { PasskeyController } from './passkey.controller';
@@ -35,7 +36,7 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
* through auth.bridge.ts.
*/
@Module({
imports: [RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule],
imports: [RateLimitModule, AuditModule, PermissionsModule, TripMembershipModule, MailerModule, AppConfigModule, TokensModule],
controllers: [AuthPublicController, AuthController, PasskeyController],
providers: [AuthService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
exports: [AuthService, PasskeyService, UserCleanupService],
+5 -85
View File
@@ -1231,76 +1231,11 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
}
// -------------------------------------------------------------------------
// MCP tokens
// -------------------------------------------------------------------------
listMcpTokens(userId: number) {
return this.db.all(
'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE user_id = ? ORDER BY created_at DESC',
userId
);
}
createMcpToken(userId: number, rawName: unknown): { error?: string; status?: number; token?: Record<string, unknown> } {
const name = rawName as string | undefined;
if (!name?.trim()) return { error: 'Token name is required', status: 400 };
if (name.trim().length > 100) return { error: 'Token name must be 100 characters or less', status: 400 };
const tokenCount = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM mcp_tokens WHERE user_id = ?', userId)!.count;
if (tokenCount >= 10) return { error: 'Maximum of 10 tokens per user reached', status: 400 };
const rawToken = 'trek_' + randomBytes(24).toString('hex');
const tokenHash = createHash('sha256').update(rawToken).digest('hex');
const tokenPrefix = rawToken.slice(0, 13);
const result = this.db.run(
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix) VALUES (?, ?, ?, ?)',
userId, name.trim(), tokenHash, tokenPrefix
);
const token = this.db.get(
'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE id = ?',
result.lastInsertRowid
);
return { token: { ...(token as object), raw_token: rawToken } };
}
deleteMcpToken(userId: number, tokenId: string): { error?: string; status?: number; success?: boolean } {
const token = this.db.get('SELECT id FROM mcp_tokens WHERE id = ? AND user_id = ?', tokenId, userId);
if (!token) return { error: 'Token not found', status: 404 };
this.db.run('DELETE FROM mcp_tokens WHERE id = ?', tokenId);
// Best-effort, like the changePassword/resetPassword revocations: a session
// sweep failure must not turn a successful token delete into a 500.
try { revokeUserSessions?.(userId); } catch { /* best-effort */ }
return { success: true };
}
// -------------------------------------------------------------------------
// Ephemeral tokens
// -------------------------------------------------------------------------
createWsToken(userId: number): { error?: string; status?: number; token?: string } {
// Bind the ws-token to the user's current password_version so a token minted
// before a password reset is rejected on connect (defence-in-depth session gate).
const pv = this.db.get<{ password_version?: number }>('SELECT password_version FROM users WHERE id = ?', userId)?.password_version ?? 0;
const token = createEphemeralToken(userId, 'ws', { pv });
if (!token) return { error: 'Service unavailable', status: 503 };
return { token };
}
createResourceToken(userId: number, rawPurpose: unknown): { error?: string; status?: number; token?: string } {
const purpose = rawPurpose as string | undefined;
if (purpose !== 'download') {
return { error: 'Invalid purpose', status: 400 };
}
const token = createEphemeralToken(userId, purpose);
if (!token) return { error: 'Service unavailable', status: 503 };
return { token };
}
// -------------------------------------------------------------------------
// MCP auth helpers
// Demo gate + JWT verification
//
// The MCP token half of this section moved to tokens/token.service.ts. What
// stays is login identity (verifyJwtToken) and the demo check, neither of
// which is about minting a token.
// -------------------------------------------------------------------------
isDemoUser(userId: number): boolean {
@@ -1309,21 +1244,6 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
return isDemoEmail(user?.email);
}
verifyMcpToken(rawToken: string): User | null {
const hash = createHash('sha256').update(rawToken).digest('hex');
const row = this.db.get<User>(`
SELECT u.id, u.username, u.email, u.role
FROM mcp_tokens mt
JOIN users u ON mt.user_id = u.id
WHERE mt.token_hash = ?
`, hash);
if (row) {
this.db.run('UPDATE mcp_tokens SET last_used_at = CURRENT_TIMESTAMP WHERE token_hash = ?', hash);
return row;
}
return null;
}
/**
* Verify a JWT the same way `auth/jwt-verify.ts#verifyJwtAndLoadUser`
* does — including the `password_version` check — so that stolen tokens
+143
View File
@@ -0,0 +1,143 @@
import { Injectable } from '@nestjs/common';
import { randomBytes, createHash } from 'crypto';
import { DatabaseService } from '../database/database.service';
import { createEphemeralToken } from '../auth/ephemeral-tokens';
// Import from sessionManager directly, NOT the ../../mcp barrel: the barrel pulls
// the whole tools fan-out (and via the domain bridges, the Nest services) into
// every consumer of this module — a nest→mcp→nest module cycle.
import { revokeUserSessions } from '../../mcp/sessionManager';
import { User } from '../../types';
/**
* Everything that mints or checks a token that is not the login JWT: the
* long-lived MCP tokens a user manages in settings, and the short-lived ws /
* download tokens.
*
* Split out of AuthService, which had grown to carry identity, profile,
* settings and tokens at once. Tokens are the cleanest cut of the four: they
* touch one table (mcp_tokens) plus the ephemeral-token store, and nothing in
* here needs to know how a password is hashed or how a session is established.
*
* The methods moved verbatim — same SQL, same validation order, same error
* strings and status codes, same best-effort session revoke on delete.
*
* Deliberately NOT here: verifyJwtToken (that is login identity, and it stays
* next to the cookie/JWT logic on AuthService) and isDemoUser (a demo gate that
* happens to read the users table).
*/
@Injectable()
export class TokenService {
constructor(private readonly db: DatabaseService) {}
listMcpTokens(userId: number) {
return this.db.all(
'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE user_id = ? ORDER BY created_at DESC',
userId
);
}
createMcpToken(userId: number, rawName: unknown): { error?: string; status?: number; token?: Record<string, unknown> } {
const name = rawName as string | undefined;
if (!name?.trim()) return { error: 'Token name is required', status: 400 };
if (name.trim().length > 100) return { error: 'Token name must be 100 characters or less', status: 400 };
const tokenCount = this.db.get<{ count: number }>('SELECT COUNT(*) as count FROM mcp_tokens WHERE user_id = ?', userId)!.count;
if (tokenCount >= 10) return { error: 'Maximum of 10 tokens per user reached', status: 400 };
const rawToken = 'trek_' + randomBytes(24).toString('hex');
const tokenHash = createHash('sha256').update(rawToken).digest('hex');
const tokenPrefix = rawToken.slice(0, 13);
const result = this.db.run(
'INSERT INTO mcp_tokens (user_id, name, token_hash, token_prefix) VALUES (?, ?, ?, ?)',
userId, name.trim(), tokenHash, tokenPrefix
);
const token = this.db.get(
'SELECT id, name, token_prefix, created_at, last_used_at FROM mcp_tokens WHERE id = ?',
result.lastInsertRowid
);
return { token: { ...(token as object), raw_token: rawToken } };
}
deleteMcpToken(userId: number, tokenId: string): { error?: string; status?: number; success?: boolean } {
const token = this.db.get('SELECT id FROM mcp_tokens WHERE id = ? AND user_id = ?', tokenId, userId);
if (!token) return { error: 'Token not found', status: 404 };
this.db.run('DELETE FROM mcp_tokens WHERE id = ?', tokenId);
// Best-effort, like the changePassword/resetPassword revocations: a session
// sweep failure must not turn a successful token delete into a 500.
try { revokeUserSessions?.(userId); } catch { /* best-effort */ }
return { success: true };
}
// -------------------------------------------------------------------------
// Ephemeral tokens
// -------------------------------------------------------------------------
createWsToken(userId: number): { error?: string; status?: number; token?: string } {
// Bind the ws-token to the user's current password_version so a token minted
// before a password reset is rejected on connect (defence-in-depth session gate).
const pv = this.db.get<{ password_version?: number }>('SELECT password_version FROM users WHERE id = ?', userId)?.password_version ?? 0;
const token = createEphemeralToken(userId, 'ws', { pv });
if (!token) return { error: 'Service unavailable', status: 503 };
return { token };
}
createResourceToken(userId: number, rawPurpose: unknown): { error?: string; status?: number; token?: string } {
const purpose = rawPurpose as string | undefined;
if (purpose !== 'download') {
return { error: 'Invalid purpose', status: 400 };
}
const token = createEphemeralToken(userId, purpose);
if (!token) return { error: 'Service unavailable', status: 503 };
return { token };
}
// -------------------------------------------------------------------------
// Admin view
//
// The same table, seen across all users. Moved here from AdminService, which
// owned a second copy of the delete purely because the admin route lived
// there. Note the two are genuinely different queries, not duplicates: the
// user-facing ones scope every statement by user_id, these deliberately do
// not, and the admin delete revokes sessions unconditionally where the
// user-facing one treats that as best-effort.
// -------------------------------------------------------------------------
listAllMcpTokens() {
return this.db.all(`
SELECT t.id, t.name, t.token_prefix, t.created_at, t.last_used_at, t.user_id, u.username
FROM mcp_tokens t
JOIN users u ON u.id = t.user_id
ORDER BY t.created_at DESC
`);
}
adminDeleteMcpToken(id: string) {
const token = this.db.get<{ id: number; user_id: number }>('SELECT id, user_id FROM mcp_tokens WHERE id = ?', id);
if (!token) return { error: 'Token not found', status: 404 };
this.db.run('DELETE FROM mcp_tokens WHERE id = ?', id);
revokeUserSessions(token.user_id);
return {};
}
// -------------------------------------------------------------------------
// Verification
// -------------------------------------------------------------------------
verifyMcpToken(rawToken: string): User | null {
const hash = createHash('sha256').update(rawToken).digest('hex');
const row = this.db.get<User>(`
SELECT u.id, u.username, u.email, u.role
FROM mcp_tokens mt
JOIN users u ON mt.user_id = u.id
WHERE mt.token_hash = ?
`, hash);
if (row) {
this.db.run('UPDATE mcp_tokens SET last_used_at = CURRENT_TIMESTAMP WHERE token_hash = ?', hash);
return row;
}
return null;
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { TokenService } from './token.service';
/**
* Tokens that are not the login JWT: the long-lived MCP tokens a user manages
* in settings, plus the short-lived ws and download tokens.
*
* A leaf module on purpose. It needs nothing but DatabaseService, which keeps
* it cheap to import — AuthModule, AdminModule and the MCP transport all reach
* for it, and any dependency added here lands in all three graphs.
*/
@Module({
providers: [TokenService],
exports: [TokenService],
})
export class TokensModule {}