diff --git a/server/src/nest/budget/budget.module.ts b/server/src/nest/budget/budget.module.ts index 5ca713d1f..46c30c578 100644 --- a/server/src/nest/budget/budget.module.ts +++ b/server/src/nest/budget/budget.module.ts @@ -3,6 +3,7 @@ import { BudgetController } from './budget.controller'; import { BudgetService } from './budget.service'; import { BudgetMcp } from './budget.mcp'; import { ExchangeRatesService } from './exchange-rates.service'; +import { ExchangeRatesRpc } from './exchange-rates.rpc'; import { PermissionsModule } from '../permissions/permissions.module'; import { AuthModule } from '../auth/auth.module'; @@ -11,7 +12,7 @@ import { AuthModule } from '../auth/auth.module'; @Module({ imports: [PermissionsModule, AuthModule], controllers: [BudgetController], - providers: [BudgetService, ExchangeRatesService, BudgetMcp], + providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc], // For in-container consumers (PluginHostDepsFactory, TripsService, // ReservationsService, BookingImportService). exports: [BudgetService, ExchangeRatesService], diff --git a/server/src/nest/budget/exchange-rates.rpc.ts b/server/src/nest/budget/exchange-rates.rpc.ts new file mode 100644 index 000000000..64d25a771 --- /dev/null +++ b/server/src/nest/budget/exchange-rates.rpc.ts @@ -0,0 +1,21 @@ +import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; +import { str } from '../plugins/host/rpc-params'; +import { ExchangeRatesService } from './exchange-rates.service'; + +/** + * The exchange-rate surface a plugin may reach (#plugins). Tenant-free like + * weather: a cached upstream feed with no user and no trip behind it, useful to any + * plugin that shows or converts money. + * + * Note this is NOT gated on the Costs addon. It carries no budget data, and the + * router never gated it either. + */ +@PluginController() +export class ExchangeRatesRpc { + constructor(private readonly exchangeRates: ExchangeRatesService) {} + + @PluginMethod('rates.get', { permission: 'rates:read' }) + get(params: Record): unknown { + return this.exchangeRates.getRates(str(params.base, 'base')); + } +} diff --git a/server/src/nest/categories/categories.module.ts b/server/src/nest/categories/categories.module.ts index 8b15b331d..4386e5766 100644 --- a/server/src/nest/categories/categories.module.ts +++ b/server/src/nest/categories/categories.module.ts @@ -2,11 +2,12 @@ import { Module } from '@nestjs/common'; import { CategoriesController } from './categories.controller'; import { CategoriesMcp } from './categories.mcp'; import { CategoriesService } from './categories.service'; +import { CategoriesRpc } from './categories.rpc'; /** Categories domain (L4 leaf module). Registered in AppModule. */ @Module({ controllers: [CategoriesController], - providers: [CategoriesService, CategoriesMcp], + providers: [CategoriesService, CategoriesMcp, CategoriesRpc], // For in-container consumers (PluginHostDepsFactory). exports: [CategoriesService], }) diff --git a/server/src/nest/categories/categories.rpc.ts b/server/src/nest/categories/categories.rpc.ts new file mode 100644 index 000000000..36b2a2642 --- /dev/null +++ b/server/src/nest/categories/categories.rpc.ts @@ -0,0 +1,17 @@ +import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; +import { CategoriesService } from './categories.service'; + +/** + * The category surface a plugin may reach (#plugins). A global, read-only + * reference list that carries no tenant data, so it needs neither an acting user + * nor a trip gate. + */ +@PluginController() +export class CategoriesRpc { + constructor(private readonly categories: CategoriesService) {} + + @PluginMethod('categories.list', { permission: 'db:read:categories' }) + list(): unknown[] { + return this.categories.list() as unknown[]; + } +} diff --git a/server/src/nest/days/day-notes.rpc.ts b/server/src/nest/days/day-notes.rpc.ts new file mode 100644 index 000000000..0f222676b --- /dev/null +++ b/server/src/nest/days/day-notes.rpc.ts @@ -0,0 +1,79 @@ +import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; +import { PluginGuards } from '../plugins/host/plugin-guards.service'; +import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors'; +import { asPayload, num } from '../plugins/host/rpc-params'; +import type { PluginRpcContext } from '../plugins/host/rpc-kit/types'; +import { RealtimeService } from '../realtime/realtime.service'; +import { DayNotesService } from './day-notes.service'; + +/** Day notes ride on the day permission, like the rest of the day surface. */ +const DAY_NOTE_EDIT_ACTION = 'day_edit'; + +type DayNoteInput = { text?: string; time?: string; icon?: string; sort_order?: number }; + +/** + * The day-note surface a plugin may reach (#plugins). Core data with no addon + * behind it, trip-scoped, so the standard membership gate applies. + * + * Every write re-checks that the day (or the note) really belongs to the trip it + * was addressed with, so a plugin cannot write a note onto another trip's day by + * naming its id. The dayNote:* broadcasts match what the REST controller emits. + */ +@PluginController() +export class DayNotesRpc { + constructor( + private readonly dayNotes: DayNotesService, + private readonly realtime: RealtimeService, + private readonly guards: PluginGuards, + ) {} + + @PluginMethod('daynotes.list', { permission: 'db:read:daynotes' }) + list(params: Record, ctx: PluginRpcContext): unknown { + return this.guards.tripRead(params, ctx, () => + this.dayNotes.list(num(params.dayId, 'dayId'), num(params.tripId, 'tripId')), + ); + } + + @PluginMethod('daynotes.create', { permission: 'db:write:daynotes' }) + create(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(params.tripId, 'tripId'); + const dayId = num(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'); + this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION); + if (!this.dayNotes.dayExists(dayId, tripId)) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`); + const i = input as DayNoteInput; + const note = this.dayNotes.create(dayId, tripId, i.text ?? '', i.time, i.icon, i.sort_order); + this.realtime.broadcast(tripId, 'dayNote:created', { dayId, note }, undefined); + return note; + } + + @PluginMethod('daynotes.update', { permission: 'db:write:daynotes' }) + update(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(params.tripId, 'tripId'); + const dayId = num(params.dayId, 'dayId'); + const noteId = num(params.noteId, 'noteId'); + const actor = this.guards.requireActor(ctx, 'day note'); + this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION); + const current = this.dayNotes.getNote(noteId, dayId, tripId); + if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`); + const note = this.dayNotes.update(noteId, current as never, asPayload(params.input) as DayNoteInput); + this.realtime.broadcast(tripId, 'dayNote:updated', { dayId, note }, undefined); + return note; + } + + @PluginMethod('daynotes.delete', { permission: 'db:write:daynotes' }) + delete(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(params.tripId, 'tripId'); + const dayId = num(params.dayId, 'dayId'); + const noteId = num(params.noteId, 'noteId'); + const actor = this.guards.requireActor(ctx, 'day note'); + this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION); + const current = this.dayNotes.getNote(noteId, dayId, tripId); + if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`); + this.dayNotes.remove(noteId); + this.realtime.broadcast(tripId, 'dayNote:deleted', { noteId, dayId }, undefined); + return { deleted: true }; + } +} diff --git a/server/src/nest/days/days.module.ts b/server/src/nest/days/days.module.ts index 87a7fe538..d61c054a0 100644 --- a/server/src/nest/days/days.module.ts +++ b/server/src/nest/days/days.module.ts @@ -4,6 +4,9 @@ import { DaysService } from './days.service'; import { DaysMcp } from './days.mcp'; import { DayNotesController } from './day-notes.controller'; import { DayNotesService } from './day-notes.service'; +import { DayNotesRpc } from './day-notes.rpc'; +import { PluginGuardsModule } from '../plugins/host/plugin-guards.module'; +import { RealtimeModule } from '../realtime/realtime.module'; import { DayNotesMcp } from './day-notes.mcp'; import { PermissionsModule } from '../permissions/permissions.module'; import { QueryHelpersModule } from '../query-helpers/query-helpers.module'; @@ -20,9 +23,9 @@ import { AuthModule } from '../auth/auth.module'; * controllers). */ @Module({ - imports: [PermissionsModule, QueryHelpersModule, PlacesModule, AuthModule], + imports: [PermissionsModule, QueryHelpersModule, PlacesModule, AuthModule, RealtimeModule, PluginGuardsModule], controllers: [DaysController, DayNotesController], - providers: [DaysService, DaysMcp, DayNotesService, DayNotesMcp], + providers: [DaysService, DaysMcp, DayNotesService, DayNotesMcp, DayNotesRpc], exports: [DaysService, DayNotesService], }) export class DaysModule {} diff --git a/server/src/nest/plugins/host/plugin-guards.module.ts b/server/src/nest/plugins/host/plugin-guards.module.ts new file mode 100644 index 000000000..268b0033d --- /dev/null +++ b/server/src/nest/plugins/host/plugin-guards.module.ts @@ -0,0 +1,23 @@ +import { Module } from '@nestjs/common'; +import { PermissionsModule } from '../../permissions/permissions.module'; +import { AddonsModule } from '../../addons/addons.module'; +import { PluginGuards } from './plugin-guards.service'; + +/** + * A leaf module whose only job is to hand PluginGuards to the domain modules. + * + * It cannot live in PluginsModule: that module imports 22 domain modules, so a + * domain importing it back to reach the guards would close a hard cycle + * (PluginsModule -> TodoModule -> PluginsModule) and the only way out would be + * forwardRef. PermissionsModule and AddonsModule are themselves leaves and + * DatabaseModule is @Global, so this module imports nothing that leads back here. + * + * Same shape and same reason as MailerModule, which broke + * AuthModule <-> NotificationsModule. + */ +@Module({ + imports: [PermissionsModule, AddonsModule], + providers: [PluginGuards], + exports: [PluginGuards], +}) +export class PluginGuardsModule {} diff --git a/server/src/nest/plugins/host/plugin-host-deps.factory.ts b/server/src/nest/plugins/host/plugin-host-deps.factory.ts index ad9b998cd..cc9ba3f7f 100644 --- a/server/src/nest/plugins/host/plugin-host-deps.factory.ts +++ b/server/src/nest/plugins/host/plugin-host-deps.factory.ts @@ -577,7 +577,6 @@ export class PluginHostDepsFactory { } }, // --- Exchange rates: the same cached upstream feed the budget uses (tenant-free). --- - getRates: (base) => this.exchangeRates.getRates(base), // --- Trip (trip_edit). Only the schema-writable fields reach updateTrip; its // NotFound/Validation errors are mapped to clean RPC codes. --- canEditTrip: (tripId, userId) => this.canEditTripAs('trip_edit', tripId, userId), @@ -750,30 +749,8 @@ export class PluginHostDepsFactory { return { deleted: true }; }, // Day notes are core (no addon) and trip-scoped; membership is enforced by the host. - listDayNotes: (tripId, dayId) => this.dayNotes.list(dayId, tripId), // --- Day notes write (day_edit). The day must belong to the trip; broadcasts the // same dayNote:* events the REST controller emits so open sessions update live. --- - createDayNote: (tripId, dayId, input) => { - if (!this.dayNotes.dayExists(dayId, tripId)) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`); - const i = input as { text?: string; time?: string; icon?: string; sort_order?: number }; - const note = this.dayNotes.create(dayId, tripId, i.text ?? '', i.time, i.icon, i.sort_order); - this.realtime.broadcast(tripId, 'dayNote:created', { dayId, note }, undefined); - return note; - }, - updateDayNote: (tripId, dayId, noteId, input) => { - const current = this.dayNotes.getNote(noteId, dayId, tripId); - if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`); - const note = this.dayNotes.update(noteId, current as never, input as { text?: string; time?: string; icon?: string; sort_order?: number }); - this.realtime.broadcast(tripId, 'dayNote:updated', { dayId, note }, undefined); - return note; - }, - deleteDayNote: (tripId, dayId, noteId) => { - const current = this.dayNotes.getNote(noteId, dayId, tripId); - if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`); - this.dayNotes.remove(noteId); - this.realtime.broadcast(tripId, 'dayNote:deleted', { noteId, dayId }, undefined); - return { deleted: true }; - }, // --- Reservations (bookings, reservation_edit). Delegates to ReservationsService // so the accommodation/budget-sync/notification/broadcast side effects match the // web app EXACTLY. socketId is undefined — a plugin has no originating socket. --- @@ -859,29 +836,9 @@ export class PluginHostDepsFactory { return members; }, // --- Read-convenience: weather (host cache, tenant-free), categories (global), roster --- - getWeather: (lat, lng, date) => getWeather(String(lat), String(lng), date, 'en'), - listCategories: () => this.categories.list() as unknown[], tripMembers: (tripId) => this.db.prepare('SELECT u.id, u.username, u.display_name, u.avatar FROM trip_members tm JOIN users u ON u.id = tm.user_id WHERE tm.trip_id = ?').all(tripId) as unknown[], // --- Todos (core, trip-scoped; the app's 'packing_edit' permission). --- - canEditTodos: (tripId, userId) => this.canEditTripAs('packing_edit', tripId, userId), - listTodos: (tripId) => this.todos.listItems(String(tripId)) as unknown[], - createTodo: (tripId, input) => { - const item = this.todos.createItem(String(tripId), input as never); - this.realtime.broadcast(tripId, 'todo:created', { item }, undefined); - return item; - }, - updateTodo: (tripId, todoId, input) => { - const updated = this.todos.updateItem(String(tripId), String(todoId), input as never, Object.keys(input)); - if (!updated) throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`); - this.realtime.broadcast(tripId, 'todo:updated', { item: updated }, undefined); - return updated; - }, - deleteTodo: (tripId, todoId) => { - if (!this.todos.deleteItem(String(tripId), String(todoId))) throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`); - this.realtime.broadcast(tripId, 'todo:deleted', { itemId: todoId }, undefined); - return { deleted: true }; - }, // --- Plugin metadata (db:meta). A per-plugin namespaced key/value store keyed // to a core entity; the plugin only ever sees rows tagged with its own id. --- metaEntityTrip: (entityType, entityId) => { diff --git a/server/src/nest/plugins/host/rpc-host.ts b/server/src/nest/plugins/host/rpc-host.ts index cf7d2db60..193ab5700 100644 --- a/server/src/nest/plugins/host/rpc-host.ts +++ b/server/src/nest/plugins/host/rpc-host.ts @@ -161,13 +161,9 @@ export interface HostDeps { createJournal(userId: number, input: Record): unknown; deleteJournal(userId: number, journeyId: number): unknown; /** A trip day's notes (trip-scoped), for `daynotes.list`. */ - listDayNotes(tripId: number, dayId: number): unknown[]; /** Create a day note (the day must be on the trip); broadcasts dayNote:created. */ - createDayNote(tripId: number, dayId: number, input: Record): unknown; /** Update a day note (scoped to the day+trip); broadcasts dayNote:updated. */ - updateDayNote(tripId: number, dayId: number, noteId: number, input: Record): unknown; /** Delete a day note (scoped to the day+trip); broadcasts dayNote:deleted. */ - deleteDayNote(tripId: number, dayId: number, noteId: number): unknown; /** All budget items of one trip, hydrated with members/payers. */ listCostsForTrip(tripId: number): unknown[]; /** All budget items across every trip the acting user can access. */ @@ -199,7 +195,6 @@ export interface HostDeps { canCreateTrip(userId: number): boolean; createTripForUser(userId: number, input: Record): unknown; // --- Exchange rates (tenant-free, like weather) --- - getRates(base: string): Promise; // --- Cross-trip reads (membership baked in — every trip the acting user can access) --- /** Every trip the acting user owns or is a member of (the listTrips baseline). */ listTripsForUser(userId: number): unknown[]; @@ -241,16 +236,9 @@ export interface HostDeps { deletePackingBag(tripId: number, bagId: number): unknown; setPackingBagMembers(tripId: number, bagId: number, userIds: number[]): unknown; // --- Read-convenience: weather (tenant-free), categories (global), the trip roster --- - getWeather(lat: number, lng: number, date: string | undefined): unknown; - listCategories(): unknown[]; tripMembers(tripId: number): unknown[]; // --- Tags (the acting user's own; no trip) --- // --- Todos (core, trip-scoped; the 'packing_edit' permission, like the REST path) --- - canEditTodos(tripId: number, userId: number): boolean; - listTodos(tripId: number): unknown[]; - createTodo(tripId: number, input: Record): unknown; - updateTodo(tripId: number, todoId: number, input: Record): unknown; - deleteTodo(tripId: number, todoId: number): unknown; // --- Plugin metadata on core entities (db:meta) --- /** The trip a trip/place/day belongs to (for the membership gate), or undefined. */ metaEntityTrip(entityType: string, entityId: number): number | undefined; @@ -596,12 +584,6 @@ export class PluginRpcHost { this.methods.set('journal.createJourney', (p, uid) => deps.createJournal(requireUid(uid), asPayload(p.input))); this.methods.set('journal.deleteJourney', (p, uid) => deps.deleteJournal(requireUid(uid), num(p.journeyId, 'journeyId'))); } - if (has('db:read:daynotes')) { - // Day notes are trip-scoped (core, no addon), so the standard membership gate applies. - this.methods.set('daynotes.list', (p, uid) => - this.tripRead(p, uid, () => deps.listDayNotes(num(p.tripId, 'tripId'), num(p.dayId, 'dayId'))), - ); - } if (has('db:read:costs')) { // "Costs" = budget items (trip-scoped). Same membership gate as trip reads; @@ -772,42 +754,9 @@ export class PluginRpcHost { }); } - if (has('rates:read')) { - // Exchange rates are tenant-free (like weather) — a cached upstream feed, no - // user or trip. Useful for any plugin that shows or converts money. - this.methods.set('rates.get', (p) => deps.getRates(str(p.base, 'base'))); - } + // rates.get now lives in src/nest/budget/exchange-rates.rpc.ts. - if (has('db:write:daynotes')) { - // Day notes are edited under the app's 'day_edit' permission (like days). The - // wiring verifies the day belongs to the trip, so a plugin can't note a day on - // another trip. Text is required; time/icon/sort_order are optional. - this.methods.set('daynotes.create', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const dayId = num(p.dayId, 'dayId'); - const actor = this.requireActor(uid, 'day note'); - const input = asPayload(p.input); - if (typeof input.text !== 'string' || input.text.trim() === '') throw new BadParams('note text is required'); - this.requireTripEdit(tripId, actor, deps.canEditDays); - return deps.createDayNote(tripId, dayId, input); - }); - this.methods.set('daynotes.update', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const dayId = num(p.dayId, 'dayId'); - const noteId = num(p.noteId, 'noteId'); - const actor = this.requireActor(uid, 'day note'); - this.requireTripEdit(tripId, actor, deps.canEditDays); - return deps.updateDayNote(tripId, dayId, noteId, asPayload(p.input)); - }); - this.methods.set('daynotes.delete', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const dayId = num(p.dayId, 'dayId'); - const noteId = num(p.noteId, 'noteId'); - const actor = this.requireActor(uid, 'day note'); - this.requireTripEdit(tripId, actor, deps.canEditDays); - return deps.deleteDayNote(tripId, dayId, noteId); - }); - } + // daynotes.* now live in src/nest/days/day-notes.rpc.ts. if (has('db:write:reservations')) { // Bookings write. Gated exactly like the reservations REST/MCP path: trip @@ -938,43 +887,9 @@ export class PluginRpcHost { }); } - if (has('weather:read')) { - // Tenant-free host cache: forecast by coordinates + optional date. No user needed. - this.methods.set('weather.get', (p) => deps.getWeather(num(p.lat, 'lat'), num(p.lng, 'lng'), typeof p.date === 'string' ? p.date : undefined)); - } - if (has('db:read:categories')) { - // Global, read-only reference list — carries no tenant data. - this.methods.set('categories.list', () => deps.listCategories()); - } + // weather.get and categories.list now live in their own domains' *.rpc.ts. // tags.* now lives in src/nest/tags/tags.rpc.ts, bound through the registry below. - if (has('db:read:todos')) { - this.methods.set('todos.list', (p, uid) => this.tripRead(p, uid, () => deps.listTodos(num(p.tripId, 'tripId')))); - } - if (has('db:write:todos')) { - // Todos are edited under the app's 'packing_edit' permission (like the REST path). - this.methods.set('todos.create', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const actor = this.requireActor(uid, 'todo'); - const input = asPayload(p.input); - if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('todo name is required'); - this.requireTripEdit(tripId, actor, deps.canEditTodos); - return deps.createTodo(tripId, input); - }); - this.methods.set('todos.update', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const todoId = num(p.todoId, 'todoId'); - const actor = this.requireActor(uid, 'todo'); - this.requireTripEdit(tripId, actor, deps.canEditTodos); - return deps.updateTodo(tripId, todoId, asPayload(p.input)); - }); - this.methods.set('todos.delete', (p, uid) => { - const tripId = num(p.tripId, 'tripId'); - const todoId = num(p.todoId, 'todoId'); - const actor = this.requireActor(uid, 'todo'); - this.requireTripEdit(tripId, actor, deps.canEditTodos); - return deps.deleteTodo(tripId, todoId); - }); - } + // todos.* now live in src/nest/todo/todo.rpc.ts. if (has('db:meta')) { // A plugin's OWN namespaced key/value store attached to a core entity. Not diff --git a/server/src/nest/plugins/plugins.module.ts b/server/src/nest/plugins/plugins.module.ts index e0deaa63f..db13fa510 100644 --- a/server/src/nest/plugins/plugins.module.ts +++ b/server/src/nest/plugins/plugins.module.ts @@ -28,7 +28,7 @@ import { PluginRuntimeService } from './plugin-runtime.service'; import { PluginRegistryService } from './registry/registry.service'; import { PluginHostDepsFactory } from './host/plugin-host-deps.factory'; import { PluginRpcRegistryService } from './host/rpc-kit/registry.service'; -import { PluginGuards } from './host/plugin-guards.service'; +import { PluginGuardsModule } from './host/plugin-guards.module'; import { TagsModule } from '../tags/tags.module'; import { CategoriesModule } from '../categories/categories.module'; import { BudgetModule } from '../budget/budget.module'; @@ -62,14 +62,14 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module' // The DI-native domain services the plugin host wiring injects // (PluginHostDepsFactory); DatabaseModule is @Global, so not listed. // DiscoveryModule is what lets PluginRpcRegistryService find the @PluginController - // providers at boot. - imports: [DiscoveryModule, TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule, CollabModule, VacayModule, TripsModule, PermissionsModule, AuditModule, AddonsModule, PlacesModule, CollectionsModule, AtlasModule, NotificationsModule, TripMembershipModule, JourneyDomainModule], + // providers at boot. PluginGuardsModule is a leaf that hands the resource gates to + // the domain modules; it must not be this module, because the domains would then + // have to import PluginsModule back and close a cycle. + imports: [DiscoveryModule, PluginGuardsModule, TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule, DaysModule, AssignmentsModule, LlmParseModule, FilesModule, CollabModule, VacayModule, TripsModule, PermissionsModule, AuditModule, AddonsModule, PlacesModule, CollectionsModule, AtlasModule, NotificationsModule, TripMembershipModule, JourneyDomainModule], controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController, PlaceDetailsController, TripWarningsController, ViewContributionsController, TripCardContributionsController, PluginPhotosController, PluginCalendarController, MapMarkersController, MapLayersController, PluginRoutesController, DayScheduleController, DayTintsController, PdfSectionsController, AtlasLayersController, JournalEntryRowsController, PluginUserSettingsController, PluginOAuthController, PluginActivityController], - providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory, PluginRpcRegistryService, PluginGuards], - // PluginRuntimeService is exported so the admin addon-toggle handler can - // cascade-disable plugins whose required addon was just turned off (#plugins - // dependencies). PluginGuards is exported so a domain module can inject it into - // its own .rpc.ts without importing the plugin host. - exports: [PluginRuntimeService, PluginGuards], + providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory, PluginRpcRegistryService], + // Exported so the admin addon-toggle handler can cascade-disable plugins whose + // required addon was just turned off (#plugins dependencies). + exports: [PluginRuntimeService], }) export class PluginsModule {} diff --git a/server/src/nest/todo/todo.module.ts b/server/src/nest/todo/todo.module.ts index e37020f77..df839db36 100644 --- a/server/src/nest/todo/todo.module.ts +++ b/server/src/nest/todo/todo.module.ts @@ -2,15 +2,18 @@ import { Module } from '@nestjs/common'; import { TodoController } from './todo.controller'; import { TodoMcp } from './todo.mcp'; import { TodoService } from './todo.service'; +import { TodoRpc } from './todo.rpc'; +import { PluginGuardsModule } from '../plugins/host/plugin-guards.module'; +import { RealtimeModule } from '../realtime/realtime.module'; import { PermissionsModule } from '../permissions/permissions.module'; import { AuthModule } from '../auth/auth.module'; /** To-do domain (S3 — Phase 2 trip sub-domain). Registered in AppModule. * Exports TodoService for in-container consumers (TripsService bundle). */ @Module({ - imports: [PermissionsModule, AuthModule], + imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule], controllers: [TodoController], - providers: [TodoService, TodoMcp], + providers: [TodoService, TodoMcp, TodoRpc], exports: [TodoService], }) export class TodoModule {} diff --git a/server/src/nest/todo/todo.rpc.ts b/server/src/nest/todo/todo.rpc.ts new file mode 100644 index 000000000..a15c4a685 --- /dev/null +++ b/server/src/nest/todo/todo.rpc.ts @@ -0,0 +1,71 @@ +import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; +import { PluginGuards } from '../plugins/host/plugin-guards.service'; +import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors'; +import { asPayload, num } from '../plugins/host/rpc-params'; +import type { PluginRpcContext } from '../plugins/host/rpc-kit/types'; +import { RealtimeService } from '../realtime/realtime.service'; +import { TodoService } from './todo.service'; + +/** The app edits todos under 'packing_edit', not under a todo-specific action. */ +const TODO_EDIT_ACTION = 'packing_edit'; + +/** + * The todo surface a plugin may reach (#plugins). Trip-scoped core data, so reads + * go through the membership gate and writes additionally need the edit permission. + * + * The broadcasts are part of the contract, not decoration: they are the same + * todo:* events the REST controller emits, and without them an open session shows + * stale data after a plugin write. They came across from the deps factory with the + * handlers. + */ +@PluginController() +export class TodoRpc { + constructor( + private readonly todos: TodoService, + private readonly realtime: RealtimeService, + private readonly guards: PluginGuards, + ) {} + + @PluginMethod('todos.list', { permission: 'db:read:todos' }) + list(params: Record, ctx: PluginRpcContext): unknown[] { + return this.guards.tripRead(params, ctx, () => this.todos.listItems(String(num(params.tripId, 'tripId'))) as unknown[]); + } + + @PluginMethod('todos.create', { permission: 'db:write:todos' }) + create(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(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'); + this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION); + const item = this.todos.createItem(String(tripId), input as never); + this.realtime.broadcast(tripId, 'todo:created', { item }, undefined); + return item; + } + + @PluginMethod('todos.update', { permission: 'db:write:todos' }) + update(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(params.tripId, 'tripId'); + const todoId = num(params.todoId, 'todoId'); + const actor = this.guards.requireActor(ctx, 'todo'); + this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION); + const input = asPayload(params.input); + const updated = this.todos.updateItem(String(tripId), String(todoId), input as never, Object.keys(input)); + if (!updated) throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`); + this.realtime.broadcast(tripId, 'todo:updated', { item: updated }, undefined); + return updated; + } + + @PluginMethod('todos.delete', { permission: 'db:write:todos' }) + delete(params: Record, ctx: PluginRpcContext): unknown { + const tripId = num(params.tripId, 'tripId'); + const todoId = num(params.todoId, 'todoId'); + const actor = this.guards.requireActor(ctx, 'todo'); + this.guards.requireTripEdit(tripId, actor, TODO_EDIT_ACTION); + if (!this.todos.deleteItem(String(tripId), String(todoId))) { + throw new ForbiddenResource(`no todo ${todoId} on trip ${tripId}`); + } + this.realtime.broadcast(tripId, 'todo:deleted', { itemId: todoId }, undefined); + return { deleted: true }; + } +} diff --git a/server/src/nest/weather/weather.module.ts b/server/src/nest/weather/weather.module.ts index 28eedb5db..3324b072a 100644 --- a/server/src/nest/weather/weather.module.ts +++ b/server/src/nest/weather/weather.module.ts @@ -1,11 +1,12 @@ import { Module } from '@nestjs/common'; import { WeatherController } from './weather.controller'; import { WeatherService } from './weather.service'; +import { WeatherRpc } from './weather.rpc'; import { WeatherMcp } from './weather.mcp'; /** Weather domain (pilot leaf module). Registered in AppModule. */ @Module({ controllers: [WeatherController], - providers: [WeatherService, WeatherMcp], + providers: [WeatherService, WeatherMcp, WeatherRpc], }) export class WeatherModule {} diff --git a/server/src/nest/weather/weather.rpc.ts b/server/src/nest/weather/weather.rpc.ts new file mode 100644 index 000000000..f9f6c7aac --- /dev/null +++ b/server/src/nest/weather/weather.rpc.ts @@ -0,0 +1,22 @@ +import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators'; +import { num } from '../plugins/host/rpc-params'; +import { WeatherService } from './weather.service'; + +/** + * The weather surface a plugin may reach (#plugins). Tenant-free: a host-cached + * forecast by coordinates plus an optional date, so no user and no trip. + * + * The language is pinned to 'en' exactly as the deps factory pinned it. A plugin + * has no locale of its own, and the wire contract never carried one. + */ +@PluginController() +export class WeatherRpc { + constructor(private readonly weather: WeatherService) {} + + @PluginMethod('weather.get', { permission: 'weather:read' }) + get(params: Record): unknown { + const lat = num(params.lat, 'lat'); + const lng = num(params.lng, 'lng'); + return this.weather.get(String(lat), String(lng), typeof params.date === 'string' ? params.date : undefined, 'en'); + } +} diff --git a/server/tests/helpers/rpc-host-deps.ts b/server/tests/helpers/rpc-host-deps.ts index 1fa2c67bb..4b2eaf9f1 100644 --- a/server/tests/helpers/rpc-host-deps.ts +++ b/server/tests/helpers/rpc-host-deps.ts @@ -1,7 +1,11 @@ import { vi } from 'vitest'; import type { HostDeps } from '../../src/nest/plugins/host/rpc-host'; import { TagsRpc } from '../../src/nest/tags/tags.rpc'; -import type { TagsService } from '../../src/nest/tags/tags.service'; +import { CategoriesRpc } from '../../src/nest/categories/categories.rpc'; +import { WeatherRpc } from '../../src/nest/weather/weather.rpc'; +import { ExchangeRatesRpc } from '../../src/nest/budget/exchange-rates.rpc'; +import { TodoRpc } from '../../src/nest/todo/todo.rpc'; +import { DayNotesRpc } from '../../src/nest/days/day-notes.rpc'; /** * The stubbed HostDeps every plugin router test builds on. It used to live inside @@ -173,12 +177,14 @@ export function makeDeps(): HostDeps { * them. Behaviour is asserted in each domain's own .rpc.test.ts. */ export function allRpcControllers(): object[] { - const tags = { - list: vi.fn(() => []), - getByIdAndUser: vi.fn(() => undefined), - create: vi.fn(() => ({})), - update: vi.fn(() => ({})), - remove: vi.fn(), - } as unknown as TagsService; - return [new TagsRpc(tags)]; + const anyService = () => + new Proxy({}, { get: () => vi.fn(() => undefined) }) as unknown as never; + return [ + new TagsRpc(anyService()), + new CategoriesRpc(anyService()), + new WeatherRpc(anyService()), + new ExchangeRatesRpc(anyService()), + new TodoRpc(anyService(), anyService(), anyService()), + new DayNotesRpc(anyService(), anyService(), anyService()), + ]; } diff --git a/server/tests/unit/days/day-notes.rpc.test.ts b/server/tests/unit/days/day-notes.rpc.test.ts new file mode 100644 index 000000000..7ba6fca7b --- /dev/null +++ b/server/tests/unit/days/day-notes.rpc.test.ts @@ -0,0 +1,119 @@ +/** + * The day-note plugin surface after it moved onto @PluginMethod. The dispatch-level + * cases come from rpc-host.test.ts unchanged except for the construction line and + * the stub identity; the rest cover the per-handler paths the router-level test had + * no room for. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host'; +import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing'; +import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service'; +import { DayNotesRpc } from '../../../src/nest/days/day-notes.rpc'; +import { DaysModule } from '../../../src/nest/days/days.module'; +import type { DayNotesService } from '../../../src/nest/days/day-notes.service'; +import type { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import type { DatabaseService } from '../../../src/nest/database/database.service'; +import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; +import { makeDeps } from '../../helpers/rpc-host-deps'; + +const req = (method: string, params: Record = {}): RpcRequest => ({ k: 'req', id: 'x', method, params }); + +/** Trip 1 belongs to user 42; day 5 and note 50 sit on it. Nothing else does. */ +function build(canEdit = true) { + const notes = { + list: vi.fn((dayId: number, tripId: number) => [{ id: 50, day_id: dayId, trip_id: tripId, text: 'note' }]), + dayExists: vi.fn((dayId: number, tripId: number) => dayId === 5 && tripId === 1), + getNote: vi.fn((id: number, dayId: number, tripId: number) => + id === 50 && dayId === 5 && tripId === 1 ? { id: 50, text: 'note' } : undefined, + ), + create: vi.fn((dayId: number, tripId: number, text: string) => ({ id: 51, day_id: dayId, trip_id: tripId, text })), + update: vi.fn((id: number) => ({ id, text: 'updated' })), + remove: vi.fn(), + } as unknown as DayNotesService & Record>; + const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType }; + const db = { + canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), + prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), + } as unknown as DatabaseService; + const guards = new PluginGuards( + db, + { checkPermission: vi.fn(() => canEdit) } as unknown as PermissionsService, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + ); + const rpc = new DayNotesRpc(notes, realtime, guards); + const host = (...grants: string[]) => + new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc])); + return { notes, realtime, rpc, host }; +} + +describe('DayNotesRpc through the router', () => { + let f: ReturnType; + beforeEach(() => { + f = build(); + }); + + it('DAYNOTES-RPC-001 daynotes.list is membership-checked (trip-scoped)', async () => { + const host = f.host('db:read:daynotes'); + expect((await host.dispatch(req('daynotes.list', { tripId: 1, dayId: 5 }), 42)).ok).toBe(true); + expect(f.notes.list).toHaveBeenCalledWith(5, 1); + const forbidden = await host.dispatch(req('daynotes.list', { tripId: 999, dayId: 5 }), 42); + expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); + }); + + it('DAYNOTES-RPC-002 create needs db:write:daynotes + day_edit, membership-checked, text required', async () => { + const host = f.host('db:write:daynotes'); + expect((await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'Pack sunscreen' } }), 42)).ok).toBe(true); + expect(f.notes.create).toHaveBeenCalledWith(5, 1, 'Pack sunscreen', undefined, undefined, undefined); + const bad = await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: ' ' } }), 42); + expect((bad as RpcError).error.code).toBe('BAD_PARAMS'); + const forbidden = await host.dispatch(req('daynotes.create', { tripId: 2, dayId: 5, input: { text: 'x' } }), 42); + expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); + }); + + it('DAYNOTES-RPC-003 delete is gated the same way (edit + membership + bound user)', async () => { + const host = f.host('db:write:daynotes'); + expect((await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), 42)).ok).toBe(true); + expect(f.notes.remove).toHaveBeenCalledWith(50); + const noUser = await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), undefined); + expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); + }); + + it('DAYNOTES-RPC-004 the read grant does not unlock a write', async () => { + const host = f.host('db:read:daynotes'); + const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError; + expect(res.error.code).toBe('PERMISSION_DENIED'); + }); + + it('DAYNOTES-RPC-005 update broadcasts and returns the updated note', async () => { + const host = f.host('db:write:daynotes'); + expect((await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 50, input: { text: 'new' } }), 42)).ok).toBe(true); + expect(f.realtime.broadcast).toHaveBeenCalledWith(1, 'dayNote:updated', expect.objectContaining({ dayId: 5 }), undefined); + }); + + it('DAYNOTES-RPC-006 a note on another day is refused, naming it', async () => { + const host = f.host('db:write:daynotes'); + const res = (await host.dispatch(req('daynotes.update', { tripId: 1, dayId: 5, noteId: 404, input: {} }), 42)) as RpcError; + expect(res.error.code).toBe('RESOURCE_FORBIDDEN'); + expect(res.error.message).toBe('no note 404 on day 5'); + }); + + it('DAYNOTES-RPC-007 without the edit permission the write is refused before it touches the service', async () => { + const noEdit = build(false); + const host = noEdit.host('db:write:daynotes'); + const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'x' } }), 42)) as RpcError; + expect(res.error.message).toBe('no permission to edit trip 1'); + expect(noEdit.notes.create).not.toHaveBeenCalled(); + }); + + it('DAYNOTES-RPC-008 a day outside the trip is refused, naming it', async () => { + const host = f.host('db:write:daynotes'); + const res = (await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 99, input: { text: 'x' } }), 42)) as RpcError; + expect(res.error.message).toBe('no day 99 on trip 1'); + }); + + it('DAYNOTES-RPC-009 the class is listed in its module providers', () => { + expect(Reflect.getMetadata('providers', DaysModule) as unknown[]).toContain(DayNotesRpc); + }); +}); diff --git a/server/tests/unit/plugins/plugin-host-deps.factory.test.ts b/server/tests/unit/plugins/plugin-host-deps.factory.test.ts index 8c81fb3fb..420b08e68 100644 --- a/server/tests/unit/plugins/plugin-host-deps.factory.test.ts +++ b/server/tests/unit/plugins/plugin-host-deps.factory.test.ts @@ -622,15 +622,8 @@ describe('host-deps factory — reservations, day notes, cross-trip + addon read expect((await call(h, 'reservations.delete', { tripId: 1, reservationId: 404 })).error.code).toBe('RESOURCE_FORBIDDEN'); }); - it('day notes create/update/delete run the wiring; a day/note outside the trip is refused', async () => { - const h = host('db:write:daynotes'); - expect((await call(h, 'daynotes.create', { tripId: 1, dayId: 3, input: { text: 'Pack' } })).ok).toBe(true); - expect((await call(h, 'daynotes.create', { tripId: 1, dayId: 88, input: { text: 'x' } })).error.code).toBe('RESOURCE_FORBIDDEN'); - expect((await call(h, 'daynotes.update', { tripId: 1, dayId: 3, noteId: 5, input: { text: 'y' } })).ok).toBe(true); - expect((await call(h, 'daynotes.update', { tripId: 1, dayId: 3, noteId: 99, input: {} })).error.code).toBe('RESOURCE_FORBIDDEN'); - expect((await call(h, 'daynotes.delete', { tripId: 1, dayId: 3, noteId: 5 })).ok).toBe(true); - expect((await call(h, 'daynotes.delete', { tripId: 1, dayId: 3, noteId: 99 })).error.code).toBe('RESOURCE_FORBIDDEN'); - }); + // daynotes.* left this factory with the decorator migration; the cases now run in + // tests/unit/days/day-notes.rpc.test.ts against DayNotesRpc. it('cross-trip reads enumerate accessible trips and reservations', async () => { const h = host('db:read:trips'); @@ -640,7 +633,7 @@ describe('host-deps factory — reservations, day notes, cross-trip + addon read expect(r.result).toHaveLength(1); }); - it('wave-13 wiring: collab reads, journal entries, atlas bucket, file content, trip create, rates delegate correctly', async () => { + it('wave-13 wiring: collab reads, journal entries, atlas bucket, file content and trip create delegate correctly', async () => { // collab reads delegate to collabService and require the collab addon const collab = host('db:read:collab'); expect((await call(collab, 'collab.listNotes', { tripId: 1 })).result).toEqual([{ id: 1, trip_id: 1, title: 'Note' }]); @@ -666,9 +659,6 @@ describe('host-deps factory — reservations, day notes, cross-trip + addon read const create = host('db:create:trips'); expect((await call(create, 'trips.create', { input: { title: 'Japan' } })).result).toMatchObject({ id: 99, user_id: 5, title: 'Japan' }); expect((await call(create, 'trips.create', { input: { title: 'boom' } })).error.code).toBe('BAD_PARAMS'); - // rates.get: tenant-free, delegates to the cached service - const rates = host('rates:read'); - expect((await call(rates, 'rates.get', { base: 'EUR' })).result).toMatchObject({ EUR: 1, USD: 1.08 }); }); it('trip-scoped reads are wired to the hydrated services (days incl. assignments, reservations incl. endpoints)', async () => { @@ -795,10 +785,8 @@ describe('host-deps factory — Wave 1 wiring (weather/categories/tags/todos/ros beforeEach(() => { checkPermission.mockReset(); checkPermission.mockReturnValue(true) }) afterAll(() => closePluginDataDb('w1')) - it('weather + categories are tenant-free reads (no user needed)', async () => { - expect((await call(host('weather:read'), 'weather.get', { lat: 48, lng: 11 }, undefined)).ok).toBe(true) - expect((await call(host('db:read:categories'), 'categories.list', {}, undefined)).ok).toBe(true) - }) + // weather.get, categories.list and rates.get left this factory with the decorator + // migration; the cases now run in tests/unit/plugins/tenant-free.rpc.test.ts. // tags.* left this factory with the decorator migration. The same cases now run in // tests/unit/tags/tags.rpc.test.ts against TagsRpc. @@ -809,15 +797,8 @@ describe('host-deps factory — Wave 1 wiring (weather/categories/tags/todos/ros expect(Array.isArray(r.result)).toBe(true) }) - it('todos list/create/update/delete run the wiring; a missing one is RESOURCE_FORBIDDEN', async () => { - const h = host('db:write:todos', 'db:read:todos') - expect((await call(h, 'todos.list', { tripId: 1 }, 5)).ok).toBe(true) - expect((await call(h, 'todos.create', { tripId: 1, input: { name: 'Pack' } }, 5)).ok).toBe(true) - expect((await call(h, 'todos.update', { tripId: 1, todoId: 90, input: { checked: 1 } }, 5)).ok).toBe(true) - expect((await call(h, 'todos.delete', { tripId: 1, todoId: 90 }, 5)).ok).toBe(true) - expect(((await call(h, 'todos.update', { tripId: 1, todoId: 404, input: {} }, 5)) as { error: { code: string } }).error.code).toBe('RESOURCE_FORBIDDEN') - expect(((await call(h, 'todos.delete', { tripId: 1, todoId: 404 }, 5)) as { error: { code: string } }).error.code).toBe('RESOURCE_FORBIDDEN') - }) + // todos.* left this factory with the decorator migration; the cases now run in + // tests/unit/todo/todo.rpc.test.ts against TodoRpc. it('packing bags list/create/update/delete/setMembers run the wiring', async () => { const h = host('db:write:packing') diff --git a/server/tests/unit/plugins/rpc-coverage.test.ts b/server/tests/unit/plugins/rpc-coverage.test.ts index 382b3650a..7c539384d 100644 --- a/server/tests/unit/plugins/rpc-coverage.test.ts +++ b/server/tests/unit/plugins/rpc-coverage.test.ts @@ -54,11 +54,27 @@ describe('plugin RPC coverage ledger', () => { // Update these two numbers in every rollout PR. They make the diff state the size // of the move out loud, which is the number a reviewer wants to see. const total = KNOWN_METHODS.length + UNCONDITIONAL_METHODS.length; - expect(fromRegistry.size).toBe(4); // tags.list / create / update / delete - expect(legacy.size).toBe(total - 4); + expect(fromRegistry.size).toBe(15); + expect(legacy.size).toBe(total - 15); }); it('RPCLEDGER-006 the migrated methods are exactly the ones this PR claims', () => { - expect([...fromRegistry].sort()).toEqual(['tags.create', 'tags.delete', 'tags.list', 'tags.update']); + expect([...fromRegistry].sort()).toEqual([ + 'categories.list', + 'daynotes.create', + 'daynotes.delete', + 'daynotes.list', + 'daynotes.update', + 'rates.get', + 'tags.create', + 'tags.delete', + 'tags.list', + 'tags.update', + 'todos.create', + 'todos.delete', + 'todos.list', + 'todos.update', + 'weather.get', + ]); }); }); diff --git a/server/tests/unit/plugins/rpc-host.test.ts b/server/tests/unit/plugins/rpc-host.test.ts index 39c05694b..32598a4f5 100644 --- a/server/tests/unit/plugins/rpc-host.test.ts +++ b/server/tests/unit/plugins/rpc-host.test.ts @@ -315,9 +315,6 @@ describe('PluginRpcHost — capability enforcement', () => { // reading content is NOT unlocked by plain db:read:files const filesList = new PluginRpcHost('p', new Set(['db:read:files']), deps); expect((await filesList.dispatch(req('files.getContent', { tripId: 1, fileId: 2 }), 42) as RpcError).error.code).toBe('PERMISSION_DENIED'); - // rates.get: tenant-free (works without a user), needs rates:read - const rates = new PluginRpcHost('p', new Set(['rates:read']), deps); - expect(ok(await rates.dispatch(req('rates.get', { base: 'EUR' }), undefined))).toBe(true); // trips.create: needs db:create:trips + the acting user's trip_create + a bound user const create = new PluginRpcHost('p', new Set(['db:create:trips']), deps); expect(ok(await create.dispatch(req('trips.create', { input: { title: 'Japan' } }), 42))).toBe(true); @@ -326,14 +323,7 @@ describe('PluginRpcHost — capability enforcement', () => { expect((await create.dispatch(req('trips.create', { input: {} }), 42) as RpcError).error.code).toBe('BAD_PARAMS'); // title required }); - it('daynotes.list is membership-checked (trip-scoped)', async () => { - const host = new PluginRpcHost('p', new Set(['db:read:daynotes']), deps); - const good = await host.dispatch(req('daynotes.list', { tripId: 1, dayId: 5 }), 42); - expect(ok(good)).toBe(true); - expect(deps.listDayNotes).toHaveBeenCalledWith(1, 5); - const forbidden = await host.dispatch(req('daynotes.list', { tripId: 999, dayId: 5 }), 42); - expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); - }); + // The daynotes cases moved to tests/unit/days/day-notes.rpc.test.ts. it('collections reads are user-scoped and need db:read:collections + a bound user', async () => { const host = new PluginRpcHost('p', new Set(['db:read:collections']), deps); @@ -344,26 +334,6 @@ describe('PluginRpcHost — capability enforcement', () => { expect((await host.dispatch(req('collections.listMine'), undefined)).ok).toBe(false); }); - it('daynotes.create needs db:write:daynotes + day_edit, membership-checked, text required', async () => { - const host = new PluginRpcHost('p', new Set(['db:write:daynotes']), deps); - const good = await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: 'Pack sunscreen' } }), 42); - expect(ok(good)).toBe(true); - expect(deps.createDayNote).toHaveBeenCalledWith(1, 5, expect.objectContaining({ text: 'Pack sunscreen' })); - const bad = await host.dispatch(req('daynotes.create', { tripId: 1, dayId: 5, input: { text: ' ' } }), 42); - expect((bad as RpcError).error.code).toBe('BAD_PARAMS'); - const forbidden = await host.dispatch(req('daynotes.create', { tripId: 2, dayId: 5, input: { text: 'x' } }), 42); - expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); - }); - - it('daynotes.delete is gated the same way (edit + membership + bound user)', async () => { - const host = new PluginRpcHost('p', new Set(['db:write:daynotes']), deps); - const good = await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), 42); - expect(ok(good)).toBe(true); - expect(deps.deleteDayNote).toHaveBeenCalledWith(1, 5, 50); - const noUser = await host.dispatch(req('daynotes.delete', { tripId: 1, dayId: 5, noteId: 50 }), undefined); - expect((noUser as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); - }); - it('packing.create needs db:write:packing + packing_edit, membership-checked, name required', async () => { const host = new PluginRpcHost('p', new Set(['db:write:packing']), deps); const good = await host.dispatch(req('packing.create', { tripId: 1, input: { name: 'Socks' } }), 42); @@ -384,27 +354,18 @@ describe('PluginRpcHost — capability enforcement', () => { expect((await noGrant.dispatch(req('packing.create', { tripId: 1, input: { name: 'x' } }), 42)).ok).toBe(false); }); - it('weather.get + categories.list are tenant-free (work without a user)', async () => { - const w = new PluginRpcHost('p', new Set(['weather:read']), deps); - expect(ok(await w.dispatch(req('weather.get', { lat: 48, lng: 11 }), undefined))).toBe(true); - const c = new PluginRpcHost('p', new Set(['db:read:categories']), deps); - expect(ok(await c.dispatch(req('categories.list', {}), undefined))).toBe(true); - }); + // weather.get, categories.list and rates.get moved to tests/unit/plugins/tenant-free.rpc.test.ts. // The tags cases moved to tests/unit/tags/tags.rpc.test.ts with the handlers. - it('trips.members + todos.list are trip-membership-gated', async () => { - const host = new PluginRpcHost('p', new Set(['db:read:trips', 'db:read:todos']), deps); + it('trips.members is trip-membership-gated', async () => { + const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps); expect(ok(await host.dispatch(req('trips.members', { tripId: 1 }), 42))).toBe(true); - expect(ok(await host.dispatch(req('todos.list', { tripId: 1 }), 42))).toBe(true); expect(((await host.dispatch(req('trips.members', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); }); - it('todos + packing-bags writes need the grant + edit right + a bound user', async () => { - const host = new PluginRpcHost('p', new Set(['db:write:todos', 'db:write:packing']), deps); - expect(ok(await host.dispatch(req('todos.create', { tripId: 1, input: { name: 'Pack' } }), 42))).toBe(true); - expect((await host.dispatch(req('todos.create', { tripId: 1, input: { name: ' ' } }), 42)).ok).toBe(false); - expect(((await host.dispatch(req('todos.create', { tripId: 2, input: { name: 'x' } }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); + it('packing-bags writes need the grant + edit right + a bound user', async () => { + const host = new PluginRpcHost('p', new Set(['db:write:packing']), deps); expect(ok(await host.dispatch(req('packing.createBag', { tripId: 1, input: { name: 'Bag' } }), 42))).toBe(true); expect(ok(await host.dispatch(req('packing.setBagMembers', { tripId: 1, bagId: 80, userIds: [5, 6] }), 42))).toBe(true); expect(deps.setPackingBagMembers).toHaveBeenCalledWith(1, 80, [5, 6]); diff --git a/server/tests/unit/plugins/tenant-free.rpc.test.ts b/server/tests/unit/plugins/tenant-free.rpc.test.ts new file mode 100644 index 000000000..b3c24dc59 --- /dev/null +++ b/server/tests/unit/plugins/tenant-free.rpc.test.ts @@ -0,0 +1,82 @@ +/** + * The three tenant-free plugin methods: weather, categories and exchange rates. + * + * They are grouped because what matters about them is the same property, and it is + * the one a migration could quietly lose: they carry no tenant data, so they work + * with NO acting user. Everything else in the plugin surface refuses that. + */ +import { describe, it, expect, vi } from 'vitest'; +import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host'; +import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing'; +import { CategoriesRpc } from '../../../src/nest/categories/categories.rpc'; +import { CategoriesModule } from '../../../src/nest/categories/categories.module'; +import { WeatherRpc } from '../../../src/nest/weather/weather.rpc'; +import { WeatherModule } from '../../../src/nest/weather/weather.module'; +import { ExchangeRatesRpc } from '../../../src/nest/budget/exchange-rates.rpc'; +import { BudgetModule } from '../../../src/nest/budget/budget.module'; +import type { CategoriesService } from '../../../src/nest/categories/categories.service'; +import type { WeatherService } from '../../../src/nest/weather/weather.service'; +import type { ExchangeRatesService } from '../../../src/nest/budget/exchange-rates.service'; +import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; +import { makeDeps } from '../../helpers/rpc-host-deps'; + +const req = (method: string, params: Record = {}): RpcRequest => ({ k: 'req', id: 'x', method, params }); + +function build() { + const categories = { list: vi.fn(() => [{ id: 1, name: 'Food' }]) } as unknown as CategoriesService & Record>; + const weather = { get: vi.fn(async () => ({ temp: 20 })) } as unknown as WeatherService & Record>; + const rates = { getRates: vi.fn(async (base: string) => ({ [base]: 1, USD: 1.08 })) } as unknown as ExchangeRatesService & Record>; + const registry = createTestPluginRegistry([ + new CategoriesRpc(categories), + new WeatherRpc(weather), + new ExchangeRatesRpc(rates), + ]); + const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), registry); + return { categories, weather, rates, host }; +} + +describe('tenant-free plugin methods', () => { + it('TENANTFREE-001 weather.get and categories.list work without a user', async () => { + const f = build(); + expect((await f.host('weather:read').dispatch(req('weather.get', { lat: 48, lng: 11 }), undefined)).ok).toBe(true); + expect((await f.host('db:read:categories').dispatch(req('categories.list', {}), undefined)).ok).toBe(true); + }); + + it('TENANTFREE-002 rates.get works without a user and needs rates:read', async () => { + const f = build(); + expect((await f.host('rates:read').dispatch(req('rates.get', { base: 'EUR' }), undefined)).ok).toBe(true); + expect(f.rates.getRates).toHaveBeenCalledWith('EUR'); + const denied = (await f.host().dispatch(req('rates.get', { base: 'EUR' }), undefined)) as RpcError; + expect(denied.error.code).toBe('PERMISSION_DENIED'); + }); + + it('TENANTFREE-003 weather coordinates are coerced, and the language stays pinned to en', async () => { + const f = build(); + // Numeric strings are accepted, as the wire contract has always allowed. + await f.host('weather:read').dispatch(req('weather.get', { lat: '48.1', lng: '11.5', date: '2027-01-01' }), undefined); + expect(f.weather.get).toHaveBeenCalledWith('48.1', '11.5', '2027-01-01', 'en'); + }); + + it('TENANTFREE-004 a non-numeric coordinate is BAD_PARAMS', async () => { + const res = (await build().host('weather:read').dispatch(req('weather.get', { lat: 'north', lng: 11 }), undefined)) as RpcError; + expect(res.error.code).toBe('BAD_PARAMS'); + expect(res.error.message).toBe('lat must be a number'); + }); + + it('TENANTFREE-005 a non-string base is BAD_PARAMS', async () => { + const res = (await build().host('rates:read').dispatch(req('rates.get', { base: 42 }), undefined)) as RpcError; + expect(res.error.code).toBe('BAD_PARAMS'); + }); + + it('TENANTFREE-006 an absent date is passed through as undefined, not as a string', async () => { + const f = build(); + await f.host('weather:read').dispatch(req('weather.get', { lat: 1, lng: 2 }), undefined); + expect(f.weather.get).toHaveBeenCalledWith('1', '2', undefined, 'en'); + }); + + it('TENANTFREE-007 each class is listed in its module providers', () => { + expect(Reflect.getMetadata('providers', CategoriesModule) as unknown[]).toContain(CategoriesRpc); + expect(Reflect.getMetadata('providers', WeatherModule) as unknown[]).toContain(WeatherRpc); + expect(Reflect.getMetadata('providers', BudgetModule) as unknown[]).toContain(ExchangeRatesRpc); + }); +}); diff --git a/server/tests/unit/todo/todo.rpc.test.ts b/server/tests/unit/todo/todo.rpc.test.ts new file mode 100644 index 000000000..2a549be56 --- /dev/null +++ b/server/tests/unit/todo/todo.rpc.test.ts @@ -0,0 +1,114 @@ +/** + * The todo plugin surface after it moved onto @PluginMethod. Note the edit gate: the + * app edits todos under 'packing_edit', not under a todo-specific action, which is + * easy to lose in a move and is asserted here explicitly. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host'; +import { createTestPluginRegistry } from '../../../src/nest/plugins/host/rpc-kit/testing'; +import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service'; +import { TodoRpc } from '../../../src/nest/todo/todo.rpc'; +import { TodoModule } from '../../../src/nest/todo/todo.module'; +import type { TodoService } from '../../../src/nest/todo/todo.service'; +import type { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import type { DatabaseService } from '../../../src/nest/database/database.service'; +import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; +import { makeDeps } from '../../helpers/rpc-host-deps'; + +const req = (method: string, params: Record = {}): RpcRequest => ({ k: 'req', id: 'x', method, params }); + +/** Trip 1 belongs to user 42; todo 90 sits on it. */ +function build(canEdit = true) { + const todos = { + listItems: vi.fn(() => [{ id: 90, name: 'Pack' }]), + createItem: vi.fn((tripId: string, input: Record) => ({ id: 91, trip_id: tripId, ...input })), + updateItem: vi.fn((_t: string, id: string) => (id === '90' ? { id: 90, checked: 1 } : undefined)), + deleteItem: vi.fn((_t: string, id: string) => id === '90'), + } as unknown as TodoService & Record>; + const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType }; + const permissions = { checkPermission: vi.fn(() => canEdit) } as unknown as PermissionsService; + const guards = new PluginGuards( + { + canAccessTrip: vi.fn((tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), + prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), + } as unknown as DatabaseService, + permissions, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + ); + const rpc = new TodoRpc(todos, realtime, guards); + const host = (...grants: string[]) => + new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc])); + return { todos, realtime, permissions, host }; +} + +describe('TodoRpc through the router', () => { + let f: ReturnType; + beforeEach(() => { + f = build(); + }); + + it('TODO-RPC-001 todos.list is trip-membership-gated', async () => { + const host = f.host('db:read:todos'); + expect((await host.dispatch(req('todos.list', { tripId: 1 }), 42)).ok).toBe(true); + expect(((await host.dispatch(req('todos.list', { tripId: 2 }), 42)) as RpcError).error.code).toBe('RESOURCE_FORBIDDEN'); + }); + + it('TODO-RPC-002 writes need the grant, the edit right and a bound user', async () => { + const host = f.host('db:write:todos'); + expect((await host.dispatch(req('todos.create', { tripId: 1, input: { name: 'Pack' } }), 42)).ok).toBe(true); + expect((await host.dispatch(req('todos.update', { tripId: 1, todoId: 90, input: { checked: 1 } }), 42)).ok).toBe(true); + expect((await host.dispatch(req('todos.delete', { tripId: 1, todoId: 90 }), 42)).ok).toBe(true); + const noUser = (await host.dispatch(req('todos.create', { tripId: 1, input: { name: 'x' } }), undefined)) as RpcError; + expect(noUser.error.message).toBe('todo writes require an authenticated user context'); + }); + + it('TODO-RPC-003 the edit gate is packing_edit, not a todo-specific action', async () => { + await f.host('db:write:todos').dispatch(req('todos.create', { tripId: 1, input: { name: 'Pack' } }), 42); + expect(f.permissions.checkPermission).toHaveBeenCalledWith('packing_edit', 'user', 42, 42, false); + }); + + it('TODO-RPC-004 a blank name is BAD_PARAMS', async () => { + const res = (await f.host('db:write:todos').dispatch(req('todos.create', { tripId: 1, input: { name: ' ' } }), 42)) as RpcError; + expect(res.error.code).toBe('BAD_PARAMS'); + expect(res.error.message).toBe('todo name is required'); + }); + + it('TODO-RPC-005 a missing todo is RESOURCE_FORBIDDEN, naming it', async () => { + const host = f.host('db:write:todos'); + const upd = (await host.dispatch(req('todos.update', { tripId: 1, todoId: 404, input: {} }), 42)) as RpcError; + expect(upd.error.message).toBe('no todo 404 on trip 1'); + const del = (await host.dispatch(req('todos.delete', { tripId: 1, todoId: 404 }), 42)) as RpcError; + expect(del.error.message).toBe('no todo 404 on trip 1'); + }); + + it('TODO-RPC-006 every write broadcasts the event the REST path emits', async () => { + const host = f.host('db:write:todos'); + await host.dispatch(req('todos.create', { tripId: 1, input: { name: 'Pack' } }), 42); + await host.dispatch(req('todos.update', { tripId: 1, todoId: 90, input: { checked: 1 } }), 42); + await host.dispatch(req('todos.delete', { tripId: 1, todoId: 90 }), 42); + expect(f.realtime.broadcast.mock.calls.map((c) => c[1])).toEqual(['todo:created', 'todo:updated', 'todo:deleted']); + }); + + it('TODO-RPC-007 a failed write never broadcasts', async () => { + await f.host('db:write:todos').dispatch(req('todos.update', { tripId: 1, todoId: 404, input: {} }), 42); + expect(f.realtime.broadcast).not.toHaveBeenCalled(); + }); + + it('TODO-RPC-008 the read grant does not unlock a write', async () => { + const res = (await f.host('db:read:todos').dispatch(req('todos.create', { tripId: 1, input: { name: 'x' } }), 42)) as RpcError; + expect(res.error.code).toBe('PERMISSION_DENIED'); + }); + + it('TODO-RPC-009 without the edit right the write is refused before it touches the service', async () => { + const noEdit = build(false); + const res = (await noEdit.host('db:write:todos').dispatch(req('todos.create', { tripId: 1, input: { name: 'x' } }), 42)) as RpcError; + expect(res.error.message).toBe('no permission to edit trip 1'); + expect(noEdit.todos.createItem).not.toHaveBeenCalled(); + }); + + it('TODO-RPC-010 the class is listed in its module providers', () => { + expect(Reflect.getMetadata('providers', TodoModule) as unknown[]).toContain(TodoRpc); + }); +});