mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(server): tighten the guard, audit and token paths
Permissions cached an empty map before it had loaded, so a DB error during the load cached permissive defaults and every later check answered from that cache - fail-open, and it never expired. The rate limiter grew its per-IP map forever; the GC the legacy version had was dropped in the fold. Idempotency did a check-then-insert, so two concurrent duplicates both ran the handler. Audit rows recorded whatever X-Forwarded-For said, which the client writes, and the request-body debug logger redacted by exact key match - it missed refresh tokens, api keys and PKCE verifiers. FORCE_HTTPS built its redirect from the client's Host header. CSP asked for unsafe-eval on top of the wasm-unsafe-eval it actually needs. The OAuth deny path redirected to an unvalidated URI, ws-token minting had no rate limit at all, and PKCE was skipped when code_verifier was absent rather than refused. An MCP session resumed with a token whose scopes had since been reduced kept the capability set it was created with, and the session cap was checked before the async registration that increments it. Plugin frame containment was lexical, so a symlink out of the directory was never noticed, and instance config accepted keys the manifest never declared.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { Observable, from, of } from 'rxjs';
|
||||
import { finalize, switchMap } from 'rxjs/operators';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
|
||||
/**
|
||||
@@ -16,8 +17,17 @@ import { DatabaseService } from '../database/database.service';
|
||||
* - 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
|
||||
* - the same key still in flight -> wait for it, then replay its response
|
||||
* - otherwise -> capture a successful JSON response under the key
|
||||
*
|
||||
* The in-flight step is the one thing the Express wrapper did not do. The row
|
||||
* only exists once the first request answers, so two overlapping replays of one
|
||||
* key (two tabs draining the same offline queue, or a client retrying after a
|
||||
* timeout) both missed the SELECT and both ran the handler — the duplicate
|
||||
* write the key exists to prevent. Waiting keeps the promise the client was
|
||||
* given: the second caller gets the first one's response, not a new error to
|
||||
* interpret.
|
||||
*
|
||||
* Capturing wraps `res.json`, so 204 / `res.end()` responses are not cached —
|
||||
* matching the Express wrapper, which only fires on `res.json`.
|
||||
*/
|
||||
@@ -26,6 +36,14 @@ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
||||
const MAX_KEY_LENGTH = 128;
|
||||
const MAX_CACHED_BODY_BYTES = 256 * 1024;
|
||||
|
||||
/**
|
||||
* (user, method, path, key) of every request currently running, resolved when it
|
||||
* answers. In memory rather than a reservation row on purpose: better-sqlite3 is
|
||||
* synchronous and the whole overlap lives inside one process, so a crash cannot
|
||||
* leave a key wedged for the table's 30-day TTL.
|
||||
*/
|
||||
const inFlight = new Map<string, Promise<void>>();
|
||||
|
||||
interface IdempotencyRow {
|
||||
status_code: number;
|
||||
response_body: string;
|
||||
@@ -53,17 +71,51 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
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>(
|
||||
const existing = this.lookup(key, userId, req);
|
||||
if (existing) return this.replay(existing, res);
|
||||
|
||||
const signature = `${userId}|${req.method}|${req.path}|${key}`;
|
||||
const pending = inFlight.get(signature);
|
||||
if (pending) {
|
||||
return from(pending).pipe(
|
||||
switchMap(() => {
|
||||
const stored = this.lookup(key, userId, req);
|
||||
if (stored) return this.replay(stored, res);
|
||||
// The first request answered without caching anything (it failed, or
|
||||
// it never went through res.json). Run this one normally rather than
|
||||
// inventing a response for it.
|
||||
return this.run(signature, key, userId, req, res, next);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return this.run(signature, key, userId, req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private lookup(key: string, userId: number, req: Request): IdempotencyRow | undefined {
|
||||
return 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));
|
||||
}
|
||||
}
|
||||
|
||||
private replay(row: IdempotencyRow, res: Response): Observable<unknown> {
|
||||
res.status(row.status_code);
|
||||
return of(JSON.parse(row.response_body));
|
||||
}
|
||||
|
||||
private run(
|
||||
signature: string,
|
||||
key: string,
|
||||
userId: number,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: CallHandler,
|
||||
): Observable<unknown> {
|
||||
const originalJson = res.json.bind(res);
|
||||
const database = this.database;
|
||||
res.json = function (body: unknown): Response {
|
||||
@@ -84,6 +136,14 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
return originalJson(body);
|
||||
};
|
||||
|
||||
return next.handle();
|
||||
let done!: () => void;
|
||||
inFlight.set(signature, new Promise<void>((resolve) => { done = resolve; }));
|
||||
|
||||
return next.handle().pipe(
|
||||
finalize(() => {
|
||||
inFlight.delete(signature);
|
||||
done();
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user