refactor(trips): trip access through TripsRepository; demo seed in a request context; dialect helpers for the trips cluster

This commit is contained in:
jubnl
2026-09-23 04:46:18 +02:00
parent 769b9577ec
commit d2e0d7e320
97 changed files with 1595 additions and 406 deletions
+8 -101
View File
@@ -1,5 +1,4 @@
import { readEnv } from '../app-config';
import { Place, Tag } from '../types';
import { resolveDbPath } from './db-path';
import { applyDurabilityPragmas } from './durability';
import { readSchemaSnapshot } from './schema-snapshot';
@@ -129,104 +128,12 @@ async function reinitialize(): Promise<void> {
console.log('[DB] Database reinitialized successfully');
}
interface PlaceWithCategory extends Place {
category_name: string | null;
category_color: string | null;
category_icon: string | null;
}
// getPlaceWithTags/canAccessTrip/isOwner and the TripAccess/PlaceWithTags
// interfaces lived here through Plan 3c Task 0a's async sweep. Task 0b moved
// their bodies onto TripsRepository.findAccessible/isOwner and
// PlacesRepository.findWithTagsAndRatings — db/repositories/Trips.repository.ts's
// TripAccess is now the single source (db/database.ts's copy is deleted, not
// re-exported); DatabaseService re-exports both type names from the
// repositories that own them now, so no importer's path changed.
interface PlaceWithTags extends Place {
category: { id: number; name: string; color: string; icon: string } | null;
tags: Tag[];
ratings: { user_id: number; username: string; avatar: string | null; rating: number }[];
rating_avg: number | null;
rating_count: number;
}
async function getPlaceWithTags(placeId: number | string): Promise<PlaceWithTags | null> {
const place = db
.prepare(
`
SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
FROM places p
LEFT JOIN categories c ON p.category_id = c.id
WHERE p.id = ?
`,
)
.get(placeId) as PlaceWithCategory | undefined;
if (!place) return null;
const tags = db
.prepare(
`
SELECT t.* FROM tags t
JOIN place_tags pt ON t.id = pt.tag_id
WHERE pt.place_id = ?
`,
)
.all(placeId) as Tag[];
// Collaborative ratings (#1435): every voter with username/avatar for the
// who-voted tooltip; the displayed value is the average.
const ratings = db
.prepare(
`
SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
JOIN users u ON pr.user_id = u.id
WHERE pr.place_id = ? ORDER BY pr.created_at
`,
)
.all(placeId) as { user_id: number; username: string; avatar: string | null; rating: number }[];
return {
...place,
category: place.category_id
? {
id: place.category_id,
name: place.category_name!,
color: place.category_color!,
icon: place.category_icon!,
}
: null,
tags,
ratings,
rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
rating_count: ratings.length,
};
}
interface TripAccess {
id: number;
user_id: number;
currency: string | null;
}
async function canAccessTrip(tripId: number | string, userId: number): Promise<TripAccess | undefined> {
return db
.prepare(
`
SELECT t.id, t.user_id, t.currency FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`,
)
.get(userId, tripId, userId) as TripAccess | undefined;
}
async function isOwner(tripId: number | string, userId: number): Promise<boolean> {
return !!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId);
}
export {
db,
closeDb,
reinitialize,
getPlaceWithTags,
canAccessTrip,
isOwner,
getRawConnection,
registerReinitializeHook,
runDemoSeed,
};
export type { TripAccess, PlaceWithTags };
export { db, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
+82
View File
@@ -127,3 +127,85 @@ export function lowerParam(platform: Platform, value: string): RawQueryFragment
return unsupported(platform);
}
// ---------------------------------------------------------------------------
// Plan 3c Task 0b (R6) — no consumer yet: Tasks 1–8 wire these in as each
// converts the statement that needs them (`place-shadow.service.ts:192`,
// `places.service.ts:642,651-652`, the ~16 `COALESCE` sites across
// `days`/`assignments`/`trip-members`/`places`). Added here, with their own
// SQLF-0xx tests pinning the SQLite text against a raw statement, so a later
// task imports a tested helper instead of writing one inline.
// ---------------------------------------------------------------------------
/**
* `datetime('now', '-N days')` — the SQLite clock shifted backwards by whole
* days, as TEXT (not a stored column's value — `dateAdd` above is the wrong
* shape for this: it shifts a *column*, not "now"). `days` is validated to be
* a non-negative integer and spelled directly into the fragment rather than
* bound: the legacy statement (`place-shadow.service.ts:192`) binds the
* WHOLE modifier string (`'-30 days'`) as one parameter, and MikroORM's raw
* fragments do not accept a placeholder inside the modifier argument of a
* SQLite date/time function — `datetime('now', ?)` with `'-30 days'` bound
* does work in raw SQLite, but composing that shape through a `raw()`
* fragment used as a QueryBuilder value needs the modifier already in the
* SQL text, the same way `dateAdd` above spells its own day count.
*/
export function nowMinusDays(platform: Platform, days: number): RawQueryFragment {
if (!Number.isInteger(days) || days < 0) {
throw new Error(`sql-functions: nowMinusDays needs a non-negative integer day count, got ${days}`);
}
if (platform instanceof SqlitePlatform) return raw(`datetime('now', '-${days} days')`);
return unsupported(platform);
}
/** `TRIM(<col>)`. Pairs with `lower()` for the `LOWER(TRIM(name))` shape (`places.service.ts:642`). */
export function trim(platform: Platform, ref: string): RawQueryFragment {
if (platform instanceof SqlitePlatform) return raw(`TRIM(${column(ref)})`);
return unsupported(platform);
}
/**
* `COALESCE(<col>, <fallbackCol>)` — both sides column references, for the
* `COALESCE(a, b)` SELECT-projection shape (`days.service.ts:93-94`,
* `assignments.service.ts:103-104`, `trip-members.service.ts:116-143`, …).
*
* Not composed by nesting a `RawQueryFragment` inside this one: MikroORM's
* `RawQueryFragment[Symbol.toPrimitive]` only returns a usable value for the
* `'string'` coercion hint (object-key position) — a template-literal
* `${fragment}` embed uses the `'default'` hint and throws
* (`node_modules/@mikro-orm/core/utils/RawQueryFragment.js`, verified
* directly, not assumed). So `coalesce`'s second argument is a second
* `column()`-validated identifier, spelled into the same fragment as the
* first — two columns, one statement, matching `lower`/`lowerParam`'s
* two-function split for the same reason (a filter KEY vs a bound VALUE
* are different shapes).
*/
export function coalesce(platform: Platform, ref: string, fallbackRef: string): RawQueryFragment {
if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ${column(fallbackRef)})`);
return unsupported(platform);
}
/**
* `COALESCE(<col>, ?)` — the value-side twin of `coalesce()` above, for the
* `COALESCE(col, ?)` UPDATE-SET shape (`places.service.ts:344,351,363,…`).
* `value` is bound as a genuine parameter, never interpolated.
*/
export function coalesceParam(platform: Platform, ref: string, value: string | number | null): RawQueryFragment {
if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ?)`, [value]);
return unsupported(platform);
}
/**
* `ABS(<col> - ?)`, for use as a filter KEY (the `'string'`-hint coercion
* `lower()` above relies on) so it composes with `$lte`/`$gte`:
* `{ [absDifference(platform, 'lat', targetLat)]: { $lte: tolerance } }`
* renders `WHERE ABS(lat - ?) <= ?`, matching `places.service.ts:651-652`'s
* `abs(lat - ?) <= ?` (and the sibling `lng` comparison at `:652`) exactly.
* Typed `RawQueryFragment & symbol`, same reason `lower()` is: only a
* `string | number | symbol` is a valid computed property name, and the
* brand only lives on that typing for values meant to be used as a key.
*/
export function absDifference(platform: Platform, ref: string, value: number): RawQueryFragment & symbol {
if (platform instanceof SqlitePlatform) return raw(`ABS(${column(ref)} - ?)`, [value]);
return unsupported(platform);
}
+16 -1
View File
@@ -1,5 +1,6 @@
import mikroOrmConfig from '../mikro-orm.config';
import { registerReinitializeHook, runDemoSeed } from './database';
import { withRequestContext } from '../nest/database/request-context';
import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriver, MikroORM } from '@mikro-orm/core';
import type { Migrator } from '@mikro-orm/migrations';
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
@@ -41,7 +42,21 @@ export async function runSchemaBootstrap(orm: AnyOrm): Promise<void> {
// Demo data depends on the seeded categories (hard-coded ids under an FK), so
// it can only run once the seeders above have.
runDemoSeed();
//
// Plan 3c Task 0b (R9): `runDemoSeed` itself stays raw better-sqlite3 today
// (`demo-seed.ts`'s own docstring: "the domain phase that gives demo
// seeding a repository read must wrap it in withRequestContext then") — but
// wrapping the call HERE, the one place `runSchemaBootstrap` already has
// `orm` in scope, covers BOTH of its real call sites at once
// (`bootstrap.ts`'s initial boot and `attachOrm`'s restore hook below, both
// of which only ever reach `runDemoSeed` through this function) with no
// second wrapper to keep in sync. A synchronous `fn` stays synchronous
// through `withRequestContext`/`RequestContext.create`, so this changes
// nothing about what `runDemoSeed` does today — only that a repository read
// added to it later already has a valid context, so Plan 3i's demo
// conversion never meets a second C1 (task-6-review-parity.md's boot-sweep
// finding).
withRequestContext(orm, () => runDemoSeed());
}
/**
+141 -1
View File
@@ -1,4 +1,144 @@
import type { Places } from '../entities/Places.entity';
import type { Tags } from '../entities/Tags.entity';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
export class PlacesRepository extends TrekRepository<Places> {}
/** A `places` row as the API emits it — every scalar column of the entity. */
export interface PlaceRow {
id: number;
trip_id: number;
name: string;
description: string | null;
lat: number | null;
lng: number | null;
address: string | null;
category_id: number | null;
price: number | null;
currency: string | null;
reservation_status: string | null;
reservation_notes: string | null;
reservation_datetime: string | null;
place_time: string | null;
end_time: string | null;
duration_minutes: number | null;
notes: string | null;
image_url: string | null;
google_place_id: string | null;
google_ftid: string | null;
website: string | null;
phone: string | null;
transport_mode: string | null;
created_at: string | null;
updated_at: string | null;
osm_id: string | null;
route_geometry: string | null;
route_color: string | null;
stop_type: string | null;
fill_percent: number | null;
amap_poi_id: string | null;
source: string | null;
}
const _placeRowKeys: AssertRowKeys<PlaceRow, Places> = true;
/** A `tags` row, byte-identical to the legacy `SELECT t.* FROM tags t ...` shape. */
export interface TagRow {
id: number;
user_id: number;
name: string;
color: string | null;
created_at: string | null;
}
const _tagRowKeys: AssertRowKeys<TagRow, Tags> = true;
interface PlaceWithCategoryRow extends PlaceRow {
category_name: string | null;
category_color: string | null;
category_icon: string | null;
}
interface PlaceRatingRow {
user_id: number;
username: string;
avatar: string | null;
rating: number;
}
/**
* `getPlaceWithTags` (`db/database.ts:146-197`, 0b's Concern for Task 4):
* the 11 `PlacesService` call sites move in Task 4, so `DatabaseService
* .getPlaceWithTags` keeps its own name/shape and delegates to this method
* NOW — no caller beyond `DatabaseService` changes in this task.
*/
export interface PlaceWithTagsRow extends PlaceRow {
category: { id: number; name: string; color: string; icon: string } | null;
tags: TagRow[];
ratings: PlaceRatingRow[];
rating_avg: number | null;
rating_count: number;
}
export class PlacesRepository extends TrekRepository<Places> {
/**
* The legacy `getPlaceWithTags`'s three statements, byte-for-byte in intent
* (`mapResults: false` on every read, matching `TripsRepository
* .findAccessible`/`InviteTokensRepository.listWithCreatorAndTrip`):
*
* ```sql
* SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
* FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
*
* SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?
*
* SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
* JOIN users u ON pr.user_id = u.id WHERE pr.place_id = ? ORDER BY pr.created_at
* ```
*
* `p.category`/`p.place_tags`/`p.place_ratings_collection` are the entity's
* own relation properties for these three joins (`Places.entity.ts`), so no
* hand-spelled join condition is needed; `pr.user` resolves to the
* `place_ratings.user_id` FK column the same way `TripsRepository
* .findAccessible`'s `t.user` resolves to `trips.user_id`.
*/
async findWithTagsAndRatings(place_id: number | string): Promise<PlaceWithTagsRow | null> {
// Raw conditions (D4's T5 escape hatch), not `.where({ 'p.id': place_id })`:
// MikroORM's typed filter rejects a `string` against `p.id`'s branded
// `number` type — matching `TripsRepository.findAccessible`'s own
// raw-bind seam (`legacy getPlaceWithTags(placeId: number | string)`
// bound the raw value with no `Number()` conversion). `p.id` is the
// physical column name.
const place = await this.qb('p')
.leftJoin('p.category', 'c')
.select(['p.*', 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon'])
.where('p.id = ?', [place_id])
.execute<PlaceWithCategoryRow | undefined>('get', false);
if (!place) return null;
const tags = await this.qb('p')
.join('p.place_tags', 't')
.select(['t.*'])
.where('p.id = ?', [place_id])
.execute<TagRow[]>('all', false);
const ratings = await this.qb('p')
.join('p.place_ratings_collection', 'pr')
.join('pr.user', 'u')
.select(['pr.user', 'u.username', 'u.avatar', 'pr.rating'])
.where('p.id = ?', [place_id])
.orderBy({ 'pr.created_at': 'asc' })
.execute<PlaceRatingRow[]>('all', false);
const { category_name, category_color, category_icon, ...placeRest } = place;
return {
...placeRest,
category: place.category_id
? { id: place.category_id, name: category_name!, color: category_color!, icon: category_icon! }
: null,
tags,
ratings,
rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
rating_count: ratings.length,
};
}
}
@@ -1,4 +1,45 @@
import type { TripMembers } from '../entities/TripMembers.entity';
import { Trips } from '../entities/Trips.entity';
import { TrekRepository } from './_shared/trek-repository';
export class TripMembersRepository extends TrekRepository<TripMembers> {}
export class TripMembersRepository extends TrekRepository<TripMembers> {
/**
* The user ids a trip may refer to: its members plus the owner. Byte-for-byte
* the legacy `DatabaseService.rosterUserIds`'s statement in intent —
* `SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id
* FROM trips WHERE id = ?` — as two reads merged through a `Set` (which
* already dedupes, the same guarantee `UNION` gives) rather than one `UNION`
* statement: the two `SELECT`s read different tables with no FK between
* them, so a single-entity `QueryBuilder` (rooted on `TripMembers`) cannot
* express the second half without losing rows on a trip that has no
* members yet — an inner join from `trip_members` would produce zero rows
* for exactly the case (an owner-only trip) the legacy statement's second
* `SELECT` exists to cover. `trips` has no `TripMembersRepository` field to
* reach it through, so this repository asks the `EntityManager` for
* `TripsRepository` the same way `DatabaseService`/the guards resolve a
* repository outside their own entity — one `EntityManager`, two
* repositories, two independent reads.
*/
async rosterUserIds(trip_id: number | string): Promise<Set<number>> {
// Raw conditions (D4's T5 escape hatch), not `.where({ 'm.trip': trip_id })`:
// MikroORM's typed filter rejects a `string` against the relation's
// branded id type, and coercing to `Number(trip_id)` first would change
// the raw-bind id-shape parity `TripsRepository`'s docstring describes.
// `m.trip_id`/`t.id` are the physical column names.
const members = await this.qb('m')
.select(['m.user'])
.where('m.trip_id = ?', [trip_id])
.execute<{ user_id: number }[]>('all', false);
const trips = this.getEntityManager().getRepository(Trips);
const owner = await trips
.qb('t')
.select(['t.user'])
.where('t.id = ?', [trip_id])
.execute<{ user_id: number } | undefined>('get', false);
const ids = new Set(members.map((m) => m.user_id));
if (owner) ids.add(owner.user_id);
return ids;
}
}
+28 -4
View File
@@ -16,12 +16,31 @@ export class TripsRepository extends TrekRepository<Trips> {
* SELECT t.id, t.user_id, t.currency FROM trips t
* LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
* WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
*
* `trip_id: number | string` (Plan 3c Task 0b): the legacy free function
* bound whatever `req.params.tripId` resolved to straight into the
* statement with no `Number()`/`toRowId` conversion first — the raw-bind
* seam. `TripAccessGuard` still does `Number(tripId)` before calling this
* (unchanged), but `DatabaseService.canAccessTrip`/`isOwner` and every
* other of the 41 in-cluster callers pass a `number | string` through
* unconverted, so this method (and `isOwner` below) must accept and bind
* that raw value rather than coerce it — a coercion here would silently
* change the `'0x10'`/`'007'`-shaped id parity the boot matrix pins
* (`Number('0x10') === 16`, a real trip id, where SQLite's own text/integer
* affinity comparison of the unconverted string never matches one).
*/
async findAccessible(trip_id: number, user_id: number): Promise<TripAccess | undefined> {
async findAccessible(trip_id: number | string, user_id: number): Promise<TripAccess | undefined> {
const row = await this.qb('t')
.select(['t.id', 't.user', 't.currency'])
.leftJoin('t.trip_members_collection', 'm', { 'm.user': user_id })
.where({ 't.id': trip_id })
// Raw condition (D4's T5 escape hatch), not `.where({ 't.id': trip_id })`:
// MikroORM's typed filter rejects a `string` against `t.id`'s branded
// `number` type, and coercing to `Number(trip_id)` first would be
// exactly the parity break the class docstring above describes.
// `t.id`/`t.user_id` are the physical column names (not translated
// through the entity's `trip`/`user` property aliasing the way a typed
// filter object is), so the raw text names them directly.
.where('t.id = ?', [trip_id])
.andWhere({ $or: [{ 't.user': user_id }, { 'm.user': { $ne: null } }] })
// `mapResults: false` leaves the driver's row alone: the keys are the
// column names, which is why the result type is spelled out here rather
@@ -32,7 +51,12 @@ export class TripsRepository extends TrekRepository<Trips> {
}
/** `SELECT id FROM trips WHERE id = ? AND user_id = ?` */
async isOwner(trip_id: number, user_id: number): Promise<boolean> {
return (await this.count({ id: trip_id, user: user_id })) > 0;
async isOwner(trip_id: number | string, user_id: number): Promise<boolean> {
const row = await this.qb('t')
.select(['t.id'])
.where('t.id = ?', [trip_id])
.andWhere({ user: user_id })
.execute<{ id: number } | undefined>('get', false);
return !!row;
}
}
+61 -18
View File
@@ -1,10 +1,21 @@
import { Inject, Injectable } from '@nestjs/common';
import { Inject, Injectable, Optional } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import type Database from 'better-sqlite3';
import { canAccessTrip, getPlaceWithTags, isOwner } from '../../db/database';
import type { PlaceWithTags, TripAccess } from '../../db/database';
import { Trips } from '../../db/entities/Trips.entity';
import { TripMembers } from '../../db/entities/TripMembers.entity';
import { Places } from '../../db/entities/Places.entity';
import type { TripAccess } from '../../db/repositories/Trips.repository';
import type { PlaceWithTagsRow as PlaceWithTags } from '../../db/repositories/Places.repository';
import { DATABASE_CONNECTION } from './database.tokens';
export type { PlaceWithTags, TripAccess };
// Plan 3c Task 0b: `TripAccess`/`PlaceWithTags` used to be db/database.ts's
// own interfaces, re-exported from here (§18.1's duplicate-declaration
// surprise). Both are deleted there now — `Trips.repository.ts`'s
// `TripAccess` and `Places.repository.ts`'s `PlaceWithTagsRow` are the single
// sources, re-exported under their original names so every one of the ~40
// importers of `{ TripAccess, PlaceWithTags }` from this module needs no
// change.
export type { TripAccess, PlaceWithTags };
/**
* Injectable wrapper around TREK's existing better-sqlite3 connection.
@@ -15,7 +26,26 @@ export type { PlaceWithTags, TripAccess };
*/
@Injectable()
export class DatabaseService {
constructor(@Inject(DATABASE_CONNECTION) private readonly conn: Database.Database) {}
constructor(
@Inject(DATABASE_CONNECTION) private readonly conn: Database.Database,
// Plan 3c Task 0b: `canAccessTrip`/`isOwner`/`rosterUserIds`/
// `getPlaceWithTags` moved off the raw better-sqlite3 singleton onto
// TripsRepository/TripMembersRepository/PlacesRepository, which need an
// EntityManager to resolve — `@Optional()` (not just `?`, which is
// TS-only and does not tell Nest's DI the provider may be absent),
// matching CronRegistrarService's own `@Optional() orm` ruling: this
// service is provided by the `@Global()` DatabaseModule, which some e2e
// harnesses compose standalone without MikroOrmModule.forRoot in the
// container (see `orm.module.ts`'s docstring) — a hard EntityManager
// dependency here would fail every one of those at `compile()`, the same
// class of break `@InjectRepository` would cause (D5). Production
// (buildApp) always has it, since `MikroOrmModule.forRoot`'s core module
// is itself `@Global()` — the same resolution `JwtAuthGuard` relies on.
// A hand-built `DatabaseService` in a unit test that calls one of the
// four methods below must pass one explicitly (`sharedTestOrm(db)).em`),
// same as `createTestUsersRepo`'s callers do for `UsersRepository`.
@Optional() private readonly em?: EntityManager,
) {}
/** The shared better-sqlite3 connection (same singleton the legacy app uses). */
get connection(): Database.Database {
@@ -38,17 +68,29 @@ export class DatabaseService {
return this.conn.prepare(sql).run(...params);
}
// Trip-access helpers delegate to the db/database exports (not this.conn):
// tests vi.mock that module and stub the helpers themselves, so the stubs
// must keep flowing through here.
/**
* The EntityManager the four repository-backed methods below resolve their
* repository through. Throws its OWN clear error when absent — never
* MikroORM's generic "global EntityManager" wording — so a hand-built
* instance that forgot to pass one fails loudly and distinctly, the same
* fail-closed shape `CronRegistrarService.runOnBoot` uses.
*/
private entityManager(): EntityManager {
if (!this.em) {
throw new Error(
'DatabaseService: no EntityManager available — construct with one (Nest DI supplies it in production) to call canAccessTrip/isOwner/rosterUserIds/getPlaceWithTags',
);
}
return this.em;
}
/** Trip visible to the user (owner or member); undefined when no access. */
async canAccessTrip(tripId: number | string, userId: number): Promise<TripAccess | undefined> {
return await canAccessTrip(tripId, userId);
return await this.entityManager().getRepository(Trips).findAccessible(tripId, userId);
}
async isOwner(tripId: number | string, userId: number): Promise<boolean> {
return await isOwner(tripId, userId);
return await this.entityManager().getRepository(Trips).isOwner(tripId, userId);
}
/**
@@ -59,18 +101,19 @@ export class DatabaseService {
* This is canAccessTrip's question asked as a set rather than a predicate, so
* it lives beside it. Domains that accept user ids in a write body intersect
* against it: holding the permission says you may edit the trip, not that any
* id you name belongs to it. Runs on the connection rather than delegating to
* db/database, because it has no legacy export to stay parity with.
* id you name belongs to it.
*/
async rosterUserIds(tripId: number | string): Promise<Set<number>> {
const rows = this.all<{ user_id: number }>(
'SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id FROM trips WHERE id = ?',
tripId, tripId,
);
return new Set(rows.map(r => r.user_id));
return await this.entityManager().getRepository(TripMembers).rosterUserIds(tripId);
}
/**
* Delegates to `PlacesRepository.findWithTagsAndRatings` (Plan 3c Task 0b).
* `PlacesService`'s 11 call sites are Task 4's — this method keeps its own
* name/shape on `DatabaseService` for now, so Task 4 is the only future
* change those 11 sites need.
*/
async getPlaceWithTags(placeId: number | string): Promise<PlaceWithTags | null> {
return await getPlaceWithTags(placeId);
return await this.entityManager().getRepository(Places).findWithTagsAndRatings(placeId);
}
}
@@ -1,7 +1,9 @@
import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { DatabaseService, type TripAccess } from '../database/database.service';
import { Trips } from '../../db/entities/Trips.entity';
import type { TripAccess } from '../database/database.service';
import { PermissionsService } from './permissions.service';
import type { User } from '../../types';
@@ -38,11 +40,23 @@ type TripRequest = Request & { user?: User; [TRIP_REQUEST_KEY]?: TripAccess };
* It deliberately does NOT replace the `verifyTripAccess`/`canEdit` methods on the
* domain services. Of their callers, the large majority are `*.mcp.ts` tools, which
* never pass through an HTTP guard; those methods stay exactly where they are.
*
* Injects `EntityManager`, not `DatabaseService`/`@InjectRepository(Trips)`
* (Plan 3c Task 0b, the `JwtAuthGuard` precedent): this guard is applied via
* `@UseGuards(…, TripAccessGuard)` on 146 handlers across 22 controller
* classes, and Nest resolves a class-referenced guard's constructor
* dependencies from the HOST CONTROLLER'S OWN module graph —
* `@InjectRepository(Trips)` would need `MikroOrmModule.forFeature([Trips])`
* added to every one of those modules (D5's blast radius). `EntityManager`
* comes from `MikroOrmModule.forRoot`'s core module, which IS `@Global()`, so
* no module needs new wiring. `this.em.getRepository(Trips)` inside
* `canActivate` is the same per-request resolution `JwtAuthGuard` uses for
* `Users`.
*/
@Injectable()
export class TripAccessGuard implements CanActivate {
constructor(
private readonly db: DatabaseService,
private readonly em: EntityManager,
private readonly permissions: PermissionsService,
private readonly reflector: Reflector,
) {}
@@ -56,7 +70,7 @@ export class TripAccessGuard implements CanActivate {
if (!user) throw new HttpException({ error: 'Unauthorized' }, 401);
const tripId = Number((request.params as Record<string, string>)?.tripId);
const trip = Number.isFinite(tripId) ? await this.db.canAccessTrip(tripId, user.id) : undefined;
const trip = Number.isFinite(tripId) ? await this.em.getRepository(Trips).findAccessible(tripId, user.id) : undefined;
// A trip the user may not see is reported as absent, never as forbidden: a 403
// would confirm the id exists to someone who has no business knowing.
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
@@ -1,7 +1,9 @@
import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { EntityManager } from '@mikro-orm/core';
import type { Request } from 'express';
import { DatabaseService, type TripAccess } from '../database/database.service';
import { Trips } from '../../db/entities/Trips.entity';
import type { TripAccess } from '../database/database.service';
import { TRIP_REQUEST_KEY } from './trip-access.guard';
import type { User } from '../../types';
@@ -43,11 +45,21 @@ type TripRequest = Request & { user?: User; [TRIP_REQUEST_KEY]?: TripAccess };
* Absent access is a 404, never a 403, for the same reason TripAccessGuard does
* it that way: a 403 would confirm the id exists to someone who has no business
* knowing. A 403 only ever goes to somebody who can already see the trip.
*
* Injects `EntityManager`, not `DatabaseService` (Plan 3c Task 0b, the
* `task-0a-review-security.md` F-A1 correction): `trip-members.controller.ts`
* has no class-level `TripAccessGuard` (its own docstring explains why —
* guards run before pipes and the e2e suite pins the error ordering), so on
* its four owner-only routes `request[TRIP_REQUEST_KEY]` is never parked and
* THIS guard's own lookup at `:73` below is the sole access check standing
* between a stranger and those routes — the same `TripAccessGuard` precedent
* applies here for the same reason (`EntityManager` is `@Global()`, no
* module needs new wiring; `@InjectRepository(Trips)` would).
*/
@Injectable()
export class TripOwnerGuard implements CanActivate {
constructor(
private readonly db: DatabaseService,
private readonly em: EntityManager,
private readonly reflector: Reflector,
) {}
@@ -70,7 +82,7 @@ export class TripOwnerGuard implements CanActivate {
let trip = request[TRIP_REQUEST_KEY];
if (!trip) {
const tripId = Number((request.params as Record<string, string>)?.[meta?.param ?? 'tripId']);
trip = Number.isFinite(tripId) ? (await this.db.canAccessTrip(tripId, user.id)) ?? undefined : undefined;
trip = Number.isFinite(tripId) ? (await this.em.getRepository(Trips).findAccessible(tripId, user.id)) ?? undefined : undefined;
if (trip) request[TRIP_REQUEST_KEY] = trip;
}
if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
@@ -104,8 +104,18 @@ export class TripCardContributionsController {
.filter((n) => Number.isInteger(n) && n > 0)
.slice(0, MAX_TRIP_IDS);
const uniqueRequested = [...new Set(requested)];
const accessFlags = await Promise.all(uniqueRequested.map((id) => this.dbs.canAccessTrip(id, userId)));
const accessible = uniqueRequested.filter((_, i) => accessFlags[i]);
// Sequential, not `Promise.all` (Plan 3c Task 0b, task-0a-review-security.md
// F-A5): the 0a async sweep's `Promise.all` was a runtime no-op then (every
// read settled on the SAME synchronous free function), but `canAccessTrip`
// is a genuine repository read now — dispatching `uniqueRequested.length`
// of them concurrently would run up to `MAX_TRIP_IDS` queries against one
// forked EntityManager at once, which MikroORM does not support. `accessible`
// is passed positionally to `hooks.tripCards` below, so the order this
// produces (the filtered `uniqueRequested` order) is load-bearing.
const accessible: number[] = [];
for (const id of uniqueRequested) {
if (await this.dbs.canAccessTrip(id, userId)) accessible.push(id);
}
if (accessible.length === 0) return { contributions: [] };
const allowed = new Set(accessible);
+11 -2
View File
@@ -1,6 +1,8 @@
import { Injectable } from '@nestjs/common';
import path from 'path';
import { EntityManager } from '@mikro-orm/core';
import { DatabaseService } from '../database/database.service';
import { Trips } from '../../db/entities/Trips.entity';
import { MAX_TRIP_DAYS, tripSpanDays, type ActiveTrip, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
@@ -161,6 +163,13 @@ export class TripsService {
private readonly unsplash: UnsplashService,
private readonly storage: StorageService,
private readonly uow: UnitOfWork,
// Plan 3c Task 0b (task-0a-review-security.md F-A1): `canAccessTrip`/
// `isOwner` below resolve `TripsRepository` directly through this,
// rather than through `this.dbs.canAccessTrip`/`isOwner` — the third of
// the security review's three sites, alongside `TripAccessGuard` and
// `TripOwnerGuard`. `EntityManager` is `@Global()` (`MikroOrmModule
// .forRoot`'s core module), so no module needs new wiring.
private readonly em: EntityManager,
) {}
private get db() {
@@ -168,12 +177,12 @@ export class TripsService {
}
async canAccessTrip(tripId: string | number, userId: number) {
const access = await this.dbs.canAccessTrip(tripId, userId);
const access = await this.em.getRepository(Trips).findAccessible(tripId, userId);
return access as { user_id: number } | null | undefined;
}
async isOwner(tripId: string | number, userId: number): Promise<boolean> {
return await this.dbs.isOwner(tripId, userId);
return await this.em.getRepository(Trips).isOwner(tripId, userId);
}
async can(action: string, role: string, ownerId: number | null, userId: number, isMember: boolean): Promise<boolean> {