feat(server): pre-init photo route and WS handshake run in a request context; InviteTokensRepository

This commit is contained in:
jubnl
2026-09-22 18:46:05 +02:00
parent e98f86efba
commit 7453c7dafa
13 changed files with 705 additions and 12 deletions
+1 -1
View File
@@ -114,7 +114,7 @@ export async function buildApp(): Promise<INestApplication> {
// Same pre-init consumption bridge as httpConfig above: the StorageService
// instance is resolvable before init, and the handlers only *register* here —
// per-request resolution runs after app.init() completed the registry load.
applyPlatformUploads(instance, app.get(StorageService));
applyPlatformUploads(instance, app.get(StorageService), orm);
// The SDK discovery router (+ its addon gate). Container-built so its deps
// are injected (same pre-init consumption bridge as httpConfig above), but
// applied here as a PATHLESS app.use: the SDK router matches absolute
+26
View File
@@ -48,3 +48,29 @@ export function currentTimestamp(platform: Platform): RawQueryFragment {
if (platform instanceof SqlitePlatform) return raw('CURRENT_TIMESTAMP');
return unsupported(platform);
}
/**
* A bare reference to another column of the same row, for a filter or update
* value that must compare against or combine with a sibling column instead
* of a bound parameter (e.g. `used_count < max_uses` — `InviteTokensRepository
* .incrementUsedCount`'s capacity guard). Portable across dialects on its own,
* but still routed through this file (not spelled with `raw()` in a
* repository) so every escape hatch stays in one place ESLint's
* `no-restricted-syntax` rule for `src/db/repositories/**` can enforce.
*/
export function columnRef(platform: Platform, ref: string): RawQueryFragment {
if (platform instanceof SqlitePlatform) return raw(column(ref));
return unsupported(platform);
}
/** A column shifted by a signed integer amount: `<col> + n` / `<col> - n`. */
export function columnIncrementedBy(platform: Platform, ref: string, amount: number): RawQueryFragment {
if (!Number.isInteger(amount)) {
throw new Error(`sql-functions: columnIncrementedBy needs an integer amount, got ${amount}`);
}
if (platform instanceof SqlitePlatform) {
const sign = amount < 0 ? '-' : '+';
return raw(`${column(ref)} ${sign} ${Math.abs(amount)}`);
}
return unsupported(platform);
}
@@ -1,4 +1,111 @@
import type { InviteTokens } from '../entities/InviteTokens.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { columnIncrementedBy, columnRef } from '../dialect/sql-functions';
import { EntityRepository } from '@mikro-orm/sql';
export class InviteTokensRepository extends EntityRepository<InviteTokens> {}
/** An `invite_tokens` row as the API emits it. */
export interface InviteTokenRow {
id: number;
token: string;
max_uses: number;
used_count: number;
expires_at: string | null;
created_by: number;
created_at: string | null;
trip_id: number | null;
}
const _inviteTokenRowKeys: AssertRowKeys<InviteTokenRow, InviteTokens> = true;
/** The column set `RegistrationInvitesService.createInvite` (Task 3) writes. */
export interface NewInviteTokenRow {
token: string;
max_uses: number;
expires_at: string | null;
created_by: number;
trip_id?: number | null;
}
/**
* Shared by `AuthService` (registration), `RegistrationInvitesService` (admin
* invite management, Task 3) and `OidcService` (SSO-bound registration,
* Task 6) — one table, one repository, per the inventory's §6 cross-domain
* ruling. Task 0 builds the three methods every later task needs in common;
* Task 3 extends this with the admin list/create/delete surface (RI1/RI5-RI7).
*/
export class InviteTokensRepository extends EntityRepository<InviteTokens> {
/**
* `SELECT * FROM invite_tokens WHERE token = ?`
*
* Not a primary-key filter — `token` is a unique column, not `id` — so this
* always re-queries; no `{ refresh: true }` needed (Task 3a review's
* precision ruling: the identity-map short-circuit only fires for a
* PK-only filter).
*/
async findValid(token: string): Promise<InviteTokenRow | null> {
const invite = await this.findOne({ token });
return invite ? (toRow(invite) as InviteTokenRow) : null;
}
/**
* `INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id)
* VALUES (?, ?, ?, ?, ?)`, re-selected (RI4/RI5's column set — Task 3 is
* the first real caller). `created_by`/`trip_id` are FK columns backed by
* `persist(false)` scalar mirrors on the entity (same pattern as
* `Categories.user`/`user_id`); the repository writes them through the
* `Ref`-typed relation properties, which MikroORM accepts a raw primary
* key for.
*/
async insertInvite(row: NewInviteTokenRow): Promise<InviteTokenRow> {
const invite = this.create({
token: row.token,
max_uses: row.max_uses,
expires_at: row.expires_at,
createdByRef: row.created_by,
trip: row.trip_id ?? null,
});
await this.getEntityManager().persist(invite).flush();
await this.getEntityManager().refresh(invite);
return toRow(invite) as InviteTokenRow;
}
/**
* `UPDATE invite_tokens SET used_count = used_count + 1
* WHERE token = ? AND (max_uses = 0 OR used_count < max_uses)
* RETURNING *`
*
* ONE conditional UPDATE … RETURNING statement (the QueryBuilder, D4's T5
* tier) — race-safe: D6's single SQLite connection serialises writers, so
* the WHERE clause's capacity check and the increment commit as one
* statement. Two callers racing the same one-use invite can never both
* see `used_count < max_uses` true and both write: exactly one UPDATE
* matches and its RETURNING carries the new row back; the other's WHERE
* clause fails once the first has committed, and it gets `null` — no
* second SELECT, no SELECT→await→UPDATE window for either caller to lose.
*
* `null` means "no row matched" — a bad/unknown token OR an invite already
* at capacity are indistinguishable from inside this method by design
* (this repository never interprets the miss): `AuthService`'s `AU11`
* only warns and continues on a miss, `OidcService`'s `O13` throws — both
* keep their own interpretation, calling this one shared method.
*
* `used_count < max_uses` compares two columns of the SAME row, and
* `used_count = used_count + 1` needs a sibling-column reference too — both
* go through `sql-functions.ts` (`columnRef`/`columnIncrementedBy`), never
* a hand-spelled `raw()` call here: repositories don't spell dialect SQL
* inline (ESLint enforces this on `src/db/repositories/**`), even for an
* expression that happens to be portable across dialects already.
*/
async incrementUsedCount(token: string): Promise<InviteTokenRow | null> {
const platform = this.getEntityManager().getPlatform();
const result = await this.qb()
.update({ used_count: columnIncrementedBy(platform, 'used_count', 1) })
.where({
token,
$or: [{ max_uses: 0 }, { used_count: { $lt: columnRef(platform, 'max_uses') } }],
})
.returning('*')
.execute('run');
return result.row ? (result.row as InviteTokenRow) : null;
}
}
@@ -125,6 +125,18 @@ export class McpTransportService {
private readonly registry: McpRegistryService,
) {}
/**
* D6 (Plan 3b Task 0): this bearer-token verification step already runs
* inside a per-request EntityManager fork — no wrapper needed here. `/mcp`
* is an ordinary (`@Public()`) Nest-routed controller, so
* `@mikro-orm/nestjs`'s `MikroOrmMiddleware` (`MikroOrmModule.forRoot`'s
* default `registerRequestContext`, applied via `NestModule.configure()`
* for ALL routes) forks a context before any guard — and therefore before
* this method — ever runs. Verified, not assumed: see
* `tests/integration/mcp.test.ts`'s "MCP bearer-token verification runs
* inside the HTTP request context" suite (MCP-CTX-001/002), which forces a
* genuine repository read at this exact point and confirms it succeeds.
*/
async verifyToken(authHeader: string | undefined): Promise<VerifyTokenResult | null> {
if (!authHeader) return null;
// M8: strictly require "Bearer" scheme (RFC 6750)
+32 -4
View File
@@ -1,9 +1,11 @@
import express, { Request, Response, NextFunction } from 'express';
import path from 'node:path';
import type { EntityManager } from '@mikro-orm/core';
import { readEnv } from '../../app-config';
import { verifyJwtAndLoadUser } from '../auth/jwt-verify';
import { db } from '../../db/database';
import { withRequestContext } from '../database/request-context';
import { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types';
@@ -125,8 +127,30 @@ async function servePhoto(storage: StorageService, req: Request, res: Response):
/**
* Static + guarded /uploads/* routes. Must be applied BEFORE the API route mounts
* (identical to its original position near the top of createApp).
*
* `orm` (Plan 3b Task 0, D6/plan3b-sql-inventory.md §5/§6): `servePhoto` is
* mounted here, on the raw Express instance, BEFORE `app.init()` — every
* `/uploads/photos/*` request runs this handler entirely outside Nest's
* per-request EntityManager fork, forever, not just during a boot window.
* `verifyJwtAndLoadUser` (`jwt-verify.ts`) reads `users` through the legacy
* `db` proxy today, so nothing here needs the ORM yet — but the inventory's
* proposed conversion (`UsersRepository.findByIdWithPasswordVersion`, Task 1)
* would throw `cannotUseGlobalContext` on every photo request the instant it
* lands, because nothing forks a context for this pre-init route. Wrapping
* the handler in `withRequestContext` NOW, before any repository call exists
* on this path, means Task 1 converts `jwt-verify.ts` without touching this
* file again and without a single broken photo request in between.
*
* Optional at the type level only, the same shape `TrekWsAdapter` uses for
* its own D6 wrapper (`src/nest/realtime/trek-ws.adapter.ts`): `bootstrap.ts`
* always passes the real `MikroORM` it already resolved. Fail-closed shape
* per the Plan 3b Rulings — a request-time choke point THROWS when the ORM
* is absent rather than running `servePhoto` unwrapped: the photo route
* answers 500 through Express's error path (`next(err)`), the same shape the
* WS adapter's message dispatch already uses (throw before calling the
* handler at all, never a silent degrade).
*/
export function applyPlatformUploads(app: express.Application, storage: StorageService): void {
export function applyPlatformUploads(app: express.Application, storage: StorageService, orm?: { em: EntityManager }): void {
// Static: avatars, covers, and journey photos.
//
// Security model (audit SEC-M9): these paths are unauthenticated by
@@ -155,9 +179,13 @@ export function applyPlatformUploads(app: express.Application, storage: StorageS
// photo's trip. Previously any share token for any trip could request
// any photo filename by UUID — fine in practice because UUIDs are
// unguessable, but the auth model was wrong.
app.get('/uploads/photos/:filename', (req: Request, res: Response, next: NextFunction) =>
servePhoto(storage, req, res).catch(next),
);
app.get('/uploads/photos/:filename', (req: Request, res: Response, next: NextFunction) => {
if (!orm) {
next(new Error('applyPlatformUploads: no MikroORM available to build a request context for /uploads/photos/*'));
return;
}
return withRequestContext(orm, () => servePhoto(storage, req, res)).catch(next);
});
// Block direct access to /uploads/files
app.use('/uploads/files', (_req: Request, res: Response) => {
+12 -1
View File
@@ -166,10 +166,21 @@ export class TrekWsAdapter extends WsAdapter {
// Must stay above anything that can close early: a socket that never gets
// this listener can still crash the process while it finishes closing.
socket.on('error', () => socket.terminate());
// D6 (Plan 3b Task 0): this dispatches Nest's OnGatewayConnection hook
// (RealtimeGateway.handleConnection) exactly the way bindMessageHandlers
// below dispatches a @SubscribeMessage handler — no HTTP request behind
// it, so nothing forks an EntityManager for it unless this ONE wrapper
// does. Confirmed unwrapped before this change (WSAD-050): a repository
// read during the handshake threw cannotUseGlobalContext. Same
// fail-closed shape as bindMessageHandlers: throw before calling rather
// than run the connection handler unwrapped.
if (!this.orm) {
throw new Error('TrekWsAdapter: no MikroORM available to build a request context for this connection');
}
// The request rides along: the handshake reads the ws token off its query
// string, so dropping it here would leave handleConnection with nothing
// to authenticate.
callback(socket, request);
withRequestContext(this.orm, () => callback(socket, request));
});
}