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:
Maurice
2026-08-07 18:01:24 +02:00
committed by GitHub
parent a634b2a26b
commit 9814480a96
25 changed files with 215 additions and 725 deletions
-184
View File
@@ -1,184 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import jwt from 'jsonwebtoken';
vi.mock('../../../src/db/database', () => ({
db: { prepare: vi.fn(() => ({ get: vi.fn(), all: vi.fn() })) },
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret' }));
import { extractToken, authenticate, adminOnly } from '../../../src/middleware/auth';
import { db } from '../../../src/db/database';
import type { Request, Response, NextFunction } from 'express';
function makeReq(overrides: {
cookies?: Record<string, string>;
headers?: Record<string, string>;
} = {}): Request {
return {
cookies: overrides.cookies || {},
headers: overrides.headers || {},
} as unknown as Request;
}
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
const json = vi.fn();
const status = vi.fn(() => ({ json }));
const res = { status } as unknown as Response;
return { res, status, json };
}
// ── extractToken ─────────────────────────────────────────────────────────────
describe('extractToken', () => {
it('returns cookie value when trek_session cookie is set', () => {
const req = makeReq({ cookies: { trek_session: 'cookie-token' } });
expect(extractToken(req)).toBe('cookie-token');
});
it('returns Bearer token from Authorization header when no cookie', () => {
const req = makeReq({ headers: { authorization: 'Bearer header-token' } });
expect(extractToken(req)).toBe('header-token');
});
it('prefers cookie over Authorization header when both are present', () => {
const req = makeReq({
cookies: { trek_session: 'cookie-token' },
headers: { authorization: 'Bearer header-token' },
});
expect(extractToken(req)).toBe('cookie-token');
});
it('returns null when neither cookie nor header are present', () => {
expect(extractToken(makeReq())).toBeNull();
});
it('returns null for Authorization header without a token (empty Bearer)', () => {
const req = makeReq({ headers: { authorization: 'Bearer ' } });
expect(extractToken(req)).toBeNull();
});
it('returns null for Authorization header without Bearer prefix', () => {
const req = makeReq({ headers: { authorization: 'Basic sometoken' } });
// split(' ')[1] returns 'sometoken' — this IS returned (not a null case)
// The function simply splits on space and takes index 1
expect(extractToken(req)).toBe('sometoken');
});
});
// ── authenticate ─────────────────────────────────────────────────────────────
describe('authenticate', () => {
it('returns 401 when no token is present', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
authenticate(makeReq(), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ code: 'AUTH_REQUIRED' }));
});
it('returns 401 when JWT is invalid', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: 'invalid.jwt.token' } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-003: calls next() and sets req.user for a valid JWT', () => {
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user' };
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
const token = jwt.sign({ id: 1 }, 'test-secret', { algorithm: 'HS256' });
const req = makeReq({ cookies: { trek_session: token } });
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
authenticate(req, res, next);
expect(next).toHaveBeenCalledOnce();
expect((req as any).user).toEqual(mockUser);
});
it('AUTH-MW-004: returns 401 for a valid JWT when user does not exist in DB', () => {
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => undefined), all: vi.fn() } as any);
const token = jwt.sign({ id: 99999 }, 'test-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: token } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-005: returns 401 for an expired JWT', () => {
const expiredToken = jwt.sign(
{ id: 1, exp: Math.floor(Date.now() / 1000) - 3600 },
'test-secret',
{ algorithm: 'HS256' }
);
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: expiredToken } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-006: returns 401 for a JWT signed with the wrong secret', () => {
const tamperedToken = jwt.sign({ id: 1 }, 'wrong-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ cookies: { trek_session: tamperedToken } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
it('AUTH-MW-007: rejects a purpose-scoped mfa_login token even when the user is valid', () => {
// The token issued after the password check but before TOTP is signed with
// the same secret. It must never authenticate a normal request, otherwise
// password alone grants full access and MFA is bypassed.
const mockUser = { id: 1, username: 'alice', email: 'alice@example.com', role: 'user', password_version: 0 };
vi.mocked(db.prepare).mockReturnValue({ get: vi.fn(() => mockUser), all: vi.fn() } as any);
const mfaToken = jwt.sign({ id: 1, purpose: 'mfa_login', pv: 0 }, 'test-secret', { algorithm: 'HS256' });
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
authenticate(makeReq({ headers: { authorization: `Bearer ${mfaToken}` } }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(401);
});
});
// ── adminOnly ─────────────────────────────────────────────────────────────────
describe('adminOnly', () => {
it('returns 403 when user role is not admin', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
const req = { ...makeReq(), user: { id: 1, role: 'user' } } as unknown as Request;
adminOnly(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(403);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('Admin') }));
});
it('calls next() when user role is admin', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
const req = { ...makeReq(), user: { id: 1, role: 'admin' } } as unknown as Request;
adminOnly(req, res, next);
expect(next).toHaveBeenCalled();
});
it('returns 403 when req.user is undefined', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
adminOnly(makeReq() as unknown as Request, res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(403);
});
});
@@ -1,176 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── In-memory store + DB mock using vi.hoisted ────────────────────────────────
const { rows, dbMock } = vi.hoisted(() => {
const rows: Record<string, { status_code: number; response_body: string }> = {};
const dbMock = {
db: {
prepare: vi.fn((sql: string) => ({
get: vi.fn((...args: unknown[]) => {
const [key, userId, method, path] = args;
return rows[`${key}:${userId}:${method}:${path}`] ?? undefined;
}),
run: vi.fn((...args: unknown[]) => {
const [key, userId, method, path, status_code, response_body] = args as [string, number, string, string, number, string];
const k = `${key}:${userId}:${method}:${path}`;
if (!rows[k]) rows[k] = { status_code, response_body };
}),
})),
},
};
return { rows, dbMock };
});
vi.mock('../../../src/db/database', () => dbMock);
import { applyIdempotency } from '../../../src/middleware/idempotency';
import type { Request, Response, NextFunction } from 'express';
function makeReq(method = 'POST', headers: Record<string, string> = {}, path = '/api/test'): Request {
return { method, path, headers } as unknown as Request;
}
function makeRes(statusCode = 200): Response {
const ctx = { status: statusCode };
const res = {
get statusCode() { return ctx.status; },
status(code: number) { ctx.status = code; return res; },
json: vi.fn((_body: unknown) => res),
} as unknown as Response;
return res;
}
beforeEach(() => {
Object.keys(rows).forEach(k => delete rows[k]);
vi.clearAllMocks();
});
describe('applyIdempotency', () => {
it('calls next() for GET requests', () => {
const req = makeReq('GET', { 'x-idempotency-key': 'key1' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalledOnce();
});
it('calls next() when header is absent for POST', () => {
const req = makeReq('POST', {});
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalledOnce();
});
it('replays cached response when key+user+method+path already stored', () => {
rows['cached-key:42:POST:/api/test'] = { status_code: 201, response_body: JSON.stringify({ id: 99 }) };
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 42);
expect(next).not.toHaveBeenCalled();
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith({ id: 99 });
});
it('different user same key does NOT replay', () => {
rows['cached-key:1:POST:/api/test'] = { status_code: 200, response_body: JSON.stringify({ ok: true }) };
const req = makeReq('POST', { 'x-idempotency-key': 'cached-key' });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 99); // different user
expect(next).toHaveBeenCalledOnce();
});
it('same key+user on different path does NOT replay (scoped cache)', () => {
// Key 'dual-key' is cached under /api/a but reused against /api/b.
// Without the (key, user_id, method, path) scoping, /api/b would
// have replayed /api/a's body — a silent cross-endpoint leak.
rows['dual-key:7:POST:/api/a'] = { status_code: 200, response_body: JSON.stringify({ from: 'a' }) };
const req = makeReq('POST', { 'x-idempotency-key': 'dual-key' }, '/api/b');
const res = makeRes();
const next = vi.fn(() => {
(res.json as ReturnType<typeof vi.fn>)({ from: 'b' });
});
applyIdempotency(req, res, next, 7);
expect(next).toHaveBeenCalledOnce();
expect(rows['dual-key:7:POST:/api/b']).toBeDefined();
expect(JSON.parse(rows['dual-key:7:POST:/api/b'].response_body)).toEqual({ from: 'b' });
// /api/a's row is untouched.
expect(JSON.parse(rows['dual-key:7:POST:/api/a'].response_body)).toEqual({ from: 'a' });
});
it('same key+user+path but different method does NOT replay', () => {
rows['m-key:3:POST:/api/x'] = { status_code: 201, response_body: JSON.stringify({ m: 'post' }) };
const req = makeReq('PATCH', { 'x-idempotency-key': 'm-key' }, '/api/x');
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 3);
expect(next).toHaveBeenCalledOnce();
});
it('stores 2xx response on first execution via wrapped res.json', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'new-key' });
const res = makeRes(201);
const next = vi.fn(() => {
// Simulate handler calling res.json
(res.json as ReturnType<typeof vi.fn>)({ id: 5 });
});
applyIdempotency(req, res, next, 7);
expect(next).toHaveBeenCalledOnce();
expect(rows['new-key:7:POST:/api/test']).toBeDefined();
expect(rows['new-key:7:POST:/api/test'].status_code).toBe(201);
expect(JSON.parse(rows['new-key:7:POST:/api/test'].response_body)).toEqual({ id: 5 });
});
it('does NOT store 4xx responses', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'fail-key' });
const res = makeRes(422);
const next = vi.fn(() => {
(res.json as ReturnType<typeof vi.fn>)({ error: 'Invalid' });
});
applyIdempotency(req, res, next, 3);
expect(rows['fail-key:3:POST:/api/test']).toBeUndefined();
});
it('returns 400 when X-Idempotency-Key exceeds 128 characters', () => {
const longKey = 'a'.repeat(129);
const req = makeReq('POST', { 'x-idempotency-key': longKey });
const res = makeRes();
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).not.toHaveBeenCalled();
expect(res.json as ReturnType<typeof vi.fn>).toHaveBeenCalledWith(
expect.objectContaining({ error: expect.stringContaining('128') }),
);
});
it('does NOT cache response body exceeding 256 KiB', () => {
const req = makeReq('POST', { 'x-idempotency-key': 'big-key' });
const res = makeRes(200);
const originalJsonSpy = res.json as ReturnType<typeof vi.fn>;
const largePayload = { data: 'x'.repeat(256 * 1024 + 1) };
const next = vi.fn(() => {
// res.json is now the wrapper; calling it exercises the size-cap branch
res.json(largePayload);
});
applyIdempotency(req, res, next, 5);
expect(next).toHaveBeenCalledOnce();
// Underlying spy was called (response reached the client)
expect(originalJsonSpy).toHaveBeenCalledWith(largePayload);
// But NOT stored in the idempotency store
expect(rows['big-key:5:POST:/api/test']).toBeUndefined();
});
it('handles PUT, PATCH, and DELETE the same as POST', () => {
for (const method of ['PUT', 'PATCH', 'DELETE'] as const) {
const req = makeReq(method, { 'x-idempotency-key': `key-${method}` });
const res = makeRes(200);
const next = vi.fn();
applyIdempotency(req, res, next, 1);
expect(next).toHaveBeenCalled();
vi.clearAllMocks();
}
});
});
@@ -1,109 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { maxLength, validateStringLengths } from '../../../src/middleware/validate';
import type { Request, Response, NextFunction } from 'express';
function makeReq(body: Record<string, unknown> = {}): Request {
return { body } as Request;
}
function makeRes(): { res: Response; status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } {
const json = vi.fn();
const status = vi.fn(() => ({ json }));
const res = { status } as unknown as Response;
return { res, status, json };
}
// ── maxLength ────────────────────────────────────────────────────────────────
describe('maxLength', () => {
it('calls next() when field is absent from body', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 10)(makeReq({}), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when field is not a string (number)', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('count', 5)(makeReq({ count: 999 }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when string length is within limit', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 10)(makeReq({ name: 'hello' }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() when string length equals max exactly', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
maxLength('name', 5)(makeReq({ name: 'hello' }), res, next);
expect(next).toHaveBeenCalled();
});
it('returns 400 when field exceeds max', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status, json } = makeRes();
maxLength('name', 4)(makeReq({ name: 'hello' }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringContaining('name') }));
});
it('error message includes field name and max length', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, json } = makeRes();
maxLength('title', 3)(makeReq({ title: 'toolong' }), res, next);
expect(json).toHaveBeenCalledWith(expect.objectContaining({ error: expect.stringMatching(/title.*3|3.*title/i) }));
});
});
// ── validateStringLengths ────────────────────────────────────────────────────
describe('validateStringLengths', () => {
it('calls next() when all fields are within limits', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ name: 10, bio: 100 })(makeReq({ name: 'Alice', bio: 'A short bio' }), res, next);
expect(next).toHaveBeenCalled();
});
it('returns 400 on first field that exceeds its limit', () => {
const next = vi.fn() as unknown as NextFunction;
const { res, status } = makeRes();
validateStringLengths({ name: 3 })(makeReq({ name: 'toolong' }), res, next);
expect(next).not.toHaveBeenCalled();
expect(status).toHaveBeenCalledWith(400);
});
it('skips fields not present in body', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ name: 10, missing: 5 })(makeReq({ name: 'Alice' }), res, next);
expect(next).toHaveBeenCalled();
});
it('skips non-string fields', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ count: 5 })(makeReq({ count: 999999 }), res, next);
expect(next).toHaveBeenCalled();
});
it('handles empty maxLengths object — calls next()', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({})(makeReq({ anything: 'value' }), res, next);
expect(next).toHaveBeenCalled();
});
it('calls next() only once even if multiple fields are valid', () => {
const next = vi.fn() as unknown as NextFunction;
const { res } = makeRes();
validateStringLengths({ a: 10, b: 10 })(makeReq({ a: 'ok', b: 'ok' }), res, next);
expect(next).toHaveBeenCalledOnce();
});
});