mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
refactor(server): move the JWT verify into nest/auth, delete four dead middlewares (#1828)
middleware/auth.ts exported seven things. Two of them — extractToken and verifyJwtAndLoadUser — are the canonical session check every auth surface goes through. The other five (authenticate, requireCookieAuth, optionalAuth, adminOnly, demoUploadBlock) are Express middlewares with no production caller left; the guards in nest/auth replaced them and only comments still mention them. The two live functions move to nest/auth/jwt-verify.ts and the file goes, along with middleware/validate.ts (nothing but its own test imported it) and middleware/idempotency.ts (its only caller was `authenticate`, and IdempotencyInterceptor has replaced it). AuthRequest and OptionalAuthRequest go with them — src/typings/express.d.ts is what types req.user now. Eight importers repoint: the three guards, auth/files/plugins-proxy services, platform.routes and the global MFA policy. Two deliberate departures from the plan for this package. JWT_SECRET does not move to app-config. It is not an env value: it is generated into data/.jwt_secret, and the admin panel rotates it at runtime through updateJwtSecret. `export let` is precisely what makes a rotation take effect in-process — a registerAs token would freeze the boot value and silently break rotation. The verify also keeps reading the db singleton rather than DatabaseService. That change is not a one-line swap: it gives the three guards a constructor dependency, which means registering them as providers everywhere they are used. Measured: 38 directories use those guards and 21 of them do not import AuthModule, on top of 34 e2e tests that each build a container around a single domain module. That is its own PR, not a rider on one that deletes dead files. tests/unit/middleware/auth.test.ts covered real behaviour, so it is not simply deleted. Its extractToken cases and the five verify cases it drove through `authenticate` come back as tests/unit/nest/auth/jwt-verify.test.ts, now hitting verifyJwtAndLoadUser directly. Four cases are new: the password_version gate — the whole reason this function exists — had no direct coverage at all. Its three adminOnly cases are dropped because AdminGuard, their successor, is covered by three e2e suites.
This commit is contained in:
@@ -71,8 +71,8 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
|
||||
// equivalent of the legacy Express app.get('*') catch-all). @Catch(NotFoundException)
|
||||
// is more specific than TrekExceptionFilter, so Nest routes 404s here.
|
||||
{ provide: APP_FILTER, useClass: SpaFallbackFilter },
|
||||
// Replays the X-Idempotency-Key the client sends on every write, matching
|
||||
// the legacy applyIdempotency middleware so retried mutations don't double-apply.
|
||||
// Replays the X-Idempotency-Key the client sends on every write, so retried
|
||||
// mutations don't double-apply.
|
||||
{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor },
|
||||
// Global Zod validation: any parameter typed with a createZodDto class
|
||||
// (the <domain>.dto.ts wrappers over @trek/shared schemas) is validated;
|
||||
|
||||
@@ -25,7 +25,7 @@ import { startTripReminders } from '../../scheduler';
|
||||
import { deleteUserCompletely } from '../../services/userCleanupService';
|
||||
import { emitUserDeleted } from '../../plugin-user-lifecycle';
|
||||
import { getFlightDistanceKm } from '../../services/distanceService';
|
||||
import { verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { verifyJwtAndLoadUser } from './jwt-verify';
|
||||
import { User } from '../../types';
|
||||
import { DEMO_EMAIL_PRIMARY, isDemoEmail } from '../common/demo';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
@@ -1410,7 +1410,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a JWT the same way `middleware/auth.ts#verifyJwtAndLoadUser`
|
||||
* Verify a JWT the same way `auth/jwt-verify.ts#verifyJwtAndLoadUser`
|
||||
* does — including the `password_version` check — so that stolen tokens
|
||||
* lose access the moment the victim resets their password.
|
||||
*
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { verifyJwtAndLoadUser } from './jwt-verify';
|
||||
|
||||
/**
|
||||
* Mirrors the legacy `requireCookieAuth` middleware: accepts ONLY the httpOnly
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
|
||||
|
||||
/**
|
||||
* Validates TREK's existing JWT session — the same httpOnly `trek_session`
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Request } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { db } from '../../db/database';
|
||||
import { JWT_SECRET } from '../../config';
|
||||
import type { User } from '../../types';
|
||||
|
||||
/**
|
||||
* The canonical JWT session check. Every auth surface goes through here — the
|
||||
* three guards, MCP bearer tokens, the file-download query token, the
|
||||
* photo-serving route and the global MFA policy — so the secret, the
|
||||
* password_version gate and the loaded user cannot drift between them.
|
||||
*
|
||||
* Free functions rather than a provider: the MFA policy in
|
||||
* middleware/mfaPolicy.ts and the platform routes run outside the container and
|
||||
* would have no way to inject one. Note JWT_SECRET is deliberately a live
|
||||
* binding from src/config, not an app-config value: the admin panel rotates it
|
||||
* at runtime and `export let` is what makes a rotation take effect in-process.
|
||||
*/
|
||||
export function extractToken(req: Request): string | null {
|
||||
// Prefer httpOnly cookie; fall back to Authorization: Bearer (MCP, API clients)
|
||||
const cookieToken = (req as any).cookies?.trek_session;
|
||||
if (cookieToken) return cookieToken;
|
||||
const authHeader = req.headers['authorization'];
|
||||
return (authHeader && authHeader.split(' ')[1]) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a JWT and load its user, enforcing the password_version gate.
|
||||
*
|
||||
* A password reset bumps `users.password_version`, which invalidates every JWT
|
||||
* that embedded the prior value — but only if every verify path actually
|
||||
* compares the claim. Several paths used to call `jwt.verify` directly and skip
|
||||
* the DB lookup, so a stolen token kept working after the victim reset.
|
||||
*/
|
||||
export function verifyJwtAndLoadUser(token: string): User | null {
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] }) as { id: number; pv?: number; purpose?: string };
|
||||
// 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.
|
||||
if (decoded.purpose) return null;
|
||||
const row = db.prepare(
|
||||
'SELECT id, username, email, role, password_version FROM users WHERE id = ?'
|
||||
).get(decoded.id) as (User & { password_version?: number }) | undefined;
|
||||
if (!row) return null;
|
||||
// Session invalidation: any token whose embedded password_version
|
||||
// predates the user's current one is rejected. Tokens issued before
|
||||
// the `pv` claim existed (decoded.pv === undefined) are treated as
|
||||
// version 0 so legacy sessions keep working until the user resets.
|
||||
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;
|
||||
// Don't leak password_version beyond the verify.
|
||||
const { password_version: _pv, ...user } = row;
|
||||
return user as User;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { extractToken, verifyJwtAndLoadUser } from './jwt-verify';
|
||||
|
||||
/**
|
||||
* Mirrors the legacy `optionalAuth` middleware: populates req.user with the
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//
|
||||
// Historical: the demo account was seeded as "demo@trek.app" (see
|
||||
// authService.demoLogin), but several guards — demoUploadBlock in
|
||||
// middleware/auth.ts, the MFA/backup-code bypasses in authService —
|
||||
// the upload block that used to live in middleware/auth.ts, the MFA/backup-code
|
||||
// bypasses in authService —
|
||||
// were still checking the pre-rename "demo@nomad.app" string, so they
|
||||
// either never fired or silently diverged between call sites. Routing
|
||||
// every check through this constant keeps them aligned.
|
||||
|
||||
@@ -4,9 +4,8 @@ import { Observable, of } from 'rxjs';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
|
||||
/**
|
||||
* Nest counterpart of the legacy `applyIdempotency` middleware
|
||||
* (server/src/middleware/idempotency.ts), which the Express `authenticate`
|
||||
* middleware runs on every authenticated request.
|
||||
* Replaces the `applyIdempotency` middleware the Express `authenticate` ran on
|
||||
* every authenticated request. Both are gone; this is the only implementation.
|
||||
*
|
||||
* The TREK client attaches an `X-Idempotency-Key` to ALL write operations (see
|
||||
* client/src/api/client.ts) and the offline sync queue replays mutations with
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { consumeEphemeralToken } from '../../services/ephemeralTokens';
|
||||
import { verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
|
||||
import type { User, TripFile } from '../../types';
|
||||
import { DatabaseService, type TripAccess } from '../database/database.service';
|
||||
import { DEFAULT_ALLOWED_EXTENSIONS, filesDir } from './files.constants';
|
||||
|
||||
@@ -3,7 +3,7 @@ import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { readEnv } from '../../app-config';
|
||||
import { verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
|
||||
import { db } from '../../db/database';
|
||||
import { mcpHandler } from '../../mcp';
|
||||
import { trekOAuthProvider, trekClientsStore } from '../../mcp/oauthProvider';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { All, Controller, Param, Req, Res } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { extractToken, verifyJwtAndLoadUser } from '../../middleware/auth';
|
||||
import { extractToken, verifyJwtAndLoadUser } from '../auth/jwt-verify';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
import { PluginRuntimeService } from './plugin-runtime.service';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user