mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +00:00
fix(db): read every request row id through toRowId, at the trip guards and the repository lookups
toRowId moves to src/db/row-id.ts so repositories can use it (src/db sits below src/nest), together with a new withRowId helper; src/nest/common/row-id.ts re-exports both. Its docstring is rewritten to state the rule plainly. TripsRepository read its number | string trip ids raw: SQLite matched '0x1' against nothing, Postgres 14 and 15 refused the cast with a 500, and 16 and later read it as trip 1. Its access reads, DaysRepository.existsInTrip and the packing template lookups now parse the id first, so an id toRowId refuses is no row on every engine. TripAccessGuard, TripOwnerGuard and JourneyAssistantGuard used Number(), which read '0x1' and '1e0' as row 1; they now use toRowId.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { columnRef } from '../dialect/sql-functions';
|
||||
import type { Days } from '../entities/Days.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
import { toRow, type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -284,15 +285,18 @@ export class DaysRepository extends TrekRepository<Days> {
|
||||
|
||||
/**
|
||||
* AS4 (`AssignmentsService.dayExists`) — `SELECT id FROM days WHERE id = ?
|
||||
* AND trip_id = ?`. Raw-bind (`number | string`, D4's T5 escape hatch,
|
||||
* `TripsRepository.findAccessible`'s precedent): the legacy guard binds
|
||||
* the route's raw params with no `Number()`/`toRowId` conversion of its
|
||||
* own, so this must accept and bind exactly what it's handed.
|
||||
* AND trip_id = ?`. Its callers hand over the route's ids as they came, so
|
||||
* both are read through `toRowId` (as in `TripsRepository.findAccessible`):
|
||||
* a spelling it refuses is no day on every engine, where bound raw Postgres
|
||||
* refused or reinterpreted it and SQLite matched nothing.
|
||||
*/
|
||||
async existsInTrip(id: number | string, trip_id: number | string): Promise<boolean> {
|
||||
const dayId = toRowId(id);
|
||||
const tripId = toRowId(trip_id);
|
||||
if (dayId === null || tripId === null) return false;
|
||||
const row = await this.qb('d')
|
||||
.select(['d.id'])
|
||||
.where('d.id = ? AND d.trip_id = ?', [id, trip_id])
|
||||
.where('d.id = ? AND d.trip_id = ?', [dayId, tripId])
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
return !!row;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PackingTemplateCategories } from '../entities/PackingTemplateCategories.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -75,11 +76,15 @@ export class PackingTemplateCategoriesRepository extends TrekRepository<PackingT
|
||||
id: number | string,
|
||||
template_id: number | string,
|
||||
): Promise<PackingTemplateCategoryRow | undefined> {
|
||||
// Route ids: a spelling toRowId refuses is no category, on every engine.
|
||||
const categoryId = toRowId(id);
|
||||
const templateId = toRowId(template_id);
|
||||
if (categoryId === null || templateId === null) return undefined;
|
||||
return await this.db()
|
||||
.selectFrom('packing_template_categories')
|
||||
.selectAll()
|
||||
.where('id', '=', id as number)
|
||||
.where('template_id', '=', template_id as number)
|
||||
.where('id', '=', categoryId)
|
||||
.where('template_id', '=', templateId)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PackingTemplateItems } from '../entities/PackingTemplateItems.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -133,12 +134,16 @@ export class PackingTemplateItemsRepository extends TrekRepository<PackingTempla
|
||||
* `updateTemplateItem` and `deleteTemplateItem` (two call sites).
|
||||
*/
|
||||
async findScoped(id: number | string, template_id: number | string): Promise<PackingTemplateItemRow | undefined> {
|
||||
// Route ids: a spelling toRowId refuses is no item, on every engine.
|
||||
const itemId = toRowId(id);
|
||||
const templateId = toRowId(template_id);
|
||||
if (itemId === null || templateId === null) return undefined;
|
||||
return await this.db()
|
||||
.selectFrom('packing_template_items as ti')
|
||||
.innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id')
|
||||
.selectAll('ti')
|
||||
.where('ti.id', '=', id as number)
|
||||
.where('tc.template_id', '=', template_id as number)
|
||||
.where('ti.id', '=', itemId)
|
||||
.where('tc.template_id', '=', templateId)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PackingTemplates } from '../entities/PackingTemplates.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -109,11 +110,10 @@ export class PackingTemplatesRepository extends TrekRepository<PackingTemplates>
|
||||
* `deletePackingTemplate`'s existence check). One method, five sites.
|
||||
*/
|
||||
async findById(id: number | string): Promise<PackingTemplateRow | undefined> {
|
||||
return await this.db()
|
||||
.selectFrom('packing_templates')
|
||||
.selectAll()
|
||||
.where('id', '=', id as number)
|
||||
.executeTakeFirst();
|
||||
// A route id toRowId refuses is no template, on every engine.
|
||||
const templateId = toRowId(id);
|
||||
if (templateId === null) return undefined;
|
||||
return await this.db().selectFrom('packing_templates').selectAll().where('id', '=', templateId).executeTakeFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
import { tripAccessExpr } from './_shared/trip-access';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
|
||||
/** What a trip-scoped request learns about the trip once access is verified. */
|
||||
export interface TripAccess {
|
||||
@@ -110,19 +111,16 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* 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).
|
||||
* `trip_id: number | string`: most of its callers hand over a route or
|
||||
* tool id as it came. The legacy statement bound it raw, which SQLite
|
||||
* compared by affinity (`'0x10'` matched nothing) while Postgres 14 and 15
|
||||
* refused the cast with an error and 16 and later read `'0x10'` as 16. So
|
||||
* this method and the other `number | string` reads below parse the id
|
||||
* with `toRowId` first: a spelling it refuses is no trip on every engine.
|
||||
*/
|
||||
async findAccessible(trip_id: number | string, user_id: number): Promise<TripAccess | undefined> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
const row = await this.accessibleTripsQuery(user_id)
|
||||
.select(['t.id', 't.user', 't.currency'])
|
||||
// Raw condition (D4's T5 escape hatch), not `.where({ 't.id': trip_id })`:
|
||||
@@ -132,7 +130,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
// `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.
|
||||
.andWhere('t.id = ?', [trip_id])
|
||||
.andWhere('t.id = ?', [id])
|
||||
// `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
|
||||
// than inferred from the entity's properties.
|
||||
@@ -187,9 +185,11 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
|
||||
/** `SELECT id FROM trips WHERE id = ? AND user_id = ?` */
|
||||
async isOwner(trip_id: number | string, user_id: number): Promise<boolean> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return false;
|
||||
const row = await this.qb('t')
|
||||
.select(['t.id'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.where('t.id = ?', [id])
|
||||
.andWhere({ user: user_id })
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
return !!row;
|
||||
@@ -199,13 +199,13 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* `SELECT user_id FROM trips WHERE id = ?` (`trip-membership.service.ts:23`,
|
||||
* TB1) — `row ? row.user_id : null` stays the caller's decision to make
|
||||
* ("owner id for budget/MCP guards"); this returns exactly that shape.
|
||||
* Raw-bind (D4's T5 escape hatch), same `number | string` seam as
|
||||
* `findAccessible`/`isOwner` above.
|
||||
*/
|
||||
async getOwnerId(trip_id: number | string): Promise<number | null> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return null;
|
||||
const row = await this.qb('t')
|
||||
.select(['t.user'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.where('t.id = ?', [id])
|
||||
.execute<{ user_id: number } | undefined>('get', false);
|
||||
return row ? row.user_id : null;
|
||||
}
|
||||
@@ -215,8 +215,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* TB4) — `joinTripAsMember`'s first check-then-act read (§18.4: the
|
||||
* sequence stays non-transactional, unchanged by this conversion). The
|
||||
* only caller (`TripMembershipService.joinTripAsMember(tripId: number, …)`)
|
||||
* always passes a real `number`, so this takes one too — no raw-bind seam
|
||||
* to preserve here, unlike `findAccessible`/`isOwner`/`getOwnerId`.
|
||||
* always passes a real `number`, so this takes one too.
|
||||
*/
|
||||
async findIdAndOwner(trip_id: number): Promise<{ id: number; user_id: number } | undefined> {
|
||||
return this.qb('t')
|
||||
@@ -290,13 +289,14 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
/**
|
||||
* `SELECT title FROM trips WHERE id = ?` (`trip-members.service.ts:156`,
|
||||
* TM7) — `addMember`'s notification-body read; the caller applies its own
|
||||
* `?? 'Untitled'` fallback (D4). Raw-bind (D4's T5 escape hatch), the same
|
||||
* `number | string` seam `findAccessible` documents.
|
||||
* `?? 'Untitled'` fallback (D4).
|
||||
*/
|
||||
async getTitle(trip_id: number | string): Promise<string | null> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return null;
|
||||
const row = await this.qb('t')
|
||||
.select(['t.title'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.where('t.id = ?', [id])
|
||||
.execute<{ title: string } | undefined>('get', false);
|
||||
return row?.title ?? null;
|
||||
}
|
||||
@@ -306,12 +306,13 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* (`trip-members.service.ts:180`, TM9) — `transferOwnership`'s first
|
||||
* check-then-act read (miss → 404 `'Trip not found'`; wrong owner → 400
|
||||
* `'Only the owner can transfer ownership'`, both decided by the caller).
|
||||
* Raw-bind, the same seam as `getTitle` above.
|
||||
*/
|
||||
async findIdTitleOwner(trip_id: number | string): Promise<{ id: number; title: string; user_id: number } | undefined> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
return this.qb('t')
|
||||
.select(['t.id', 't.title', 't.user'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.where('t.id = ?', [id])
|
||||
.execute<{ id: number; title: string; user_id: number } | undefined>('get', false);
|
||||
}
|
||||
|
||||
@@ -341,13 +342,14 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* `.select(['t.*'])` — MikroORM's QueryBuilder recognises the bare
|
||||
* `<alias>.*` marker (verified against `QueryBuilder.js`'s own
|
||||
* `prepareFields`, not assumed) and emits every column unprefixed, the
|
||||
* same `SELECT t.*` shape the legacy statement used. Raw-bind, the same
|
||||
* `number | string` seam `getTitle`/`findIdTitleOwner` above preserve.
|
||||
* same `SELECT t.*` shape the legacy statement used.
|
||||
*/
|
||||
async findRaw(trip_id: number | string): Promise<TripRawRow | null> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return null;
|
||||
const row = await this.qb('t')
|
||||
.select(['t.*'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.where('t.id = ?', [id])
|
||||
.execute<TripRawRow | undefined>('get', false);
|
||||
return row ?? null;
|
||||
}
|
||||
@@ -400,7 +402,9 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* same apart from `is_owner`.
|
||||
*/
|
||||
async findListShapeById(trip_id: number | string, user_id: number): Promise<TripSelectRow | undefined> {
|
||||
const row = await this.tripSelectQuery(user_id).where('t.id', '=', trip_id as number).executeTakeFirst();
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
const row = await this.tripSelectQuery(user_id).where('t.id', '=', id).executeTakeFirst();
|
||||
return row as TripSelectRow | undefined;
|
||||
}
|
||||
|
||||
@@ -418,15 +422,14 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* `TripMembersService.getTripForViewer` (TM1, Task 6 review's "for Task
|
||||
* 7" note) — same reasoning: every caller already holds access.
|
||||
*
|
||||
* Raw-bind (`number | string`, D4's T5 escape hatch — `TripSelectKyselyDB`'s
|
||||
* `trips.id` is typed `number | string` for exactly this): the legacy
|
||||
* statement bound the route's unconverted `tripId` with no `Number()`/
|
||||
* `toRowId` conversion, matching `findAccessible`'s documented seam.
|
||||
* `trip_id` is read through `toRowId`, as in `findAccessible`.
|
||||
*/
|
||||
async findForViewer(trip_id: number | string, user_id: number): Promise<TripSelectRow | undefined> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
const row = await this.tripSelectQuery(user_id)
|
||||
.leftJoin('trip_members as m', (join) => join.onRef('m.trip_id', '=', 't.id').on('m.user_id', '=', user_id))
|
||||
.where('t.id', '=', trip_id as number)
|
||||
.where('t.id', '=', id)
|
||||
.where((eb) => tripAccessExpr(eb, 't.user_id', 'm.user_id', user_id))
|
||||
.executeTakeFirst();
|
||||
return row as TripSelectRow | undefined;
|
||||
@@ -769,14 +772,9 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* access check here, matching the legacy statement — the caller's own
|
||||
* `verifyTripAccess`/token validity gates this read.
|
||||
*
|
||||
* `id: number` (Plan 4 Task 8a, rule 23): unlike `findAccessible`/
|
||||
* `isOwner`, this is never on the guard's raw-`req.params` path — its one
|
||||
* caller (`share.service.ts#getSharedTripData`) passes `shareRow.trip_id`,
|
||||
* a `number` straight off a Kysely-typed `share_tokens` row, never an
|
||||
* unconverted URL param — so the `number | string` raw-bind seam those
|
||||
* two methods' own docstrings describe does not apply here, and this one
|
||||
* narrows to a typed filter now rather than waiting on that seam's guard-
|
||||
* level parse (deferred, out of this task's scope).
|
||||
* `id: number` (Plan 4 Task 8a, rule 23): its one caller
|
||||
* (`share.service.ts#getSharedTripData`) passes `shareRow.trip_id`, a
|
||||
* `number` straight off a Kysely-typed `share_tokens` row.
|
||||
*/
|
||||
async findPublicForShare(id: number): Promise<TripPublicShareRow | undefined> {
|
||||
return await this.qb('t')
|
||||
@@ -817,11 +815,13 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** BG15/BG16/BGM2/BGM3 — `SELECT currency FROM trips WHERE id = ?`, four legacy call sites, one statement. */
|
||||
async getCurrency(id: number | string): Promise<string | null | undefined> {
|
||||
async getCurrency(trip_id: number | string): Promise<string | null | undefined> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
const row = await this.kysely<Pick<DB, 'trips'>>()
|
||||
.selectFrom('trips')
|
||||
.select('currency')
|
||||
.where('id', '=', id as number)
|
||||
.where('id', '=', id)
|
||||
.executeTakeFirst();
|
||||
return row?.currency;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* How a row id that arrives as text becomes a number before it reaches SQL.
|
||||
* `src/nest/common/row-id.ts` re-exports both helpers for the Nest layers.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The one rule by which a row id from outside (a path, a query, a body, an MCP
|
||||
* resource URI, a plugin RPC param, a websocket message) becomes the number a
|
||||
* repository binds.
|
||||
*
|
||||
* Only the canonical spelling is an id: a safe integer, or a string of decimal
|
||||
* digits naming one ('007' is 7, as SQLite's own conversion reads it). Every
|
||||
* other spelling names no row and returns null: 'abc', '0x5', '5e0', '5.0',
|
||||
* '+5', ' 5', '5 ', '5_0', '-5', '' and a number past 2^53. Bound to SQL as
|
||||
* sent, those strings answer three ways. SQLite compares a TEXT operand with an
|
||||
* INTEGER column by numeric affinity, so ' 5', '5.0', '+5' and '5e0' match row
|
||||
* 5 there while '0x5' matches nothing. Postgres 14 and 15 refuse the cast with
|
||||
* an error, a 500. Postgres 16 and later read hex and underscores as a number.
|
||||
* `Number()` and `parseInt()` read most of them as 5 on every engine, and hand
|
||||
* NaN or a number past the bigint range to Postgres, which refuses it.
|
||||
*
|
||||
* Our own clients only ever send `String(id)` of an integer column, so the
|
||||
* refusal costs nothing but a hand-made request, which gets the answer an id
|
||||
* that names no row gets. Keep the regex as it is: narrowing it to refuse
|
||||
* '007' or widening it to any spelling an engine accepts brings the
|
||||
* difference back.
|
||||
*
|
||||
* A caller that ran `Number(id)` before handing the value in has already lost
|
||||
* the spelling: `toRowId(Number('0x10'))` is 16. Pass the raw value.
|
||||
*/
|
||||
export function toRowId(value: unknown): number | null {
|
||||
if (typeof value === 'number') {
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
}
|
||||
if (typeof value === 'string' && /^\d+$/.test(value)) {
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `read` with the id `toRowId` parses from `value`, or answers undefined
|
||||
* without reading when it refuses the value. For the lookups that take an id
|
||||
* from a request: a spelling no client sends ('0x1', '1e0', '1.0', '+1', '1_0',
|
||||
* a number past 2^53) is no row, the same answer on every engine, where bound
|
||||
* raw SQLite matched nothing, Postgres 14 and 15 refused the cast with an
|
||||
* error and Postgres 16 and later read hex and underscores as a number.
|
||||
*/
|
||||
export async function withRowId<T>(value: unknown, read: (id: number) => Promise<T>): Promise<T | undefined> {
|
||||
const id = toRowId(value);
|
||||
return id === null ? undefined : read(id);
|
||||
}
|
||||
Reference in New Issue
Block a user