From 3f38621024fb22b5a753f617ca4a47c3692425c3 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 21 Nov 2026 13:23:02 +0100 Subject: [PATCH] feat(server): let a trip owner switch trip addons for one trip A trip can now turn a trip addon (lists, costs, documents, collab, road trip, tours) on or off for itself, whatever the instance switch says. No row in the new trip_addon_overrides table means the trip follows the instance; a row is the owner's choice. Going back to the instance setting deletes the row, and no addon data is touched either way. - GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the owner writes) and the MCP tools get_trip_addons and set_trip_addon, on the shared tripAddons contract; tripAddons:changed tells the members. - Every trip-scoped addon surface asks the trip: REST through TripAddonGuard, MCP through a per-call gate on the named or pinned trip, plugin RPC and events, the share link, the offline bundle, reminders, doc sync, the assistant (tools, keep_attached_file), booking costs, the trip summary prompt, and the cross-trip tour reads (library, Atlas stats, collection save). - Routes without a trip open while the addon is on in any of the user's trips. Switching an addon on that the instance has off ends the members' MCP sessions so they reconnect with its tools. - A copied trip takes its owner's choices along. Behaviour changes: an anonymous call to an addon route that is off now gets 401 instead of 404, and with an instance switch off the packing, todo and files plugin RPC methods, the files MCP tools, todo reminder mails, core plugin events, plugin view contributions, the share link's lists, costs and chat sections and the offline bundle's lists follow it. --- server/scripts/repository-owners.json | 1 + server/scripts/size-baseline.json | 2 +- server/scripts/test-size-baseline.json | 4 +- server/src/db/entities/Addons.entity.ts | 5 +- .../db/entities/TripAddonOverrides.entity.ts | 30 ++ server/src/db/entities/Trips.entity.ts | 3 + server/src/db/entities/index.ts | 2 + .../src/db/kysely/TripAddonOverrides.table.ts | 10 + server/src/db/kysely/db.ts | 2 + ...046490_a_trip_can_switch_its_own_addons.ts | 42 +++ .../TripAddonOverrides.repository.ts | 116 ++++++ server/src/nest-mcp/helpers.ts | 14 + server/src/nest-mcp/index.ts | 1 + server/src/nest-mcp/registry.ts | 2 +- server/src/nest-mcp/types.ts | 18 +- server/src/nest-rpc/plugin-guards.service.ts | 52 ++- server/src/nest/addons/addon-gate.ts | 88 ++++- server/src/nest/addons/addon.guard.ts | 15 +- server/src/nest/addons/addons.constants.ts | 58 +++ server/src/nest/addons/addons.module.ts | 32 +- server/src/nest/addons/addons.service.ts | 71 +++- .../src/nest/addons/trip-addon-tool-gate.ts | 48 +++ server/src/nest/addons/trip-addon.guard.ts | 53 +++ .../src/nest/addons/trip-addons.controller.ts | 53 +++ server/src/nest/addons/trip-addons.mcp.ts | 66 ++++ server/src/nest/addons/trip-addons.service.ts | 117 +++++++ server/src/nest/app.module.ts | 17 +- .../nest/assistant/assistant-attached-file.ts | 4 +- .../assistant/assistant-attachment-tools.ts | 15 +- .../assistant-attachments.service.ts | 4 +- .../assistant-booking-import.service.ts | 2 +- .../assistant/assistant-keep-file.service.ts | 18 +- .../nest/assistant/assistant-share.service.ts | 2 +- .../nest/assistant/assistant-tools.service.ts | 5 +- .../assistant/assistant-tour-file.service.ts | 6 +- .../src/nest/assistant/assistant.service.ts | 2 +- .../booking-import/booking-import.service.ts | 4 +- server/src/nest/budget/budget.controller.ts | 9 +- server/src/nest/budget/budget.mcp.ts | 5 +- server/src/nest/budget/costs.rpc.ts | 26 +- server/src/nest/collab/collab.controller.ts | 51 ++- server/src/nest/collab/collab.mcp.ts | 5 +- server/src/nest/collab/collab.rpc.ts | 25 +- .../src/nest/doc-sync/doc-sync.controller.ts | 6 +- server/src/nest/doc-sync/doc-sync.mcp.ts | 6 +- server/src/nest/doc-sync/doc-sync.service.ts | 14 +- .../nest/files/files-download.controller.ts | 11 +- server/src/nest/files/files.controller.ts | 34 +- server/src/nest/files/files.mcp.ts | 17 + server/src/nest/files/files.module.ts | 3 + server/src/nest/files/files.rpc.ts | 28 +- .../mail-ingest/mail-ingest-apply.service.ts | 6 +- .../notification-preferences.service.ts | 17 +- .../notifications/reminder-jobs.service.ts | 10 +- server/src/nest/packing/packing.controller.ts | 9 +- server/src/nest/packing/packing.mcp.ts | 4 +- server/src/nest/packing/packing.rpc.ts | 28 +- .../paddle-obstacles.controller.ts | 2 +- .../paddle-routing.controller.ts | 4 +- .../view-contributions.controller.ts | 12 + .../src/nest/plugins/plugin-event-addons.ts | 51 +++ .../nest/plugins/plugin-runtime.service.ts | 6 +- .../receipt-scan/receipt-scan.controller.ts | 2 +- .../nest/reservations/reservation-inputs.ts | 13 + .../nest/reservations/reservations.module.ts | 3 + .../nest/reservations/reservations.service.ts | 24 +- .../roadtrip/charging-lookup.controller.ts | 4 +- .../src/nest/roadtrip/charging.controller.ts | 4 +- .../roadtrip/day-boundaries.controller.ts | 4 +- .../nest/roadtrip/google-route.controller.ts | 10 +- .../roadtrip/roadtrip-hazards.controller.ts | 4 +- .../roadtrip-preferences.controller.ts | 4 +- .../src/nest/roadtrip/roadtrip.controller.ts | 12 +- server/src/nest/share/share.module.ts | 3 + server/src/nest/share/share.service.ts | 12 +- .../ski-routing/ski-routing.controller.ts | 4 +- server/src/nest/todo/todo.controller.ts | 9 +- server/src/nest/todo/todo.mcp.ts | 3 +- server/src/nest/todo/todo.rpc.ts | 13 +- .../nest/tours/collection-tours.controller.ts | 5 +- server/src/nest/tours/collection-tours.mcp.ts | 9 +- .../nest/tours/collection-tours.service.ts | 10 +- .../nest/tours/tour-activities.controller.ts | 4 +- .../tours/tour-activity-stats.controller.ts | 2 +- .../nest/tours/tour-activity-stats.service.ts | 16 +- .../src/nest/tours/tour-drafts.controller.ts | 4 +- .../tours/tour-horse-routes.controller.ts | 4 +- .../src/nest/tours/tour-library.controller.ts | 5 +- server/src/nest/tours/tour-library.service.ts | 11 +- .../tours/tour-packing-link.controller.ts | 4 +- .../nest/tours/tour-packing-link.service.ts | 12 +- server/src/nest/tours/tour-packing.mcp.ts | 9 +- .../nest/tours/tour-poi-search.controller.ts | 4 +- server/src/nest/tours/tour-ski.controller.ts | 4 +- .../nest/tours/tour-trail-grade.controller.ts | 4 +- .../src/nest/tours/tour-visits.controller.ts | 4 +- .../nest/tours/tour-walk-import.controller.ts | 4 +- .../src/nest/tours/tours-import.controller.ts | 11 +- .../nest/tours/tours-wanderer.controller.ts | 4 +- server/src/nest/tours/tours-wanderer.mcp.ts | 15 +- server/src/nest/tours/tours.controller.ts | 4 +- .../nest/tours/wanderer-watch.controller.ts | 6 +- .../trip-read-model/trip-read-model.module.ts | 2 + .../trip-read-model.service.ts | 24 +- server/src/nest/trips/trip-prompts.mcp.ts | 9 + server/src/nest/trips/trips.controller.ts | 2 +- server/src/nest/trips/trips.mcp.ts | 24 +- server/src/nest/trips/trips.service.ts | 3 + .../nest/wanderer/wanderer-enabled.guard.ts | 7 +- .../src/nest/wanderer/wanderer.controller.ts | 5 +- server/tests/e2e/addons.e2e.test.ts | 2 + server/tests/e2e/doc-sync.e2e.test.ts | 18 +- server/tests/e2e/files.e2e.test.ts | 7 + server/tests/e2e/paddle-obstacles.e2e.test.ts | 12 +- server/tests/e2e/roadtrip.e2e.test.ts | 9 +- server/tests/e2e/route-row-ids.e2e.test.ts | 1 + .../e2e/tours-activity-stats.e2e.test.ts | 21 +- server/tests/e2e/tours-planned.e2e.test.ts | 27 +- .../e2e/trip-addons-enforcement.e2e.test.ts | 329 ++++++++++++++++++ server/tests/e2e/trip-addons.e2e.test.ts | 250 +++++++++++++ server/tests/helpers/factories/settings.ts | 10 + server/tests/helpers/notifications.ts | 8 +- server/tests/helpers/plugin-host.ts | 3 + server/tests/helpers/test-addons.ts | 2 + .../broadcast-parity/plan.cases.ts | 10 +- .../plugins/boot-registry-order.test.ts | 2 + server/tests/unit/budget/costs.rpc.test.ts | 46 ++- server/tests/unit/db/connection.test.ts | 1 + server/tests/unit/db/entities-index.test.ts | 7 +- .../tests/unit/db/entity-class-fields.test.ts | 3 +- server/tests/unit/db/legacy-baseline.test.ts | 1 + .../TripAddonOverrides.repository.test.ts | 133 +++++++ server/tests/unit/files/files.rpc.test.ts | 4 +- server/tests/unit/mcp/tools-prompts.test.ts | 19 + server/tests/unit/nest-mcp/tool-gate.test.ts | 1 + .../tests/unit/nest-rpc/plugin-guards.test.ts | 56 ++- server/tests/unit/nest/addon-guard.test.ts | 45 ++- server/tests/unit/nest/addons.service.test.ts | 28 ++ .../assistant-attachment-tools.test.ts | 28 +- .../assistant-attachments.service.test.ts | 34 +- .../assistant-booking-import.service.test.ts | 2 +- .../assistant-keep-file.service.test.ts | 22 +- .../assistant/assistant-share.service.test.ts | 4 +- .../assistant-tour-file.service.test.ts | 14 +- .../booking-import.service.test.ts | 6 +- .../tests/unit/nest/budget-items.mcp.test.ts | 5 +- .../tests/unit/nest/calendar.service.test.ts | 3 +- server/tests/unit/nest/city-walk.mcp.test.ts | 6 +- .../tests/unit/nest/collab.controller.test.ts | 39 ++- .../nest/collection-tours.controller.test.ts | 5 +- .../unit/nest/collection-tours.mcp.test.ts | 10 +- .../nest/collection-tours.service.test.ts | 15 +- .../nest/doc-sync/doc-sync.service.test.ts | 13 +- .../tests/unit/nest/files.controller.test.ts | 102 ++++-- server/tests/unit/nest/hike-plan.mcp.test.ts | 6 +- .../nest/integrations/airtrailImport.test.ts | 2 + .../notification-preferences.service.test.ts | 19 + .../paddle-obstacles.controller.test.ts | 2 +- .../paddle-routing.controller.test.ts | 15 +- .../unit/nest/receipt-scan.controller.test.ts | 2 +- .../unit/nest/reminder-jobs.service.test.ts | 19 + .../unit/nest/reservations.service.test.ts | 31 +- .../tests/unit/nest/roadtrip-planning.test.ts | 10 +- .../unit/nest/roadtrip-read-tools.test.ts | 2 +- .../unit/nest/roadtrip.controller.test.ts | 16 +- server/tests/unit/nest/share.service.test.ts | 2 + .../ski-routing.controller.test.ts | 15 +- .../nest/tour-activities.controller.test.ts | 4 +- .../tour-activity-stats.controller.test.ts | 2 +- .../unit/nest/tour-change-save.mcp.test.ts | 6 +- .../unit/nest/tour-change-undo.mcp.test.ts | 6 +- .../tests/unit/nest/tour-change.mcp.test.ts | 6 +- .../unit/nest/tour-drafts.controller.test.ts | 4 +- .../nest/tour-horse-routes.controller.test.ts | 4 +- .../nest/tour-packing-link.controller.test.ts | 4 +- .../tests/unit/nest/tour-packing.mcp.test.ts | 6 +- server/tests/unit/nest/tour-plan.mcp.test.ts | 4 +- .../unit/nest/tour-ski.controller.test.ts | 4 +- server/tests/unit/nest/tour-stops.mcp.test.ts | 4 +- .../unit/nest/tour-visits.controller.test.ts | 4 +- .../nest/tour-walk-import.controller.test.ts | 4 +- .../unit/nest/tours-wanderer.mcp.test.ts | 8 +- .../tests/unit/nest/tours.controller.test.ts | 18 +- .../tests/unit/nest/tours.permissions.test.ts | 25 +- .../unit/nest/trip-addon-tool-gate.test.ts | 185 ++++++++++ .../tests/unit/nest/trip-addon.guard.test.ts | 108 ++++++ .../unit/nest/trip-addons.controller.test.ts | 71 ++++ .../unit/nest/trip-addons.service.test.ts | 263 ++++++++++++++ .../unit/nest/trip-read-model.service.test.ts | 11 +- server/tests/unit/nest/trips.service.test.ts | 23 +- .../nest/wanderer-watch.controller.test.ts | 5 +- server/tests/unit/packing/packing.rpc.test.ts | 2 +- .../plugins/addon-domains-errors.rpc.test.ts | 2 +- .../unit/plugins/addon-gates.rpc.test.ts | 8 +- .../unit/plugins/plugin-event-addons.test.ts | 61 ++++ .../tests/unit/plugins/rpc-fallbacks.test.ts | 2 +- .../view-contributions.controller.test.ts | 15 +- server/tests/unit/todo/todo.rpc.test.ts | 2 +- shared/src/addons/trip-addons.schema.spec.ts | 36 ++ shared/src/addons/trip-addons.schema.ts | 47 +++ shared/src/index.ts | 2 + shared/src/realtime/events.schema.spec.ts | 11 +- shared/src/realtime/events.schema.ts | 5 + 203 files changed, 3710 insertions(+), 498 deletions(-) create mode 100644 server/src/db/entities/TripAddonOverrides.entity.ts create mode 100644 server/src/db/kysely/TripAddonOverrides.table.ts create mode 100644 server/src/db/migrations/Migration20200101046490_a_trip_can_switch_its_own_addons.ts create mode 100644 server/src/db/repositories/TripAddonOverrides.repository.ts create mode 100644 server/src/nest/addons/addons.constants.ts create mode 100644 server/src/nest/addons/trip-addon-tool-gate.ts create mode 100644 server/src/nest/addons/trip-addon.guard.ts create mode 100644 server/src/nest/addons/trip-addons.controller.ts create mode 100644 server/src/nest/addons/trip-addons.mcp.ts create mode 100644 server/src/nest/addons/trip-addons.service.ts create mode 100644 server/src/nest/plugins/plugin-event-addons.ts create mode 100644 server/tests/e2e/trip-addons-enforcement.e2e.test.ts create mode 100644 server/tests/e2e/trip-addons.e2e.test.ts create mode 100644 server/tests/unit/db/repositories/TripAddonOverrides.repository.test.ts create mode 100644 server/tests/unit/nest/trip-addon-tool-gate.test.ts create mode 100644 server/tests/unit/nest/trip-addon.guard.test.ts create mode 100644 server/tests/unit/nest/trip-addons.controller.test.ts create mode 100644 server/tests/unit/nest/trip-addons.service.test.ts create mode 100644 server/tests/unit/plugins/plugin-event-addons.test.ts create mode 100644 shared/src/addons/trip-addons.schema.spec.ts create mode 100644 shared/src/addons/trip-addons.schema.ts diff --git a/server/scripts/repository-owners.json b/server/scripts/repository-owners.json index b121a6fb6..ff68ca02a 100644 --- a/server/scripts/repository-owners.json +++ b/server/scripts/repository-owners.json @@ -145,6 +145,7 @@ "TrekPhotoCacheMeta": "memories", "TrekPhotoSignals": "photos", "TrekPhotos": "photos", + "TripAddonOverrides": "addons", "TripAlbumLinks": "memories", "TripDocumentLinks": "doc-sync", "TripFiles": "files", diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index 4edfa2ef0..b611e1cc0 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -15,6 +15,6 @@ "src/nest/places/places.service.ts": 1546, "src/nest/plugins/plugin-runtime.service.ts": 1460, "src/nest/plugins/runtime/plugin-sdk.ts": 1093, - "src/nest/reservations/reservations.service.ts": 1166, + "src/nest/reservations/reservations.service.ts": 1163, "src/nest/vacay/vacay.service.ts": 1393 } diff --git a/server/scripts/test-size-baseline.json b/server/scripts/test-size-baseline.json index 57beb068e..892cb1b60 100644 --- a/server/scripts/test-size-baseline.json +++ b/server/scripts/test-size-baseline.json @@ -1,9 +1,9 @@ { "tests/unit/nest/atlas.service.test.ts": 2154, "tests/unit/nest/budget.service.db.test.ts": 2219, - "tests/unit/nest/doc-sync/doc-sync.service.test.ts": 2511, + "tests/unit/nest/doc-sync/doc-sync.service.test.ts": 2510, "tests/unit/nest/journey-domain.service.test.ts": 3876, "tests/unit/nest/maps.service.test.ts": 3680, "tests/unit/nest/places.service.test.ts": 2545, - "tests/unit/nest/trips.service.test.ts": 2363 + "tests/unit/nest/trips.service.test.ts": 2362 } diff --git a/server/src/db/entities/Addons.entity.ts b/server/src/db/entities/Addons.entity.ts index 4fc8d9e51..3538b681f 100644 --- a/server/src/db/entities/Addons.entity.ts +++ b/server/src/db/entities/Addons.entity.ts @@ -1,6 +1,7 @@ -import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core'; +import { Collection, EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core'; import { AddonsRepository } from '../repositories/Addons.repository'; import { IntegerFlagType } from '../types'; +import { TripAddonOverrides } from './TripAddonOverrides.entity'; export interface AddonConfig { [key: string]: unknown; @@ -16,6 +17,7 @@ export class Addons { enabled?: boolean | null; config?: AddonConfig | null; sort_order?: number | null = 0; + trip_addon_overrides_collection = new Collection(this); } export const AddonsSchema = defineEntity({ @@ -30,5 +32,6 @@ export const AddonsSchema = defineEntity({ enabled: p.type(IntegerFlagType).nullable().default(false), config: p.json().nullable().default('{}'), sort_order: p.integer().nullable(), + trip_addon_overrides_collection: () => p.oneToMany(TripAddonOverrides).mappedBy('addon').hidden(), }, }); diff --git a/server/src/db/entities/TripAddonOverrides.entity.ts b/server/src/db/entities/TripAddonOverrides.entity.ts new file mode 100644 index 000000000..0bc364c01 --- /dev/null +++ b/server/src/db/entities/TripAddonOverrides.entity.ts @@ -0,0 +1,30 @@ +import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core'; +import { TripAddonOverridesRepository } from '../repositories/TripAddonOverrides.repository'; +import { DbTimestampType } from '../types'; +import { Addons } from './Addons.entity'; +import { Trips } from './Trips.entity'; + +export class TripAddonOverrides { + [EntityRepositoryType]?: TripAddonOverridesRepository; + [PrimaryKeyProp]?: ['trip', 'addon']; + trip!: Ref; + trip_id!: number; + addon!: Ref; + addon_id!: string; + enabled!: number; + updated_at?: string | null; +} + +export const TripAddonOverridesSchema = defineEntity({ + class: TripAddonOverrides, + repository: () => TripAddonOverridesRepository, + uniques: [{ properties: ['trip', 'addon'] }], + properties: { + trip: () => p.manyToOne(Trips).primary().ref().hidden(), + trip_id: p.integer().persist(false), + addon: () => p.manyToOne(Addons).primary().ref().hidden().index('idx_trip_addon_overrides_addon_id'), + addon_id: p.text().persist(false).index('idx_trip_addon_overrides_addon_id'), + enabled: p.integer(), + updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + }, +}); diff --git a/server/src/db/entities/Trips.entity.ts b/server/src/db/entities/Trips.entity.ts index b0f7d5be9..2fb735467 100644 --- a/server/src/db/entities/Trips.entity.ts +++ b/server/src/db/entities/Trips.entity.ts @@ -35,6 +35,7 @@ import { Tags } from './Tags.entity'; import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity'; import { TodoItems } from './TodoItems.entity'; import { TourDrafts } from './TourDrafts.entity'; +import { TripAddonOverrides } from './TripAddonOverrides.entity'; import { TripAlbumLinks } from './TripAlbumLinks.entity'; import { TripDocumentLinks } from './TripDocumentLinks.entity'; import { TripFiles } from './TripFiles.entity'; @@ -98,6 +99,7 @@ export class Trips { todo_category_assignees_collection = new Collection(this); todo_items_collection = new Collection(this); tour_drafts_collection = new Collection(this); + trip_addon_overrides_collection = new Collection(this); trip_album_links_collection = new Collection(this); trip_document_links_collection = new Collection(this); trip_files_collection = new Collection(this); @@ -177,6 +179,7 @@ export const TripsSchema = defineEntity({ todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('trip').hidden(), todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('trip').hidden(), tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(), + trip_addon_overrides_collection: () => p.oneToMany(TripAddonOverrides).mappedBy('trip').hidden(), trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('trip').hidden(), trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('trip').hidden(), trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('trip').hidden(), diff --git a/server/src/db/entities/index.ts b/server/src/db/entities/index.ts index 0cb3eb08b..92d600432 100644 --- a/server/src/db/entities/index.ts +++ b/server/src/db/entities/index.ts @@ -144,6 +144,7 @@ import { ToursSchema } from './Tours.entity'; import { TrekPhotoCacheMetaSchema } from './TrekPhotoCacheMeta.entity'; import { TrekPhotoSignalsSchema } from './TrekPhotoSignals.entity'; import { TrekPhotosSchema } from './TrekPhotos.entity'; +import { TripAddonOverridesSchema } from './TripAddonOverrides.entity'; import { TripAlbumLinksSchema } from './TripAlbumLinks.entity'; import { TripDocumentLinksSchema } from './TripDocumentLinks.entity'; import { TripFilesSchema } from './TripFiles.entity'; @@ -319,6 +320,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [ TrekPhotoCacheMetaSchema, TrekPhotoSignalsSchema, TrekPhotosSchema, + TripAddonOverridesSchema, TripAlbumLinksSchema, TripDocumentLinksSchema, TripFilesSchema, diff --git a/server/src/db/kysely/TripAddonOverrides.table.ts b/server/src/db/kysely/TripAddonOverrides.table.ts new file mode 100644 index 000000000..fcf585e81 --- /dev/null +++ b/server/src/db/kysely/TripAddonOverrides.table.ts @@ -0,0 +1,10 @@ +// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand: +// change the migration, then run `npm run gen:db-types`. +import type { InsertOptional } from './columns'; + +export interface TripAddonOverridesTable { + trip_id: number; + addon_id: string; + enabled: number; + updated_at: InsertOptional; +} diff --git a/server/src/db/kysely/db.ts b/server/src/db/kysely/db.ts index bb4fabea7..d3cd495bb 100644 --- a/server/src/db/kysely/db.ts +++ b/server/src/db/kysely/db.ts @@ -150,6 +150,7 @@ import type { ToursTable } from './Tours.table'; import type { TrekPhotoCacheMetaTable } from './TrekPhotoCacheMeta.table'; import type { TrekPhotoSignalsTable } from './TrekPhotoSignals.table'; import type { TrekPhotosTable } from './TrekPhotos.table'; +import type { TripAddonOverridesTable } from './TripAddonOverrides.table'; import type { TripAlbumLinksTable } from './TripAlbumLinks.table'; import type { TripDocumentLinksTable } from './TripDocumentLinks.table'; import type { TripFilesTable } from './TripFiles.table'; @@ -331,6 +332,7 @@ export interface DB { trek_photo_cache_meta: TrekPhotoCacheMetaTable; trek_photo_signals: TrekPhotoSignalsTable; trek_photos: TrekPhotosTable; + trip_addon_overrides: TripAddonOverridesTable; trip_album_links: TripAlbumLinksTable; trip_document_links: TripDocumentLinksTable; trip_files: TripFilesTable; diff --git a/server/src/db/migrations/Migration20200101046490_a_trip_can_switch_its_own_addons.ts b/server/src/db/migrations/Migration20200101046490_a_trip_can_switch_its_own_addons.ts new file mode 100644 index 000000000..27118697e --- /dev/null +++ b/server/src/db/migrations/Migration20200101046490_a_trip_can_switch_its_own_addons.ts @@ -0,0 +1,42 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * A trip can switch a trip addon (lists, costs, files, collab, road trip, + * tours) on or off for itself, whatever the instance says. + * + * No row means the trip follows the instance switch in `addons.enabled`. A row + * is the owner's explicit choice in either direction: `enabled` 1 turns the + * addon on for this trip although the admin switched it off, 0 hides it here + * although it is on everywhere else. Going back to the instance setting + * deletes the row. Nothing of the addon's data is touched either way. + * + * The rows go with their trip, and with their addon should an addon row ever + * be removed. The primary key leads with `trip_id`, which covers the trip's + * foreign key; `addon_id` gets an index of its own for the addon's. + */ +export class Migration20200101046490_a_trip_can_switch_its_own_addons extends Migration { + override name = 'Migration20200101046490_a_trip_can_switch_its_own_addons'; + + override up(): void { + engineDdl(this, { + sqlite: [ + `CREATE TABLE trip_addon_overrides ( + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + addon_id TEXT NOT NULL REFERENCES addons(id) ON DELETE CASCADE, + enabled INTEGER NOT NULL, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (trip_id, addon_id) + )`, + 'CREATE INDEX idx_trip_addon_overrides_addon_id ON trip_addon_overrides(addon_id)', + ], + postgres: [ + 'create table "trip_addon_overrides" ("trip_id" bigint not null, "addon_id" text not null, "enabled" bigint not null, "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), primary key ("trip_id", "addon_id"))', + 'create index "idx_trip_addon_overrides_addon_id" on "trip_addon_overrides" ("addon_id")', + 'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_trip_id_addon_id_unique" unique ("trip_id", "addon_id")', + 'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on update cascade on delete cascade', + 'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_addon_id_foreign" foreign key ("addon_id") references "addons" ("id") on update cascade on delete cascade', + ], + }); + } +} diff --git a/server/src/db/repositories/TripAddonOverrides.repository.ts b/server/src/db/repositories/TripAddonOverrides.repository.ts new file mode 100644 index 000000000..f5f76ae68 --- /dev/null +++ b/server/src/db/repositories/TripAddonOverrides.repository.ts @@ -0,0 +1,116 @@ +import type { TripAddonOverrides } from '../entities/TripAddonOverrides.entity'; +import type { DB } from '../kysely/db'; +import { dbNow } from '../types'; +import { TrekRepository } from './_shared/trek-repository'; + +/** One trip's explicit choice for one addon: on or off, whatever the instance says. */ +interface TripAddonOverrideRow { + addon_id: string; + enabled: boolean; +} + +type OverridesKyselyDB = Pick; +type OverridesAccessKyselyDB = Pick; + +/** + * `trip_addon_overrides`: a sparse, trip-scoped override of the instance's addon + * switch. No row means the trip follows `addons.enabled`; a row is the owner's + * explicit on (1) or off (0). Resetting to the instance setting deletes the row, + * so a trip never holds a row that merely repeats the default it inherits. + */ +export class TripAddonOverridesRepository extends TrekRepository { + /** Every override the trip holds, in addon id order. */ + async listForTrip(trip_id: number): Promise { + const rows = await this.kysely() + .selectFrom('trip_addon_overrides') + .select(['addon_id', 'enabled']) + .where('trip_id', '=', trip_id) + .orderBy('addon_id') + .execute(); + return rows.map((row) => ({ addon_id: row.addon_id, enabled: row.enabled === 1 })); + } + + /** The trip's override for one addon: true or false, or null when it follows the instance. */ + async findForTrip(trip_id: number, addon_id: string): Promise { + const row = await this.kysely() + .selectFrom('trip_addon_overrides') + .select('enabled') + .where('trip_id', '=', trip_id) + .where('addon_id', '=', addon_id) + .executeTakeFirst(); + return row ? row.enabled === 1 : null; + } + + /** The choices these trips made for one addon; a trip that follows the instance has no row. */ + async listForTrips( + trip_ids: readonly number[], + addon_id: string, + ): Promise> { + if (trip_ids.length === 0) return []; + const rows = await this.kysely() + .selectFrom('trip_addon_overrides') + .select(['trip_id', 'enabled']) + .where('addon_id', '=', addon_id) + .where('trip_id', 'in', [...trip_ids]) + .execute(); + return rows.map((row) => ({ trip_id: row.trip_id, enabled: row.enabled === 1 })); + } + + /** Sets the trip's choice for one addon, replacing an earlier one, and stamps when. */ + async upsertOverride(trip_id: number, addon_id: string, enabled: boolean): Promise { + const value = enabled ? 1 : 0; + const at = dbNow(); + await this.kysely() + .insertInto('trip_addon_overrides') + .values({ trip_id, addon_id, enabled: value, updated_at: at }) + .onConflict((oc) => oc.columns(['trip_id', 'addon_id']).doUpdateSet({ enabled: value, updated_at: at })) + .execute(); + } + + /** Drops the trip's choice for one addon, so the instance setting applies again. */ + async deleteOverride(trip_id: number, addon_id: string): Promise { + await this.kysely() + .deleteFrom('trip_addon_overrides') + .where('trip_id', '=', trip_id) + .where('addon_id', '=', addon_id) + .execute(); + } + + /** + * Gives a copied trip the choices of the trip it was copied from, in one + * statement. The new trip holds no rows yet, so the conflict target only + * keeps a repeated copy from failing. + */ + async copyForTrip(from_trip_id: number, to_trip_id: number): Promise { + await this.kysely() + .insertInto('trip_addon_overrides') + .columns(['trip_id', 'addon_id', 'enabled', 'updated_at']) + .expression((eb) => + eb + .selectFrom('trip_addon_overrides as o') + .select([eb.val(to_trip_id).as('trip_id'), 'o.addon_id', 'o.enabled', eb.val(dbNow()).as('updated_at')]) + .where('o.trip_id', '=', from_trip_id), + ) + .onConflict((oc) => oc.columns(['trip_id', 'addon_id']).doNothing()) + .execute(); + } + + /** + * Whether any trip the user owns or is a member of switched the addon on for + * itself. Routes without a trip (a library, a search across trips) open on + * that when the instance switch is off. + */ + async anyEnabledForUser(user_id: number, addon_id: string): Promise { + const row = await this.kysely() + .selectFrom('trip_addon_overrides as o') + .innerJoin('trips as t', 't.id', 'o.trip_id') + .leftJoin('trip_members as m', (join) => join.onRef('m.trip_id', '=', 't.id').on('m.user_id', '=', user_id)) + .select('o.trip_id') + .where('o.addon_id', '=', addon_id) + .where('o.enabled', '=', 1) + .where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('m.user_id', 'is not', null)])) + .limit(1) + .executeTakeFirst(); + return row !== undefined; + } +} diff --git a/server/src/nest-mcp/helpers.ts b/server/src/nest-mcp/helpers.ts index 4b169149e..bc9b191cf 100644 --- a/server/src/nest-mcp/helpers.ts +++ b/server/src/nest-mcp/helpers.ts @@ -3,6 +3,7 @@ * App-agnostic on purpose — host-specific canned errors (permission wording, * RBAC lookups, broadcasts) belong in the host, built on `errorResult`. */ +import type { McpToolGate } from './types'; /** The text-content result shape MCP tool handlers return. */ export interface McpTextResult { @@ -67,3 +68,16 @@ export const TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT = { ...TOOL_ANNOTATIONS_NON_IDEMPOTENT, openWorldHint: true, } as const; + +/** + * One tool gate out of several, asked in order: the first refusal answers + * the call, and the handler runs only when every gate let it through. + */ +export function combineToolGates(...gates: readonly McpToolGate[]): McpToolGate { + // Chained rather than run side by side: a later gate is not asked once an earlier one refused. + return (tool, ctx, args) => + gates.reduce>(async (earlier, gate) => { + const refusal = await earlier; + return refusal !== undefined ? refusal : gate(tool, ctx, args); + }, Promise.resolve(undefined)); +} diff --git a/server/src/nest-mcp/index.ts b/server/src/nest-mcp/index.ts index eee7151c0..2b2af8cad 100644 --- a/server/src/nest-mcp/index.ts +++ b/server/src/nest-mcp/index.ts @@ -1,5 +1,6 @@ export { McpController, Prompt, Resource, ResourceTemplate, Tool } from './decorators'; export { + combineToolGates, demoDenied, errorResult, ok, diff --git a/server/src/nest-mcp/registry.ts b/server/src/nest-mcp/registry.ts index 024d2a619..c7c4d6ca1 100644 --- a/server/src/nest-mcp/registry.ts +++ b/server/src/nest-mcp/registry.ts @@ -339,7 +339,7 @@ export class McpRegistry { const gate = this.toolGate; if (!gate) return handler; return async function (this: unknown, ...handlerArgs: unknown[]) { - const refusal = await gate(options, ctx); + const refusal = await gate(options, ctx, handlerArgs[0]); return refusal !== undefined ? refusal : handler.apply(this, handlerArgs); }; } diff --git a/server/src/nest-mcp/types.ts b/server/src/nest-mcp/types.ts index 350eac294..bee9f280b 100644 --- a/server/src/nest-mcp/types.ts +++ b/server/src/nest-mcp/types.ts @@ -32,6 +32,12 @@ export interface McpContext { * consumers (list_trips / get_trip_summary) treat absence as "no notice". */ getDeprecationNotice?: () => string | null; + /** + * The one trip a session is about, set by a session pinned to a trip (the + * assistant's trip chat). The addon gates then ask that trip instead of the + * user's trips as a whole. Absent for an MCP client, which may name any trip. + */ + tripId?: number; } /** @@ -268,15 +274,17 @@ export type McpAccessValidator = (access: McpDeclarativeAccess, entry: McpRegist /** * Host-supplied check run before every registered tool handler, after the - * SDK validated the arguments and inside the `around` wrapper. Return a result - * to answer the call with it instead of running the handler, or undefined to - * let the handler run. The package attaches no meaning to it; TREK's demo-mode - * write block lives in `src/mcp/nest-mcp-policy.ts`. + * SDK validated the arguments and inside the `around` wrapper. It is handed + * the tool's options, the session context and the arguments the handler is + * about to receive (after the host's input mapper). Return a result to answer + * the call with it instead of running the handler, or undefined to let the + * handler run. The package attaches no meaning to it; TREK's demo-mode write + * block and its per-trip addon check live in `src/mcp/nest-mcp-policy.ts`. * * Registered entries only: a dynamic tool's source owns its own checks, * because the host cannot know what a contributor's annotations promise. */ -export type McpToolGate = (tool: ToolOptions, ctx: McpContext) => unknown; +export type McpToolGate = (tool: ToolOptions, ctx: McpContext, args?: unknown) => unknown; /** * Host-supplied translation of an error a registered tool handler threw into diff --git a/server/src/nest-rpc/plugin-guards.service.ts b/server/src/nest-rpc/plugin-guards.service.ts index 7687c5498..bc63a31a8 100644 --- a/server/src/nest-rpc/plugin-guards.service.ts +++ b/server/src/nest-rpc/plugin-guards.service.ts @@ -10,6 +10,12 @@ import { rowIdParam } from './rpc-params'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; +/** The trip addon a read or write belongs to, and the word its refusal names it by. */ +export interface RpcAddon { + addonId: string; + noun: string; +} + /** * The resource gates every plugin RPC handler needs, lifted out of PluginRpcHost's * private methods and the host factory's canEditTripAs / requireAddon so that @@ -39,7 +45,12 @@ export class PluginGuards { * so a plugin cannot read another user's trips by naming their id. A userless * context (a job, or onLoad) has no acting user and is refused. */ - async tripRead(params: Record, ctx: PluginRpcContext, read: (userId: number) => T): Promise { + async tripRead( + params: Record, + ctx: PluginRpcContext, + read: (userId: number) => T, + addon?: RpcAddon, + ): Promise { const tripId = rowIdParam(params.tripId, 'tripId'); if (ctx.actingUserId === undefined) { throw new ForbiddenResource('trip reads require an authenticated user context'); @@ -47,6 +58,7 @@ export class PluginGuards { if (!(await this.trips.findAccessible(tripId, ctx.actingUserId))) { throw new ForbiddenResource(`no access to trip ${tripId}`); } + if (addon) await this.requireAddon(addon.addonId, addon.noun, { tripId, userId: ctx.actingUserId }); // The read runs only for a bound, membership-checked user, so hand the id through // and per-user visibility filters (packing's private items) still apply. return read(ctx.actingUserId); @@ -63,11 +75,15 @@ export class PluginGuards { return ctx.actingUserId; } - /** A write is allowed only if the acting user can access AND edit the trip. */ - async requireTripEdit(tripId: number, userId: number, action: string): Promise { + /** + * A write is allowed only if the acting user can access AND edit the trip, + * and, given the addon the write belongs to, only while it is on for the trip. + */ + async requireTripEdit(tripId: number, userId: number, action: string, addon?: RpcAddon): Promise { if (!(await this.trips.findAccessible(tripId, userId))) throw new ForbiddenResource(`no access to trip ${tripId}`); if (!(await this.canEditAs(action, tripId, userId))) throw new ForbiddenResource(`no permission to edit trip ${tripId}`); + if (addon) await this.requireAddon(addon.addonId, addon.noun, { tripId, userId }); } /** @@ -110,9 +126,35 @@ export class PluginGuards { /** * A subsystem read is refused when its addon is off, matching the app, where a * disabled addon means there is simply nothing to read. + * + * Given the trip a call is about and the acting user, it asks what applies to + * that trip (the owner's choice, else the instance switch), once the user may + * see the trip. For a trip the user cannot see it reads the instance switch, + * so the answer never tells the plugin what a stranger's trip chose; the + * access check that follows refuses the call anyway. */ - async requireAddon(addonId: string, noun: string): Promise { - if (!(await this.addons.isAddonEnabled(addonId))) throw new ForbiddenResource(`the ${noun} addon is disabled`); + async requireAddon(addonId: string, noun: string, trip?: { tripId: number; userId?: number }): Promise { + const forTrip = + trip?.userId !== undefined && (await this.trips.findAccessible(trip.tripId, trip.userId)) ? trip.tripId : null; + const on = + forTrip === null + ? await this.addons.isAddonEnabled(addonId) + : await this.addons.isEnabledForTrip(forTrip, addonId); + if (!on) throw new ForbiddenResource(`the ${noun} addon is disabled`); + } + + /** + * For a read across all of a user's trips: the ids of the trips the addon + * applies to, in the order given. Refused only when it applies to none of + * them and the instance has it off, as requireAddon refuses. + */ + async tripsWithAddon(addonId: string, noun: string, tripIds: readonly number[]): Promise { + const on = await Promise.all(tripIds.map((id) => this.addons.isEnabledForTrip(id, addonId))); + const kept = tripIds.filter((_id, i) => on[i]); + if (kept.length === 0 && !(await this.addons.isAddonEnabled(addonId))) { + throw new ForbiddenResource(`the ${noun} addon is disabled`); + } + return kept; } /** diff --git a/server/src/nest/addons/addon-gate.ts b/server/src/nest/addons/addon-gate.ts index 1b84cfa07..06b13eb5f 100644 --- a/server/src/nest/addons/addon-gate.ts +++ b/server/src/nest/addons/addon-gate.ts @@ -1,5 +1,6 @@ import { ADDON_IDS } from '../../addons'; import type { McpContext } from '../../nest-mcp'; +import { addonOffMessage, TRIP_ADDON_IDS } from './addons.constants'; import type { AddonsService } from './addons.service'; /** @@ -20,21 +21,94 @@ import type { AddonsService } from './addons.service'; * `addons` is public rather than private because the gate is a module-level * function in the same file, not a method — TypeScript's `private` is scoped to * the class body. + * + * A gate runs once per session, when the tools are attached. A session about + * no one trip registers a tool while the instance has the addon on or any + * trip of the user switched it on for itself; a session pinned to one trip + * (`ctx.tripId`, the assistant's trip chat) asks that trip alone, so a trip + * that has the addon off is never offered its tools. Each gate also names the addons it stands + * for (`addonIds`), so the host's tool gate (`trekTripAddonToolGate`) can ask + * again on every call, for the trip the call names. */ export interface HasAddons { readonly addons: AddonsService; } -/** Gate an MCP entry on an addon being enabled. */ -export function addonGate(addonId: string) { - return (_ctx: McpContext, self: HasAddons): Promise => self.addons.isAddonEnabled(addonId); +/** A `when:` gate that also names the addons it requires, for the per-call check. */ +type AddonGatePredicate = ((ctx: McpContext, self: HasAddons) => Promise) & { + readonly addonIds: readonly string[]; +}; + +/** A gate of one's own that rides on addons: the per-call check asks them for the trip the call names. */ +export function gateOnAddons( + addonIds: readonly string[], + predicate: (ctx: McpContext, self: HasAddons) => Promise, +): AddonGatePredicate { + return Object.assign(predicate, { addonIds }); +} + +/** + * A trip addon is on for a session pinned to one trip while that trip has it + * on, and for any other session while the instance or one of the user's trips + * has it on; any other addon is the instance switch. + */ +async function onForUser(ctx: McpContext, self: HasAddons, addonId: string): Promise { + if (!TRIP_ADDON_IDS.has(addonId)) return self.addons.isAddonEnabled(addonId); + if (ctx.tripId !== undefined) return self.addons.isEnabledForTrip(ctx.tripId, addonId); + return self.addons.isEnabledForUserAnywhere(ctx.userId, addonId); +} + +/** Gate an MCP entry on an addon being on for the user somewhere. */ +export function addonGate(addonId: string): AddonGatePredicate { + return gateOnAddons([addonId], (ctx, self) => onForUser(ctx, self, addonId)); +} + +/** + * Gate an MCP entry on the instance switch alone, for a surface that stays + * bound to it although its addon is a trip addon (doc-sync: the document + * providers follow the instance's Documents switch). Each call still asks the + * trip it names, so a trip that has the addon off refuses it too. + */ +export function instanceAddonGate(addonId: string): AddonGatePredicate { + return gateOnAddons([addonId], (_ctx, self) => self.addons.isAddonEnabled(addonId)); +} + +/** Gate an MCP entry on every one of several addons, such as a tour's packing link. */ +export function allAddonsGate(...addonIds: string[]): AddonGatePredicate { + return gateOnAddons(addonIds, async (ctx, self) => + (await Promise.all(addonIds.map((id) => onForUser(ctx, self, id)))).every(Boolean), + ); } /** * Gate on one of collab's sub-feature flags. Every collab entry rides both the - * addon toggle and its own flag — notes, polls, chat or links. + * addon toggle and its own flag (notes, polls, chat or links). The flags stay + * instance-wide; only the addon follows the trip. */ -export function collabFeatureGate(feature: 'chat' | 'notes' | 'polls' | 'links') { - return async (_ctx: McpContext, self: HasAddons): Promise => - (await self.addons.isAddonEnabled(ADDON_IDS.COLLAB)) && (await self.addons.getCollabFeatures())[feature]; +export function collabFeatureGate(feature: 'chat' | 'notes' | 'polls' | 'links'): AddonGatePredicate { + return gateOnAddons( + [ADDON_IDS.COLLAB], + async (ctx, self) => + (await onForUser(ctx, self, ADDON_IDS.COLLAB)) && (await self.addons.getCollabFeatures())[feature], + ); +} + +/** The addons an entry's `when:` gate stands for; none for a gate built some other way. */ +export function addonsOfGate(when: unknown): readonly string[] { + if (typeof when !== 'function') return []; + const ids = (when as { addonIds?: unknown }).addonIds; + return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : []; +} + +/** + * What a trip resource answers while its addon is off for that trip. + * Resources are read outside the tool gate, so each asks for its trip itself, + * after its access check, and answers with the text a tool or route would. + */ +export function addonOffResource(uri: URL, addonId: string) { + return { + contents: [ + { uri: uri.href, mimeType: 'application/json', text: JSON.stringify({ error: addonOffMessage(addonId) }) }, + ], + }; } diff --git a/server/src/nest/addons/addon.guard.ts b/server/src/nest/addons/addon.guard.ts index ff07ac4b3..d86da4316 100644 --- a/server/src/nest/addons/addon.guard.ts +++ b/server/src/nest/addons/addon.guard.ts @@ -1,8 +1,11 @@ +import type { User } from '../../types'; import { AddonsService } from './addons.service'; import { REQUIRE_ADDON, type RequireAddonMeta } from './require-addon.decorator'; import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; +import type { Request } from 'express'; + /** * Enforces @RequireAddon. Replaces the three hand-written addon guards * (collections, airtrail, journey), which differed only in which addon id they @@ -11,6 +14,13 @@ import { Reflector } from '@nestjs/core'; * A handler-level @RequireAddon overrides the controller's, so a route group * can carry one addon and a single endpoint another. Without the decorator the * guard is a no-op — it never gates a route that did not ask for it. + * + * It reads the instance switch, and nothing else while no user is known yet, + * which is the case where it runs ahead of JwtAuthGuard. Placed after + * JwtAuthGuard on a route that has no trip (a tour library, a search across + * trips), it also opens for a user one of whose trips switched the addon on + * although the instance has it off. A trip-scoped route takes TripAddonGuard + * after TripAccessGuard instead, which asks the one trip. */ @Injectable() export class AddonGuard implements CanActivate { @@ -26,7 +36,10 @@ export class AddonGuard implements CanActivate { ]); if (!meta) return true; const ids = typeof meta.addonId === 'string' ? [meta.addonId] : meta.addonId; - const enabled = await Promise.all(ids.map((id) => this.addons.isAddonEnabled(id))); + const user = context.switchToHttp().getRequest().user; + const enabled = await Promise.all( + ids.map((id) => (user ? this.addons.isEnabledForUserAnywhere(user.id, id) : this.addons.isAddonEnabled(id))), + ); if (!enabled.includes(true)) { throw new HttpException({ error: `${meta.label} addon is not enabled` }, 404); } diff --git a/server/src/nest/addons/addons.constants.ts b/server/src/nest/addons/addons.constants.ts new file mode 100644 index 000000000..b92593629 --- /dev/null +++ b/server/src/nest/addons/addons.constants.ts @@ -0,0 +1,58 @@ +import { ADDON_IDS, type AddonId } from '../../addons'; +import type { AddonRow } from '../../db/repositories/Addons.repository'; + +/** + * The word that leads `