From 39346ceca725d85605534401e773269513cd42a8 Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 18 Nov 2026 13:20:06 +0100 Subject: [PATCH] fix(mcp,rpc): parse resource URI, websocket and plugin RPC ids with toRowId Eleven MCP tool files carried their own parseId, which used Number() and so took '0x1' and '1e20'; they now share uriRowId. The websocket join and book:join read the id with toRowId instead of Number(). Plugin RPC ids go through rowIdParam instead of num(), and a param that may be left out goes through the new optionalRowIdParam. num() let '0x5', 1.5 and 1e20 through, which Postgres refuses or reads its own way while SQLite matches nothing. accommodations.create read its refs with Math.trunc(Number()), and accommodations.update bound its open input's refs as sent. collab.createMessage took replyTo only when typeof was 'number', which let 1.5 and 1e20 through. All three now read their ids as row ids. A canonical numeric string still passes, as the published contract says, and the refusal keeps num()'s message. --- server/src/nest-rpc/plugin-guards.service.ts | 4 +- server/src/nest-rpc/rpc-params.ts | 19 +++++ .../nest/accommodations/accommodations.mcp.ts | 8 +- .../nest/accommodations/accommodations.rpc.ts | 42 +++++----- server/src/nest/assignments/itinerary.rpc.ts | 12 +-- server/src/nest/atlas/atlas.rpc.ts | 4 +- server/src/nest/budget/budget.mcp.ts | 12 +-- server/src/nest/budget/budget.service.ts | 2 +- server/src/nest/budget/costs.rpc.ts | 16 ++-- server/src/nest/collab/collab.mcp.ts | 12 +-- server/src/nest/collab/collab.rpc.ts | 25 +++--- .../src/nest/collections/collections.rpc.ts | 8 +- server/src/nest/day-notes/day-notes.mcp.ts | 10 +-- server/src/nest/day-notes/day-notes.rpc.ts | 20 ++--- server/src/nest/days/days.mcp.ts | 8 +- server/src/nest/days/days.rpc.ts | 12 +-- server/src/nest/files/files.rpc.ts | 20 ++--- server/src/nest/journey/journal.rpc.ts | 19 +++-- server/src/nest/journey/journey.mcp.ts | 12 +-- server/src/nest/packing/packing.mcp.ts | 10 +-- server/src/nest/packing/packing.rpc.ts | 36 ++++---- server/src/nest/packing/packing.service.ts | 8 +- server/src/nest/places/places.mcp.ts | 8 +- server/src/nest/places/places.rpc.ts | 12 +-- .../nest/plugins/host/rpc/host-surface.rpc.ts | 10 +-- server/src/nest/plugins/host/rpc/meta.rpc.ts | 4 +- server/src/nest/realtime/realtime.gateway.ts | 12 +-- .../src/nest/reservations/reservations.mcp.ts | 8 +- .../src/nest/reservations/reservations.rpc.ts | 12 +-- server/src/nest/tags/tags.rpc.ts | 6 +- server/src/nest/todo/todo.mcp.ts | 8 +- server/src/nest/todo/todo.rpc.ts | 14 ++-- server/src/nest/todo/todo.service.ts | 2 +- .../nest/trip-members/trip-members.service.ts | 2 +- server/src/nest/trips/trips.mcp.ts | 10 +-- server/src/nest/trips/trips.rpc.ts | 27 +++--- server/tests/unit/nest-rpc/rpc-params.test.ts | 26 ++++++ .../unit/nest/accommodations.rpc.test.ts | 82 +++++++++++++++++++ .../tests/unit/nest/realtime.gateway.test.ts | 20 +++++ .../plugins/addon-domains-errors.rpc.test.ts | 17 ++++ 40 files changed, 365 insertions(+), 234 deletions(-) create mode 100644 server/tests/unit/nest-rpc/rpc-params.test.ts create mode 100644 server/tests/unit/nest/accommodations.rpc.test.ts diff --git a/server/src/nest-rpc/plugin-guards.service.ts b/server/src/nest-rpc/plugin-guards.service.ts index 1056c5405..7687c5498 100644 --- a/server/src/nest-rpc/plugin-guards.service.ts +++ b/server/src/nest-rpc/plugin-guards.service.ts @@ -6,7 +6,7 @@ import { AddonsService } from '../nest/addons/addons.service'; import { PermissionsService } from '../nest/permissions/permissions.service'; import { BadParams, ForbiddenResource } from './rpc-errors'; import type { PluginRpcContext } from './rpc-kit/types'; -import { num } from './rpc-params'; +import { rowIdParam } from './rpc-params'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; @@ -40,7 +40,7 @@ export class PluginGuards { * context (a job, or onLoad) has no acting user and is refused. */ async tripRead(params: Record, ctx: PluginRpcContext, read: (userId: number) => T): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); if (ctx.actingUserId === undefined) { throw new ForbiddenResource('trip reads require an authenticated user context'); } diff --git a/server/src/nest-rpc/rpc-params.ts b/server/src/nest-rpc/rpc-params.ts index 583972fc5..7c4c3ce54 100644 --- a/server/src/nest-rpc/rpc-params.ts +++ b/server/src/nest-rpc/rpc-params.ts @@ -1,3 +1,4 @@ +import { toRowId } from '../db/row-id'; import { BadParams } from './rpc-errors'; /** @@ -15,6 +16,24 @@ export const num = (v: unknown, name: string): number => { return n; }; +/** + * A row id, or another whole number compared with an integer column (a list + * position, a pagination cursor): a safe integer or its decimal digits, read + * through toRowId. num() let '0x5', '5e0', 1.5 and 1e20 through, + * which SQLite matches against nothing while Postgres refuses the cast or reads + * the string its own way; a canonical numeric string still passes, as the + * published contract says. The refusal keeps num()'s message. + */ +export const rowIdParam = (v: unknown, name: string): number => { + const id = toRowId(v); + if (id === null) throw new BadParams(`${name} must be a number`); + return id; +}; + +/** rowIdParam for a param that may be left out: absent stays undefined, anything else must be a row id. */ +export const optionalRowIdParam = (v: unknown, name: string): number | undefined => + v === undefined ? undefined : rowIdParam(v, name); + export const str = (v: unknown, name: string): string => { if (typeof v !== 'string') throw new BadParams(`${name} must be a string`); return v; diff --git a/server/src/nest/accommodations/accommodations.mcp.ts b/server/src/nest/accommodations/accommodations.mcp.ts index 8aded1b9a..6e2654cdf 100644 --- a/server/src/nest/accommodations/accommodations.mcp.ts +++ b/server/src/nest/accommodations/accommodations.mcp.ts @@ -10,6 +10,7 @@ import { TOOL_ANNOTATIONS_READONLY, ok, } from '../../nest-mcp'; +import { uriRowId } from '../common/row-id'; import { UnitOfWork } from '../database/unit-of-work'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { PlacesService } from '../places/places.service'; @@ -23,11 +24,6 @@ import { import { z } from 'zod'; -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** * Accommodation MCP surface. The four tools and the * trek://trips/{tripId}/accommodations resource moved here verbatim from @@ -355,7 +351,7 @@ export class AccommodationsMcp { access: { group: 'trips', mode: 'read' }, }) async tripAccommodationsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.accommodations.verifyTripAccess(id, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/accommodations/accommodations.rpc.ts b/server/src/nest/accommodations/accommodations.rpc.ts index 9abc2c997..f46fe50ac 100644 --- a/server/src/nest/accommodations/accommodations.rpc.ts +++ b/server/src/nest/accommodations/accommodations.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { optionalRowIdParam, rowIdParam, schemaMessage } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { AccommodationsService } from './accommodations.service'; import { accommodationCreateRequestSchema, accommodationUpdateRequestSchema } from '@trek/shared'; @@ -43,15 +43,16 @@ export class AccommodationsRpc { @PluginMethod('accommodations.create', { permission: 'db:write:accommodations' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'accommodation'); const parsed = accommodationCreateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid accommodation: ${schemaMessage(parsed.error)}`); await this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION); const input = parsed.data as AccommodationInput; - const placeId = Math.trunc(Number(input.place_id)); - const startDayId = Math.trunc(Number(input.start_day_id)); - const endDayId = Math.trunc(Number(input.end_day_id)); + // The schema took only a whole number or its digits for each. + const placeId = rowIdParam(input.place_id, 'place_id'); + const startDayId = rowIdParam(input.start_day_id, 'start_day_id'); + const endDayId = rowIdParam(input.end_day_id, 'end_day_id'); if (!placeId || !startDayId || !endDayId) throw new BadParams('place_id, start_day_id, and end_day_id are required'); // Verifies the place and both days belong to this trip. @@ -76,32 +77,33 @@ export class AccommodationsRpc { @PluginMethod('accommodations.update', { permission: 'db:write:accommodations' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const accommodationId = num(params.accommodationId, 'accommodationId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const accommodationId = rowIdParam(params.accommodationId, 'accommodationId'); const actor = this.guards.requireActor(ctx, 'accommodation'); const parsed = accommodationUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid accommodation: ${schemaMessage(parsed.error)}`); await this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION); const existing = await this.days.getAccommodation(accommodationId, tripId); if (!existing) throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`); - const input = parsed.data as { - place_id?: number; - start_day_id?: number; - end_day_id?: number; + const fields = parsed.data as { check_in?: string; check_in_end?: string; check_out?: string; confirmation?: string; notes?: string; }; - const errors = await this.days.validateAccommodationRefs( - tripId, - input.place_id, - input.start_day_id, - input.end_day_id, - ); + // The input is open: a ref is read like a plugin RPC id, so '0x1' or 1.5 is BAD_PARAMS, not bound. + const refs = { + place_id: optionalRowIdParam(parsed.data.place_id, 'place_id'), + start_day_id: optionalRowIdParam(parsed.data.start_day_id, 'start_day_id'), + end_day_id: optionalRowIdParam(parsed.data.end_day_id, 'end_day_id'), + }; + const errors = await this.days.validateAccommodationRefs(tripId, refs.place_id, refs.start_day_id, refs.end_day_id); if (errors.length > 0) throw new ForbiddenResource(errors[0].message); - const { accommodation, mirror } = await this.days.updateAccommodation(accommodationId, existing, input); + const { accommodation, mirror } = await this.days.updateAccommodation(accommodationId, existing, { + ...fields, + ...refs, + }); this.realtime.broadcast(tripId, 'accommodation:updated', { accommodation }); await this.days.announceMirror(tripId, mirror, (event, payload) => this.realtime.broadcast(tripId, event, payload)); return accommodation; @@ -109,8 +111,8 @@ export class AccommodationsRpc { @PluginMethod('accommodations.delete', { permission: 'db:write:accommodations' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const accommodationId = num(params.accommodationId, 'accommodationId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const accommodationId = rowIdParam(params.accommodationId, 'accommodationId'); const actor = this.guards.requireActor(ctx, 'accommodation'); await this.guards.requireTripEdit(tripId, actor, ACCOMMODATION_EDIT_ACTION); if (!(await this.days.getAccommodation(accommodationId, tripId))) { diff --git a/server/src/nest/assignments/itinerary.rpc.ts b/server/src/nest/assignments/itinerary.rpc.ts index 0383917df..776781cd9 100644 --- a/server/src/nest/assignments/itinerary.rpc.ts +++ b/server/src/nest/assignments/itinerary.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, str } from '../../nest-rpc/rpc-params'; +import { str, rowIdParam } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { AssignmentsService } from './assignments.service'; @@ -26,9 +26,9 @@ export class ItineraryRpc { @PluginMethod('itinerary.assign', { permission: 'db:write:itinerary' }) async assign(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); - const placeId = num(params.placeId, 'placeId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); + const placeId = rowIdParam(params.placeId, 'placeId'); const actor = this.guards.requireActor(ctx, 'itinerary'); const notes = params.notes === undefined || params.notes === null ? null : str(params.notes, 'notes'); await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION); @@ -44,8 +44,8 @@ export class ItineraryRpc { @PluginMethod('itinerary.unassign', { permission: 'db:write:itinerary' }) async unassign(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const assignmentId = num(params.assignmentId, 'assignmentId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const assignmentId = rowIdParam(params.assignmentId, 'assignmentId'); const actor = this.guards.requireActor(ctx, 'itinerary'); await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION); const existing = await this.assignments.getAssignmentForTrip(assignmentId, tripId); diff --git a/server/src/nest/atlas/atlas.rpc.ts b/server/src/nest/atlas/atlas.rpc.ts index b2cdf50a3..85580af1e 100644 --- a/server/src/nest/atlas/atlas.rpc.ts +++ b/server/src/nest/atlas/atlas.rpc.ts @@ -3,7 +3,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { AtlasService, BucketItemExistsError } from './atlas.service'; /** @@ -100,7 +100,7 @@ export class AtlasRpc { @PluginMethod('atlas.deleteBucketItem', { permission: 'db:write:atlas' }) async deleteBucketItem(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireAtlasUser(ctx, 'writes'); - const itemId = num(params.itemId, 'itemId'); + const itemId = rowIdParam(params.itemId, 'itemId'); await this.requireAtlasAddon(); if (!(await this.atlas.deleteBucketItem(userId, itemId))) { throw new ForbiddenResource(`no bucket item ${itemId} for this user`); diff --git a/server/src/nest/budget/budget.mcp.ts b/server/src/nest/budget/budget.mcp.ts index c7a6ef8a4..a8de6fdf1 100644 --- a/server/src/nest/budget/budget.mcp.ts +++ b/server/src/nest/budget/budget.mcp.ts @@ -20,6 +20,7 @@ import { addonGate } from '../addons/addon-gate'; import { AddonsService } from '../addons/addons.service'; import { RuntimeEnvService } from '../app-config/runtime-env.service'; import { DomainError } from '../common/domain-error'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { TripMembershipService } from '../trip-membership/trip-membership.service'; import { BudgetWritesService } from './budget-writes.service'; @@ -59,11 +60,6 @@ const splitMembersSchema = z 'Unequal split: what each participant owes, in the expense currency. The amounts must add up to the expense total. Ask the user; do not guess.', ); -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - function formatCents(cents: number): string { return (cents / 100).toFixed(2); } @@ -841,7 +837,7 @@ export class BudgetMcp { access: { group: 'budget', mode: 'read' }, }) async tripBudgetResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) { return { contents: [ @@ -874,7 +870,7 @@ export class BudgetMcp { access: { group: 'budget', mode: 'read' }, }) async tripBudgetPerPersonResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) { return { contents: [ @@ -908,7 +904,7 @@ export class BudgetMcp { access: { group: 'budget', mode: 'read' }, }) async tripBudgetSettlementResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/budget/budget.service.ts b/server/src/nest/budget/budget.service.ts index 07cfa656d..fc3b058a5 100644 --- a/server/src/nest/budget/budget.service.ts +++ b/server/src/nest/budget/budget.service.ts @@ -1466,7 +1466,7 @@ export class BudgetService { return await this.createBudgetItem(tripId, data); } - /** `id: number` — Plan 4 Task 8b (U6): `BudgetController.update`/the `costs.update` RPC method both parse/hand this a real row id now (`toRowId`/`num()`). */ + /** `id: number` — Plan 4 Task 8b (U6): `BudgetController.update`/the `costs.update` RPC method both parse/hand this a real row id now (`toRowId`/`rowIdParam()`). */ async update(id: number, tripId: string | number, data: Parameters[2] & { fallback_fx?: BudgetFallbackFx }) { await this.freezeForeignRate(tripId, data, id); return await this.updateBudgetItem(id, tripId, data); diff --git a/server/src/nest/budget/costs.rpc.ts b/server/src/nest/budget/costs.rpc.ts index 96a502d37..9751e6a7a 100644 --- a/server/src/nest/budget/costs.rpc.ts +++ b/server/src/nest/budget/costs.rpc.ts @@ -3,7 +3,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { rowIdParam, schemaMessage } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { TripAccessService } from '../trip-membership/trip-access.service'; import { TripMembershipService } from '../trip-membership/trip-membership.service'; @@ -42,7 +42,7 @@ export class CostsRpc { async getByTrip(params: Record, ctx: PluginRpcContext): Promise { return await this.guards.tripRead(params, ctx, async () => { await this.requireBudgetAddon(); - return await this.budget.listBudgetItems(num(params.tripId, 'tripId')); + return await this.budget.listBudgetItems(rowIdParam(params.tripId, 'tripId')); }); } @@ -65,7 +65,7 @@ export class CostsRpc { @PluginMethod('costs.create', { permission: 'db:write:costs' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.requireCostActor(ctx); await this.requireBudgetAddon(); const parsed = budgetCreateItemRequestSchema.safeParse(params.input); @@ -82,8 +82,8 @@ export class CostsRpc { @PluginMethod('costs.update', { permission: 'db:write:costs' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const itemId = num(params.itemId, 'itemId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const itemId = rowIdParam(params.itemId, 'itemId'); const actor = this.requireCostActor(ctx); await this.requireBudgetAddon(); const parsed = budgetUpdateItemRequestSchema.safeParse(params.input); @@ -92,7 +92,7 @@ export class CostsRpc { await this.refuseForeignLinks(tripId, parsed.data); const before = parsed.data.reservation_id !== undefined ? await this.budget.getBudgetItem(itemId, tripId) : null; // update re-freezes the FX rate on a currency change, exactly like create. - // Plan 4 Task 8b (U6) — itemId is already a real row id (num() above); + // Plan 4 Task 8b (U6) — itemId is already a real row id (rowIdParam() above); // BudgetService.update's id param no longer needs the String() wrapper. const item = await this.budget.update(itemId, String(tripId), parsed.data); if (item == null) throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`); @@ -112,8 +112,8 @@ export class CostsRpc { @PluginMethod('costs.delete', { permission: 'db:write:costs' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const itemId = num(params.itemId, 'itemId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const itemId = rowIdParam(params.itemId, 'itemId'); const actor = this.requireCostActor(ctx); await this.requireBudgetAddon(); await this.requireCostEdit(tripId, actor); diff --git a/server/src/nest/collab/collab.mcp.ts b/server/src/nest/collab/collab.mcp.ts index 4ab4037cf..2c09dbaf3 100644 --- a/server/src/nest/collab/collab.mcp.ts +++ b/server/src/nest/collab/collab.mcp.ts @@ -14,6 +14,7 @@ import { } from '../../nest-mcp'; import { collabFeatureGate } from '../addons/addon-gate'; import { AddonsService } from '../addons/addons.service'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { CollabService } from './collab.service'; import { @@ -35,11 +36,6 @@ const collabPollsOn = collabFeatureGate('polls'); const collabChatOn = collabFeatureGate('chat'); const collabLinksOn = collabFeatureGate('links'); -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - function accessDenied(uri: string) { return { contents: [ @@ -553,7 +549,7 @@ export class CollabMcp { access: { group: 'collab', mode: 'read' }, }) async tripCollabNotesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href); const notes = await this.collab.listNotes(id); return jsonContent(uri.href, notes); @@ -568,7 +564,7 @@ export class CollabMcp { access: { group: 'collab', mode: 'read' }, }) async tripCollabPollsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href); const polls = await this.collab.listPolls(id); return jsonContent(uri.href, polls); @@ -583,7 +579,7 @@ export class CollabMcp { access: { group: 'collab', mode: 'read' }, }) async tripCollabMessagesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.collab.verifyTripAccess(id, ctx.userId))) return accessDenied(uri.href); const messages = await this.collab.listMessages(id); return jsonContent(uri.href, messages); diff --git a/server/src/nest/collab/collab.rpc.ts b/server/src/nest/collab/collab.rpc.ts index 8d78fbbf7..01fd9f3a7 100644 --- a/server/src/nest/collab/collab.rpc.ts +++ b/server/src/nest/collab/collab.rpc.ts @@ -3,7 +3,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, optionalRowIdParam, rowIdParam } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { CollabService } from './collab.service'; @@ -33,7 +33,7 @@ export class CollabRpc { listNotes(params: Record, ctx: PluginRpcContext): unknown { return this.guards.tripRead(params, ctx, async () => { await this.requireCollabAddon(); - return (await this.collab.listNotes(num(params.tripId, 'tripId'))) as unknown[]; + return (await this.collab.listNotes(rowIdParam(params.tripId, 'tripId'))) as unknown[]; }); } @@ -41,7 +41,7 @@ export class CollabRpc { listPolls(params: Record, ctx: PluginRpcContext): unknown { return this.guards.tripRead(params, ctx, async () => { await this.requireCollabAddon(); - return (await this.collab.listPolls(num(params.tripId, 'tripId'))) as unknown[]; + return (await this.collab.listPolls(rowIdParam(params.tripId, 'tripId'))) as unknown[]; }); } @@ -49,14 +49,14 @@ export class CollabRpc { listMessages(params: Record, ctx: PluginRpcContext): unknown { return this.guards.tripRead(params, ctx, async () => { await this.requireCollabAddon(); - const before = params.before != null ? num(params.before, 'before') : undefined; - return (await this.collab.listMessages(num(params.tripId, 'tripId'), before)) as unknown[]; + const before = params.before != null ? rowIdParam(params.before, 'before') : undefined; + return (await this.collab.listMessages(rowIdParam(params.tripId, 'tripId'), before)) as unknown[]; }); } @PluginMethod('collab.createNote', { permission: 'db:write:collab' }) async createNote(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'collab note'); const input = asPayload(params.input); if (typeof input.title !== 'string' || input.title.trim() === '') throw new BadParams('note title is required'); @@ -69,7 +69,7 @@ export class CollabRpc { @PluginMethod('collab.createPoll', { permission: 'db:write:collab' }) async createPoll(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'collab poll'); const input = asPayload(params.input); if (typeof input.question !== 'string' || input.question.trim() === '') @@ -85,15 +85,15 @@ export class CollabRpc { @PluginMethod('collab.votePoll', { permission: 'db:write:collab' }) async votePoll(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'collab poll'); await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION); await this.requireCollabAddon(); const result = await this.collab.votePoll( String(tripId), - String(num(params.pollId, 'pollId')), + String(rowIdParam(params.pollId, 'pollId')), actor, - num(params.optionIndex, 'optionIndex'), + rowIdParam(params.optionIndex, 'optionIndex'), ); // The service reports its own validation failures rather than throwing. if (result.error) throw new BadParams(result.error); @@ -103,14 +103,15 @@ export class CollabRpc { @PluginMethod('collab.createMessage', { permission: 'db:write:collab' }) async createMessage(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'collab message'); if (typeof params.text !== 'string' || params.text.trim() === '' || params.text.length > 4000) { throw new BadParams('message text is required (max 4000 chars)'); } await this.guards.requireTripEdit(tripId, actor, COLLAB_EDIT_ACTION); await this.requireCollabAddon(); - const replyTo = typeof params.replyTo === 'number' ? params.replyTo : null; + // Left out or null is no reply; anything else must be a message id. + const replyTo = optionalRowIdParam(params.replyTo ?? undefined, 'replyTo') ?? null; const result = await this.collab.createMessage(String(tripId), actor, params.text, replyTo); if (result.error) throw new BadParams(result.error); this.realtime.broadcast(tripId, 'collab:message:created', { message: result.message }, undefined); diff --git a/server/src/nest/collections/collections.rpc.ts b/server/src/nest/collections/collections.rpc.ts index 847460080..923c5d7a7 100644 --- a/server/src/nest/collections/collections.rpc.ts +++ b/server/src/nest/collections/collections.rpc.ts @@ -3,7 +3,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { schemaMessage, rowIdParam } from '../../nest-rpc/rpc-params'; import { CollectionsService } from './collections.service'; import { collectionCopyToTripRequestSchema, @@ -40,7 +40,7 @@ export class CollectionsRpc { // getCollection is user-scoped by the service, so a plugin only ever fetches one // the acting user may see. const userId = this.requireCollectionsUser(ctx, 'reads'); - const id = num(params.id, 'id'); + const id = rowIdParam(params.id, 'id'); await this.requireCollectionsAddon(); return this.collections.getCollection(userId, id); } @@ -59,7 +59,7 @@ export class CollectionsRpc { const parsed = collectionUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid collection: ${schemaMessage(parsed.error)}`); const userId = this.requireCollectionsUser(ctx, 'writes'); - const id = num(params.id, 'id'); + const id = rowIdParam(params.id, 'id'); await this.requireCollectionsAddon(); return this.mapCollectionError(() => this.collections.updateCollection(userId, id, parsed.data as never, undefined), @@ -89,7 +89,7 @@ export class CollectionsRpc { @PluginMethod('collections.deletePlace', { permission: 'db:write:collections' }) async deletePlace(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireCollectionsUser(ctx, 'writes'); - const placeId = num(params.placeId, 'placeId'); + const placeId = rowIdParam(params.placeId, 'placeId'); await this.requireCollectionsAddon(); // Awaited so a refusal actually reaches the plugin as RESOURCE_FORBIDDEN/BAD_PARAMS // instead of being dropped as an unhandled rejection while this returns diff --git a/server/src/nest/day-notes/day-notes.mcp.ts b/server/src/nest/day-notes/day-notes.mcp.ts index 892ad3961..fa00b1b9f 100644 --- a/server/src/nest/day-notes/day-notes.mcp.ts +++ b/server/src/nest/day-notes/day-notes.mcp.ts @@ -9,6 +9,7 @@ import { TOOL_ANNOTATIONS_NON_IDEMPOTENT, ok, } from '../../nest-mcp'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { DayNotesService } from './day-notes.service'; import { @@ -41,11 +42,6 @@ const NOTE_BODY = 'Despite the field name this is the content, not a clock time'; const noteTitleSchema = dayNoteCreateRequestSchema.shape.text.describe(NOTE_TITLE); -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** * Day-note MCP surface — ported 1:1 from the legacy registrars: the three * tools from the DAY NOTES block of src/mcp/tools/days.ts and the @@ -213,8 +209,8 @@ export class DayNotesMcp { { tripId, dayId }: { tripId: string | string[]; dayId: string | string[] }, ctx: McpContext, ) { - const tId = parseId(tripId); - const dId = parseId(dayId); + const tId = uriRowId(tripId); + const dId = uriRowId(dayId); if (tId === null || dId === null || !(await this.notes.verifyTripAccess(tId, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/day-notes/day-notes.rpc.ts b/server/src/nest/day-notes/day-notes.rpc.ts index 03bb534b7..51fa20812 100644 --- a/server/src/nest/day-notes/day-notes.rpc.ts +++ b/server/src/nest/day-notes/day-notes.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { DayNotesService } from './day-notes.service'; @@ -32,14 +32,14 @@ export class DayNotesRpc { return await this.guards.tripRead( params, ctx, - async () => await this.dayNotes.list(num(params.dayId, 'dayId'), num(params.tripId, 'tripId')), + async () => await this.dayNotes.list(rowIdParam(params.dayId, 'dayId'), rowIdParam(params.tripId, 'tripId')), ); } @PluginMethod('daynotes.create', { permission: 'db:write:daynotes' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); const actor = this.guards.requireActor(ctx, 'day note'); const input = asPayload(params.input); if (typeof input.text !== 'string' || input.text.trim() === '') throw new BadParams('note text is required'); @@ -54,9 +54,9 @@ export class DayNotesRpc { @PluginMethod('daynotes.update', { permission: 'db:write:daynotes' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); - const noteId = num(params.noteId, 'noteId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); + const noteId = rowIdParam(params.noteId, 'noteId'); const actor = this.guards.requireActor(ctx, 'day note'); await this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION); const current = await this.dayNotes.getNote(noteId, dayId, tripId); @@ -68,9 +68,9 @@ export class DayNotesRpc { @PluginMethod('daynotes.delete', { permission: 'db:write:daynotes' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); - const noteId = num(params.noteId, 'noteId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); + const noteId = rowIdParam(params.noteId, 'noteId'); const actor = this.guards.requireActor(ctx, 'day note'); await this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION); const current = await this.dayNotes.getNote(noteId, dayId, tripId); diff --git a/server/src/nest/days/days.mcp.ts b/server/src/nest/days/days.mcp.ts index b453a2683..efc22600e 100644 --- a/server/src/nest/days/days.mcp.ts +++ b/server/src/nest/days/days.mcp.ts @@ -11,6 +11,7 @@ import { ok, } from '../../nest-mcp'; import type { MirrorSender } from '../accommodations/accommodations.service'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { DayRemovalService, DayDeleteError, type DayRemoval } from './day-removal.service'; import { DaysService, DayReorderError, DayAppendError, type DatedDayAppend, type DaySender } from './days.service'; @@ -25,11 +26,6 @@ import type { DayCreateRequest, DayReorderRequest, DayUpdateRequest } from '@tre import { z } from 'zod'; -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** * Day MCP surface — ported 1:1 from the legacy registrars: the seven tools of * src/mcp/tools/days.ts and the trek://trips/{tripId}/days resource from src/mcp/resources.ts @@ -250,7 +246,7 @@ export class DaysMcp { access: { group: 'trips', mode: 'read' }, }) async tripDaysResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.days.verifyTripAccess(id, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/days/days.rpc.ts b/server/src/nest/days/days.rpc.ts index 0e1662022..b767c88da 100644 --- a/server/src/nest/days/days.rpc.ts +++ b/server/src/nest/days/days.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { schemaMessage, rowIdParam } from '../../nest-rpc/rpc-params'; import type { MirrorSender } from '../accommodations/accommodations.service'; import { RealtimeService } from '../realtime/realtime.service'; import { DayRemovalService, DayDeleteError, type DayRemoval } from './day-removal.service'; @@ -28,7 +28,7 @@ export class DaysRpc { @PluginMethod('days.create', { permission: 'db:write:days' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'day'); const parsed = dayCreateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid day: ${schemaMessage(parsed.error)}`); @@ -56,8 +56,8 @@ export class DaysRpc { @PluginMethod('days.update', { permission: 'db:write:days' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); const actor = this.guards.requireActor(ctx, 'day'); const parsed = dayUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid day: ${schemaMessage(parsed.error)}`); @@ -72,8 +72,8 @@ export class DaysRpc { @PluginMethod('days.delete', { permission: 'db:write:days' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const dayId = num(params.dayId, 'dayId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const dayId = rowIdParam(params.dayId, 'dayId'); const actor = this.guards.requireActor(ctx, 'day'); await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION); if (!(await this.days.getDay(dayId, tripId))) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`); diff --git a/server/src/nest/files/files.rpc.ts b/server/src/nest/files/files.rpc.ts index 2ef80d336..e669b39e1 100644 --- a/server/src/nest/files/files.rpc.ts +++ b/server/src/nest/files/files.rpc.ts @@ -5,7 +5,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { isDemoEmail } from '../common/demo'; import { RealtimeService } from '../realtime/realtime.service'; import { StorageService } from '../storage/storage.service'; @@ -60,14 +60,14 @@ export class FilesRpc { async list(params: Record, ctx: PluginRpcContext): Promise { // Trash excluded, the same view the files tab shows. return await this.guards.tripRead(params, ctx, async () => - this.files.listFiles(num(params.tripId, 'tripId'), false), + this.files.listFiles(rowIdParam(params.tripId, 'tripId'), false), ); } @PluginMethod('files.getContent', { permission: 'db:read:files:content' }) getContent(params: Record, ctx: PluginRpcContext): unknown { return this.guards.tripRead(params, ctx, () => - this.readContent(num(params.tripId, 'tripId'), num(params.fileId, 'fileId')), + this.readContent(rowIdParam(params.tripId, 'tripId'), rowIdParam(params.fileId, 'fileId')), ); } @@ -92,7 +92,7 @@ export class FilesRpc { @PluginMethod('files.create', { permission: 'db:write:files' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'file'); const input = asPayload(params.input); if (typeof input.name !== 'string' || input.name.trim() === '' || input.name.length > 255) { @@ -155,8 +155,8 @@ export class FilesRpc { @PluginMethod('files.createLink', { permission: 'db:write:files' }) async createLink(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const fileId = num(params.fileId, 'fileId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const fileId = rowIdParam(params.fileId, 'fileId'); const actor = this.guards.requireActor(ctx, 'file link'); await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION); if (!(await this.files.getFileById(fileId, tripId))) @@ -174,8 +174,8 @@ export class FilesRpc { @PluginMethod('files.update', { permission: 'db:write:files' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const fileId = num(params.fileId, 'fileId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const fileId = rowIdParam(params.fileId, 'fileId'); const actor = this.guards.requireActor(ctx, 'file'); await this.guards.requireTripEdit(tripId, actor, EDIT_ACTION); const current = await this.files.getFileById(fileId, tripId); @@ -203,8 +203,8 @@ export class FilesRpc { @PluginMethod('files.softDelete', { permission: 'db:write:files' }) async softDelete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const fileId = num(params.fileId, 'fileId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const fileId = rowIdParam(params.fileId, 'fileId'); const actor = this.guards.requireActor(ctx, 'file'); await this.guards.requireTripEdit(tripId, actor, DELETE_ACTION); if (!(await this.files.getFileById(fileId, tripId))) diff --git a/server/src/nest/journey/journal.rpc.ts b/server/src/nest/journey/journal.rpc.ts index 6383a7cae..15c08dbc8 100644 --- a/server/src/nest/journey/journal.rpc.ts +++ b/server/src/nest/journey/journal.rpc.ts @@ -3,8 +3,9 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { DemoService } from '../common/demo.service'; +import { toRowId } from '../common/row-id'; import { AllowedFileTypesService } from '../files/allowed-file-types.service'; import { StorageService } from '../storage/storage.service'; import { JourneyDomainService } from './journey-domain.service'; @@ -68,7 +69,7 @@ export class JournalRpc { @PluginMethod('journal.getEntries', { permission: 'db:read:journal' }) async getEntries(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireJournalUser(ctx, 'reads'); - const journeyId = num(params.journeyId, 'journeyId'); + const journeyId = rowIdParam(params.journeyId, 'journeyId'); await this.requireJourneyAddon(); // listEntries self-gates via canAccessJourney and returns null when the user // cannot see it. @@ -82,7 +83,7 @@ export class JournalRpc { const userId = this.requireJournalUser(ctx, 'writes'); const input = asPayload(params.input); if (typeof input.entry_date !== 'string' || input.entry_date === '') throw new BadParams('entry_date is required'); - const journeyId = num(params.journeyId, 'journeyId'); + const journeyId = rowIdParam(params.journeyId, 'journeyId'); await this.requireJourneyAddon(); const entry = await this.journey.createEntry(journeyId, userId, input as never); if (!entry) throw new ForbiddenResource(`no editable journey ${journeyId} for this user`); @@ -92,7 +93,7 @@ export class JournalRpc { @PluginMethod('journal.updateEntry', { permission: 'db:write:journal' }) async updateEntry(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireJournalUser(ctx, 'writes'); - const entryId = num(params.entryId, 'entryId'); + const entryId = rowIdParam(params.entryId, 'entryId'); await this.requireJourneyAddon(); const entry = await this.journey.updateEntry(entryId, userId, asPayload(params.input) as never); if (!entry) throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`); @@ -102,7 +103,7 @@ export class JournalRpc { @PluginMethod('journal.deleteEntry', { permission: 'db:write:journal' }) async deleteEntry(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireJournalUser(ctx, 'writes'); - const entryId = num(params.entryId, 'entryId'); + const entryId = rowIdParam(params.entryId, 'entryId'); await this.requireJourneyAddon(); if (!(await this.journey.deleteEntry(entryId, userId))) { throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`); @@ -143,9 +144,9 @@ export class JournalRpc { @PluginMethod('journal.addEntryPhoto', { permission: 'db:write:journal' }) async addEntryPhoto(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireJournalUser(ctx, 'writes'); - const entryId = num(params.entryId, 'entryId'); - // num() accepts "3" and 1.5; a row id is neither. - if (!Number.isInteger(entryId) || entryId <= 0) throw new BadParams('entryId must be a positive integer'); + // toRowId: num() took 1.5 and '0x3'; a row id is neither. + const entryId = toRowId(params.entryId); + if (entryId === null || entryId <= 0) throw new BadParams('entryId must be a positive integer'); await this.requireJourneyAddon(); const parsed = journalPluginPhotoInputSchema.safeParse(params.input); @@ -197,7 +198,7 @@ export class JournalRpc { @PluginMethod('journal.deleteJourney', { permission: 'db:write:journal' }) async deleteJourney(params: Record, ctx: PluginRpcContext): Promise { const userId = this.requireJournalUser(ctx, 'writes'); - const journeyId = num(params.journeyId, 'journeyId'); + const journeyId = rowIdParam(params.journeyId, 'journeyId'); await this.requireJourneyAddon(); if (!(await this.journey.deleteJourney(journeyId, userId))) { throw new ForbiddenResource(`no deletable journal ${journeyId} for this user`); diff --git a/server/src/nest/journey/journey.mcp.ts b/server/src/nest/journey/journey.mcp.ts index 7c49d5d93..75af555a8 100644 --- a/server/src/nest/journey/journey.mcp.ts +++ b/server/src/nest/journey/journey.mcp.ts @@ -14,6 +14,7 @@ import { import type { JourneyContributor } from '../../types'; import { addonGate } from '../addons/addon-gate'; import { AddonsService } from '../addons/addons.service'; +import { uriRowId } from '../common/row-id'; import { JourneyDomainService } from './journey-domain.service'; import { JourneyPhotoCaptureService } from './journey-photo-capture.service'; import { JourneySettingsService } from './journey-settings.service'; @@ -46,11 +47,6 @@ function notFound(msg: string) { return { content: [{ type: 'text' as const, text: msg }], isError: true }; } -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - function accessDenied(uri: string) { return { contents: [ @@ -769,7 +765,7 @@ export class JourneyMcp { access: { group: 'journey', mode: 'read' }, }) async journeyDetailResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) { - const id = parseId(journeyId); + const id = uriRowId(journeyId); if (id === null) return accessDenied(uri.href); const journey = await this.journey.getJourneyFull(id, ctx.userId); if (!journey) return accessDenied(uri.href); @@ -785,7 +781,7 @@ export class JourneyMcp { access: { group: 'journey', mode: 'read' }, }) async journeyEntriesResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) { - const id = parseId(journeyId); + const id = uriRowId(journeyId); if (id === null) return accessDenied(uri.href); if (!(await this.journey.canAccessJourney(id, ctx.userId))) return accessDenied(uri.href); return jsonContent(uri.href, await this.journey.listEntries(id, ctx.userId)); @@ -800,7 +796,7 @@ export class JourneyMcp { access: { group: 'journey', mode: 'read' }, }) async journeyContributorsResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) { - const id = parseId(journeyId); + const id = uriRowId(journeyId); if (id === null) return accessDenied(uri.href); const journey = await this.journey.getJourneyFull(id, ctx.userId); if (!journey) return accessDenied(uri.href); diff --git a/server/src/nest/packing/packing.mcp.ts b/server/src/nest/packing/packing.mcp.ts index 125153fa5..bb3520e0d 100644 --- a/server/src/nest/packing/packing.mcp.ts +++ b/server/src/nest/packing/packing.mcp.ts @@ -14,6 +14,7 @@ import { } from '../../nest-mcp'; import { addonGate } from '../addons/addon-gate'; import { AddonsService } from '../addons/addons.service'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { PackingWritesService } from './packing-writes.service'; import { PackingService } from './packing.service'; @@ -38,11 +39,6 @@ type PackingListRow = { category?: string | null; bag_id?: number | null; checke /** Legacy registrar gate: the whole packing surface rides the packing addon. */ const packingAddonOn = addonGate(ADDON_IDS.PACKING); -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** * Packing MCP surface — ported from the legacy registrars: the seventeen * tools from src/mcp/tools/packing.ts and the trek://trips/{tripId}/packing + @@ -712,7 +708,7 @@ export class PackingMcp { access: { group: 'packing', mode: 'read' }, }) async tripPackingResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.packing.verifyTripAccess(id, ctx.userId))) { return { contents: [ @@ -746,7 +742,7 @@ export class PackingMcp { access: { group: 'packing', mode: 'read' }, }) async tripPackingBagsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.packing.verifyTripAccess(id, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/packing/packing.rpc.ts b/server/src/nest/packing/packing.rpc.ts index 10ce75eb8..6a392465d 100644 --- a/server/src/nest/packing/packing.rpc.ts +++ b/server/src/nest/packing/packing.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam, schemaMessage } from '../../nest-rpc/rpc-params'; import { isUpdateConflict } from '../common/conflictResult'; import { RealtimeService } from '../realtime/realtime.service'; import { PackingService, isInvalidBagRef } from './packing.service'; @@ -37,12 +37,14 @@ export class PackingRpc { list(params: Record, ctx: PluginRpcContext): unknown { // Scoped to the acting user so the #858 visibility filter applies: a plugin must // not see another member's private items. - return this.guards.tripRead(params, ctx, (userId) => this.packing.listItems(num(params.tripId, 'tripId'), userId)); + return this.guards.tripRead(params, ctx, (userId) => + this.packing.listItems(rowIdParam(params.tripId, 'tripId'), userId), + ); } @PluginMethod('packing.create', { permission: 'db:write:packing' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'packing item'); const parsed = packingCreateItemRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid packing item: ${schemaMessage(parsed.error)}`); @@ -57,8 +59,8 @@ export class PackingRpc { @PluginMethod('packing.update', { permission: 'db:write:packing' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const itemId = num(params.itemId, 'itemId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const itemId = rowIdParam(params.itemId, 'itemId'); const actor = this.guards.requireActor(ctx, 'packing item'); const parsed = packingUpdateItemRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid packing item: ${schemaMessage(parsed.error)}`); @@ -66,7 +68,7 @@ export class PackingRpc { // Read the privacy BEFORE the write, so a public/private toggle routes correctly. const before = await this.packing.getItemPrivacy(tripId, itemId); const input = parsed.data as Record; - // Plan 4 Task 8b (U6) — itemId is already a real row id (num() above); + // Plan 4 Task 8b (U6) — itemId is already a real row id (rowIdParam() above); // PackingService.updateItem's id param no longer needs the String() wrapper. const updated = await this.packing.updateItem( String(tripId), @@ -89,8 +91,8 @@ export class PackingRpc { @PluginMethod('packing.delete', { permission: 'db:write:packing' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const itemId = num(params.itemId, 'itemId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const itemId = rowIdParam(params.itemId, 'itemId'); const actor = this.guards.requireActor(ctx, 'packing item'); await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION); // Plan 4 Task 8b (U6) — same drop of itemId's String() wrapper as update above. @@ -108,13 +110,13 @@ export class PackingRpc { return await this.guards.tripRead( params, ctx, - async () => (await this.packing.listBags(String(num(params.tripId, 'tripId')))) as unknown[], + async () => (await this.packing.listBags(String(rowIdParam(params.tripId, 'tripId')))) as unknown[], ); } @PluginMethod('packing.createBag', { permission: 'db:write:packing' }) async createBag(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'packing bag'); const input = asPayload(params.input); if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('bag name is required'); @@ -130,12 +132,12 @@ export class PackingRpc { @PluginMethod('packing.updateBag', { permission: 'db:write:packing' }) async updateBag(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const bagId = num(params.bagId, 'bagId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const bagId = rowIdParam(params.bagId, 'bagId'); const actor = this.guards.requireActor(ctx, 'packing bag'); await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION); const input = asPayload(params.input); - // Plan 4 Task 8b (U6) — bagId is already a real row id (num() above); + // Plan 4 Task 8b (U6) — bagId is already a real row id (rowIdParam() above); // PackingService.updateBag's bagId param no longer needs the String() wrapper. const bag = await this.packing.updateBag(String(tripId), bagId, input as never, Object.keys(input)); if (!bag) throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`); @@ -145,8 +147,8 @@ export class PackingRpc { @PluginMethod('packing.deleteBag', { permission: 'db:write:packing' }) async deleteBag(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const bagId = num(params.bagId, 'bagId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const bagId = rowIdParam(params.bagId, 'bagId'); const actor = this.guards.requireActor(ctx, 'packing bag'); await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION); // Plan 4 Task 8b (U6) — same drop of bagId's String() wrapper as updateBag above. @@ -161,8 +163,8 @@ export class PackingRpc { @PluginMethod('packing.setBagMembers', { permission: 'db:write:packing' }) async setBagMembers(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const bagId = num(params.bagId, 'bagId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const bagId = rowIdParam(params.bagId, 'bagId'); const actor = this.guards.requireActor(ctx, 'packing bag'); await this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION); // userIds sits on the params object itself, not under `input`. diff --git a/server/src/nest/packing/packing.service.ts b/server/src/nest/packing/packing.service.ts index 4791fe04a..5c5e9561b 100644 --- a/server/src/nest/packing/packing.service.ts +++ b/server/src/nest/packing/packing.service.ts @@ -259,7 +259,7 @@ export class PackingService { * controller can detect a public↔private transition and route the * broadcast. `id: number` (Plan 4 Task 8b, U6 — the program's gate-level * id parsing carry: `PackingController.update` parses `:id` once via - * `toRowId` and threads the number here; `packing.rpc.ts`'s `num()`- + * `toRowId` and threads the number here; `packing.rpc.ts`'s `rowIdParam()`- * derived `itemId` was already a number). */ async getItemPrivacy(tripId: string | number, id: number): Promise { @@ -309,7 +309,7 @@ export class PackingService { return (await this.enrichItems([await this.itemsRepo.findById(itemId)]))[0]; } - /** `id: number` — same Plan 4 Task 8b (U6) gate-level narrowing as {@link getItemPrivacy} (`PackingController.update`/`packing.mcp.ts`'s Zod-typed `itemId`/`packing.rpc.ts`'s `num()`-derived `itemId`). */ + /** `id: number` — same Plan 4 Task 8b (U6) gate-level narrowing as {@link getItemPrivacy} (`PackingController.update`/`packing.mcp.ts`'s Zod-typed `itemId`/`packing.rpc.ts`'s `rowIdParam()`-derived `itemId`). */ async updateItem( tripId: string | number, id: number, @@ -469,7 +469,7 @@ export class PackingService { }, userId); } - /** `id: number` — same Plan 4 Task 8b (U6) narrowing as {@link addContributor} (`PackingController.remove`/`packing.mcp.ts`'s Zod-typed `itemId`/`packing.rpc.ts`'s `num()`-derived `itemId`). */ + /** `id: number` — same Plan 4 Task 8b (U6) narrowing as {@link addContributor} (`PackingController.remove`/`packing.mcp.ts`'s Zod-typed `itemId`/`packing.rpc.ts`'s `rowIdParam()`-derived `itemId`). */ async deleteItem(tripId: string | number, id: number, actingUserId?: number) { // Return the deleted row (not just a boolean) so callers can target the // delete broadcast at the owner when the item was private (#858). @@ -607,7 +607,7 @@ export class PackingService { return await this.tripMembersRepo.rosterUserIds(tripId); } - /** `bagId: number` (Plan 4 Task 8b, U6 — the program's gate-level id parsing carry: `PackingController.setBagMembers` parses `:bagId` once via `toRowId`; `packing.mcp.ts`'s Zod-typed `bagId`/`packing.rpc.ts`'s `num()`-derived `bagId` were already numbers). */ + /** `bagId: number` (Plan 4 Task 8b, U6 — the program's gate-level id parsing carry: `PackingController.setBagMembers` parses `:bagId` once via `toRowId`; `packing.mcp.ts`'s Zod-typed `bagId`/`packing.rpc.ts`'s `rowIdParam()`-derived `bagId` were already numbers). */ async setBagMembers(tripId: string | number, bagId: number, userIds: number[]) { const bag = await this.bagsRepo.findInTrip(bagId, tripId); if (!bag) return null; diff --git a/server/src/nest/places/places.mcp.ts b/server/src/nest/places/places.mcp.ts index 4bc0d0ed0..1262d1133 100644 --- a/server/src/nest/places/places.mcp.ts +++ b/server/src/nest/places/places.mcp.ts @@ -34,11 +34,7 @@ import { isUpdateConflict } from '../common/conflictResult'; import { isDirectionsUrl } from '../place-import/place-import.service'; import { TripAccessService } from '../trip-membership/trip-access.service'; import { inOrder } from '../common/in-order'; - -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} +import { uriRowId } from '../common/row-id'; /** Hours as the column keeps them: JSON text, or null to clear (#2472). */ const hoursText = (hours: PlaceOpeningHours | null | undefined): string | null => (hours ? JSON.stringify(hours) : null); @@ -583,7 +579,7 @@ export class PlacesMcp { access: { group: 'places', mode: 'read' }, }) async tripPlacesResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.tripsRepo.findAccessible(id, ctx.userId))) { return { contents: [{ diff --git a/server/src/nest/places/places.rpc.ts b/server/src/nest/places/places.rpc.ts index f396901cd..39d9eea70 100644 --- a/server/src/nest/places/places.rpc.ts +++ b/server/src/nest/places/places.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { schemaMessage, rowIdParam } from '../../nest-rpc/rpc-params'; import { JourneyDomainService } from '../journey/journey-domain.service'; import { RealtimeService } from '../realtime/realtime.service'; import type { OriginWriter } from './place-origins.helpers'; @@ -69,7 +69,7 @@ export class PlacesRpc { @PluginMethod('places.create', { permission: 'db:write:places' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'place'); const parsed = placeCreateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid place: ${schemaMessage(parsed.error)}`); @@ -85,8 +85,8 @@ export class PlacesRpc { @PluginMethod('places.update', { permission: 'db:write:places' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const placeId = num(params.placeId, 'placeId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const placeId = rowIdParam(params.placeId, 'placeId'); const actor = this.guards.requireActor(ctx, 'place'); const parsed = placeUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid place: ${schemaMessage(parsed.error)}`); @@ -107,8 +107,8 @@ export class PlacesRpc { @PluginMethod('places.delete', { permission: 'db:write:places' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const placeId = num(params.placeId, 'placeId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const placeId = rowIdParam(params.placeId, 'placeId'); const actor = this.guards.requireActor(ctx, 'place'); await this.guards.requireTripEdit(tripId, actor, PLACE_EDIT_ACTION); // Scope the id to the trip before anything else: onPlaceDeleted keys on the place diff --git a/server/src/nest/plugins/host/rpc/host-surface.rpc.ts b/server/src/nest/plugins/host/rpc/host-surface.rpc.ts index 9a8eb07e9..1376e922d 100644 --- a/server/src/nest/plugins/host/rpc/host-surface.rpc.ts +++ b/server/src/nest/plugins/host/rpc/host-surface.rpc.ts @@ -10,7 +10,7 @@ import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types'; -import { asPayload, num, str } from '../../../../nest-rpc/rpc-params'; +import { asPayload, num, str, rowIdParam } from '../../../../nest-rpc/rpc-params'; import { UnitOfWork } from '../../../database/unit-of-work'; import { UnreadableLlmResponse } from '../../../llm-parse/clients/openai-compatible.client'; import { createLlmClient } from '../../../llm-parse/llm-client.factory'; @@ -66,7 +66,7 @@ export class HostSurfaceRpc { async getUser(params: Record, ctx: PluginRpcContext): Promise { // Scoped to people the acting user can actually see (themselves, or someone they // share a trip with), so a plugin cannot enumerate every account by looping ids. - const id = num(params.id, 'id'); + const id = rowIdParam(params.id, 'id'); if (ctx.actingUserId === undefined) throw new ForbiddenResource('user reads require an authenticated user context'); if (id !== ctx.actingUserId && !(await this.sharesATrip(ctx.actingUserId, id))) { throw new ForbiddenResource(`no access to user ${id}`); @@ -82,7 +82,7 @@ export class HostSurfaceRpc { async broadcastToTrip(params: Record, ctx: PluginRpcContext): Promise { // The TARGET is gated like a read: only a trip room the acting user belongs to. // Namespacing the event type alone does not cross the membership boundary. - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); if (ctx.actingUserId === undefined) throw new ForbiddenResource('broadcasts require an authenticated user context'); if (!(await this.trips.findAccessible(tripId, ctx.actingUserId))) throw new ForbiddenResource(`no access to trip ${tripId}`); @@ -95,7 +95,7 @@ export class HostSurfaceRpc { @PluginMethod('ws.broadcastToUser', { permission: 'ws:broadcast:user' }) broadcastToUser(params: Record, ctx: PluginRpcContext): unknown { // Authorised by identity, not by a predicate: only the acting user's own sockets. - const userId = num(params.userId, 'userId'); + const userId = rowIdParam(params.userId, 'userId'); if (ctx.actingUserId === undefined || userId !== ctx.actingUserId) { throw new ForbiddenResource('a plugin may only broadcast to the acting user'); } @@ -122,7 +122,7 @@ export class HostSurfaceRpc { // 'admin' is deliberately absent: there is no arbitrary-recipient or // admin-broadcast path, so a plugin cannot spam or phish through the host. if (scope !== 'user' && scope !== 'trip') throw new BadParams("scope must be 'user' or 'trip'"); - const targetId = num(input.targetId, 'targetId'); + const targetId = rowIdParam(input.targetId, 'targetId'); if (scope === 'user' && targetId !== actor) throw new ForbiddenResource('a plugin may only notify the acting user'); if (scope === 'trip' && !(await this.trips.findAccessible(targetId, actor))) { throw new ForbiddenResource('the acting user is not a member of that trip'); diff --git a/server/src/nest/plugins/host/rpc/meta.rpc.ts b/server/src/nest/plugins/host/rpc/meta.rpc.ts index 8b14a3e25..719e5952b 100644 --- a/server/src/nest/plugins/host/rpc/meta.rpc.ts +++ b/server/src/nest/plugins/host/rpc/meta.rpc.ts @@ -14,7 +14,7 @@ import { PluginGuards } from '../../../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../../../nest-rpc/rpc-kit/types'; -import { num, str } from '../../../../nest-rpc/rpc-params'; +import { str, rowIdParam } from '../../../../nest-rpc/rpc-params'; import { UnitOfWork } from '../../../database/unit-of-work'; import { InjectRepository } from '@mikro-orm/nestjs'; @@ -126,7 +126,7 @@ export class MetaRpc { if (!META_ENTITY_TYPES.has(entityType)) { throw new BadParams(`invalid entityType "${entityType}" (${[...META_ENTITY_TYPES].join('|')})`); } - const entityId = num(params.entityId, 'entityId'); + const entityId = rowIdParam(params.entityId, 'entityId'); if (ctx.actingUserId === undefined) throw new ForbiddenResource('metadata requires an authenticated user context'); const tripId = await this.entityTrip(entityType, entityId); if (tripId === undefined || !(await this.trips.findAccessible(tripId, ctx.actingUserId))) { diff --git a/server/src/nest/realtime/realtime.gateway.ts b/server/src/nest/realtime/realtime.gateway.ts index 78cc16c44..a19468534 100644 --- a/server/src/nest/realtime/realtime.gateway.ts +++ b/server/src/nest/realtime/realtime.gateway.ts @@ -7,6 +7,7 @@ import { User } from '../../types'; import { logError } from '../audit/audit-log.logger'; import { EphemeralTokenService } from '../auth-core/ephemeral-token.service'; import { readAppSetting } from '../common/app-settings.registry'; +import { toRowId } from '../common/row-id'; import { TripAccessService } from '../trip-membership/trip-access.service'; import { JOURNEY_ACCESS, type JourneyAccess } from './journey-access.types'; import { @@ -190,9 +191,10 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa // `NaN` and throw (`no such column: NaN`), leaving this handler's // promise unanswered instead of the legacy `Access denied` frame. The // platform now renders a bound `NaN` as `NULL` too (`NulSafeSqlitePlatform`), - // so this guard is defence in depth, not the only fix. - const tripId = Number(message.tripId); - if (!Number.isFinite(tripId) || !(await this.trips.findAccessible(tripId, user.id))) { + // so this guard is defence in depth, not the only fix. toRowId, not + // Number(): '0x1' or '1e0' joined trip 1's room. + const tripId = toRowId(message.tripId); + if (tripId === null || !(await this.trips.findAccessible(tripId, user.id))) { return { type: 'error', message: 'Access denied' }; } this.rooms.join(socket, tripId); @@ -215,8 +217,8 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa const user = userOf(socket); if (!user || !message?.journeyId) return undefined; - const journeyId = Number(message.journeyId); - if (!Number.isFinite(journeyId) || !(await this.journeys.canAccessJourney(journeyId, user.id))) { + const journeyId = toRowId(message.journeyId); + if (journeyId === null || !(await this.journeys.canAccessJourney(journeyId, user.id))) { return { type: 'error', message: 'Access denied' }; } diff --git a/server/src/nest/reservations/reservations.mcp.ts b/server/src/nest/reservations/reservations.mcp.ts index d54c5b912..3c358ea0c 100644 --- a/server/src/nest/reservations/reservations.mcp.ts +++ b/server/src/nest/reservations/reservations.mcp.ts @@ -4,6 +4,7 @@ import { TOOL_ANNOTATIONS_NON_IDEMPOTENT, errorResult, ok, } from '../../nest-mcp'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { z } from 'zod'; import { BudgetService } from '../budget/budget.service'; @@ -107,11 +108,6 @@ function resolveEndpointCoords(endpoints: TransportEndpoint[] | undefined): { en return { endpoints: out }; } -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** The linked cost a tool's price becomes: the entry the booking form sends for one. */ function linkedCost(price: number | null | undefined, category: string | undefined) { return price != null && price > 0 ? { total_price: price, category } : undefined; @@ -621,7 +617,7 @@ export class ReservationsMcp { access: { group: 'reservations', mode: 'read' }, }) async tripReservationsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.reservations.verifyTripAccess(id, ctx.userId))) { return { contents: [{ diff --git a/server/src/nest/reservations/reservations.rpc.ts b/server/src/nest/reservations/reservations.rpc.ts index a6506a242..29d04dcd2 100644 --- a/server/src/nest/reservations/reservations.rpc.ts +++ b/server/src/nest/reservations/reservations.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { schemaMessage, rowIdParam } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { withoutOrigin } from './reservation-origin.contract'; import { ReservationsService } from './reservations.service'; @@ -32,7 +32,7 @@ export class ReservationsRpc { @PluginMethod('reservations.create', { permission: 'db:write:reservations' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'reservation'); const parsed = reservationCreateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid reservation: ${schemaMessage(parsed.error)}`); @@ -57,8 +57,8 @@ export class ReservationsRpc { @PluginMethod('reservations.update', { permission: 'db:write:reservations' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const reservationId = num(params.reservationId, 'reservationId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const reservationId = rowIdParam(params.reservationId, 'reservationId'); const actor = this.guards.requireActor(ctx, 'reservation'); const parsed = reservationUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid reservation: ${schemaMessage(parsed.error)}`); @@ -89,8 +89,8 @@ export class ReservationsRpc { @PluginMethod('reservations.delete', { permission: 'db:write:reservations' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const reservationId = num(params.reservationId, 'reservationId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const reservationId = rowIdParam(params.reservationId, 'reservationId'); const actor = this.guards.requireActor(ctx, 'reservation'); await this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION); const { deleted, accommodationDeleted, deletedBudgetItemIds } = await this.reservations.remove( diff --git a/server/src/nest/tags/tags.rpc.ts b/server/src/nest/tags/tags.rpc.ts index 3d5deee52..be795caa4 100644 --- a/server/src/nest/tags/tags.rpc.ts +++ b/server/src/nest/tags/tags.rpc.ts @@ -1,7 +1,7 @@ import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { TagsService } from './tags.service'; /** @@ -42,7 +42,7 @@ export class TagsRpc { throw new ForbiddenResource('tag writes require an authenticated user context'); } const input = asPayload(params.input); - const tagId = num(params.tagId, 'tagId'); + const tagId = rowIdParam(params.tagId, 'tagId'); await this.requireOwnTag(tagId, ctx.actingUserId); return this.tags.update( tagId, @@ -56,7 +56,7 @@ export class TagsRpc { if (ctx.actingUserId === undefined) { throw new ForbiddenResource('tag writes require an authenticated user context'); } - const tagId = num(params.tagId, 'tagId'); + const tagId = rowIdParam(params.tagId, 'tagId'); await this.requireOwnTag(tagId, ctx.actingUserId); await this.tags.remove(tagId); return { deleted: true }; diff --git a/server/src/nest/todo/todo.mcp.ts b/server/src/nest/todo/todo.mcp.ts index 73c3c9fdb..a6ef55a6b 100644 --- a/server/src/nest/todo/todo.mcp.ts +++ b/server/src/nest/todo/todo.mcp.ts @@ -14,6 +14,7 @@ import { } from '../../nest-mcp'; import { addonGate } from '../addons/addon-gate'; import { AddonsService } from '../addons/addons.service'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { TodoService } from './todo.service'; import { idSchema } from '@trek/shared'; @@ -23,11 +24,6 @@ import { z } from 'zod'; /** Legacy registrar gate: the whole todo surface rides the packing addon. */ const packingAddonOn = addonGate(ADDON_IDS.PACKING); -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - /** * Todo MCP surface — ported 1:1 from the legacy registrars: the eight tools * from src/mcp/tools/todos.ts and the trek://trips/{tripId}/todos resource @@ -297,7 +293,7 @@ export class TodoMcp { access: { group: 'todos', mode: 'read' }, }) async tripTodosResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.todos.verifyTripAccess(id, ctx.userId))) { return { contents: [ diff --git a/server/src/nest/todo/todo.rpc.ts b/server/src/nest/todo/todo.rpc.ts index e86b31e1a..580c97536 100644 --- a/server/src/nest/todo/todo.rpc.ts +++ b/server/src/nest/todo/todo.rpc.ts @@ -2,7 +2,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { asPayload, num } from '../../nest-rpc/rpc-params'; +import { asPayload, rowIdParam } from '../../nest-rpc/rpc-params'; import { RealtimeService } from '../realtime/realtime.service'; import { TodoService } from './todo.service'; @@ -31,13 +31,13 @@ export class TodoRpc { return await this.guards.tripRead( params, ctx, - async () => (await this.todos.listItems(String(num(params.tripId, 'tripId')))) as unknown[], + async () => (await this.todos.listItems(String(rowIdParam(params.tripId, 'tripId')))) as unknown[], ); } @PluginMethod('todos.create', { permission: 'db:write:todos' }) async create(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'todo'); const input = asPayload(params.input); if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('todo name is required'); @@ -49,8 +49,8 @@ export class TodoRpc { @PluginMethod('todos.update', { permission: 'db:write:todos' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const todoId = num(params.todoId, 'todoId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const todoId = rowIdParam(params.todoId, 'todoId'); const actor = this.guards.requireActor(ctx, 'todo'); await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION); const input = asPayload(params.input); @@ -62,8 +62,8 @@ export class TodoRpc { @PluginMethod('todos.delete', { permission: 'db:write:todos' }) async delete(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const todoId = num(params.todoId, 'todoId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const todoId = rowIdParam(params.todoId, 'todoId'); const actor = this.guards.requireActor(ctx, 'todo'); await this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION); if (!(await this.todos.deleteItem(String(tripId), todoId))) { diff --git a/server/src/nest/todo/todo.service.ts b/server/src/nest/todo/todo.service.ts index 00d02278d..b479a409e 100644 --- a/server/src/nest/todo/todo.service.ts +++ b/server/src/nest/todo/todo.service.ts @@ -103,7 +103,7 @@ export class TodoService { * parsing carry: `TodoController.update` now parses `:id` once via * `toRowId` and threads the number here, instead of the raw route string * reaching `TodoItemsRepository.findInTrip`/`.update` and relying on - * SQLite's column-affinity CAST to match it; `todos.rpc.ts`'s `num()` and + * SQLite's column-affinity CAST to match it; `todos.rpc.ts`'s `rowIdParam()` and * `todo.mcp.ts`'s Zod-typed `itemId` were already real numbers). `tripId` * stays `string | number` — a separate, still-accepted carry (the trip id * is gated for ACCESS by `TripAccessGuard`, not threaded as a parsed diff --git a/server/src/nest/trip-members/trip-members.service.ts b/server/src/nest/trip-members/trip-members.service.ts index a524f0daa..4739b6b60 100644 --- a/server/src/nest/trip-members/trip-members.service.ts +++ b/server/src/nest/trip-members/trip-members.service.ts @@ -206,7 +206,7 @@ export class TripMembersService { /** * `tripId: number` (Plan 4 Task 8a — narrowed from `string | number`): - * every caller now passes an already-parsed id — `trips.rpc.ts`'s `num()`, + * every caller now passes an already-parsed id — `trips.rpc.ts`'s `rowIdParam()`, * `trips.mcp.ts`'s Zod-typed tool input, and `TripMembersController * .removeMember`'s own `toRowId` parse (added alongside this narrowing, * the route's one remaining raw-string caller). diff --git a/server/src/nest/trips/trips.mcp.ts b/server/src/nest/trips/trips.mcp.ts index ccb10d483..339d54ee3 100644 --- a/server/src/nest/trips/trips.mcp.ts +++ b/server/src/nest/trips/trips.mcp.ts @@ -20,6 +20,7 @@ import { AddonsService } from '../addons/addons.service'; import { CalendarService } from '../calendar/calendar.service'; import { CollabService } from '../collab/collab.service'; import { DomainError } from '../common/domain-error'; +import { uriRowId } from '../common/row-id'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; import { tripIdPromptArg } from '../mcp-shared/prompt-args'; import { TodoService } from '../todo/todo.service'; @@ -39,11 +40,6 @@ import { import { z } from 'zod'; -function parseId(value: string | string[]): number | null { - const n = Number(Array.isArray(value) ? value[0] : value); - return Number.isInteger(n) && n > 0 ? n : null; -} - function accessDenied(uri: string) { return { contents: [ @@ -738,7 +734,7 @@ export class TripsMcp { access: (ctx) => canReadTrips(ctx.scopes), }) async tripResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.trips.canAccessTrip(id, ctx.userId))) return accessDenied(uri.href); const trip = await this.trips.get(id, ctx.userId); return jsonContent(uri.href, trip); @@ -752,7 +748,7 @@ export class TripsMcp { access: (ctx) => canReadTrips(ctx.scopes), }) async tripMembersResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) { - const id = parseId(tripId); + const id = uriRowId(tripId); if (id === null || !(await this.trips.canAccessTrip(id, ctx.userId))) return accessDenied(uri.href); const ownerRow = await this.trips.getOwner(id); if (!ownerRow) return accessDenied(uri.href); diff --git a/server/src/nest/trips/trips.rpc.ts b/server/src/nest/trips/trips.rpc.ts index 85a84c0e8..0265eccc2 100644 --- a/server/src/nest/trips/trips.rpc.ts +++ b/server/src/nest/trips/trips.rpc.ts @@ -6,7 +6,7 @@ import { PluginGuards } from '../../nest-rpc/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../nest-rpc/rpc-errors'; import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorators'; import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types'; -import { num, schemaMessage } from '../../nest-rpc/rpc-params'; +import { schemaMessage, rowIdParam } from '../../nest-rpc/rpc-params'; import { AccommodationsService } from '../accommodations/accommodations.service'; import { DaysService } from '../days/days.service'; import { RealtimeService } from '../realtime/realtime.service'; @@ -64,7 +64,7 @@ export class TripsRpc { return this.guards.tripRead(params, ctx, async () => // db:read:trips is a read grant on the trip, not on the credential that // publishes it anonymously — see withoutFeedToken. RP1 — TripsRepository.findRaw. - withoutFeedToken(await this.em.getRepository(Trips).findRaw(num(params.tripId, 'tripId'))), + withoutFeedToken(await this.em.getRepository(Trips).findRaw(rowIdParam(params.tripId, 'tripId'))), ); } @@ -77,13 +77,15 @@ export class TripsRpc { return this.guards.tripRead( params, ctx, - async () => await this.em.getRepository(Places).listForTripOrdered(num(params.tripId, 'tripId')), + async () => await this.em.getRepository(Places).listForTripOrdered(rowIdParam(params.tripId, 'tripId')), ); } @PluginMethod('trips.getReservations', { permission: 'db:read:trips' }) getReservations(params: Record, ctx: PluginRpcContext): unknown { - return this.guards.tripRead(params, ctx, async () => this.reservations.list(String(num(params.tripId, 'tripId')))); + return this.guards.tripRead(params, ctx, async () => + this.reservations.list(String(rowIdParam(params.tripId, 'tripId'))), + ); } @PluginMethod('trips.getDays', { permission: 'db:read:trips' }) @@ -93,7 +95,7 @@ export class TripsRpc { return this.guards.tripRead( params, ctx, - async () => ((await this.days.list(num(params.tripId, 'tripId'))) as { days: unknown[] }).days, + async () => ((await this.days.list(rowIdParam(params.tripId, 'tripId'))) as { days: unknown[] }).days, ); } @@ -102,7 +104,7 @@ export class TripsRpc { return this.guards.tripRead( params, ctx, - async () => (await this.accommodations.list(num(params.tripId, 'tripId'))) as unknown[], + async () => (await this.accommodations.list(rowIdParam(params.tripId, 'tripId'))) as unknown[], ); } @@ -133,13 +135,14 @@ export class TripsRpc { return this.guards.tripRead( params, ctx, - async () => await this.em.getRepository(TripMembers).listRawUsernameAndDisplayName(num(params.tripId, 'tripId')), + async () => + await this.em.getRepository(TripMembers).listRawUsernameAndDisplayName(rowIdParam(params.tripId, 'tripId')), ); } @PluginMethod('trips.update', { permission: 'db:write:trips' }) async update(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); + const tripId = rowIdParam(params.tripId, 'tripId'); const actor = this.guards.requireActor(ctx, 'trip'); const parsed = tripUpdateRequestSchema.safeParse(params.input); if (!parsed.success) throw new BadParams(`invalid trip: ${schemaMessage(parsed.error)}`); @@ -202,8 +205,8 @@ export class TripsRpc { @PluginMethod('trips.addMember', { permission: 'db:write:members' }) async addMember(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const targetUserId = num(params.userId, 'userId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const targetUserId = rowIdParam(params.userId, 'userId'); const actor = this.guards.requireActor(ctx, 'trip member'); await this.guards.requireTripEdit(tripId, actor, MEMBER_MANAGE_ACTION); // RP5 — UsersRepository.findIdAndEmail (existence check only; the `email` field is unused here). @@ -222,8 +225,8 @@ export class TripsRpc { @PluginMethod('trips.removeMember', { permission: 'db:write:members' }) async removeMember(params: Record, ctx: PluginRpcContext): Promise { - const tripId = num(params.tripId, 'tripId'); - const targetUserId = num(params.userId, 'userId'); + const tripId = rowIdParam(params.tripId, 'tripId'); + const targetUserId = rowIdParam(params.userId, 'userId'); const actor = this.guards.requireActor(ctx, 'trip member'); await this.guards.requireTripEdit(tripId, actor, MEMBER_MANAGE_ACTION); // Never remove the OWNER through this path: that would orphan the trip. diff --git a/server/tests/unit/nest-rpc/rpc-params.test.ts b/server/tests/unit/nest-rpc/rpc-params.test.ts new file mode 100644 index 000000000..0091403d0 --- /dev/null +++ b/server/tests/unit/nest-rpc/rpc-params.test.ts @@ -0,0 +1,26 @@ +import { BadParams } from '../../../src/nest-rpc/rpc-errors'; +import { optionalRowIdParam, rowIdParam } from '../../../src/nest-rpc/rpc-params'; + +import { describe, expect, it } from 'vitest'; + +describe('rowIdParam', () => { + it('RPCPARAM-001: takes a safe integer and the decimal string of one, as the published contract allows', () => { + expect(rowIdParam(5, 'tripId')).toBe(5); + expect(rowIdParam('5', 'tripId')).toBe(5); + expect(rowIdParam('007', 'tripId')).toBe(7); + }); + + it('RPCPARAM-002: refuses what num() let through and an engine reads its own way, with num() message', () => { + for (const value of ['0x5', '5e0', '5.0', '+5', ' 5', 1.5, 1e20, '99999999999999999999', '-1', 'abc', undefined]) { + expect(() => rowIdParam(value, 'tripId'), String(value)).toThrow(new BadParams('tripId must be a number')); + } + }); + + it('RPCPARAM-003: optionalRowIdParam leaves an absent param out and reads any other one like rowIdParam', () => { + expect(optionalRowIdParam(undefined, 'dayId')).toBeUndefined(); + expect(optionalRowIdParam('5', 'dayId')).toBe(5); + for (const value of [null, '0x5', '5e0', 1.5, '']) { + expect(() => optionalRowIdParam(value, 'dayId'), String(value)).toThrow(new BadParams('dayId must be a number')); + } + }); +}); diff --git a/server/tests/unit/nest/accommodations.rpc.test.ts b/server/tests/unit/nest/accommodations.rpc.test.ts new file mode 100644 index 000000000..d42589b78 --- /dev/null +++ b/server/tests/unit/nest/accommodations.rpc.test.ts @@ -0,0 +1,82 @@ +/** + * The plugin RPC accommodation writes read their place and day refs as row ids. + * + * accommodations.create read them with Math.trunc(Number(...)), so '0x5' was + * place 5 and 1e20 reached Postgres, which refuses it as out of range; + * accommodations.update bound the open input's refs as sent. Both now refuse + * such a value with BAD_PARAMS before the service sees it. + */ +import type { TripsRepository } from '../../../src/db/repositories/Trips.repository'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; +import { PluginGuards } from '../../../src/nest-rpc/plugin-guards.service'; +import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing'; +import { AccommodationsRpc } from '../../../src/nest/accommodations/accommodations.rpc'; +import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host'; +import type { RpcError, RpcRequest } from '../../../src/nest/plugins/protocol/envelope'; +import { makeDeps } from '../../helpers/rpc-host-deps'; + +import { describe, expect, it, vi } from 'vitest'; + +const req = (method: string, params: Record): RpcRequest => ({ k: 'req', id: 'x', method, params }); + +function build() { + const service = { + getAccommodation: vi.fn(async () => ({ id: 3, place_id: 1, start_day_id: 1, end_day_id: 1 })), + validateAccommodationRefs: vi.fn(async () => []), + createAccommodation: vi.fn(async () => ({ accommodation: {}, mirror: {} })), + updateAccommodation: vi.fn(async () => ({ accommodation: {}, mirror: {} })), + announceMirror: vi.fn(async () => undefined), + }; + const guards = new PluginGuards( + { findAccessible: vi.fn(async () => ({ id: 1, user_id: 42 })) } as unknown as TripsRepository, + { checkPermission: vi.fn(() => true) } as unknown as PermissionsService, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, + ); + const registry = createTestPluginRegistry([ + new AccommodationsRpc(service as never, { broadcast: vi.fn() } as never, guards), + ]); + const host = new PluginRpcHost('p', new Set(['db:write:accommodations']), makeDeps(), registry); + return { host, service }; +} + +const MALFORMED = ['0x5', '5e0', '5.0', 1.5, 1e20, 'abc']; + +describe('AccommodationsRpc row ids', () => { + it('ACCRPC-001: create refuses a malformed place or day ref with BAD_PARAMS and writes nothing', async () => { + const { host, service } = build(); + const valid = { place_id: 5, start_day_id: 6, end_day_id: 6 }; + const cases = (['place_id', 'start_day_id', 'end_day_id'] as const).flatMap((field) => + MALFORMED.map((value) => ({ ...valid, [field]: value })), + ); + const replies = await Promise.all( + cases.map((input) => host.dispatch(req('accommodations.create', { tripId: 1, input }), 42)), + ); + expect(replies.map((r) => (r as RpcError).error?.code)).toEqual(cases.map(() => 'BAD_PARAMS')); + expect(service.createAccommodation).not.toHaveBeenCalled(); + + await host.dispatch(req('accommodations.create', { tripId: 1, input: { ...valid, place_id: '5' } }), 42); + expect(service.createAccommodation).toHaveBeenCalledWith(1, expect.objectContaining({ place_id: 5 })); + }); + + it('ACCRPC-002: update refuses a malformed ref in its open input with BAD_PARAMS and writes nothing', async () => { + const { host, service } = build(); + const cases = (['place_id', 'start_day_id', 'end_day_id'] as const).flatMap((field) => + MALFORMED.map((value) => ({ [field]: value })), + ); + const replies = await Promise.all( + cases.map((input) => host.dispatch(req('accommodations.update', { tripId: 1, accommodationId: 3, input }), 42)), + ); + expect(replies.map((r) => (r as RpcError).error)).toEqual( + cases.map((input) => + expect.objectContaining({ code: 'BAD_PARAMS', message: `${Object.keys(input)[0]} must be a number` }), + ), + ); + expect(service.updateAccommodation).not.toHaveBeenCalled(); + + await host.dispatch(req('accommodations.update', { tripId: 1, accommodationId: 3, input: { place_id: '5' } }), 42); + expect(service.validateAccommodationRefs).toHaveBeenCalledWith(1, 5, undefined, undefined); + }); +}); diff --git a/server/tests/unit/nest/realtime.gateway.test.ts b/server/tests/unit/nest/realtime.gateway.test.ts index c16654b32..950d029e1 100644 --- a/server/tests/unit/nest/realtime.gateway.test.ts +++ b/server/tests/unit/nest/realtime.gateway.test.ts @@ -242,6 +242,14 @@ describe('RealtimeGateway rooms', () => { expect(gw.handleLeave({ tripId: 7 }, ws)).toEqual({ type: 'left', tripId: 7 }); }); + it('WSGW-011b: join refuses a spelling of a reachable trip id that toRowId refuses, and joins no room', async () => { + const { gw, ws } = await connect('/ws?token=x'); + const spellings = ['0x7', '7e0', '7.0', ' 7', '+7', 7.5, 1e20]; + const replies = await Promise.all(spellings.map((tripId) => gw.handleJoin({ tripId } as never, ws))); + expect(replies).toEqual(spellings.map(() => ({ type: 'error', message: 'Access denied' }))); + expect(await gw.handleJoin({ tripId: '7' } as never, ws)).toEqual({ type: 'joined', tripId: 7 }); + }); + it('WSGW-012: a frame with no tripId is ignored rather than answered', async () => { const { gw, ws } = await connect('/ws?token=x'); expect(await gw.handleJoin({}, ws)).toBeUndefined(); @@ -412,6 +420,18 @@ describe('book rooms', () => { expect(bookPeers(4)).toEqual([]); }); + it('WSGW-BOOK-002b: refuses a spelling of a visible journey id that toRowId refuses, and adds nobody', async () => { + const gw = new RealtimeGateway(new TripAccessService(db), tokens, journeys, users, appSettings); + const ws = socket(); + registerSocket(ws, { id: 3, username: 'm' } as User); + const j = nextJourney++; + const spellings = [`0x${j.toString(16)}`, `${j}e0`, `${j}.0`, ` ${j}`, j + 0.5, 1e20]; + const replies = await Promise.all(spellings.map((journeyId) => gw.handleBookJoin({ journeyId } as never, ws))); + expect(replies).toEqual(spellings.map(() => ({ type: 'error', message: 'Access denied' }))); + expect(bookPeers(j)).toEqual([]); + expect(canAccessJourney).not.toHaveBeenCalled(); + }); + it('WSGW-BOOK-003: tells everyone in the book who is in it', async () => { const j = nextJourney++; const { ws: first } = await joined(j); diff --git a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts b/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts index 09c0db0d2..e02a32b7e 100644 --- a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts +++ b/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts @@ -266,6 +266,23 @@ describe('addon-gated domains validate their input', () => { }); }); + it('ADDONERR-002b collab.createMessage reads replyTo with rowIdParam: a malformed one is BAD_PARAMS, none is null', async () => { + const createMessage = vi.fn(() => ({ error: null, message: {} })); + const host = build({ collab: { createMessage } }); + const send = (replyTo: unknown) => + host.dispatch(req('collab.createMessage', { tripId: 1, text: 'hi', replyTo }), 42); + // typeof === 'number' let 1.5 and 1e20 through to SQL and dropped the digits '5' a plugin may send. + const refused = await Promise.all(['0x5', '5e0', 1.5, 1e20, 'abc'].map((replyTo) => send(replyTo))); + expect(refused.map((r) => err(r))).toEqual( + refused.map(() => expect.objectContaining({ code: 'BAD_PARAMS', message: 'replyTo must be a number' })), + ); + expect(createMessage).not.toHaveBeenCalled(); + await send('5'); + await send(null); + await send(undefined); + expect(createMessage.mock.calls.map((call) => (call as unknown[])[3])).toEqual([5, null, null]); + }); + it('ADDONERR-003 atlas rejects a code that is empty or too long', async () => { const host = build(); expect(err(await host.dispatch(req('atlas.markCountry', { code: '' }), 42)).message).toBe(