mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 19:40:34 +00:00
9814480a96
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.
90 lines
3.7 KiB
TypeScript
90 lines
3.7 KiB
TypeScript
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';
|
|
import type { Request, Response } from 'express';
|
|
import { Observable, of } from 'rxjs';
|
|
import { DatabaseService } from '../database/database.service';
|
|
|
|
/**
|
|
* 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
|
|
* that key, so a migrated mutating route MUST honour it — otherwise a replayed
|
|
* POST would create a duplicate instead of returning the cached response. This
|
|
* reproduces the legacy behaviour exactly, against the same `idempotency_keys`
|
|
* table:
|
|
* - non-mutating method, or no key, or no authenticated user -> pass through
|
|
* - key longer than the cap -> 400 with the exact legacy message
|
|
* - (key, user, method, path) already stored -> replay the cached response
|
|
* - otherwise -> capture a successful JSON response under the key
|
|
*
|
|
* Capturing wraps `res.json`, so 204 / `res.end()` responses are not cached —
|
|
* matching the Express wrapper, which only fires on `res.json`.
|
|
*/
|
|
|
|
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
const MAX_KEY_LENGTH = 128;
|
|
const MAX_CACHED_BODY_BYTES = 256 * 1024;
|
|
|
|
interface IdempotencyRow {
|
|
status_code: number;
|
|
response_body: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class IdempotencyInterceptor implements NestInterceptor {
|
|
constructor(private readonly database: DatabaseService) {}
|
|
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
const req = context.switchToHttp().getRequest<Request & { user?: { id: number } }>();
|
|
const res = context.switchToHttp().getResponse<Response>();
|
|
|
|
if (!MUTATING_METHODS.has(req.method)) return next.handle();
|
|
|
|
const key = req.headers['x-idempotency-key'] as string | undefined;
|
|
if (!key) return next.handle();
|
|
|
|
// Idempotency only applies to authenticated requests — the legacy code runs
|
|
// inside `authenticate`, after req.user is set.
|
|
const userId = req.user?.id;
|
|
if (userId == null) return next.handle();
|
|
|
|
if (key.length > MAX_KEY_LENGTH) {
|
|
throw new HttpException({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' }, 400);
|
|
}
|
|
|
|
// Scope the lookup by method + path as well as user, so the same key replayed
|
|
// against a different endpoint can't return an unrelated cached body.
|
|
const existing = this.database.get<IdempotencyRow>(
|
|
'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?',
|
|
key, userId, req.method, req.path,
|
|
);
|
|
if (existing) {
|
|
res.status(existing.status_code);
|
|
return of(JSON.parse(existing.response_body));
|
|
}
|
|
|
|
const originalJson = res.json.bind(res);
|
|
const database = this.database;
|
|
res.json = function (body: unknown): Response {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
try {
|
|
const serialized = JSON.stringify(body);
|
|
if (serialized.length <= MAX_CACHED_BODY_BYTES) {
|
|
database.run(
|
|
`INSERT OR IGNORE INTO idempotency_keys (key, user_id, method, path, status_code, response_body, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
key, userId, req.method, req.path, res.statusCode, serialized, Math.floor(Date.now() / 1000),
|
|
);
|
|
}
|
|
} catch {
|
|
// Non-fatal: if storage fails, the request still succeeds.
|
|
}
|
|
}
|
|
return originalJson(body);
|
|
};
|
|
|
|
return next.handle();
|
|
}
|
|
}
|